Skip to content

The OSINT investigator's workbench. One case, one folder, every tool. Local-first: your media and your investigations never leave your machine.

JavaScript

Draw FIRMS fires as map marks, add place names, page Sentinel lookups, and give Compare and Detect full screen (#96)

OsintMeThatf82984977f73
diff --git a/README.md b/README.md
index 1b95b20..98c0173 100644
--- a/README.md
+++ b/README.md
@@ -61,7 +61,7 @@ to fix a point on the map.*
| **Reverse Search** | Prepare an image or a video frame for keyless reverse-image services. With the capture extension, pressing an engine opens it with the picture already in it. Nothing leaves the machine until you press one. |
| **Inspect** | Reads any photo or video closely: sharpest-frame capture onto a strip, frame adjustments, editable crop and ELA hints. Frames and edits are kept with the file as you make them; a frame or an adjusted video enters the Media Library only when you save it to the case. |
| **Collage** | Lays out frames and images from any number of files on one canvas, with per-piece warp, scale, rotate and crop, and auto-stitch to solve a panorama's layout. Saved as you go; the picture it exports is case media. |
-| **Satellite** | Coordinates or a place name become an imagery crop. The search bar proposes matches as you type: saved work, coordinates and a bundled city list answer offline, and the geocoder fills in the rest once you pause. Select-area capture with an optional scale bar and north arrow, map rotation, measurement tools, a right-click menu on any point, stacked overlays (borders, roads, railways, power lines, fires, night lights), your own KML, KMZ, GeoJSON, GPX or My Maps layers, GeoConfirmed conflicts narrowed to a period, and editable AOI grids for area review. Esri/OSM by default, plus the Esri Wayback archive, Sentinel-2 with a date calendar and a cloud-ceiling slider, and Sentinel-1 radar passes; add a Mapbox or Google key for more basemaps. Open it in several tabs and they stay in sync. |
+| **Satellite** | Coordinates or a place name become an imagery crop. The search bar proposes matches as you type: saved work, coordinates and a bundled city list answer offline, and the geocoder fills in the rest once you pause. Select-area capture with an optional scale bar and north arrow, map rotation, measurement tools, a right-click menu on any point, stacked overlays (borders, village names, roads, railways, power lines, fires, night lights), your own KML, KMZ, GeoJSON, GPX or My Maps layers, GeoConfirmed conflicts narrowed to a period, and editable AOI grids for area review. Esri/OSM by default, plus the Esri Wayback archive, Sentinel-2 with a date calendar and a cloud-ceiling slider, and Sentinel-1 radar passes; add a Mapbox or Google key for more basemaps. Open it in several tabs and they stay in sync. |
| **Compare** | Links two dated map views for side-by-side, swipe, fade or blink, with Difference highlights laid over any of them. All dates lists every picture of a point, oldest first, to set on either side. Ground-anchored notes, shapes, numbered markers and measurements follow both maps. Editable sessions and rendered previews stay in the case; attributed PNG/GIF copies go to exports. |
| **Detect** | Sweeps drawn areas of Sentinel-2 for vessels, fires, construction, burn scars and other changes, and of Sentinel-1 radar for vessels, razed buildings, new structures and floods through cloud, once or as a saved routine. Only a candidate you keep becomes a case pin, dated by the passes that found it. |
| **Coords & Sky** | Convert common coordinate formats, copy the result, open map or geocoding links, and read the sun and moon at that point on a date: rise, set, azimuth, altitude, twilights, moon phase and bright-limb angle, in local time and UTC, computed offline. |
diff --git a/docs/IMAGERY_PROVIDERS.md b/docs/IMAGERY_PROVIDERS.md
index dee1b1c..c8338eb 100644
--- a/docs/IMAGERY_PROVIDERS.md
+++ b/docs/IMAGERY_PROVIDERS.md
@@ -195,7 +195,10 @@ scene above it is dropped before rendering, so the tile comes back empty rather
than cloudy. Left implicit that reads as the app hiding cloudy days: a date the
calendar offered renders black, and the dataMask probe calls it a coverage gap.
Stating the ceiling on every request (tiles, the probe, the WFS date list) means
-what filters a date is our number, not the instance's.
+what filters a date is our number, not the instance's. Detect reads a day it has
+settled on at 100 whatever its ceiling, because the ceiling's job there is to pick
+the newest pass: sent as `MAXCC` it dropped the whole tile of a day chosen over it
+(26/09/2026 over Lyman, 51% cloud, came back without a pixel at 30).
The provider id carries the layer, the window and the ceiling:
`sentinel2~SWIR~2026-05-01~2026-05-31~CC20`
@@ -250,8 +253,10 @@ picked on its centre sweeps nodata over the rest. The automatic date rules
(`resolve_dates`) take the newest pass that is both under the cloud ceiling and
at full cover, and name the best partial share when there is none.
-Still one request for the whole set of areas, not one per area. `truncated` says
-the WFS hit its 100-feature ceiling, so older passes in the window are missing.
+Still one lookup for the whole set of areas, not one per area, read in pages of
+100 granules (`FEATURE_OFFSET`), newest first (checked 2026-09), up to five. Each
+page is one request on the meter. `truncated` says the fifth page was full, so
+the oldest passes in the window are missing.
WFS dates are still candidates. Before changing the map, the picker sends an
8×8 WMS `dataMask` check for the selected layer and day. A failed check leaves
@@ -471,22 +476,28 @@ meter, no free-allowance box and no eco threshold. Nothing about it is billed.
| | |
|---|---|
| Credential | one `MAP_KEY`, from the FIRMS page; it serves the global and the US/Canada services alike |
-| Where it goes | **in the path** of every request, which is why the browser never builds one: `/api/firms/tiles/{z}/{x}/{y}` for the app, `/api/ingest/firms` for the extension |
-| Asking | WMS `GetMap` in EPSG:3857 — the projection the tile grid is already in, so a tile is its own square and nothing is reprojected |
-| Live | `fires_viirs_24 / _48 / _72 / _7`, and the same for `fires_viirs_snpp`, `fires_viirs_noaa20` and `fires_modis` |
+| Where it goes | **in the path** of every request, which is why the browser never builds one: `/api/firms/points/{z}/{x}/{y}` for the app, `/api/ingest/firms` for the extension |
+| Asking | the app gets vector tiles (`/api/firms/points/{z}/{x}/{y}`, z0 to z13) and draws every square itself. Far out, and for a dated range at every zoom, a tile is one WMS `GetMap` in EPSG:3857 — the projection the tile grid is already in, so nothing is reprojected — drawn with squares of 1 px, which the backend reads back into marks, one per 3 px (`firmspoints.picture_tile`). From z8 in, a rolling window comes from the **area API**'s points: one request per satellite, 4° cell and five days, held in memory, and every tile of every zoom over that cell is cut from them (`firmspoints.tile`) |
+| Drawing | squares sized to the footprint (375 m VIIRS, 1 km MODIS, never under 7 px) with a dark ring, and for a window longer than a day FIRMS's "24 h" in red over the rest in amber. The map draws them (`lib/map/firePoints.js`), so a square keeps its size through a zoom and stays where it is while the next level loads, where a picture's squares grew with its pixels until the next picture landed. From z11.5 to z12 a rolling window's squares give way to the footprints, scan by track, each with its own ring and edge and the ground showing inside, so a square under another keeps its outline. A square read off a picture has no footprint and stays a square. The extension's one picture is FIRMS's own far out, asked in the path after the key and dressed with the ring, and drawn from the points close in |
+| Windows | FIRMS counts whole UTC days, not hours: "24 h" is yesterday and today, "48 h" and "72 h" reach two and three days back, "7 days" seven (matched pixel for pixel against the WMS layers, 2026-09-27). The points are filtered the same way, or the day's main pass would drop out of "24 h" at the zoom where the points take over |
+| Live | `fires_viirs_24 / _48 / _72 / _7`, and the same for `fires_viirs_snpp`, `fires_viirs_noaa20` and `fires_modis`. The combined `fires_viirs` is S-NPP, NOAA-20 and NOAA-21 (checked pixel for pixel, 2026-09) |
| History | the same layer names without the suffix, dated with `TIME=from/to`, up to **31 days** per request |
-| Zoom ceiling | source tiles stop at z14. Deeper views reuse the z14 tile with nearest-neighbour scaling, keeping each detection visible as a square without another NASA request |
-| Allowance | 5,000 requests per 10 minutes, and a long range counts as several. Nothing polls, and a layer that is off asks for nothing |
-| Caching | none on disk. The live layers are what is burning now (upstream refreshes every 15 minutes) and a cached fire is a lie with a timestamp; the browser holds one for 5 minutes |
+| Zoom ceiling | tiles are 512 px and stop at z13, where a VIIRS square is already 20 px or more. Deeper views draw the z13 tile's squares bigger, so a square stays the size of its footprint without another NASA request |
+| Allowance | 5,000 transactions per 10 minutes, counted per day covered and per satellite: a WMS tile of the last 24 hours on the combined VIIRS layer is 3, a tile of 31 days 93, and an area request 2 per day and satellite whatever its box, so a week of one cell is 48 and every zoom under it is then free (measured 2026-09). The count fell back to zero in one go after ten quiet minutes. Nothing polls, and a layer that is off asks for nothing |
+| Area API | `api/area/csv/{key}/{source}/{west,south,east,north}/{days}/{first day}`, `days` 1 to 5 counted forward. The near-real-time files (`VIIRS_SNPP_NRT`, `VIIRS_NOAA20_NRT`, `VIIRS_NOAA21_NRT`, `MODIS_NRT`) hold about the last three months, the archive files before. A wrong key answers `400 Invalid MAP_KEY.` |
+| Refusal | a spent allowance and a key FIRMS does not know answer the same 28 KB placard. The key-status endpoint costs nothing and tells them apart: it gives a key it knows its count, and a key it does not a 403. A spent allowance pauses the layer a minute at a time and leaves the key alone; only the 403 benches it. Any area answer that is not the table is read through the same endpoint |
+| Caching | none on disk. The live layers are what is burning now (upstream refreshes every 15 minutes) and a cached fire is a lie with a timestamp; the browser holds one for 5 minutes, and a range that ended before yesterday for 6 hours. The points are held in memory, today and yesterday for 5 minutes and older days for 6 hours, a million rows at most (about 24 MB), least recently drawn out first |
-NOAA-21 is left out on purpose: FIRMS gives it the rolling layers and no dated
-one, and a sensor that could answer "now" but not "that day" is a trap in a tool
-whose second question is always the date.
+NOAA-21 is not offered on its own: FIRMS gives it the rolling layers and no
+dated one, and a sensor that could answer "now" but not "that day" is a trap in
+a tool whose second question is always the date. It is inside the combined
+VIIRS layer, which is why that one counts three transactions a day.
The extension asks differently for the same reason it draws differently: it has
no tile grid to hang tiles on, so it asks for **one picture of the ground it can
see** per settled view and lays it under its own drawing, rotated with the map.
-That is also one request where tiles would be a dozen.
+That is also one request where tiles would be a dozen. Close in, that picture is
+drawn from the same points as the map's vector tiles, so both show the same squares.
## Esri Wayback is one release at a time
@@ -530,20 +541,22 @@ id and its cache always name one.
Drawn over any basemap, fetched by the browser straight from their own servers
(all answer cross-origin), never through the proxy, never cached on disk and
-never in a capture. Borders are the one layer the map opens with; every other is
-asked for only once its switch is on (`frontend/src/lib/map/basemap.js`).
+never in a capture. Borders and Place names are the layers the map opens with;
+every other is asked for only once its switch is on
+(`frontend/src/lib/map/basemap.js`).
Checked 2026-09-13.
| Layer | Source | Licence / terms | Notes |
|---|---|---|---|
-| Borders | Esri `Reference/World_Boundaries_and_Places` | Esri terms, as World Imagery | carries the place names |
+| Borders | Esri `Reference/World_Boundaries_and_Places` | Esri terms, as World Imagery | carries the larger place names |
+| Place names | OpenFreeMap `planet` vector tiles (OpenMapTiles schema), found through its TileJSON since the tile paths change with each weekly build | data ODbL © OSM contributors, © OpenMapTiles, OpenFreeMap credited; no key and no quota | `place` layer only, towns down to hamlets, in `name:latin`; imagery only; the browser draws the text, so no glyphs are fetched. Checked 2026-09-27 |
| Roads | Esri `Reference/World_Transportation` | Esri terms, as World Imagery | imagery only |
-| OSM railways | OpenRailwayMap `standard` | © OSM contributors, style © OpenRailwayMap | |
+| Railways | OpenRailwayMap `standard` | © OSM contributors, style © OpenRailwayMap | |
| Power lines | Open Infrastructure Map vector tiles (`/map/power`, `/telecoms`, `/petroleum`) | data ODbL, analysis CC-BY 4.0, credit and link required | no published tile usage policy, so the style is ours, requests only follow the view, and nothing is prefetched |
| Sea marks | OpenSeaMap `seamark` | © OpenSeaMap contributors (CC-BY-SA) | |
| GPS traces | `gps.tile.openstreetmap.org/lines` | OSMF tile policy | |
-| Night lights | NASA GIBS WMTS, `VIIRS_NOAA20_DayNightBand_At_Sensor_Radiance` (from 2024-03-25), `VIIRS_SNPP_…` (from 2020-11-18, with gaps), `VIIRS_Black_Marble` 2016 | public domain | Level 8 (750 m); opaque, drawn lowest at 85% |
| Active fires | NASA FIRMS, keyed, through the app | see above | |
+| Night lights | NASA GIBS WMTS, `VIIRS_NOAA20_DayNightBand_At_Sensor_Radiance` (from 2024-03-25), `VIIRS_SNPP_…` (from 2020-11-18, with gaps), `VIIRS_Black_Marble` 2016 | public domain | Level 8 (750 m); opaque, drawn lowest at 85% |
## GeoConfirmed is a query, not a feed
diff --git a/docs/SPEC.md b/docs/SPEC.md
index 3df8ce2..e994ed3 100644
--- a/docs/SPEC.md
+++ b/docs/SPEC.md
@@ -171,7 +171,7 @@ proof for publication.
| ✅ **Map chrome** | Puts modes in one rail, map layers in their tool panel or popup, imagery in the map corner and position in a status line, each tool declared once. |
| ✅ **Point menu** | Right-clicking the ground copies that point in every format, looks it up, saves, measures, reads the sky or opens its imagery history from it, opens it in the other map tabs, and links it out. |
| ✅ **Map windows** | Opens the map in several tabs with the view in the URL, links map tabs and extension panels on other sites to one camera, and syncs saved points, grids and sweeps live to every tab and extension panel. |
-| ✅ **Map layers** | Stacks key-less overlays (borders, roads, railways, power lines, sea marks, GPS traces), NASA FIRMS fires and VIIRS night lights for a chosen day, and filters drawn pins by kind and folder. |
+| ✅ **Map layers** | Stacks key-less overlays (borders, place names, roads, railways, power lines, sea marks, GPS traces), NASA FIRMS fires and VIIRS night lights for a chosen day, and filters drawn pins by kind and folder. |
| ✅ **Added map layers** | Opens a KML, KMZ, GeoJSON or GPX file, or follows a public My Maps or map URL refreshed only while enabled, and draws it with its own colours, optionally its own icons composed once at import, a legend that filters and a search that goes to one feature — read, cited and never adopted into the case. |
| ✅ **Dates on a layer** | Narrows a dated added layer (GeoConfirmed, KML timestamps, GPX waypoints) to a period dragged on a strip of its events over time or picked on a calendar, kept with the legend. |
| ✅ **GeoConfirmed layer** | Adds one GeoConfirmed conflict over a window of days or dates or its whole history, optionally only the view, in GeoConfirmed's own icons, grouped by faction with each event's sources and geolocation one click away. |
@@ -204,13 +204,14 @@ proof for publication.
| ✅ **Sizes in Detect** | Right-clicks Detect's map for its own point menu, measures a hull with a ruler, sizes each candidate along its footprint, walks the largest first, and hides the drawing or blinks A against B from the review. |
| ✅ **Analyzers of your own** | Builds a Detect analyzer from up to six rules on any band, index, ground class or radar polarisation, read on A, B or the change, tried live on the map over any Copernicus layer, painted rule by rule or as the detections alone, with a point reading; optional checks (marked places reread as the rules change) and five calibrated examples that ship with theirs; also opened from a built-in or a Difference reading, with a shape filter for every analyzer. |
| ✅ **Examine: Inspect and Collage** | Keeps one work per file, saved as it is made, with its frames on a strip; lays collages out of frames and images from any file; merges a case's 0.3.0 sessions on open. |
-| ✅ **One camera for the map tabs** | Satellite, Compare and Detect show the same ground, and the link carries it to other windows; a Detect review and a saved comparison keep theirs, and Settings turns it off. |
+| ✅ **One camera for the map tabs** | Satellite, Compare and Detect show the same ground, and the link carries it to other windows; a Detect review keeps its own, and Settings turns it off. |
| ✅ **Comparisons in Saved work** | A saved comparison stands on the map with the captures, at its frame's centre with the frame outlined, dated A → B, and reopens in Compare; an export can also be kept in the case under it. |
| ✅ **Dated pins and pictures** | A kept Detect candidate files a claim at its pin (a change between two passes, or a thing seen on one); comparisons and pinned evidence carry each picture's date, estimates marked; Detect layers filter a change by its span; exports are named by their pictures' dates. |
| ✅ **An evolution of one point** | Exports Sentinel-2 passes or Wayback pictures ticked by hand on their previews, back to 2015, as one GIF or one sheet drawn from the tile proxy on the same ground, repeats and empty pictures left out and counted. |
| ✅ **Signed exports, marks in their colours** | Compare exports close their credits line with the Azimut logo and name unless unticked, and a GIF keeps every mark's colour exact. |
| ✅ **One turn on every map** | A middle-drag turns any map or Inspect frame like a wheel about the grabbed point, settling on north, in 15° steps with Ctrl; a middle click or Shift+↑ puts north back, Shift+← / → steps. |
| ✅ **Checked proof points** | A proof point taken from a capture's centre reads greyed until checked; Save and To post show each one on the map first, and one saved for later stays off the case map. |
+| ✅ **Compare and Detect full screen** | Both take the whole screen with their bars and panel, as Satellite does, and any change of tab gives it back. |
---
@@ -334,7 +335,10 @@ stops making sense.
- **Oil slicks by radar:** dark patches on the sea near anchorages and lanes, which Sentinel-1 shows through cloud.
- **Map files out of the case:** export pins, claims and Detect findings as KML or GeoJSON, with TimeStamp and TimeSpan so another viewer's time slider reads them.
- **Update ffmpeg from the app:** download a static build into the workspace and prefer it at runtime, like the scraper update, if the bundled copy ever lags in a way users hit.
+- **Place names in their own script:** the Arabic or Cyrillic name under the Latin one, for searching local sources. Needs the engine's right-to-left text plugin, bundled rather than fetched.
- **A deleted case waits before it is gone:** artifacts, entities and bulk deletes are all recoverable, while removing a case is the one act with no way back and only a typed DELETE in front of it. Move the folder aside instead, and empty it later.
+- **A fire detection to click:** the points the app already draws close in, read back under the pointer for the detection's time, satellite, confidence and power.
+- **The sky over the area, not the tile:** Detect's pass list and its newest pass judged by the cloud over the drawn area (one small SCL read per pass) rather than the 110 km tile's figure.
## 8. Explicit non-goals
diff --git a/docs/UI.md b/docs/UI.md
index 0c4b0ef..ec747ac 100644
--- a/docs/UI.md
+++ b/docs/UI.md
@@ -1281,19 +1281,23 @@ tabs left the window, or on the home view, with a key-less pair: an Esri Wayback
today's World Imagery on B. That costs the release list and tiles, never a
Copernicus request or a point's history, and A stays empty when no release list
comes back rather than showing B twice. Panning that untouched pair leaves
-nothing to discard, and Save still takes it. **New** starts over from a menu of
-starting pairs, the same ones a removed pair offers above its empty slots. Each
+nothing unsaved, and Save still takes it. **New** starts over from a menu of
+starting pairs, the same ones a removed pair offers above its empty slots, and
+**Revert** shows only on an edited saved comparison, taking it back to the saved
+version. Each
side keeps its provider, Wayback release, Sentinel-2 day and reference layers.
The source cards and mode controls use the application's shared theme, buttons
-and spacing. On a card the date is a chip beside the provider, reading the same
-for Wayback and for Sentinel-2, so the card's layers icon means one thing. A
+and spacing. The date is a chip beside the provider, reading the same for
+Wayback and for Sentinel-2 on every map tab, so the card's layers icon means one thing. A
Wayback chip names the release, so the day its pixels were taken sits beside it,
as it does under the chip on Satellite. The
-cards are as wide as the maps under them, so the split between A and B is one
-line down the tool. Both Layers buttons open the same A/B sheet, including each
+cards float over the maps they describe, one per pane, so no bar takes the maps'
+height; the place search and the camera sit in B's corner. Both Layers buttons open the same A/B sheet, including each
side's FIRMS period, VIIRS night and saved case work.
-The mode dock holds the four views: side by side, through a swipe, with B faded
+One row sits above the maps. With a pair on screen the mode dock takes the
+title's place there, beside the name, **All dates**, **Export** and **Save**, and
+below 1400 px its four views show as icons. The dock holds the four views: side by side, through a swipe, with B faded
over A, or as alternating whole frames. Blink has three speeds and can pause on
either side. **Difference** sits beside them as a switch, offered only when the
two sides are a matched pair, and lays its highlights over whichever view is on.
@@ -1301,8 +1305,9 @@ Sweeping an area over time is the Detect tab's job, not Compare's. Keys 1–4
switch views, 5 toggles Difference, and Space pauses blink. Dragging, zooming or rotating either
map moves the other in the same frame. Both stop at the lower provider zoom
ceiling. **Swap A and B** exchanges the complete source stacks and annotation
-sides. One compass in the bar reads the shared turn, resets it to north and takes
-an exact angle.
+sides. One compass over the stage reads the shared turn, resets it to north and takes
+an exact angle. **Full screen** ends the header row and gives the whole tool the
+screen, its bars and annotation rail included. Esc gives the window back.
A radar side knows the other side's pass: its picker marks the passes on the same
track, the only ones that compare like with like. **Two radar passes** joins
@@ -1312,7 +1317,7 @@ satellite and radar pairs stay in the New menu marked *set up*, and the two
archives stay in the imagery picker marked *Needs a free key* or *Needs its
layer*. Pressing one lays the same setup card as Detect's over the stage.
-**All dates** in the bar opens a strip under the maps whenever A and B show the
+**All dates** in the header opens a strip under the maps whenever A and B show the
same dated archive: Sentinel-2, Sentinel-1 or Esri Wayback. It lists every picture
that archive holds of the point under the crosshair, oldest on the left: the
Copernicus days and passes of a window around A and B, one request, or the
@@ -1324,8 +1329,13 @@ read, and a view that moved says so rather than refreshing on its own.
Difference opens no column: its strip joins the view's own controls in the footer
under the stage, and its full settings open above that strip only from the gear.
-The strip keeps one width through a read, so the panel hanging from it stays put;
-what the read is doing shows in the panel's readout and the map legend. The panel
+The strip keeps one width through a read, so the panel hanging from it stays put
+and the gear never moves. **Read** says what the reading is doing on the button
+itself: amber **Read** when pressing it is the next move, **Reading…**,
+**Loading…** while map tiles are still coming in, and a disabled **Up to date**
+when nothing moved since the last read. The map legend says the same in words
+("out of date, press Read"). A reading waits for tiles to finish instead of
+failing on them. The panel
lies over the highlights and closes on Escape or a press anywhere outside it.
**Difference** checks that the sources can be compared before it runs.
@@ -1334,14 +1344,23 @@ Two Sentinel-1 passes of one track are a pair too: the rendered radar picture is
read with no tone matching, and passes from two tracks are refused, because they
see the ground from two angles.
Sentinel-2 also offers six spectral indices — NDVI, NDWI, MNDWI, NBR, NDBI and
-BSI, the ones Detect measures — from the actual bands. Band frames are fetched by
-an explicit act only — **Read this view**, or switching the cloud filter on —
-one metered request per side; reopening a session or moving the camera never
-fetches. Each frame is kept with a margin of ground around the view, so the
-reading keeps its bands while the camera stays inside that margin, and past it
-the last reading stays up, marked in the strip as an earlier read, until **Read**. A changed view must be run again before
-export. A reading recomputes by itself after every move, on the
-frames it holds; what it never does on a pan is spend a request.
+BSI, the ones Detect measures — from the actual bands. A new pair's band frames
+are fetched by an explicit act — **Read**, turning Difference on, choosing a
+method or an index, or switching the cloud filter on — one metered request per
+side. Reopening a session or changing a date never fetches on its own. Each frame
+is kept with a margin of ground around the view, so the reading keeps its bands
+while the camera stays inside that margin. Frames are asked for at the
+resolution the reading draws at, never finer. The cloud map is read at
+Sentinel-2's own 20 m, which lets its margin reach up to a whole view past each
+edge for no more pixels. Once a pair has been read with its bands, the reading
+follows the camera with them. Past the margin it fetches them again once the
+camera has rested for a moment, and only then, however many drags it took. The
+pan has just drawn Sentinel-2 tiles, which are metered requests too. A reading
+that follows the camera waits for bands already on their way, and a Read the
+camera moved under reads the view it settles on, so a request is never spent and
+then thrown away. Until a new pair is read, the last reading stays up, drained
+to grey so it cannot pass for this view's. A changed view must be run again
+before export.
These viewport captures depend on display resolution and zoom. Use the Detect
tab for a fixed analysis grid across camera changes. An index reading carries
**Save as a Detect analyzer** in the Detection tab: the same index, line, way it
@@ -1401,7 +1420,9 @@ drag inside one pans the imagery under it. The wheel still belongs to the map wh
the pointer is: the marks are drawn over it rather than in it, and a zoom that
stopped on whatever had been drawn read as a map that had frozen. Clicking the ground beside a mark lets it go;
dragging the map is a pan and keeps it. The tool rail packs into two columns, like
-Proof Maker's, so it stays short enough to fit a laptop window. Its colour, width
+Proof Maker's, so it stays short enough to fit a laptop window. The tab on its
+edge, or `[`, folds it to a strip marked *Annotations* that keeps the tool in hand,
+and this browser remembers the fold. Its colour, width
and fill panels close on Escape, on their own button, on a press anywhere else,
and with the button behind them when the selection is dropped. **Pressing the tool
already in hand puts it down** and gives the cursor back, on this rail and on Proof
@@ -1414,7 +1435,7 @@ name, anchored on the point and closed by the next click — or open it in
Satellite or Detect. The rows Satellite offers for its own rails are left out
rather than shown dead.
-**Save comparison** writes the editable version-2 session under `.compare/` and
+**Save** writes the editable version-2 session under `.compare/` and
updates its rendered media preview in My work (PNG, or GIF for blink). The preview
records the date of each picture, one Esri or Wayback only estimated marked `~` on
its Time tab, where **Date a change** offers a claim that something changed between
@@ -1459,7 +1480,7 @@ Views destination only, never kept in the case. Tile captures wait
for loaded frames and reject incomplete tiles. Google Maps JS uses the
user-triggered Azimut Capture extension and retains its on-map credits.
-The search bar in the header proposes matches as you type, in the order they can
+The search bar floating at the top of the map proposes matches as you type, in the order they can
answer: the coordinates the text parses to, saved work in this case, cities from
a gazetteer shipped with the app (GeoNames, credited under the list), and last
the geocoder's streets and hamlets. The first three cost no network and appear on
@@ -1586,8 +1607,9 @@ which it is (`lib/map/tools.js`) rather than adding a button somewhere.
- **Its settings** open in the rail's one **panel slot**, beside it. One mode is
armed, so one panel is open; a panel cannot cross another or the map's own
controls.
-- **Layers** — what is drawn over the imagery: borders with their place names,
- roads, OSM railways, power lines, sea marks, GPS traces, active fires, night lights, the
+- **Layers** — what is drawn over the imagery: borders with the larger place
+ names, town and village names, roads, railways, power lines, sea marks,
+ GPS traces, active fires, night lights, the
case's saved work, and the points another tool handed over (a sheet's
coordinate column, a Timeline window). None of them changes what the
pointer does, so none takes a rail seat: they are a list in the panel beside
@@ -1633,26 +1655,45 @@ something off the map — Save place and Capture — on the right. What marks th
point, and whether that point is the map's centre or a pin dropped somewhere,
is one small menu beside them: both are set once and the two acts are pressed
all day. The engine's scale bracket reads under the coordinates, where how far
-a pixel goes and where you are make one instrument. Fullscreen sits with the
-tool's title, because it is what the window does with the tool rather than what
-the tool does with the map.
+a pixel goes and where you are make one instrument. Link, new tab and fullscreen
+close the imagery card on its right, one frame as on Compare's source cards,
+because they are what the window does with the tool rather than what the tool
+does with the map. On a narrow map the card splits in two lines, the provider
+and those three on top, rather than slide under the search. Sentinel-2 is dated on its
+own chip there, as on Compare and Detect, and the pill under it reads the day
+again with how it was chosen, as the radar pass does.
**Active fires** are NASA FIRMS, and answer two questions with the same marks:
what is burning now (the last 24, 48 or 72 hours, or the week) and what was
burning on a given day (any range back through the archive, up to 31 days).
-Which instrument and which stretch of time are chosen in the row itself. It
-needs a key, and says so with the reason rather than failing on the first tile;
-a key pasted into Settings is picked up on the way back to the map. Source
-tiles stop at z14. Farther in, the map enlarges their pixels into visible
-squares instead of hiding the detections or asking NASA for invented detail.
+Which instrument and which stretch of time are chosen in the row itself. A
+detection is a square the size of its footprint, never under 7 px, with a dark
+ring so it reads on any ground; close in, its inside shows the ground and each
+square keeps its own edge, even under another. A window
+longer than a day draws the last 24 hours in red over the rest in amber, and the
+row says so. The windows are FIRMS's own, counted in whole UTC days. The map
+draws every square itself, at every zoom: a square keeps its size through a
+zoom and stays where it is while the next level loads, then the new level
+refines it. From zoom 8 in, a live window comes from the points fetched for the
+ground around, so zooming in costs nothing more; farther out, and for a date,
+the squares are read off FIRMS's own picture of each tile. It needs a key, and says which of three things stops it rather than
+failing on the first tile: no key, a key switched off, a key FIRMS refused. A key
+pasted into Settings is picked up on the way back to the map. A spent allowance
+is none of those: the layer stays on, says it refills within ten minutes, and
+asks NASA nothing in the meantime. Tiles stop at z13. Farther in, the map
+draws those squares bigger instead of asking NASA for invented detail.
**The reference layers** are key-less and each is simply on or off: Esri's
-borders (country, region, district, with names) and roads, Open Infrastructure
-Map's power lines, OpenSeaMap's buoys and harbours, and the raw GPS traces people
-uploaded to OSM, which show tracks nobody has mapped yet. Borders start on —
-reading imagery starts with which side of a line the ground is on — and none of
-the others fetches a tile before its switch is pressed. The roads follow the
-labels' rule: over a street map they are greyed, since it already draws them. Power lines are drawn
+borders (country, region, district, with names) and roads, OpenStreetMap's
+town, village and hamlet names from OpenFreeMap, Open Infrastructure Map's power
+lines, OpenSeaMap's buoys and harbours, and the raw GPS traces people uploaded to
+OSM, which show tracks nobody has mapped yet. Borders and place names start on —
+reading imagery starts with which side of a line the ground is on and what the
+place is called — and none of the others fetches a tile before its switch is
+pressed. The place names fill in
+where Esri names only the cities. They are written in Latin script, and where
+two would overlap the larger place is kept. The roads and the place names are
+greyed over a street map, since it already draws them. Power lines are drawn
from vector tiles in the app's own small style, coloured by voltage on Open
Infrastructure Map's scale, dashed where the line is buried, with towers from
zoom 14, substations, plants, pipelines and telecom masts. No overlay reaches a
@@ -1691,7 +1732,7 @@ The row states five things:
row that leaves the app, and it leaves on a click.
- **How fresh what is drawn is.** A file says when it was opened and nothing
more: it is exactly what was dropped in. A followed map says when it was last
- read, and says *stale* when that was long enough ago to matter — before the
+ read, and says *out of date* when that was long enough ago to matter, so before the
marks are read, not after.
- **Both counts.** `3 200 features · 412 shown` whenever a group is switched
off. The number drawn never passes for the number loaded.
@@ -1916,8 +1957,9 @@ A, newer on B — unsaved and unnamed, because nothing has been filed.
**Open in…** lists the app's other map tabs first, then the maps outside it. A
tab opens on the point at the zoom it was looked at: Satellite flies there, and
Compare and Detect move their camera and keep their own pictures and work. In
-Detect a point asked for this way wins over the case's landing frame. A
-fullscreen map is left first.
+Detect a point asked for this way wins over the case's landing frame. Changing
+tab, from this menu or any other way, leaves full screen. Leaving it, however it
+is left, keeps the ground and zoom the map reached.
**The map tabs share one camera.** Satellite, Compare and Detect look at the same
ground: a map leaves the window's camera where it comes to rest, even when its glide
@@ -1925,9 +1967,9 @@ ends after you switched tab, and a map tab that shows takes it in one move, turn
included. A hidden map never moves, so it loads no tiles and asks Copernicus nothing
for ground nobody is looking at.
A map whose imagery stops short of the shared zoom lands at its own ceiling and
-leaves the deeper zoom standing for the tab that has it. Two things keep their
-ground: a Detect run under review, and a saved comparison, whose camera is part of
-what was saved.
+leaves the deeper zoom standing for the tab that has it. A Detect run under
+review keeps its ground. A saved comparison follows like the rest, and moving it
+leaves it saved; Save keeps the new view.
Switching case leaves the camera where it is, since a view is not case state.
Settings → General → Map tabs turns it off, and each tab keeps its own camera again.
@@ -1974,7 +2016,7 @@ address in place: a back button holding four hundred camera positions would be
worse than none. Everything else — the case, its saved points, a sweep in
progress — is shared already, below.
-A detached tab carries its number in its title and its heading, because two
+A detached tab carries its number in its title and beside its search, because two
identical maps on a second screen cannot otherwise be told apart, and `solo=1`
in the same address, which is what keeps it the map alone across a reload. The
first window is unnumbered. The browser can refuse a second tab, and says so.
@@ -2022,8 +2064,8 @@ the key, which brings its layers with it, and the Sentinel-1 layer added to it b
hand for the radar analyzers, field by field — and one press opens the Copernicus
card in Settings. The panel still opens on what the case already holds.
-Detect opens on Esri World Imagery, with Borders and saved results visible, framed
-on the areas this case watches — once, after which the camera is yours. That
+Detect opens on Esri World Imagery, with Borders, Place names and saved results
+visible, framed on the areas this case watches — once, after which the camera is yours. That
framing waits for the tab to show. Arriving from another map tab while they share
one view, Detect opens where that map was instead, since that is the ground in hand.
A case with no area opens where the other map tabs left the window, or on the home
@@ -2053,7 +2095,8 @@ the ruler down.
The right dock has Routines, Saved and Areas tabs, with New detection always at
the top. The tabs name their own list, so nothing is titled twice, and a second
row appears only inside a routine, a review, the wizard or the library, where it
-carries Back. **Analyzers** sits at the end of the tab row. Its toggle or the `]`
+carries Back. **Analyzers** sits at the end of the tab row, then **Full screen**,
+which gives Detect the whole screen with its dock. Its toggle or the `]`
key collapses the dock to an icon rail; pressing a tab reopens it and resizes the
map. Detect's basemap, overlays, saved-work visibility and collapsed state are
viewer preferences carried by Settings → Backup. **Watched areas** is a row of the
@@ -2132,12 +2175,20 @@ pan, a zoom or a turn.
**When** asks its questions in the order they are decided, in the step itself. A
change names **A**, the picture before, and **B**, the one to look in; B is the
-**Newest pass**, looked up when the run starts under the cloud ceiling, until
-**A day I choose** asks for one. Vessels and hotspots read one image and ask only
-that. A routine names no B: it asks what each run compares the newest pass with,
+newest pass under the cloud ceiling, and its button names the ceiling (**Newest
+pass under 30% cloud**), since it is not always the newest pass there is. Once
+the passes are found, the line under it names the day it takes and the newer ones
+it steps over, each with its cloud. The ceiling's slider, 30% to start, sits
+wherever the newest pass is taken: under that button, and under a routine's
+question. Above 30% it warns that the pass taken can be mostly cloud. **A day I
+choose** asks for one, and a chosen day is read whatever its cloud: the ceiling
+only picks the newest pass, and ground under cloud is left out pixel by pixel.
+The map shows a chosen day whole, as the run reads it, and its chip adds the
+tile's cloud when that is over 30%. Vessels and hotspots read one image and
+ask only that. A routine names no B: it asks what each run compares the newest pass with,
**The pass before** (what changed since the last run; A serves the first run only)
or **A fixed picture** (everything changed since that day), and a one-image routine
-asks nothing but its picture and cloud ceiling. The slot still missing is tinted,
+asks nothing but its cloud ceiling, with its picture under **Picture**. The slot still missing is tinted,
and the reason is written under the Next button. **Passes over the area** lists
what exists right under the question, each row with its A and B buttons, and a
typed day works too. One choice stands for every area; **Set them per area…**
@@ -2154,11 +2205,13 @@ hand is pinned to the pass on the other side's track at launch, and an automatic
pass is looked for on the reference's track.
**Find passes** explicitly asks Copernicus about the areas and counts one request
-against its quota. The picker shows cloud and coverage over all of them. It looks
-30 days, 90 days or a year back, or under **Dates…** between two days picked in a
-calendar that starts at the satellite's launch. The catalogue gives at most 100
-passes, newest first, so a list it cut short offers **Older passes**, one more
-request for the ones before the oldest listed. At launch, each area independently resolves its latest usable pass
+a catalogue page against its quota, which is one for most windows. The picker
+shows coverage over all of them and the cloud of each pass's 110 km tile, so a
+small area can be clearer or cloudier than its row says. It looks 30 days, 90
+days or a year back, or under **Dates…** between two days picked in a calendar
+that starts at the satellite's launch. The catalogue answers newest first and a
+lookup reads up to five pages, so a list it still cut short offers **Older
+passes**, one more lookup for the ones before the oldest listed. At launch, each area independently resolves its latest usable pass
under the cloud ceiling. Different tracks can therefore use different days.
An unresolved area fails by name without stopping the rest. Opening Detect reads
local state only; pass lookups happen only on request or during an explicit run.
diff --git a/frontend/e2e/app.fixture.js b/frontend/e2e/app.fixture.js
index 2e7e8e2..3c19467 100644
--- a/frontend/e2e/app.fixture.js
+++ b/frontend/e2e/app.fixture.js
@@ -29,6 +29,52 @@ const CLEAR_TILE_PNG = Buffer.from(
'base64'
);
+/** Where the fixture's TileJSON says OpenFreeMap's tiles are, as the real one does. */
+const PLACE_TILES = 'https://tiles.openfreemap.org/planet/fixture-build/{z}/{x}/{y}.pbf';
+
+/**
+ * One vector tile holding one village, in OpenFreeMap's `place` layer: the
+ * least the Place names style writes a label from. Encoded here, by the Mapbox
+ * Vector Tile layout, so the fixture needs no encoder.
+ *
+ * The village stands at sixteen points of a grid rather than one. The map opens
+ * deeper than the tiles go, so one tile spans more than the map is wide, and a
+ * single point could fall outside the view.
+ */
+function placeTile(name) {
+ const varint = (n) => {
+ const out = [];
+ for (; n > 0x7f; n >>>= 7) out.push((n & 0x7f) | 0x80);
+ return [...out, n];
+ };
+ const key = (field, wire) => varint((field << 3) | wire);
+ const nested = (field, body) => [...key(field, 2), ...varint(body.length), ...body];
+ const text = (value) => [...Buffer.from(value, 'utf8')];
+ const zigzag = (n) => (n << 1) ^ (n >> 31);
+ // on a 4096 extent; each point is written as a step from the one before
+ const grid = [512, 1536, 2560, 3584].flatMap((y) => [512, 1536, 2560, 3584].map((x) => [x, y]));
+ const steps = grid.flatMap(([x, y], i) => {
+ const [px, py] = i ? grid[i - 1] : [0, 0];
+ return [...varint(zigzag(x - px)), ...varint(zigzag(y - py))];
+ });
+ const feature = [
+ ...nested(2, [0, 0, 1, 1]), // tags: class=village, name:latin=<name>
+ ...key(3, 0), 1, // points
+ ...nested(4, [...varint(1 | (grid.length << 3)), ...steps]), // one MoveTo, sixteen points
+ ];
+ const layer = [
+ ...key(15, 0), 2,
+ ...nested(1, text('place')),
+ ...nested(2, feature),
+ ...nested(3, text('class')),
+ ...nested(3, text('name:latin')),
+ ...nested(4, nested(1, text('village'))),
+ ...nested(4, nested(1, text(name))),
+ ...key(5, 0), ...varint(4096),
+ ];
+ return Buffer.from(nested(3, layer));
+}
+
const media = [{
path: PANEL_PATH,
filename: 'panel.svg',
@@ -696,6 +742,7 @@ export async function installAppFixture(page, options = {}) {
const unexpected = [];
const railTiles = [];
const referenceTiles = [];
+ const placeNameTiles = [];
const captures = [];
const placeWrites = [];
const proofSaves = [];
@@ -962,13 +1009,26 @@ export async function installAppFixture(page, options = {}) {
}
// Esri's reference layers are drawn straight from their host too, and
- // Borders is the one layer the map opens with — so every map spec asks for
- // these. Answered here, so no run touches the network to draw a border.
+ // Borders is on whenever a map opens — so every map spec asks for these.
+ // Answered here, so no run touches the network to draw a border.
if (url.hostname === 'services.arcgisonline.com') {
referenceTiles.push(request.url());
return route.fulfill({ contentType: 'image/png', body: CLEAR_TILE_PNG });
}
+ // The place names are OpenFreeMap's vector tiles, found through its TileJSON,
+ // and are on whenever a map opens, like Borders. A tile is empty unless the
+ // spec names a village (`placeNames`), so no label lands on what another
+ // spec is looking at; with one, every tile holds that village.
+ if (url.hostname === 'tiles.openfreemap.org') {
+ placeNameTiles.push(request.url());
+ if (path === '/planet') {
+ return json(route, { tilejson: '3.0.0', tiles: [PLACE_TILES], minzoom: 0, maxzoom: 14 });
+ }
+ const body = options.placeNames ? placeTile(options.placeNames) : Buffer.alloc(0);
+ return route.fulfill({ contentType: 'application/x-protobuf', body });
+ }
+
if (url.hostname !== '127.0.0.1') {
unexpected.push(`${request.method()} ${request.url()}`);
return route.abort('blockedbyclient');
@@ -1981,6 +2041,7 @@ export async function installAppFixture(page, options = {}) {
placeWrites,
railTiles,
referenceTiles,
+ placeNameTiles,
widgetLoads,
gridWrites,
skyQueries,
@@ -2091,3 +2152,36 @@ export async function openProofWithPanel(page) {
requestAnimationFrame(() => requestAnimationFrame(resolve));
}));
}
+
+/**
+ * Where a map is and how close, read as a user would: the point menu's DD row
+ * at the map's centre, then 200 px right of it. The first is the place, the gap
+ * between the two is the zoom. Read until two readings agree, so a glide or a
+ * zoom still easing in is not taken for where the map rests. Tab closes the
+ * menu, since Esc would also leave a fullscreen tool.
+ */
+export async function restingCamera(page, map) {
+ const read = async () => {
+ const box = await map.boundingBox();
+ const at = async (dx) => {
+ await page.mouse.click(box.x + box.width / 2 + dx, box.y + box.height / 2, { button: 'right' });
+ const menu = page.getByRole('menu', { name: 'This point' });
+ const text = await menu.locator('.item.copy')
+ .filter({ has: page.locator('.fmt', { hasText: /^DD$/ }) }).locator('.coords').textContent();
+ await page.keyboard.press('Tab');
+ await expect(menu).toBeHidden();
+ return text.split(',').map(Number);
+ };
+ const [lat, lon] = await at(0);
+ const [, east] = await at(200);
+ return { lat, lon, span: east - lon };
+ };
+ let last = null;
+ await expect.poll(async () => {
+ const now = await read();
+ const still = !!last && now.lat === last.lat && now.lon === last.lon && now.span === last.span;
+ last = now;
+ return still;
+ }).toBe(true);
+ return last;
+}
diff --git a/frontend/e2e/compare.spec.js b/frontend/e2e/compare.spec.js
index 5a40c20..433e8bc 100644
--- a/frontend/e2e/compare.spec.js
+++ b/frontend/e2e/compare.spec.js
@@ -1,5 +1,5 @@
import { test, expect } from '@playwright/test';
-import { awaitMapReady, installAppFixture } from './app.fixture.js';
+import { awaitMapReady, installAppFixture, restingCamera } from './app.fixture.js';
async function openCompare(page, providerB = 'Esri World Imagery') {
const fixture = await installAppFixture(page);
@@ -31,6 +31,8 @@ async function openCompare(page, providerB = 'Esri World Imagery') {
await page.locator('.provider-card').filter({ hasText: letter === 'A' ? 'Esri World Imagery' : providerB }).click();
}
await awaitMapReady(page, 2);
+ // the drawing rail starts folded, and these tests draw
+ await page.getByRole('button', { name: 'Show the annotation tools', exact: true }).click();
return { fixture, errors, saved };
}
@@ -81,7 +83,7 @@ test('linked maps keep annotations on the ground through pan, modes and save', a
await expect(page.getByRole('slider', { name: 'B opacity' })).toBeVisible();
await page.getByRole('button', { name: 'Blink', exact: true }).click();
await page.getByRole('button', { name: 'Slow', exact: true }).click();
- await page.getByRole('button', { name: 'Save comparison', exact: true }).click();
+ await page.getByRole('button', { name: 'Save', exact: true }).click();
await page.getByRole('dialog').getByRole('button', { name: 'Save comparison', exact: true }).click();
await expect.poll(() => saved.length).toBe(1);
expect(saved[0].spec.version).toBe(2);
@@ -130,7 +132,7 @@ test('stamps a numbered marker and a symbol on the ground, and saves both', asyn
await page.getByTitle('Numbered marker (N)', { exact: true }).click();
await expect(page.getByTitle('Select and move (V)', { exact: true })).toHaveAttribute('aria-pressed', 'true');
- await page.getByRole('button', { name: 'Save comparison', exact: true }).click();
+ await page.getByRole('button', { name: 'Save', exact: true }).click();
await page.getByRole('dialog').getByRole('button', { name: 'Save comparison', exact: true }).click();
await expect.poll(() => saved.length).toBe(1);
const marks = saved[0].spec.annotations;
@@ -169,7 +171,7 @@ test('an export frame can be drawn across every overlaid reading mode', async ({
await dialog.getByRole('button', { name: 'Close', exact: true }).click();
}
- await page.getByRole('button', { name: 'Save comparison', exact: true }).click();
+ await page.getByRole('button', { name: 'Save', exact: true }).click();
await page.getByRole('dialog', { name: 'Save comparison' })
.getByRole('button', { name: 'Save comparison', exact: true }).click();
await expect.poll(() => saved.length).toBe(1);
@@ -219,8 +221,13 @@ test('spectral frames are requested only by Run, including after reopening and m
await page.getByRole('button', { name: 'Difference settings', exact: true }).click();
await expect(page.getByLabel('Method', { exact: true })).toHaveValue('index');
expect(requests).toHaveLength(0);
+ // Nothing held covers this view, so Read is lit and the legend asks for it.
+ const read = page.locator('.difference-bar button.read');
+ await expect(read).toHaveText('Read');
+ await expect(read).toHaveClass(/\bdue\b/);
+ await expect(page.locator('.change-legend')).toContainText('Not read yet, press Read');
// Read sits on the strip, so pressing it leaves the settings open.
- await page.getByRole('button', { name: 'Read', exact: true }).click();
+ await read.click();
await expect(page.locator('.secondary .change-map')).toBeVisible({ timeout: 20000 });
await expect(page.locator('aside.settings')).toBeVisible();
expect(requests.map((request) => request.day)).toEqual(['2026-08-01', '2026-09-01']);
@@ -232,16 +239,115 @@ test('spectral frames are requested only by Run, including after reopening and m
// The press on the map put the settings away, and the pan spent nothing.
await expect(page.locator('aside.settings')).toBeHidden();
await expect(page.locator('.secondary .change-map')).not.toHaveCSS('transform', 'none');
- await expect(page.getByRole('button', { name: 'Read', exact: true })).toBeEnabled();
+ // The reading followed on the frames it holds, and Read says there is nothing to do.
+ await expect(read).toHaveText('Up to date');
+ await expect(read).toBeDisabled();
expect(requests).toHaveLength(2);
+ // Choosing another index is asking for it: its bands come without a second
+ // press, and the follow-up the choice schedules does not throw them away.
+ await page.getByRole('button', { name: 'Difference settings', exact: true }).click();
+ await page.locator('aside.settings select').nth(1).selectOption('nbr');
+ await expect.poll(() => requests.length).toBe(4);
+ expect(requests.slice(2).map((request) => request.product)).toEqual(['nbr', 'nbr']);
+ await expect(read).toHaveText('Up to date', { timeout: 20000 });
// The cloud filter reads Sentinel-2's own classification, so switching it on
// over a picture method asks for the sky then and there, rather than leaving
// an unfiltered reading up behind an "on" switch.
- await page.getByRole('button', { name: 'Difference settings', exact: true }).click();
await page.getByLabel('Method', { exact: true }).selectOption('colour');
await page.getByRole('button', { name: /Clouds & shadows/ }).click();
- await expect.poll(() => requests.length).toBe(4);
- expect(requests.slice(2).map((request) => request.product)).toEqual(['sky', 'sky']);
+ await expect.poll(() => requests.length).toBe(6);
+ expect(requests.slice(4).map((request) => request.product)).toEqual(['sky', 'sky']);
+ expect(errors).toEqual([]);
+});
+
+test('the cloud filter reads the sky at 20 m, keeps a Read the map moved under, and follows the map once it rests', async ({ page }) => {
+ await installAppFixture(page);
+ const errors = [];
+ const requests = [];
+ let slow = 0;
+ page.on('pageerror', (error) => errors.push(error.message));
+ await page.setViewportSize({ width: 1600, height: 900 });
+ await page.route('**/api/satellite/providers', (route) => route.fulfill({ json: [
+ { id: 'sentinel2', label: 'Sentinel-2', url: 'https://tiles.invalid/{z}/{x}/{y}.png',
+ imagery: true, max_zoom: 19, tile_size: 256, oversample: 1, attribution: 'Browser fixture' },
+ ] }));
+ await page.route('**/api/satellite/sentinel/**', (route) => route.fulfill({ json:
+ route.request().url().includes('/layers') ? { layers: [{ id: 'TRUE_COLOR', title: 'True colour' }] } : { days: [] },
+ }));
+ const side = (day) => ({ present: true, provider: 'sentinel2', overlays: [],
+ sentinel: { layer: 'TRUE_COLOR', date: day, maxcc: 100 } });
+ await page.route('**/api/cases/*/compare/sessions', (route) => route.fulfill({ json: [{ name: 'Clouds', title: 'Clouds', mode: 'change' }] }));
+ await page.route('**/api/cases/*/compare/sessions/Clouds', (route) => route.fulfill({ json: {
+ title: 'Clouds', spec: { version: 2, camera: { lat: 48.8584, lon: 2.2945, zoom: 14, bearing: 0 }, mode: 'change',
+ change_assist: { method: 'colour', ignore_clouds: true, ignore_shadows: true },
+ a: side('2026-08-01'), b: side('2026-09-01') },
+ } }));
+ await page.route('**/api/compare/sentinel-frame', async (route) => {
+ const body = route.request().postDataJSON();
+ requests.push(body);
+ const png = await page.evaluate(({ width, height }) => {
+ const canvas = document.createElement('canvas');
+ canvas.width = width; canvas.height = height;
+ const ctx = canvas.getContext('2d');
+ ctx.fillStyle = 'rgb(128,4,0)';
+ ctx.fillRect(0, 0, width, height);
+ return canvas.toDataURL().split(',')[1];
+ }, body);
+ if (slow) await new Promise((resolve) => setTimeout(resolve, slow));
+ await route.fulfill({ contentType: 'image/png', body: Buffer.from(png, 'base64') });
+ });
+ await page.goto('/#compare');
+ await page.getByRole('button', { name: 'Open', exact: true }).click();
+ await page.locator('.session-open').click();
+ await awaitMapReady(page, 2);
+ const read = page.locator('.difference-bar button.read');
+ const map = await page.locator('.compare-stage .surface-shell').first().boundingBox();
+ const pan = async (dx) => {
+ const x = map.x + map.width / 2;
+ const y = map.y + map.height / 2;
+ await page.mouse.move(x, y);
+ await page.mouse.down();
+ await page.mouse.move(x + dx, y, { steps: 10 });
+ await page.mouse.up();
+ };
+ await expect(read).toHaveText('Read');
+
+ // Bands slow to come, and the map nudged while they do: the read still lands.
+ slow = 2500;
+ await read.click();
+ await page.waitForTimeout(400);
+ await pan(30);
+ await expect(read).toHaveText('Up to date', { timeout: 15000 });
+ expect(requests).toHaveLength(2);
+ slow = 0;
+
+ // The sky is asked for at the classification's own 20 m, not the screen's.
+ // a Mercator metre is 1/cos(latitude) of a ground one, and cos(latitude) = 1/cosh(y/R)
+ const ground = (asked) => (asked.east - asked.west) / asked.width / Math.cosh((asked.north + asked.south) / 2 / 6378137);
+ expect(requests.map((asked) => asked.product)).toEqual(['sky', 'sky']);
+ for (const asked of requests) expect(ground(asked)).toBeGreaterThan(19);
+
+ // So its margin reaches a whole view: a third of the map away is still free.
+ await pan(Math.round(map.width / 3));
+ await page.waitForTimeout(300);
+ await expect(read).toHaveText('Up to date', { timeout: 15000 });
+ expect(requests).toHaveLength(2);
+
+ // Far past it, the pair already read follows: its sky comes once the map
+ // rests, and only then, however many drags it took to get there.
+ const sweep = async () => {
+ const y = map.y + map.height / 2;
+ await page.mouse.move(map.x + 20, y);
+ await page.mouse.down();
+ await page.mouse.move(map.x + map.width - 20, y, { steps: 10 });
+ await page.mouse.up();
+ };
+ for (let drag = 0; drag < 3; drag += 1) await sweep();
+ await expect.poll(() => requests.length, { timeout: 15000 }).toBe(4);
+ await page.waitForTimeout(1500);
+ expect(requests).toHaveLength(4);
+ await expect(read).toHaveText('Up to date', { timeout: 15000 });
+ expect(requests.slice(2).map((asked) => asked.product)).toEqual(['sky', 'sky']);
expect(errors).toEqual([]);
});
@@ -320,7 +426,7 @@ test('on a turned map a box runs along the screen, and turns from its grip', asy
expect(Math.max(...xs) - Math.min(...xs)).toBeCloseTo(80, -1);
expect(Math.max(...ys) - Math.min(...ys)).toBeCloseTo(160, -1);
- await page.getByRole('button', { name: 'Save comparison', exact: true }).click();
+ await page.getByRole('button', { name: 'Save', exact: true }).click();
await page.getByRole('dialog').getByRole('button', { name: 'Save comparison', exact: true }).click();
await expect.poll(() => saved.length).toBe(1);
// Drawn with the map turned 30° clockwise (compass 330° up), then a quarter turn.
@@ -440,3 +546,53 @@ test("Difference's settings stay put through a read, lie over the highlights, an
await expect(panel).toBeHidden();
expect(errors).toEqual([]);
});
+
+test('takes the whole screen with both maps, and gives it up to the tab it hands over to', async ({ page }) => {
+ const { errors } = await openCompare(page);
+ const held = () => page.evaluate(() => document.fullscreenElement?.classList.contains('compare-tool') ?? false);
+ const stage = page.locator('.compare-stage');
+ const before = await stage.boundingBox();
+ await page.getByRole('button', { name: 'Full screen', exact: true }).click();
+ await expect.poll(held).toBe(true);
+ await expect.poll(async () => (await stage.boundingBox()).height).toBeGreaterThan(before.height);
+ // both maps were told: each draws across the whole of its new box
+ await expect.poll(() => page.locator('.compare-stage .map').evaluateAll((maps) => maps.map((map) =>
+ Math.abs(map.querySelector('canvas').getBoundingClientRect().width - map.getBoundingClientRect().width) < 2)))
+ .toEqual([true, true]);
+
+ // the header came along, and a dialog opened from it is painted over the screen
+ await page.getByRole('button', { name: 'Open', exact: true }).click();
+ await expect(page.getByRole('dialog', { name: 'Open comparison' })).toBeVisible();
+ await page.getByRole('dialog', { name: 'Open comparison' }).getByRole('button', { name: 'Close' }).click();
+ expect(await held()).toBe(true);
+
+ // the ground and the zoom reached in full screen are the ones the window gets back
+ const map = page.locator('.surface-shell.primary .map');
+ const box = await map.boundingBox();
+ await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2);
+ await page.mouse.wheel(0, -120);
+ await expect(page.locator('.camera-readout')).toHaveText('z17.0');
+ await page.mouse.down();
+ await page.mouse.move(box.x + box.width / 2 - 150, box.y + box.height / 2 - 60, { steps: 8 });
+ await page.mouse.up();
+ const there = await restingCamera(page, map);
+ await page.getByRole('button', { name: 'Exit full screen', exact: true }).click();
+ await expect.poll(held).toBe(false);
+ const back = await restingCamera(page, map);
+ expect(back.lat).toBeCloseTo(there.lat, 4);
+ expect(back.lon).toBeCloseTo(there.lon, 4);
+ expect(back.span / there.span).toBeCloseTo(1, 1);
+ await expect(page.locator('.camera-readout')).toHaveText('z17.0');
+
+ // Open in… another tab leaves the screen on the way, and that tab opens at this zoom
+ await page.getByRole('button', { name: 'Full screen', exact: true }).click();
+ await expect.poll(held).toBe(true);
+ const full = await map.boundingBox();
+ await page.mouse.click(full.x + full.width / 2, full.y + full.height / 2, { button: 'right' });
+ await page.getByRole('menu', { name: 'This point' }).getByRole('menuitem', { name: /^Open in/ }).click();
+ await page.getByRole('menu', { name: 'Open this point in' }).getByRole('menuitem', { name: 'Satellite', exact: true }).click();
+ await expect.poll(() => page.evaluate(() => Boolean(document.fullscreenElement))).toBe(false);
+ await expect(page.locator('.tabstrip .tab-btn.active')).toHaveText('Satellite');
+ await expect(page.locator('.tool-host:not(.hidden) .hud-coords')).toContainText('z17');
+ expect(errors).toEqual([]);
+});
diff --git a/frontend/e2e/detect.spec.js b/frontend/e2e/detect.spec.js
index 2a13784..f2803d7 100644
--- a/frontend/e2e/detect.spec.js
+++ b/frontend/e2e/detect.spec.js
@@ -1,5 +1,5 @@
import { test, expect } from '@playwright/test';
-import { awaitMapReady, installAppFixture } from './app.fixture.js';
+import { awaitMapReady, installAppFixture, restingCamera } from './app.fixture.js';
const recipe = { id: 'change', name: 'Surface change', method: 'surface', phenomenon: 'Surface change',
colour: '#f6a81a', style: 'both', parameters: { sensitivity: 60, min_area: 0, max_area: 0,
@@ -77,6 +77,17 @@ test('landing, dock rail and the When step fit the existing map workspace', asyn
const { errors, calls, prefs } = await openDetect(page);
await expect(page.getByRole('button', { name: 'Imagery provider', exact: true })).toContainText('Esri World Imagery');
await expect(page.locator('.detect-tool > header')).toHaveCount(0);
+ // The ruler is stacked on the left between the search and the zoom buttons.
+ const [search, ruler, zoom] = await Promise.all([page.locator('.detect-tool .search'),
+ page.getByRole('button', { name: 'Measure', exact: true }), page.getByRole('button', { name: 'Zoom in' })]
+ .map((element) => element.boundingBox()));
+ expect(search.y + search.height).toBeLessThan(ruler.y);
+ expect(ruler.y + ruler.height).toBeLessThan(zoom.y);
+ expect(Math.abs(ruler.x - zoom.x)).toBeLessThan(8);
+ // The closed Layers chip is as tall as the imagery chip over it.
+ const [chip, picker] = await Promise.all(['.detect-tool .map-choices > :first-child', '.detect-tool .layer-picker']
+ .map((selector) => page.locator(selector).boundingBox()));
+ expect(Math.abs(picker.height - chip.height)).toBeLessThanOrEqual(1);
const map = page.locator('.detect-tool .map');
const before = await map.boundingBox();
await page.getByRole('button', { name: 'Collapse Detect panel', exact: true }).click();
@@ -319,3 +330,47 @@ test('an analyzer of your own is built over the map: its rules painted, a point
expect(previews.every((entry) => entry.recipe.method === 'rules')).toBe(true);
expect(errors).toEqual([]);
});
+
+test('takes the whole screen with its panel, folds it there, and gives it up to Compare', async ({ page }) => {
+ const { errors } = await openDetect(page);
+ const held = () => page.evaluate(() => document.fullscreenElement?.classList.contains('detect-tool') ?? false);
+ const map = page.locator('.detect-tool .map');
+ const before = await map.boundingBox();
+ await page.getByRole('button', { name: 'Full screen', exact: true }).click();
+ await expect.poll(held).toBe(true);
+ await expect.poll(async () => (await map.boundingBox()).height).toBeGreaterThan(before.height);
+ await expect(page.getByRole('button', { name: 'New detection', exact: true })).toBeVisible();
+ // the panel still folds away, leaving the map the whole width
+ const panelled = await map.boundingBox();
+ await page.keyboard.press(']');
+ await expect(page.locator('.dock-tabs.rail')).toBeVisible();
+ await expect.poll(async () => (await map.boundingBox()).width).toBeGreaterThan(panelled.width + 200);
+ await expect(page.getByRole('button', { name: 'Exit full screen', exact: true })).toBeVisible();
+ await page.keyboard.press(']');
+
+ // the ground and the zoom reached in full screen are the ones the window gets back
+ const middle = await map.boundingBox();
+ await page.mouse.move(middle.x + middle.width / 2, middle.y + middle.height / 2);
+ await page.mouse.wheel(0, -120);
+ await page.mouse.down();
+ await page.mouse.move(middle.x + middle.width / 2 - 150, middle.y + middle.height / 2 - 60, { steps: 8 });
+ await page.mouse.up();
+ const there = await restingCamera(page, map);
+ await page.getByRole('button', { name: 'Exit full screen', exact: true }).click();
+ await expect.poll(held).toBe(false);
+ const back = await restingCamera(page, map);
+ expect(back.lat).toBeCloseTo(there.lat, 4);
+ expect(back.lon).toBeCloseTo(there.lon, 4);
+ expect(back.span / there.span).toBeCloseTo(1, 1);
+
+ // Open in… Compare leaves the screen on the way
+ await page.getByRole('button', { name: 'Full screen', exact: true }).click();
+ await expect.poll(held).toBe(true);
+ const box = await map.boundingBox();
+ await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2, { button: 'right' });
+ await page.getByRole('menu', { name: 'This point' }).getByRole('menuitem', { name: /^Open in/ }).click();
+ await page.getByRole('menu', { name: 'Open this point in' }).getByRole('menuitem', { name: 'Compare', exact: true }).click();
+ await expect.poll(() => page.evaluate(() => Boolean(document.fullscreenElement))).toBe(false);
+ await expect(page.locator('.tool-host:not(.hidden) h2')).toHaveText('Compare');
+ expect(errors).toEqual([]);
+});
diff --git a/frontend/e2e/satellite-corner.spec.js b/frontend/e2e/satellite-corner.spec.js
new file mode 100644
index 0000000..73a64b1
--- /dev/null
+++ b/frontend/e2e/satellite-corner.spec.js
@@ -0,0 +1,47 @@
+import { test, expect } from '@playwright/test';
+import { awaitMapReady, installAppFixture } from './app.fixture.js';
+
+/**
+ * The imagery card in the map's top-right corner: provider, date and the window
+ * buttons in one frame, with the date pill and the compass under it. Its blur
+ * makes a stacking context, so what opens from it is only on top if the card
+ * itself is, and that is a question only a browser answers.
+ */
+
+const SENTINEL = [
+ { id: 'esri-world-imagery', label: 'Esri World Imagery', url: 'https://tiles.invalid/{z}/{x}/{y}.png',
+ imagery: true, max_zoom: 19, tile_size: 256, attribution: 'Browser fixture' },
+ { id: 'sentinel2', label: 'Sentinel-2 (Copernicus)', url: 'https://tiles.invalid/{z}/{x}/{y}.png',
+ meter: 'sentinelhub', imagery: true, max_zoom: 19, tile_size: 256, attribution: 'Copernicus Sentinel data' },
+];
+
+/** Whether `top` is what the eye sees at a point it shares with `under`. */
+async function paintedOver(page, top, under) {
+ const a = await top.boundingBox();
+ const b = await under.boundingBox();
+ const x = Math.max(a.x, b.x) + 4;
+ const y = Math.max(a.y, b.y) + 4;
+ expect(x).toBeLessThan(Math.min(a.x + a.width, b.x + b.width));
+ expect(y).toBeLessThan(Math.min(a.y + a.height, b.y + b.height));
+ const handle = await top.elementHandle();
+ return page.evaluate(([el, px, py]) => el.contains(document.elementFromPoint(px, py)), [handle, x, y]);
+}
+
+test('opens the provider list over the date pill under the card', async ({ page }) => {
+ await installAppFixture(page);
+ await page.route('**/api/satellite/providers', (route) => route.fulfill({ json: SENTINEL }));
+ await page.route('**/api/satellite/sentinel/**', (route) => route.fulfill({ json: { dates: [] } }));
+ await page.goto('/#satellite');
+ await awaitMapReady(page);
+
+ const chip = page.getByRole('button', { name: 'Imagery provider' });
+ await chip.click();
+ await page.getByRole('option', { name: 'Sentinel-2 (Copernicus)' }).click();
+ const pill = page.locator('.surface-ctl .date-pill');
+ await expect(pill).toBeVisible();
+
+ await chip.click();
+ const list = page.getByRole('listbox', { name: 'Imagery provider' });
+ await expect(list).toBeVisible();
+ expect(await paintedOver(page, list, pill)).toBe(true);
+});
diff --git a/frontend/e2e/satellite-fires.spec.js b/frontend/e2e/satellite-fires.spec.js
new file mode 100644
index 0000000..8629f5b
--- /dev/null
+++ b/frontend/e2e/satellite-fires.spec.js
@@ -0,0 +1,128 @@
+import { test, expect } from '@playwright/test';
+import { awaitMapReady, installAppFixture, mapPicture } from './app.fixture.js';
+
+/**
+ * Active fires in a real browser.
+ *
+ * The map draws every detection itself, from vector tiles, at every zoom: a
+ * square keeps its size through a zoom and stays where it is while the next
+ * level loads, where FIRMS's pictures swelled with their pixels. Whether a
+ * tinted square paints at all depends on the engine reading the distance field
+ * it was given, and whether the marks are kept while a level loads is the
+ * engine's overzooming, so both are proved here rather than in a unit test
+ * that stubs the engine out.
+ */
+
+const hud = (page) => page.locator('.hud-coords').first();
+/** FIRMS's picture of a patch with nothing burning. */
+const CLEAR_PNG = Buffer.from(
+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGNgYGBgAAAABQABpfZFQAAAAABJRU5ErkJggg==',
+ 'base64'
+);
+
+/** A protobuf varint, and a length-delimited field around some bytes. */
+function varint(value) {
+ const out = [];
+ let rest = value;
+ while (rest > 127) {
+ out.push((rest & 0x7f) | 0x80);
+ rest = Math.floor(rest / 128);
+ }
+ out.push(rest);
+ return out;
+}
+const field = (number, bytes) => [...varint((number << 3) | 2), ...varint(bytes.length), ...bytes];
+const text = (value) => [...Buffer.from(value)];
+const zigzag = (n) => (n << 1) ^ (n >> 31);
+
+/** A vector tile of recent 375 m marks at these tile coordinates, laid out as
+ * `engine/mvt.py` writes them: one MultiPoint in a layer named `marks`. */
+function marksTile(points) {
+ const geometry = [(points.length << 3) | 1];
+ let x = 0;
+ let y = 0;
+ for (const [px, py] of points) {
+ geometry.push(zigzag(px - x), zigzag(py - y));
+ [x, y] = [px, py];
+ }
+ const feature = [...field(2, [0, 0, 1, 1]), ...varint(3 << 3), 1, ...field(4, geometry.flatMap(varint))];
+ const uint = (value) => field(4, [...varint(5 << 3), ...varint(value)]);
+ const layer = [
+ ...varint(15 << 3), 2, ...field(1, text('marks')), ...field(2, feature),
+ ...field(3, text('recent')), ...field(3, text('side')), ...uint(1), ...uint(375),
+ ...varint(5 << 3), ...varint(4096),
+ ];
+ return Buffer.from(field(3, layer));
+}
+
+/** FIRMS behind the fixture: a key that works, marks in every tile. */
+async function withFires(page) {
+ const asked = { points: [], pictures: [] };
+ await page.route('**/api/firms/sensors', (route) => route.fulfill({ json: {
+ keyed: true, state: 'ready', paused: null,
+ sensors: [{ id: 'viirs', label: 'VIIRS (S-NPP, NOAA-20, NOAA-21)' }],
+ windows: ['24h', '48h', '72h', '7d'], max_zoom: 13, max_range_days: 31,
+ } }));
+ const tile = marksTile([[2048, 2048], [1024, 1024], [3072, 3072], [1024, 3072]]);
+ await page.route('**/api/firms/points/**', (route) => {
+ asked.points.push(Number(new URL(route.request().url()).pathname.split('/').at(-3)));
+ return route.fulfill({ contentType: 'application/vnd.mapbox-vector-tile', body: tile });
+ });
+ await page.route('**/api/firms/tiles/**', (route) => {
+ asked.pictures.push(Number(new URL(route.request().url()).pathname.split('/').at(-3)));
+ return route.fulfill({ contentType: 'image/png', body: CLEAR_PNG });
+ });
+ return asked;
+}
+
+/** How many pixels of the map are FIRMS's recent red. */
+async function redPixels(page) {
+ const picture = await mapPicture(page);
+ return page.evaluate(async (bytes) => {
+ const image = await createImageBitmap(new Blob([new Uint8Array(bytes)], { type: 'image/png' }));
+ const canvas = new OffscreenCanvas(image.width, image.height);
+ const context = canvas.getContext('2d');
+ context.drawImage(image, 0, 0);
+ const { data } = context.getImageData(0, 0, image.width, image.height);
+ let red = 0;
+ for (let i = 0; i < data.length; i += 4) if (data[i] > 225 && data[i + 1] < 90 && data[i + 2] < 50) red += 1;
+ return red;
+ }, [...picture]);
+}
+
+async function wheelTo(page, level) {
+ const box = await page.locator('.map').boundingBox();
+ await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2);
+ for (let guard = 0; guard < 20; guard += 1) {
+ const now = Number(/z(\d+)/.exec(await hud(page).innerText())[1]);
+ if (now === level) return;
+ await page.mouse.wheel(0, now > level ? 120 : -120);
+ await expect(hud(page)).toContainText(`z${now > level ? now - 1 : now + 1}`);
+ }
+}
+
+test('the map draws the fires itself, close in and far out, and lays no picture of them', async ({ page }) => {
+ const errors = [];
+ page.on('console', (message) => { if (message.type() === 'error') errors.push(message.text()); });
+ await installAppFixture(page);
+ const asked = await withFires(page);
+ await page.goto('/#satellite');
+ await awaitMapReady(page);
+ const fires = page.getByRole('button', { name: 'Active fires', exact: true });
+ if (!(await fires.isVisible())) await page.getByRole('button', { name: /Layers/ }).first().click();
+ const before = await redPixels(page);
+ await fires.click();
+
+ // z10 on the readout is engine zoom 9, where the tiles carry the detections
+ await wheelTo(page, 10);
+ await expect.poll(() => asked.points.includes(9)).toBe(true);
+ await expect.poll(() => redPixels(page)).toBeGreaterThan(before + 40);
+
+ // z7 is engine zoom 6, where they are read off FIRMS's picture: marks all the same
+ await wheelTo(page, 7);
+ await expect.poll(() => asked.points.includes(6)).toBe(true);
+ await expect.poll(() => redPixels(page)).toBeGreaterThan(before + 40);
+ // the map never lays a picture of the fires of its own
+ expect(asked.pictures).toEqual([]);
+ expect(errors).toEqual([]);
+});
diff --git a/frontend/e2e/satellite-overlays.spec.js b/frontend/e2e/satellite-overlays.spec.js
index 3ff2b56..acbb905 100644
--- a/frontend/e2e/satellite-overlays.spec.js
+++ b/frontend/e2e/satellite-overlays.spec.js
@@ -246,7 +246,7 @@ test('lays the railways over the imagery, and lifts them off again', async ({ pa
await page.goto('/#satellite');
await awaitMapReady(page);
// the railways are a layer, listed with the others in the panel on the right
- const rails = page.getByLabel('OSM railways');
+ const rails = page.getByLabel('Railways', { exact: true });
expect(fixture.railTiles).toEqual([]);
await rails.click();
@@ -266,6 +266,50 @@ test('lays the railways over the imagery, and lifts them off again', async ({ pa
expect(fixture.railTiles.length).toBe(laid);
});
+/**
+ * The map's picture without its bottom edge, where the credit line sits. A
+ * layer switched on adds its credit there, which changes the picture whether
+ * or not the layer drew anything.
+ */
+async function groundPicture(page) {
+ await expect(page.locator('.map[data-map-ready="true"]')).toBeVisible();
+ const box = await page.locator('.map').boundingBox();
+ return page.screenshot({ clip: { ...box, height: box.height - 60 } });
+}
+
+/** The ground once it has stopped changing: every tile in, every fade done. */
+async function settledGround(page) {
+ let last = await groundPicture(page);
+ await expect.poll(async () => {
+ const next = await groundPicture(page);
+ const still = next.equals(last);
+ last = next;
+ return still;
+ }).toBe(true);
+ return last;
+}
+
+test('opens with the village names written over the imagery, and lifts them at the switch', async ({ page }) => {
+ const fixture = await installAppFixture(page, { placeNames: 'Qushayhi' });
+ await page.goto('/#satellite');
+ await awaitMapReady(page);
+ // on from the start, like Borders: the tiles are found through the TileJSON,
+ // which names the current build
+ await expect.poll(() => fixture.placeNameTiles.some((url) => url.endsWith('.pbf'))).toBe(true);
+ expect(fixture.placeNameTiles[0]).toBe('https://tiles.openfreemap.org/planet');
+ await expect(page.getByText(/OpenFreeMap © OpenMapTiles/)).toBeVisible();
+
+ const names = page.getByLabel('Place names', { exact: true });
+ await names.click();
+ const bare = await settledGround(page);
+
+ // back on, the names are written again, and off, the ground is as it was
+ await names.click();
+ await expect.poll(async () => repainted(bare, await groundPicture(page))).toBe(true);
+ await names.click();
+ await expect.poll(async () => repainted(bare, await groundPicture(page))).toBe(false);
+});
+
test('measures a path clicked on the map, and clears it', async ({ page }) => {
await installAppFixture(page);
await page.goto('/#satellite');
diff --git a/frontend/e2e/satellite-search.spec.js b/frontend/e2e/satellite-search.spec.js
index c5e5229..ec77cce 100644
--- a/frontend/e2e/satellite-search.spec.js
+++ b/frontend/e2e/satellite-search.spec.js
@@ -120,6 +120,25 @@ test('closes on Escape and on a press elsewhere', async ({ page }) => {
await bar(page).click();
await expect(page.locator('#sat-suggestions')).toBeVisible();
- await page.getByRole('heading', { name: 'Satellite' }).click();
+ await page.locator('.tabstrip').getByRole('button', { name: 'Satellite', exact: true }).click();
await expect(page.locator('#sat-suggestions')).toHaveCount(0);
});
+
+test('drops its suggestions over the tool rail, not behind it', async ({ page }) => {
+ await installAppFixture(page);
+ await page.goto('/#satellite');
+ await awaitMapReady(page);
+
+ await bar(page).fill('kr');
+ const list = page.locator('#sat-suggestions');
+ await expect(list).toBeVisible();
+ const rail = await page.locator('.map-tools').boundingBox();
+ const drop = await list.boundingBox();
+ // a point both cover: whatever answers there is what the eye sees
+ const x = Math.max(rail.x, drop.x) + 4;
+ const y = Math.max(rail.y, drop.y) + 4;
+ expect(x).toBeLessThan(Math.min(rail.x + rail.width, drop.x + drop.width));
+ expect(y).toBeLessThan(Math.min(rail.y + rail.height, drop.y + drop.height));
+ const onTop = await page.evaluate(([px, py]) => !!document.elementFromPoint(px, py)?.closest('#sat-suggestions'), [x, y]);
+ expect(onTop).toBe(true);
+});
diff --git a/frontend/e2e/satellite-windows.spec.js b/frontend/e2e/satellite-windows.spec.js
index a33796d..87b063a 100644
--- a/frontend/e2e/satellite-windows.spec.js
+++ b/frontend/e2e/satellite-windows.spec.js
@@ -71,9 +71,9 @@ test('hands a second window the view the first one is showing', async ({ page, c
// same ground…
await expect(second.locator('.hud-coords')).toContainText('50.450');
// …and it says which window it is, since two of them look identical
- await expect(second.getByRole('heading', { name: 'Satellite · 2' })).toBeVisible();
+ await expect(second.locator('.map-bar .window-no')).toHaveText('Map 2');
// the first one stays unnumbered and keeps its own view
- await expect(page.getByRole('heading', { name: 'Satellite', exact: true })).toBeVisible();
+ await expect(page.locator('.map-bar .window-no')).toHaveCount(0);
// two windows, two cameras: moving one leaves the other alone
const box = await second.locator('.map').boundingBox();
diff --git a/frontend/src/App.svelte b/frontend/src/App.svelte
index a226c86..22fe15b 100644
--- a/frontend/src/App.svelte
+++ b/frontend/src/App.svelte
@@ -25,6 +25,7 @@
import { readSolo, splitHash } from './lib/hash.js';
import { guideFor } from './lib/guide.js';
import { openGuide } from './lib/navigate.js';
+ import { leaveFullscreen } from './lib/fullscreen.js';
import { createToolLoader } from './lib/toolLoader.js';
import { loadEntityTypes } from './lib/entityTypes.svelte.js';
import Icon from './components/Icon.svelte';
@@ -142,6 +143,14 @@
}
previousTool = nextTool;
});
+ // A tool that holds the screen is left with it. Its host is hidden as soon as
+ // another tool is picked, and a hidden fullscreen element blacks the screen
+ // out with the new tool behind it. Every way across lands here: a toast's
+ // action, Open in…, a candidate sent to Compare.
+ $effect(() => {
+ uiState.tool;
+ leaveFullscreen();
+ });
function openWorkspace(ws) {
uiState.tool = lastTool[ws.id] ?? ws.tools[0];
}
diff --git a/frontend/src/lib/extensionMapEngine.test.js b/frontend/src/lib/extensionMapEngine.test.js
index 957f3ba..04c7646 100644
--- a/frontend/src/lib/extensionMapEngine.test.js
+++ b/frontend/src/lib/extensionMapEngine.test.js
@@ -1167,7 +1167,7 @@ describe('the fire layer in the panel', () => {
const keyed = {
'/api/ingest/firms/sensors': {
keyed: true,
- sensors: [{ id: 'viirs', label: 'VIIRS (S-NPP + NOAA-20)' }],
+ sensors: [{ id: 'viirs', label: 'VIIRS (S-NPP, NOAA-20, NOAA-21)' }],
},
};
@@ -1252,7 +1252,7 @@ describe('the fire layer in the panel', () => {
answers: {
'/api/ingest/firms/sensors': {
keyed: true,
- sensors: [{ id: 'viirs', label: 'VIIRS (S-NPP + NOAA-20)' }],
+ sensors: [{ id: 'viirs', label: 'VIIRS (S-NPP, NOAA-20, NOAA-21)' }],
},
},
});
@@ -1286,7 +1286,7 @@ describe('the fire layer in the panel', () => {
answers: {
'/api/ingest/firms/sensors': {
keyed: true,
- sensors: [{ id: 'viirs', label: 'VIIRS (S-NPP + NOAA-20)' }],
+ sensors: [{ id: 'viirs', label: 'VIIRS (S-NPP, NOAA-20, NOAA-21)' }],
},
},
});
diff --git a/frontend/src/lib/extensionMapTools.test.js b/frontend/src/lib/extensionMapTools.test.js
index cf96084..0324863 100644
--- a/frontend/src/lib/extensionMapTools.test.js
+++ b/frontend/src/lib/extensionMapTools.test.js
@@ -926,7 +926,7 @@ describe('the reference windows', () => {
describe('the fire layer, on both sides of the boundary', () => {
const SENSORS = [
- { id: 'viirs', label: 'VIIRS (S-NPP + NOAA-20)' },
+ { id: 'viirs', label: 'VIIRS (S-NPP, NOAA-20, NOAA-21)' },
{ id: 'modis', label: 'MODIS (Terra + Aqua)' },
];
@@ -1010,9 +1010,11 @@ describe('the fire layer, on both sides of the boundary', () => {
// the app caps the tile source rather than refusing to draw: past this it
// keeps showing that level, scaled. The panel holds its one picture the
// same way, and neither asks again.
+ // The same ground detail, counted two ways: the app's source tiles are
+ // 512 px, and a host map counts its zoom in 256 px tiles, one level deeper.
const basemap = readFileSync(join(here, './map/basemap.js'), 'utf8');
- const firms = /id: 'firms',[\s\S]*?maxZoom: (\d+)/.exec(basemap);
- expect(ext.FIRE_MAX_ZOOM).toBe(Number(firms[1]));
+ const firms = /id: 'firms',[\s\S]*?tileSize: (\d+),[\s\S]*?maxZoom: (\d+)/.exec(basemap);
+ expect(ext.FIRE_MAX_ZOOM).toBe(Number(firms[2]) + Math.log2(Number(firms[1]) / 256));
});
it('offers no seat at all until a key is behind it', () => {
diff --git a/frontend/src/lib/fullscreen.fixture.js b/frontend/src/lib/fullscreen.fixture.js
new file mode 100644
index 0000000..4c36c4a
--- /dev/null
+++ b/frontend/src/lib/fullscreen.fixture.js
@@ -0,0 +1,30 @@
+// A screen for happy-dom, which has no Fullscreen API: an element asks for it,
+// the document says who holds it, and `fullscreenchange` fires as a browser's
+// would. `leave()` is Esc, which the page hears about only afterwards.
+import { vi } from 'vitest';
+
+export function fakeScreen({ refuse = false } = {}) {
+ let holder = null;
+ const give = (next) => {
+ holder = next;
+ document.dispatchEvent(new Event('fullscreenchange'));
+ };
+ Object.defineProperty(document, 'fullscreenElement', { configurable: true, get: () => holder });
+ const request = vi.fn(async function request() {
+ if (refuse) throw new TypeError('Permissions check failed');
+ give(this);
+ });
+ const exit = vi.fn(async () => give(null));
+ HTMLElement.prototype.requestFullscreen = request;
+ document.exitFullscreen = exit;
+ return {
+ request,
+ exit,
+ leave: () => give(null),
+ restore() {
+ delete document.fullscreenElement;
+ delete document.exitFullscreen;
+ delete HTMLElement.prototype.requestFullscreen;
+ },
+ };
+}
diff --git a/frontend/src/lib/fullscreen.js b/frontend/src/lib/fullscreen.js
index 8b44784..0392945 100644
--- a/frontend/src/lib/fullscreen.js
+++ b/frontend/src/lib/fullscreen.js
@@ -1,4 +1,4 @@
-// Fullscreen-aware overlays.
+// A tool on the whole screen, and the overlays that have to follow it there.
//
// The Fullscreen API paints *only* the fullscreen element's subtree, so an
// overlay parked on <body> (modals, confirms, toasts) is simply invisible while
@@ -36,3 +36,28 @@ export function portal(node, doc = document) {
},
};
}
+
+/**
+ * Hand `element` the whole screen, or give it back. Rejects when the browser
+ * refuses, so the tool can say so.
+ */
+export async function toggleFullscreen(element, doc = document) {
+ if (doc.fullscreenElement) await doc.exitFullscreen().catch(() => {});
+ else await element.requestFullscreen();
+}
+
+/**
+ * Tell `onchange` whether `element` holds the screen, each time that changes.
+ * Esc leaves fullscreen without asking the page, so a tool reads its state back
+ * from here rather than flipping a flag itself. Returns the unsubscribe.
+ */
+export function followFullscreen(element, onchange, doc = document) {
+ const changed = () => onchange(doc.fullscreenElement === element);
+ doc.addEventListener('fullscreenchange', changed);
+ return () => doc.removeEventListener('fullscreenchange', changed);
+}
+
+/** Give the screen back, if anything holds it. */
+export function leaveFullscreen(doc = document) {
+ if (doc.fullscreenElement) void doc.exitFullscreen().catch(() => {});
+}
diff --git a/frontend/src/lib/fullscreen.test.js b/frontend/src/lib/fullscreen.test.js
index ce3cc7a..eaad570 100644
--- a/frontend/src/lib/fullscreen.test.js
+++ b/frontend/src/lib/fullscreen.test.js
@@ -1,5 +1,5 @@
-import { describe, it, expect } from 'vitest';
-import { overlayHost, portal } from './fullscreen.js';
+import { describe, it, expect, vi } from 'vitest';
+import { followFullscreen, leaveFullscreen, overlayHost, portal, toggleFullscreen } from './fullscreen.js';
// Minimal DOM stand-ins: the action only ever appends and removes, so a couple
// of objects tracking parentage are enough (no jsdom in this suite).
@@ -135,3 +135,95 @@ describe('portal', () => {
expect(node.parent).toBe(null);
});
});
+
+// A document whose browser grants the screen and gives it back, as a real one
+// would: the element changes, then `fullscreenchange` fires.
+function makeScreenDoc() {
+ const doc = makeDoc(makeHost('body'));
+ doc.exitFullscreen = vi.fn(async () => {
+ doc.fullscreenElement = null;
+ doc.fire();
+ });
+ return doc;
+}
+function makeTool(doc, { refuse = false } = {}) {
+ const tool = makeHost('tool');
+ tool.requestFullscreen = vi.fn(async () => {
+ if (refuse) throw new TypeError('Permissions check failed');
+ doc.fullscreenElement = tool;
+ doc.fire();
+ });
+ return tool;
+}
+
+describe('toggleFullscreen', () => {
+ it('hands the tool the screen, then gives it back', async () => {
+ const doc = makeScreenDoc();
+ const tool = makeTool(doc);
+
+ await toggleFullscreen(tool, doc);
+ expect(doc.fullscreenElement).toBe(tool);
+
+ await toggleFullscreen(tool, doc);
+ expect(doc.exitFullscreen).toHaveBeenCalledOnce();
+ expect(doc.fullscreenElement).toBe(null);
+ });
+
+ it('rejects when the browser refuses, so the tool can say so', async () => {
+ const doc = makeScreenDoc();
+ await expect(toggleFullscreen(makeTool(doc, { refuse: true }), doc)).rejects.toThrow('Permissions');
+ expect(doc.fullscreenElement).toBe(null);
+ });
+});
+
+describe('followFullscreen', () => {
+ it('reads the state back from the browser, Esc included', async () => {
+ const doc = makeScreenDoc();
+ const tool = makeTool(doc);
+ const seen = [];
+ followFullscreen(tool, (on) => seen.push(on), doc);
+
+ await toggleFullscreen(tool, doc);
+ // Esc: the browser leaves on its own and only tells the page afterwards
+ doc.fullscreenElement = null;
+ doc.fire();
+
+ expect(seen).toEqual([true, false]);
+ });
+
+ it('says false while another element holds the screen', () => {
+ const doc = makeScreenDoc();
+ const seen = [];
+ followFullscreen(makeTool(doc), (on) => seen.push(on), doc);
+
+ doc.fullscreenElement = makeHost('video');
+ doc.fire();
+
+ expect(seen).toEqual([false]);
+ });
+
+ it('unhooks when its effect is torn down', () => {
+ const doc = makeScreenDoc();
+ followFullscreen(makeTool(doc), () => {}, doc)();
+ expect(doc.listeners).toEqual([]);
+ });
+});
+
+describe('leaveFullscreen', () => {
+ it('gives the screen back when something holds it', async () => {
+ const doc = makeScreenDoc();
+ const tool = makeTool(doc);
+ await toggleFullscreen(tool, doc);
+
+ leaveFullscreen(doc);
+
+ expect(doc.exitFullscreen).toHaveBeenCalledOnce();
+ expect(doc.fullscreenElement).toBe(null);
+ });
+
+ it('asks nothing of the browser when nothing does', () => {
+ const doc = makeScreenDoc();
+ leaveFullscreen(doc);
+ expect(doc.exitFullscreen).not.toHaveBeenCalled();
+ });
+});
diff --git a/frontend/src/lib/guide.js b/frontend/src/lib/guide.js
index 36169fa..c31946f 100644
--- a/frontend/src/lib/guide.js
+++ b/frontend/src/lib/guide.js
@@ -208,7 +208,7 @@ export const GUIDE = [
},
{
label: 'Layers cost nothing until they are on',
- text: 'Roads, railways, power lines, sea marks, GPS traces, fires and night lights are listed in the Layers tab of the side panel, and none of them is fetched before its switch is pressed. Borders are the one layer the map opens with.',
+ text: 'Roads, railways, power lines, sea marks, GPS traces, fires and night lights are listed in the Layers tab of the side panel, and none of them is fetched before its switch is pressed. Borders and place names are the layers the map opens with.',
},
{
label: 'Somebody else’s map over yours',
diff --git a/frontend/src/lib/map/acquisitions.js b/frontend/src/lib/map/acquisitions.js
index ae8d213..f9e2713 100644
--- a/frontend/src/lib/map/acquisitions.js
+++ b/frontend/src/lib/map/acquisitions.js
@@ -133,6 +133,16 @@ export function coverageWarning(entry) {
return `${entry.date} reaches ${Math.round(entry.coverage * 100)}% of the areas. The rest has no imagery that day and will be reported as not swept.`;
}
+/**
+ * What to say about a chosen Sentinel-2 pass over the cloud ceiling, or ''.
+ * It is read all the same, since a chosen day is the analyst's call; the
+ * clouds are left out pixel by pixel, which is worth knowing before the run.
+ */
+export function cloudWarning(entry, maxcc = 100) {
+ if (!entry || entry.cloud == null || !(entry.cloud > maxcc)) return '';
+ return `${entry.date} is ${Math.round(entry.cloud)}% cloud over its tile. It is read anyway, and ground under cloud is left out.`;
+}
+
/** The share of a finished run's areas that had imagery on both dates. */
export function sweptNote(swept) {
if (!Number.isFinite(swept) || swept >= FULL_COVER) return '';
diff --git a/frontend/src/lib/map/addedLayer.js b/frontend/src/lib/map/addedLayer.js
index caa106f..548f10d 100644
--- a/frontend/src/lib/map/addedLayer.js
+++ b/frontend/src/lib/map/addedLayer.js
@@ -32,10 +32,8 @@
* did draw the source's picture, the ones that did not draw our tinted shape.
* That split is also the fallback. An icon that 404s, decodes badly or never
* arrives costs its features nothing beyond the pictogram they would have had.
- * - **No map labels.** `text-field` needs real glyphs, which the engine does not
- * load and which this feature will not make it load. A feature's name lives in
- * the hover reading and in the card, both resolved through the engine's own
- * hit testing.
+ * - **No map labels.** A feature's name lives in the hover reading and in the
+ * card, both resolved through the engine's own hit testing.
*/
import { Popup } from 'maplibre-gl';
import { paths } from '../../components/Icon.svelte';
diff --git a/frontend/src/lib/map/addedLayer.test.js b/frontend/src/lib/map/addedLayer.test.js
index 2e4f701..dcd961e 100644
--- a/frontend/src/lib/map/addedLayer.test.js
+++ b/frontend/src/lib/map/addedLayer.test.js
@@ -361,7 +361,7 @@ describe('an added layer on the map', () => {
expect(marks.layout['symbol-sort-key']).toEqual(['get', 'index']);
});
- it('draws no text, because the engine loads no glyphs and will not start', async () => {
+ it('draws no text: a feature’s name is read in the hover and the card', async () => {
const engine = stubEngine();
await createAddedLayer(engine).set(COLLECTION, { categories: CATEGORIES });
diff --git a/frontend/src/lib/map/addedLayers.js b/frontend/src/lib/map/addedLayers.js
index f2d41c5..ddda626 100644
--- a/frontend/src/lib/map/addedLayers.js
+++ b/frontend/src/lib/map/addedLayers.js
@@ -132,7 +132,7 @@ export function freshness(layer, now = Date.now()) {
const at = layer.checked_at || layer.fetched_at;
const said = timeAgo(at, now);
if (!said) return 'never read';
- return layer.stale ? `stale — last read ${said}` : `read ${said}`;
+ return layer.stale ? `out of date, last read ${said}` : `read ${said}`;
}
/** Where a row came from, in the width a row has. */
diff --git a/frontend/src/lib/map/addedLayers.test.js b/frontend/src/lib/map/addedLayers.test.js
index e9b0e8e..da569a8 100644
--- a/frontend/src/lib/map/addedLayers.test.js
+++ b/frontend/src/lib/map/addedLayers.test.js
@@ -145,7 +145,7 @@ describe('how fresh what is drawn actually is', () => {
stale: true,
});
- expect(freshness(stale, NOW)).toBe('stale — last read 10 Sep 2026');
+ expect(freshness(stale, NOW)).toBe('out of date, last read 10 Sep 2026');
});
it('says a subscription nothing has ever read has never been read', () => {
diff --git a/frontend/src/lib/map/basemap.js b/frontend/src/lib/map/basemap.js
index 063ee8d..3fe29dc 100644
--- a/frontend/src/lib/map/basemap.js
+++ b/frontend/src/lib/map/basemap.js
@@ -17,9 +17,11 @@
* throwaway intermediate zoom levels mid-gesture, which a billed provider paid
* for. MapLibre overzooms what it already holds instead.
*/
+import { FIRE_MARKS } from './firePoints.js';
import { createGoogleGlass, loadGoogleMaps } from './gmaps.js';
import { INFRASTRUCTURE } from './infrastructure.js';
import { tileTemplate as nightTemplate } from './nightlights.js';
+import { PLACE_NAMES } from './placeNames.js';
/** What a `{s}` template is served from when the provider names no hosts. */
const DEFAULT_SUBDOMAINS = ['a', 'b', 'c'];
@@ -49,7 +51,10 @@ const ALTERNATE = 'basemap-alternate';
* for one night, and changing either is a different set of tiles.
*
* `vector` is a layer drawn from vector tiles by a style of our own: several
- * sources and several engine layers, switched on and off as one.
+ * sources and several engine layers, switched on and off as one. Its sources
+ * may be a function too, for the same reason as `url`. A source is a tile
+ * template, or `{ url }` naming a TileJSON for a provider whose tile paths
+ * change with each build.
*/
const OVERLAYS = [
{
@@ -117,18 +122,30 @@ const OVERLAYS = [
attribution: 'Esri, HERE, Garmin, © OpenStreetMap contributors, and the GIS user community',
maxZoom: 19,
},
+ {
+ // The towns, villages and hamlets the borders leave out (placeNames.js),
+ // over them because the smaller names are the ones being looked for.
+ id: 'placenames',
+ layer: 'basemap-placenames',
+ vector: PLACE_NAMES,
+ attribution: 'OpenFreeMap © OpenMapTiles · Data © OpenStreetMap contributors',
+ },
{
// Active fire detections, live or from the archive (engine/firms.py). The
// key is NASA's and stays on the backend, so this one address is ours.
+ // The map draws every detection itself (firePoints.js): a picture's squares
+ // swelled with its pixels until the next zoom's picture landed, a mark
+ // keeps its size and stays where it is while the next tiles come.
id: 'firms',
layer: 'basemap-firms',
- url: (params) => `/api/firms/tiles/{z}/{x}/{y}?${new URLSearchParams(params)}`,
+ vector: FIRE_MARKS,
attribution: 'Active fire data: NASA FIRMS',
- // The source stops at z14. Past it, MapLibre enlarges those pixels instead
- // of requesting invented detail, so a detection remains a visible square.
- maxZoom: 14,
- viewMaxZoom: 24,
- resampling: 'nearest',
+ // 512 px is a quarter of the requests for the same screen, and FIRMS counts
+ // requests against a ten-minute allowance (engine/firms.py).
+ tileSize: 512,
+ // The tiles stop at z13, where a square is already its 375 m footprint.
+ // Past it the map draws the z13 marks bigger, never blurred.
+ maxZoom: 13,
},
];
@@ -144,13 +161,33 @@ export function overlayLayers(overlay) {
return overlay.vector.layers.map((entry) => `${overlay.layer}-${entry.id}`);
}
-/** …and the sources behind them, as `[id, spec]`. */
+/** A vector overlay's sources for one question, by name. */
+function vectorSources(overlay, params) {
+ const { sources } = overlay.vector;
+ return typeof sources === 'function' ? sources(params ?? {}) : sources;
+}
+
+/** Every source an overlay adds, whatever the question: what is taken off with
+ * it, and what a failed tile is traced back through. */
+export function overlaySourceIds(overlay) {
+ if (!overlay.vector) return [overlay.layer];
+ return Object.keys(vectorSources(overlay, {})).map((name) => `${overlay.layer}-${name}`);
+}
+
+/** …and the sources behind them for one question, as `[id, spec]`. */
export function overlaySources(overlay, params) {
const { attribution } = overlay;
if (overlay.vector) {
- return Object.entries(overlay.vector.sources).map(([name, url]) => [
+ return Object.entries(vectorSources(overlay, params)).map(([name, where]) => [
`${overlay.layer}-${name}`,
- { type: 'vector', tiles: [url], minzoom: 0, maxzoom: overlay.vector.maxZoom, attribution },
+ {
+ type: 'vector',
+ ...(typeof where === 'string' ? { tiles: [where] } : where),
+ ...(overlay.tileSize ? { tileSize: overlay.tileSize } : {}),
+ minzoom: 0,
+ maxzoom: overlay.vector.maxZoom,
+ attribution,
+ },
]);
}
const template = typeof overlay.url === 'function' ? overlay.url(params ?? {}) : overlay.url;
@@ -160,7 +197,7 @@ export function overlaySources(overlay, params) {
{
type: 'raster',
tiles: tileUrls(template, overlay.subdomains),
- tileSize: 256,
+ tileSize: overlay.tileSize ?? 256,
minzoom: 0,
maxzoom: overlay.maxZoom,
attribution,
@@ -256,6 +293,10 @@ export function createBasemaps(engine, hooks = {}) {
onWidgetLoad = () => {},
onWidgetAuthFailure = () => {},
onWidgetFailed = () => {},
+ /** An overlay's tile failed, by overlay id. The engine shows nothing for
+ * it, so the tool that owns the layer can ask why (FIRMS: a spent
+ * allowance, a refused key). */
+ onOverlayTrouble = () => {},
} = hooks;
const map = engine.impl;
@@ -310,6 +351,13 @@ export function createBasemaps(engine, hooks = {}) {
}
map.on('sourcedata', onSourceData);
+ function onError(event) {
+ const source = event?.sourceId;
+ const overlay = source && OVERLAYS.find((entry) => overlaySourceIds(entry).includes(source));
+ if (overlay) onOverlayTrouble(overlay.id);
+ }
+ map.on('error', onError);
+
function dropTiles() {
if (map.getLayer(IMAGERY)) map.removeLayer(IMAGERY);
if (map.getSource(IMAGERY)) map.removeSource(IMAGERY);
@@ -374,6 +422,9 @@ export function createBasemaps(engine, hooks = {}) {
for (const [id, spec] of overlaySources(overlay, params)) map.addSource(id, spec);
const before = under(overlay);
if (overlay.vector) {
+ for (const [name, image, options] of overlay.vector.images ?? []) {
+ if (!map.hasImage(name)) map.addImage(name, image(), options);
+ }
for (const entry of overlay.vector.layers) {
map.addLayer(
{ ...entry, id: `${overlay.layer}-${entry.id}`, source: `${overlay.layer}-${entry.source}` },
@@ -384,7 +435,6 @@ export function createBasemaps(engine, hooks = {}) {
}
const paint = {};
if (overlay.opacity != null) paint['raster-opacity'] = overlay.opacity;
- if (overlay.resampling) paint['raster-resampling'] = overlay.resampling;
map.addLayer(
{
id: overlay.layer,
@@ -406,7 +456,7 @@ export function createBasemaps(engine, hooks = {}) {
function dropOverlay(overlay) {
for (const id of overlayLayers(overlay)) if (map.getLayer(id)) map.removeLayer(id);
- for (const [id] of overlaySources(overlay, {})) if (map.getSource(id)) map.removeSource(id);
+ for (const id of overlaySourceIds(overlay)) if (map.getSource(id)) map.removeSource(id);
}
return {
@@ -511,6 +561,7 @@ export function createBasemaps(engine, hooks = {}) {
dispose() {
map.off('sourcedata', onSourceData);
+ map.off('error', onError);
glass?.destroy();
glass = null;
},
diff --git a/frontend/src/lib/map/basemap.test.js b/frontend/src/lib/map/basemap.test.js
index dafe843..266e6be 100644
--- a/frontend/src/lib/map/basemap.test.js
+++ b/frontend/src/lib/map/basemap.test.js
@@ -127,16 +127,23 @@ describe('the source one provider is served from', () => {
});
});
+/** The FIRMS overlay's engine layers, lowest first (`firePoints.js`). */
+const FIRE_LAYERS = ['basemap-firms-foot-fill', 'basemap-firms-foot-ring', 'basemap-firms-foot-edge', 'basemap-firms-mark'];
+
describe('the layers on a map', () => {
/** A MapLibre map, as far as basemap.js reaches into it. */
function stubMap() {
const sources = new Map();
const layers = [];
+ const images = new Map();
const calls = { setMaxZoom: [], on: [], off: [] };
return {
calls,
sources,
layers,
+ images,
+ hasImage: (name) => images.has(name),
+ addImage: (name, image, options) => images.set(name, { image, options }),
addSource: (id, spec) => sources.set(id, spec),
removeSource: (id) => sources.delete(id),
getSource: (id) => sources.get(id),
@@ -386,21 +393,44 @@ describe('the layers on a map', () => {
expect(map.sources.get('basemap-railway').maxzoom).toBe(19);
expect(map.getLayer('basemap-railway').maxzoom).toBe(19);
expect(map.sources.get('basemap-railway').tiles).toHaveLength(3);
+ expect(map.sources.get('basemap-railway').tileSize).toBe(256);
});
});
- it('keeps FIRMS detections as visible squares beyond the last source zoom', async () => {
+ it('draws FIRMS as marks the map paints itself, at every zoom and for any question', async () => {
await withStubbedGoogle(async ({ createBasemaps }) => {
const map = stubMap();
- createBasemaps(stubEngine(map)).setOverlay('firms', true, {
- sensor: 'viirs',
- window: '24h',
- });
- expect(map.sources.get('basemap-firms').maxzoom).toBe(14);
- expect(map.getLayer('basemap-firms')).toMatchObject({
- maxzoom: 24,
- paint: { 'raster-resampling': 'nearest' },
- });
+ const basemaps = createBasemaps(stubEngine(map));
+ basemaps.setOverlay('firms', true, { sensor: 'viirs', window: '7d' });
+ const marks = map.sources.get('basemap-firms-marks');
+ // one vector source from z0: no picture to swell while the next level loads
+ expect(marks).toMatchObject({ type: 'vector', minzoom: 0, maxzoom: 13, tileSize: 512 });
+ expect(marks.tiles).toEqual(['/api/firms/points/{z}/{x}/{y}?sensor=viirs&window=7d&v=2']);
+ expect(map.layers.map((l) => l.id)).toEqual(FIRE_LAYERS);
+ for (const layer of map.layers) expect(layer.source).toBe('basemap-firms-marks');
+ // one tintable square for both colours
+ expect(map.images.get('firms-square').options).toEqual({ sdf: true });
+ // a dated range is the same marks, asked with its days
+ basemaps.setOverlay('firms', true, { sensor: 'viirs', window: 'dates', first: '2026-09-01', last: '2026-09-03' });
+ expect(map.sources.get('basemap-firms-marks').tiles[0]).toContain('window=dates&first=2026-09-01&last=2026-09-03');
+ expect(map.layers.map((l) => l.id)).toEqual(FIRE_LAYERS);
+ // and nothing else is laid for it: no picture layer under the marks
+ expect([...map.sources.keys()]).toEqual(['basemap-firms-marks']);
+ });
+ });
+
+ it('tells the tool when a tile of one of its overlays fails, and of nothing else', async () => {
+ await withStubbedGoogle(async ({ createBasemaps }) => {
+ const map = stubMap();
+ const trouble = vi.fn();
+ const basemaps = createBasemaps(stubEngine(map), { onOverlayTrouble: trouble });
+ const [, onError] = map.calls.on.find(([name]) => name === 'error');
+ onError({ sourceId: 'basemap-firms-marks' });
+ onError({ sourceId: 'somebody-else' });
+ onError({ error: new Error('style') });
+ expect(trouble.mock.calls).toEqual([['firms']]);
+ basemaps.dispose();
+ expect(map.calls.off).toContainEqual(['error', onError]);
});
});
@@ -431,9 +461,9 @@ describe('the layers on a map', () => {
sensor: 'modis',
window: '48h',
});
- const [url] = map.sources.get('basemap-firms').tiles;
+ const [url] = map.sources.get('basemap-firms-marks').tiles;
// through the app, because the key is NASA's and stays on the backend
- expect(url).toContain('/api/firms/tiles/{z}/{x}/{y}?');
+ expect(url).toContain('/api/firms/points/{z}/{x}/{y}?');
expect(url).toContain('sensor=modis');
expect(url).toContain('window=48h');
});
@@ -445,16 +475,16 @@ describe('the layers on a map', () => {
const basemaps = createBasemaps(stubEngine(map));
const params = { sensor: 'viirs', window: '24h' };
basemaps.setOverlay('firms', true, params);
- const first = map.sources.get('basemap-firms');
+ const first = map.sources.get('basemap-firms-marks');
// the same question again is the same tiles: rebuilding would refetch
// every one of them, which reads on screen as a reloading map
basemaps.setOverlay('firms', true, { ...params });
- expect(map.sources.get('basemap-firms')).toBe(first);
+ expect(map.sources.get('basemap-firms-marks')).toBe(first);
basemaps.setOverlay('firms', true, { sensor: 'viirs', window: '7d' });
- expect(map.sources.get('basemap-firms')).not.toBe(first);
- expect(map.sources.get('basemap-firms').tiles[0]).toContain('window=7d');
- expect(map.layers.map((l) => l.id)).toEqual(['basemap-firms']);
+ expect(map.sources.get('basemap-firms-marks')).not.toBe(first);
+ expect(map.sources.get('basemap-firms-marks').tiles[0]).toContain('window=7d');
+ expect(map.layers.map((l) => l.id)).toEqual(FIRE_LAYERS);
});
});
@@ -465,11 +495,7 @@ describe('the layers on a map', () => {
basemaps.setOverlay('firms', true, { sensor: 'viirs', window: '24h' });
basemaps.setOverlay('boundaries', true);
basemaps.setOverlay('railway', true);
- expect(map.layers.map((l) => l.id)).toEqual([
- 'basemap-railway',
- 'basemap-boundaries',
- 'basemap-firms',
- ]);
+ expect(map.layers.map((l) => l.id)).toEqual(['basemap-railway', 'basemap-boundaries', ...FIRE_LAYERS]);
});
});
@@ -530,6 +556,33 @@ describe('the layers on a map', () => {
});
});
+ it('reads the place names from the TileJSON that names OpenFreeMap’s current build', async () => {
+ await withStubbedGoogle(async ({ createBasemaps }) => {
+ const map = stubMap();
+ const basemaps = createBasemaps(stubEngine(map));
+ basemaps.setOverlay('boundaries', true);
+ expect(map.sources.has('basemap-placenames-openmaptiles')).toBe(false);
+
+ basemaps.setOverlay('placenames', true);
+ const source = map.sources.get('basemap-placenames-openmaptiles');
+ expect(source).toMatchObject({
+ type: 'vector',
+ url: 'https://tiles.openfreemap.org/planet',
+ maxzoom: 14,
+ attribution: expect.stringContaining('OpenStreetMap'),
+ });
+ // a dated template would break the week the build it names is removed
+ expect(source).not.toHaveProperty('tiles');
+ // over the borders, whose own names are the larger places
+ expect(map.layers.map((l) => l.id)).toEqual(['basemap-boundaries', 'basemap-placenames-label']);
+ expect(map.getLayer('basemap-placenames-label').source).toBe('basemap-placenames-openmaptiles');
+
+ basemaps.setOverlay('placenames', false);
+ expect(map.sources.has('basemap-placenames-openmaptiles')).toBe(false);
+ expect(map.layers.map((l) => l.id)).toEqual(['basemap-boundaries']);
+ });
+ });
+
it('slides a vector overlay into the stack as one block', async () => {
await withStubbedGoogle(async ({ createBasemaps }) => {
const map = stubMap();
@@ -550,7 +603,7 @@ describe('the layers on a map', () => {
const map = stubMap();
const basemaps = createBasemaps(stubEngine(map));
basemaps.show(ESRI, ESRI.id, 256);
- for (const id of ['firms', 'boundaries', 'seamarks', 'railway', 'roads', 'gpstraces']) {
+ for (const id of ['firms', 'placenames', 'boundaries', 'seamarks', 'railway', 'roads', 'gpstraces']) {
basemaps.setOverlay(id, true, id === 'firms' ? { sensor: 'viirs', window: '24h' } : undefined);
}
basemaps.setOverlay('nightlights', true, { source: 'noaa20', day: '2026-09-12' });
@@ -562,12 +615,13 @@ describe('the layers on a map', () => {
'basemap-railway',
'basemap-seamarks',
'basemap-boundaries',
- 'basemap-firms',
+ 'basemap-placenames-label',
+ ...FIRE_LAYERS,
]);
});
});
- it('has no CARTO labels layer: its tiles now ask for a key, and the borders name places', () => {
+ it('has no CARTO labels layer: its tiles now ask for a key', () => {
expect(OVERLAY_IDS).not.toContain('labels');
});
@@ -601,8 +655,8 @@ describe('the layers on a map', () => {
const basemaps = createBasemaps(stubEngine(map));
for (const id of OVERLAY_IDS) basemaps.setOverlay(id, true, params[id]);
for (const [id, source] of map.sources) {
- const expected = id === 'basemap-firms' ? /^\/api\/firms\/tiles\// : /^https:\/\//;
- for (const url of source.tiles) expect(url, id).toMatch(expected);
+ const expected = id === 'basemap-firms-marks' ? /^\/api\/firms\/points\// : /^https:\/\//;
+ for (const url of source.tiles ?? [source.url]) expect(url, id).toMatch(expected);
expect(source.attribution, id).toBeTruthy();
}
});
@@ -614,7 +668,10 @@ describe('the layers on a map', () => {
const basemaps = createBasemaps(stubEngine(map));
await basemaps.show(WIDGET, WIDGET.id, 256);
basemaps.dispose();
- expect(map.calls.off).toEqual([['sourcedata', expect.any(Function)]]);
+ expect(map.calls.off).toEqual([
+ ['sourcedata', expect.any(Function)],
+ ['error', expect.any(Function)],
+ ]);
expect(glasses[0].destroyed).toBe(1);
});
});
diff --git a/frontend/src/lib/map/changeAssist.js b/frontend/src/lib/map/changeAssist.js
index 7a25733..72d713c 100644
--- a/frontend/src/lib/map/changeAssist.js
+++ b/frontend/src/lib/map/changeAssist.js
@@ -50,10 +50,12 @@ export const CHANGE_DISPLAYS = Object.freeze([
]);
export const CHANGE_PALETTES = Object.freeze({
+ // Cyan and magenta are rare on the ground, so they stand out over soil,
+ // vegetation and roofs alike, where green and red sank into them.
directional: Object.freeze({
- gain: [34, 197, 94],
- loss: [239, 68, 68],
- changed: [250, 204, 21],
+ gain: [0, 229, 255],
+ loss: [255, 0, 170],
+ changed: [255, 221, 0],
}),
// Okabe-Ito hues: distinguishable under the common red/green deficiencies.
colourblind: Object.freeze({
@@ -86,7 +88,7 @@ export const CHANGE_DEFAULTS = Object.freeze({
method: 'colour',
index: 'ndvi',
threshold: 'auto',
- sensitivity: 55,
+ sensitivity: 70,
normalize: 'auto',
smoothing: 1,
alignment: 4,
diff --git a/frontend/src/lib/map/changeAssist.test.js b/frontend/src/lib/map/changeAssist.test.js
index 5344f79..09c20c4 100644
--- a/frontend/src/lib/map/changeAssist.test.js
+++ b/frontend/src/lib/map/changeAssist.test.js
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest';
-import { CHANGE_DEFAULTS, changeCompatibility, changeNeedsFrames, changeSettings } from './changeAssist.js';
+import { CHANGE_DEFAULTS, CHANGE_PALETTES, changeCompatibility, changeNeedsFrames, changeSettings } from './changeAssist.js';
const side = (patch = {}) => ({
present: true,
@@ -106,6 +106,14 @@ describe('Difference settings', () => {
expect(changeSettings({ normalize: 'histogram' })).toMatchObject({ normalize: 'histogram' });
});
+ it('reaches a mid-strength change by default, drawn in hues the ground rarely has', () => {
+ expect(CHANGE_DEFAULTS.sensitivity).toBe(70);
+ expect(CHANGE_DEFAULTS.palette).toBe('directional');
+ // cyan and magenta: no longer green over vegetation or red over soil and roofs
+ expect(CHANGE_PALETTES.directional.gain).toEqual([0, 229, 255]);
+ expect(CHANGE_PALETTES.directional.loss).toEqual([255, 0, 170]);
+ });
+
it('keeps every value inside its range', () => {
expect(
changeSettings({
diff --git a/frontend/src/lib/map/changeCapture.js b/frontend/src/lib/map/changeCapture.js
index 80eac4e..daa3841 100644
--- a/frontend/src/lib/map/changeCapture.js
+++ b/frontend/src/lib/map/changeCapture.js
@@ -2,26 +2,36 @@
* Capture-sized change detection, with Sentinel-2 band frames fetched once and
* then reused.
*
- * A band frame is a metered request, so it is asked for by an explicit act —
- * Run, or switching the cloud filter on — and never by a pan. To keep the
- * filter working while the analyst moves around, each frame is fetched with a
+ * A band frame is a metered request, so one is fetched only when the caller
+ * allows it (`fetchAllowed`); Compare says when. Each frame is fetched with a
* margin of ground around the view and held: a later reading whose view still
- * falls inside it, at a similar resolution, is served from that copy. A move
- * past the margin, a zoom, or another date leaves the reading waiting for Run
- * rather than quietly spending a request.
+ * falls inside it, at a similar resolution, is served from that copy, or from a
+ * fetch still on its way that reaches it, rather than giving up on bands
+ * already paid for. Past that, a reading not allowed to fetch is told so.
*/
import { changeNeedsFrames } from './changeAssist.js';
import { runChangeDetection } from './changeRunner.js';
-import { compose, frameBox, groundPerPixel, imageToMercator, invert, scale, screenToMercator } from './groundFrame.js';
+import { compose, frameBox, groundPerPixel, imageToMercator, invert, mercatorPerPixel, scale,
+ screenToMercator } from './groundFrame.js';
/** Ground kept around the view, as a share of it on each side. */
const MARGIN = 0.2;
+/**
+ * Sentinel-2 classifies the scene at 20 m, so a finer sky frame buys no
+ * detail, only pixels on the bill. Read at 20 m, the pixels a 20% margin
+ * would take at the view's resolution cover far more ground, and the margin
+ * grows into them, up to a whole view past each edge.
+ */
+const SKY_GROUND_METRES = 20;
+const MARGIN_MAX = 1;
/** What the backend will render, one side at a time. */
const MAX_EDGE = 2048;
/** How far the held copy's resolution may drift from what a reading wants. */
const SCALE_RANGE = [0.6, 2.5];
const held = new Map();
+/** Fetches under way, each with the ground and resolution it will hold. */
+const inflight = new Map();
const grow = (box, share) => {
const width = (box.east - box.west) * share;
@@ -36,6 +46,7 @@ const covers = (outer, inner) => outer.west <= inner.west && outer.east >= inner
/** For tests only: the held frames otherwise last as long as the page. */
export function forgetBandFrames() {
held.clear();
+ inflight.clear();
}
function frameKey(side, product) {
@@ -44,37 +55,58 @@ function frameKey(side, product) {
sentinel.maxcc ?? ''].join('|');
}
+/** Whether a frame, held or on its way, reaches `box` at about `resolution`. */
+function serves(frame, box, resolution) {
+ if (!frame || !covers(frame.box, box)) return false;
+ const drift = frame.metresPerPixel / resolution;
+ return drift >= SCALE_RANGE[0] && drift <= SCALE_RANGE[1];
+}
+
/**
- * The bytes of one band frame over `box`, from the held copy or from the network.
+ * The bytes of one band frame over `box`, from the held copy, a fetch already
+ * on its way, or the network. Resolutions are Web Mercator metres per pixel,
+ * the unit the box is in. `floor` is the product's own: no frame is asked for
+ * finer than the sensor measured it.
*
* @returns {Promise<{blob: Blob, box: object, width: number, height: number}|null>}
* null when a fetch was needed and `fetchAllowed` said no.
*/
-async function frameBytes(side, product, box, metresPerPixel, fetchAllowed) {
+async function frameBytes(side, product, box, metresPerPixel, fetchAllowed, floor = 0) {
const key = frameKey(side, product);
+ const resolution = Math.max(metresPerPixel, floor);
const copy = held.get(key);
- const drift = copy ? copy.metresPerPixel / metresPerPixel : 0;
- if (copy && covers(copy.box, box) && drift >= SCALE_RANGE[0] && drift <= SCALE_RANGE[1]) {
- return copy;
- }
+ if (serves(copy, box, resolution)) return copy;
+ const pending = inflight.get(key);
+ if (serves(pending, box, resolution)) return pending.promise;
if (!fetchAllowed) return null;
- const wanted = grow(box, MARGIN);
- const width = Math.min(MAX_EDGE, Math.max(1, Math.round((wanted.east - wanted.west) / metresPerPixel)));
- const height = Math.min(MAX_EDGE, Math.max(1, Math.round((wanted.north - wanted.south) / metresPerPixel)));
- const response = await fetch('/api/compare/sentinel-frame', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ ...wanted, width, height, day: side.sentinel.effectiveDate || side.sentinel.date,
- maxcc: side.sentinel.maxcc, layer: side.sentinel.layer, product }),
- });
- if (!response.ok) {
- const body = await response.json().catch(() => ({}));
- throw new Error(typeof body.detail === 'string' ? body.detail : `Band request failed (${response.status})`);
+ // As many pixels as a 20% margin at the view's own resolution: exactly that
+ // margin when the floor does not bite, more ground when it does.
+ const margin = Math.min(MARGIN_MAX, ((1 + 2 * MARGIN) * (resolution / metresPerPixel) - 1) / 2);
+ const wanted = grow(box, margin);
+ const width = Math.min(MAX_EDGE, Math.max(1, Math.round((wanted.east - wanted.west) / resolution)));
+ const height = Math.min(MAX_EDGE, Math.max(1, Math.round((wanted.north - wanted.south) / resolution)));
+ const fetched = { box: wanted, width, height, metresPerPixel: (wanted.east - wanted.west) / width };
+ fetched.promise = (async () => {
+ const response = await fetch('/api/compare/sentinel-frame', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ ...wanted, width, height, day: side.sentinel.effectiveDate || side.sentinel.date,
+ maxcc: side.sentinel.maxcc, layer: side.sentinel.layer, product }),
+ });
+ if (!response.ok) {
+ const body = await response.json().catch(() => ({}));
+ throw new Error(typeof body.detail === 'string' ? body.detail : `Band request failed (${response.status})`);
+ }
+ fetched.blob = await response.blob();
+ held.set(key, fetched);
+ return fetched;
+ })();
+ inflight.set(key, fetched);
+ try {
+ return await fetched.promise;
+ } finally {
+ if (inflight.get(key) === fetched) inflight.delete(key);
}
- const fetched = { blob: await response.blob(), box: wanted, width, height,
- metresPerPixel: (wanted.east - wanted.west) / width };
- held.set(key, fetched);
- return fetched;
}
/**
@@ -85,8 +117,11 @@ async function frameBytes(side, product, box, metresPerPixel, fetchAllowed) {
*/
export async function bandFrame(frame, width, height, side, product, fetchAllowed = true) {
const box = frameBox(frame);
- const metres = groundPerPixel(frame) * frame.width / width;
- const source = await frameBytes(side, product, box, metres, fetchAllowed);
+ // Along the projection, as the box is: a ground metre here would ask for
+ // 1/cos(latitude) more pixels a side than the reading draws.
+ const metres = mercatorPerPixel(frame.zoom) * frame.width / width;
+ const floor = product === 'sky' ? SKY_GROUND_METRES / Math.cos((frame.lat * Math.PI) / 180) : 0;
+ const source = await frameBytes(side, product, box, metres, fetchAllowed, floor);
if (!source) return null;
// No colour management and no premultiplied alpha: these bytes are a
// measurement and a scene class, not a picture.
diff --git a/frontend/src/lib/map/changeCapture.test.js b/frontend/src/lib/map/changeCapture.test.js
index 9c81ade..8ce6053 100644
--- a/frontend/src/lib/map/changeCapture.test.js
+++ b/frontend/src/lib/map/changeCapture.test.js
@@ -1,6 +1,7 @@
// @vitest-environment happy-dom
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { changeSettings } from './changeAssist.js';
+import { mercatorPerPixel } from './groundFrame.js';
const runChangeDetection = vi.fn(async ({ width, height }) => ({
pixels: new Uint8ClampedArray(width * height * 4), width, height, counts: {},
@@ -105,6 +106,60 @@ describe('captured change frames', () => {
}));
});
+ it('asks for the resolution the reading draws at, along the projection the box is in', async () => {
+ vi.stubGlobal('createImageBitmap', vi.fn(async () => ({ close: vi.fn() })));
+ fetch.mockResolvedValue({ ok: true, blob: async () => new Blob() });
+ const north = { ...frame, lat: 60, bearing: 0 };
+ await bandFrame(north, 80, 60, { sentinel: { date: '2026-09-01' } }, 'ndvi');
+ const asked = JSON.parse(fetch.mock.calls[0][1].body);
+ // Ground metres over a Mercator box asked for twice the pixels a side at 60°.
+ const drawn = mercatorPerPixel(north.zoom) * north.width / 80;
+ expect((asked.east - asked.west) / asked.width).toBeCloseTo(drawn, 0);
+ expect(asked.width).toBe(Math.round(80 * 1.4));
+ });
+
+ it('reads the sky at its own 20 m, over more ground for no more pixels', async () => {
+ vi.stubGlobal('createImageBitmap', vi.fn(async () => ({ close: vi.fn() })));
+ fetch.mockResolvedValue({ ok: true, blob: async () => new Blob() });
+ const side = { sentinel: { date: '2026-09-01' } };
+ const flat = { ...frame, bearing: 0 };
+ await bandFrame(flat, 400, 300, side, 'ndvi');
+ await bandFrame(flat, 400, 300, side, 'sky');
+ const [index, sky] = fetch.mock.calls.map(([, request]) => JSON.parse(request.body));
+ const ground = (asked) => (asked.east - asked.west) / asked.width * Math.cos((flat.lat * Math.PI) / 180);
+ expect(ground(sky)).toBeCloseTo(20, 0);
+ expect(sky.width * sky.height).toBeLessThanOrEqual(index.width * index.height);
+ // a whole view past each edge, where the index keeps a fifth of one
+ expect((sky.east - sky.west) / (index.east - index.west)).toBeCloseTo(3 / 1.4, 1);
+ });
+
+ it('serves a view zoomed in from the sky it holds, since 20 m is all the sky there is', async () => {
+ vi.stubGlobal('createImageBitmap', vi.fn(async () => ({ close: vi.fn() })));
+ fetch.mockResolvedValue({ ok: true, blob: async () => new Blob() });
+ const side = { sentinel: { date: '2026-09-01' } };
+ await bandFrame(frame, 400, 300, side, 'sky');
+ expect(await bandFrame({ ...frame, zoom: frame.zoom + 2 }, 400, 300, side, 'sky', false)).not.toBeNull();
+ expect(fetch).toHaveBeenCalledTimes(1);
+ });
+
+ it('lets a reading that may not fetch wait on bands already on their way', async () => {
+ vi.stubGlobal('createImageBitmap', vi.fn(async () => ({ close: vi.fn() })));
+ let land;
+ fetch.mockReturnValue(new Promise((resolve) => (land = () => resolve({ ok: true, blob: async () => new Blob() }))));
+ const side = { sentinel: { date: '2026-09-01' } };
+ const asked = bandFrame(frame, 400, 300, side, 'sky');
+ await Promise.resolve();
+ // the camera nudged while the bands were coming: the reading that took over waits for them
+ const following = bandFrame({ ...frame, lng: frame.lng + 0.0005 }, 400, 300, side, 'sky', false);
+ land();
+ expect(await following).not.toBeNull();
+ expect(await asked).not.toBeNull();
+ expect(fetch).toHaveBeenCalledTimes(1);
+ // past what is on its way, it still says so rather than spending
+ const away = bandFrame({ ...frame, lng: frame.lng + 1 }, 400, 300, side, 'sky', false);
+ expect(await away).toBeNull();
+ });
+
it('reports a quota refusal without decoding or computing a mask', async () => {
fetch.mockResolvedValue({ ok: false, status: 429, json: async () => ({ detail: 'Sentinel Hub is paused' }) });
await expect(bandFrame(frame, 80, 60, { sentinel: { date: '2026-09-01' } }, 'ndvi'))
diff --git a/frontend/src/lib/map/compare.js b/frontend/src/lib/map/compare.js
index 013521a..ce6416c 100644
--- a/frontend/src/lib/map/compare.js
+++ b/frontend/src/lib/map/compare.js
@@ -30,6 +30,7 @@ export const BLINK_SPEEDS = Object.freeze([
/** Reference layers Compare can persist, grouped the way the sheet lists them. */
export const COMPARE_LAYERS = Object.freeze([
{ id: 'boundaries', label: 'Borders', hint: 'Country, region and district borders', group: 'reference' },
+ { id: 'placenames', label: 'Place names', hint: 'Towns, villages and hamlets from OpenStreetMap', group: 'reference' },
{ id: 'roads', label: 'Roads', hint: 'Road network', group: 'reference' },
{ id: 'railway', label: 'Railways', hint: 'Tracks, sidings and stations', group: 'reference' },
{ id: 'power', label: 'Power lines', hint: 'Lines, towers and substations', group: 'reference' },
diff --git a/frontend/src/lib/map/detectWhen.js b/frontend/src/lib/map/detectWhen.js
index 69453c4..8222fb9 100644
--- a/frontend/src/lib/map/detectWhen.js
+++ b/frontend/src/lib/map/detectWhen.js
@@ -7,15 +7,76 @@
* area" when the areas really do differ.
*
* A is the picture before, B the one to look in. An empty B date is the
- * newest pass, looked up when the run starts; a routine never holds one.
+ * newest pass under the cloud ceiling, looked up when the run starts; a routine
+ * never holds one.
*/
import { sunPosition } from './changeDetect.js';
import { zoneRing } from './analyzers.js';
+import { FULL_COVER } from './acquisitions.js';
+import { onTrack } from '../radar.js';
/** How much a 10 m building's shadow may change length between two passes,
* in metres, before it reads as a change: half a Sentinel-2 pixel. */
export const SHADOW_SHIFT_M = 5;
+/** The cloud ceiling a new detection starts with. Above it, a pass taken on its
+ * own can be mostly cloud. */
+export const ADVISED_MAXCC = 30;
+
+/** What a ceiling above the advised one costs, or '' at or under it. */
+export function ceilingWarning(maxcc) {
+ if (!(maxcc > ADVISED_MAXCC)) return '';
+ return `Above ${ADVISED_MAXCC}%, the pass taken can be mostly cloud, and ground under cloud is left out.`;
+}
+
+/**
+ * What "the newest pass" means once the cloud ceiling is part of it, in words.
+ * It is the newest pass the ceiling allows, which is not always the newest
+ * there is. Radar sees through cloud, and a ceiling of 100 lets every pass
+ * through, so only a real ceiling is said.
+ */
+export function newestLabel({ maxcc = 100, radar = false } = {}) {
+ return radar || !(maxcc < 100) ? 'newest pass' : `newest pass under ${maxcc}% cloud`;
+}
+
+/**
+ * The pass "newest" would take from a looked-up list, newest first, and the
+ * newer ones it steps over, each with why: 'cloud' or 'cover'. The rule is the
+ * one the run applies at launch (`resolve_dates`): the tile's cloud known and
+ * at or under the ceiling, and the whole area covered. Radar keeps to `track`.
+ */
+export function newestPick(list, { maxcc = 100, radar = false, track = '' } = {}) {
+ const skipped = [];
+ for (const entry of radar ? onTrack(list, track) : (list ?? [])) {
+ const why = !radar && !(entry.cloud != null && entry.cloud <= maxcc) ? 'cloud'
+ : !((entry.coverage ?? 0) >= FULL_COVER) ? 'cover' : '';
+ if (!why) return { pass: entry, skipped };
+ skipped.push({ ...entry, why });
+ }
+ return { pass: null, skipped };
+}
+
+function skippedLabel(entry) {
+ if (entry.why === 'cover') return `${entry.date} (${Math.round((entry.coverage ?? 0) * 100)}% of the area)`;
+ return `${entry.date} (${entry.cloud == null ? 'cloud unknown' : `${Math.round(entry.cloud)}% cloud`})`;
+}
+
+/**
+ * The line under "newest" once the passes are known: which day it takes now,
+ * and the newer ones it steps over, so a clearer-looking map is not a mystery.
+ */
+export function newestLine(pick, { maxcc = 100, radar = false } = {}) {
+ if (!pick) return '';
+ const shown = pick.skipped.slice(0, 3).map(skippedLabel);
+ const more = pick.skipped.length > 3 ? ` and ${pick.skipped.length - 3} more` : '';
+ const newer = shown.length ? ` Newer: ${shown.join(', ')}${more}. Pick one below to read it anyway.` : '';
+ if (!pick.pass) {
+ const rule = radar || !(maxcc < 100) ? 'covers the whole area' : `is under ${maxcc}% cloud over the whole area`;
+ return `No pass in this window ${rule}. Pick one below.`;
+ }
+ return newer ? `Now ${pick.pass.date}.${newer}` : `Now ${pick.pass.date}, looked up again when the run starts.`;
+}
+
/** A side as a line: its day, and a radar pass's time. */
export function sideLine(source, radar = false) {
if (!source?.date) return '';
@@ -76,22 +137,24 @@ export function whenNeed({ single, routine, against, followupId, pairs, chooseB
/** One area's days, for the list shown when the areas differ. */
export function areaLine(pair, { single, routine, radar = false }) {
+ const newest = newestLabel({ maxcc: pair?.b?.maxcc, radar });
const a = sideLine(pair?.a, radar) || 'not chosen';
- const b = sideLine(pair?.b, radar) || 'newest pass';
- if (single) return routine ? 'newest pass' : b;
+ const b = sideLine(pair?.b, radar) || newest;
+ if (single) return routine ? newest : b;
return routine ? `A ${a}` : `A ${a} → B ${b}`;
}
/** The step as one line, for the recap before the start. */
-export function whenSummary({ single, routine, against, pairs, radar = false }) {
+export function whenSummary({ single, routine, against, pairs, radar = false, maxcc = 100 }) {
if (pairs.length > 1 && !uniform(pairs)) return 'Its own days for each area';
+ const newest = newestLabel({ maxcc, radar });
const a = sideLine(sharedSide(pairs, 'a'), radar);
- const b = sideLine(sharedSide(pairs, 'b'), radar) || 'newest pass';
+ const b = sideLine(sharedSide(pairs, 'b'), radar) || newest;
if (routine) {
- if (single) return 'Each run: the newest pass';
+ if (single) return `Each run: the ${newest}`;
return against === 'previous'
- ? `Each run: the newest pass against the one before${a ? `, first against ${a}` : ''}`
- : `Each run: the newest pass against ${a || 'A'}`;
+ ? `Each run: the ${newest} against the one before${a ? `, first against ${a}` : ''}`
+ : `Each run: the ${newest} against ${a || 'A'}`;
}
if (single) return b.charAt(0).toUpperCase() + b.slice(1);
return `${a || 'A not chosen'} → ${b}`;
diff --git a/frontend/src/lib/map/detectWhen.test.js b/frontend/src/lib/map/detectWhen.test.js
index cce27a2..719ef3d 100644
--- a/frontend/src/lib/map/detectWhen.test.js
+++ b/frontend/src/lib/map/detectWhen.test.js
@@ -1,6 +1,7 @@
import { describe, expect, it } from 'vitest';
import {
- areaLine, setSide, shadowLength, shadowWarning, sharedSide, sideLine, uniform, whenNeed, whenSummary, withRule,
+ ADVISED_MAXCC, areaLine, ceilingWarning, newestLabel, newestLine, newestPick, setSide, shadowLength, shadowWarning, sharedSide, sideLine, uniform,
+ whenNeed, whenSummary, withRule,
} from './detectWhen.js';
const pair = (id, a = '', b = '', extra = {}) => ({
@@ -73,16 +74,19 @@ describe('the When step of a detection', () => {
it('lists one area\'s days when the areas differ', () => {
const once = { single: false, routine: false };
- expect(areaLine(pair('x', '2026-08-01'), once)).toBe('A 2026-08-01 → B newest pass');
+ // "newest" is the newest the ceiling allows, and says so
+ expect(areaLine(pair('x', '2026-08-01'), once)).toBe('A 2026-08-01 → B newest pass under 30% cloud');
expect(areaLine(pair('x', '', '2026-09-06'), once)).toBe('A not chosen → B 2026-09-06');
expect(areaLine(pair('x', '', '2026-09-06'), { ...once, single: true })).toBe('2026-09-06');
expect(areaLine(pair('x', '2026-08-01'), { ...once, routine: true })).toBe('A 2026-08-01');
- expect(areaLine(pair('x'), { single: true, routine: true })).toBe('newest pass');
+ expect(areaLine(pair('x'), { single: true, routine: true })).toBe('newest pass under 30% cloud');
});
it('sums the step up in one line', () => {
const once = { single: false, routine: false, against: 'previous' };
expect(whenSummary({ ...once, pairs: [pair('x', '2026-08-01')] })).toBe('2026-08-01 → newest pass');
+ expect(whenSummary({ ...once, maxcc: 30, pairs: [pair('x', '2026-08-01')] }))
+ .toBe('2026-08-01 → newest pass under 30% cloud');
expect(whenSummary({ ...once, pairs: [pair('x', '2026-08-01', '2026-09-06')] })).toBe('2026-08-01 → 2026-09-06');
expect(whenSummary({ ...once, single: true, pairs: [pair('x')] })).toBe('Newest pass');
expect(whenSummary({ ...once, pairs: [pair('x', '2026-08-01'), pair('y', '2026-07-20')] }))
@@ -94,8 +98,87 @@ describe('the When step of a detection', () => {
.toBe('Each run: the newest pass against 2026-08-01');
expect(whenSummary({ ...routine, single: true, against: 'previous', pairs: [pair('x')] }))
.toBe('Each run: the newest pass');
+ expect(whenSummary({ ...routine, single: true, maxcc: 20, against: 'previous', pairs: [pair('x')] }))
+ .toBe('Each run: the newest pass under 20% cloud');
const radar = [{ ...pair('x', '2026-08-01'), a: { date: '2026-08-01', time: '16:32:10' } }];
expect(whenSummary({ ...once, radar: true, pairs: radar })).toBe('2026-08-01 16:32 UTC → newest pass');
+ // radar sees through cloud, whatever the ceiling says
+ expect(whenSummary({ ...once, radar: true, maxcc: 30, pairs: radar })).toBe('2026-08-01 16:32 UTC → newest pass');
+ });
+});
+
+describe('what "newest" takes, and what it steps over', () => {
+ // Lyman, 2026-09-26: three newer passes over the ceiling, then a clear one
+ const lyman = [
+ { date: '2026-09-26', cloud: 51.1, coverage: 1 },
+ { date: '2026-09-24', cloud: 82.2, coverage: 1 },
+ { date: '2026-09-22', cloud: 89.2, coverage: 1 },
+ { date: '2026-09-19', cloud: 0.7, coverage: 1 },
+ { date: '2026-09-17', cloud: 13.5, coverage: 1 },
+ ];
+
+ it('warns about a ceiling only above the advised one', () => {
+ expect(ADVISED_MAXCC).toBe(30);
+ expect(ceilingWarning(30)).toBe('');
+ expect(ceilingWarning(20)).toBe('');
+ expect(ceilingWarning(undefined)).toBe('');
+ expect(ceilingWarning(31)).toBe('Above 30%, the pass taken can be mostly cloud, and ground under cloud is left out.');
+ });
+
+ it('names the ceiling in the label, and only a real one', () => {
+ expect(newestLabel({ maxcc: 30 })).toBe('newest pass under 30% cloud');
+ expect(newestLabel({ maxcc: 100 })).toBe('newest pass');
+ expect(newestLabel({ maxcc: 30, radar: true })).toBe('newest pass');
+ expect(newestLabel()).toBe('newest pass');
+ });
+
+ it('takes the newest pass the ceiling allows and lists the newer ones it skips', () => {
+ const pick = newestPick(lyman, { maxcc: 30 });
+ expect(pick.pass.date).toBe('2026-09-19');
+ expect(pick.skipped.map((entry) => [entry.date, entry.why])).toEqual([
+ ['2026-09-26', 'cloud'], ['2026-09-24', 'cloud'], ['2026-09-22', 'cloud'],
+ ]);
+ expect(newestLine(pick, { maxcc: 30 })).toBe(
+ 'Now 2026-09-19. Newer: 2026-09-26 (51% cloud), 2026-09-24 (82% cloud), 2026-09-22 (89% cloud). '
+ + 'Pick one below to read it anyway.'
+ );
+ });
+
+ it('takes the newest pass itself when the ceiling is off', () => {
+ const pick = newestPick(lyman, { maxcc: 100 });
+ expect(pick).toEqual({ pass: lyman[0], skipped: [] });
+ expect(newestLine(pick)).toBe('Now 2026-09-26, looked up again when the run starts.');
+ });
+
+ it('steps over a pass whose cloud is unknown or that misses part of the area, as the run does', () => {
+ const pick = newestPick([
+ { date: '2026-09-26', cloud: null, coverage: 1 },
+ { date: '2026-09-24', cloud: 5, coverage: 0.6 },
+ { date: '2026-09-22', cloud: 5, coverage: 1 },
+ ], { maxcc: 30 });
+ expect(pick.pass.date).toBe('2026-09-22');
+ expect(newestLine(pick, { maxcc: 30 })).toContain('2026-09-26 (cloud unknown), 2026-09-24 (60% of the area)');
+ });
+
+ it('says so when nothing in the window will do', () => {
+ const pick = newestPick(lyman.slice(0, 3), { maxcc: 30 });
+ expect(pick.pass).toBeNull();
+ expect(newestLine(pick, { maxcc: 30 })).toBe('No pass in this window is under 30% cloud over the whole area. Pick one below.');
+ });
+
+ it('keeps a radar pick on the track the pair reads', () => {
+ const passes = [
+ { date: '2026-09-25', time: '15:11:51', coverage: 1 },
+ { date: '2026-09-22', time: '03:38:55', coverage: 1 },
+ ];
+ expect(newestPick(passes, { radar: true, track: '03:38:27' }).pass.date).toBe('2026-09-22');
+ expect(newestPick(passes, { radar: true }).pass.date).toBe('2026-09-25');
+ });
+
+ it('shortens a long run of skipped passes', () => {
+ const cloudy = Array.from({ length: 5 }, (_, day) => ({ date: `2026-09-2${9 - day}`, cloud: 90, coverage: 1 }));
+ const line = newestLine(newestPick([...cloudy, { date: '2026-09-20', cloud: 2, coverage: 1 }], { maxcc: 30 }), { maxcc: 30 });
+ expect(line).toMatch(/^Now 2026-09-20\. Newer: .* and 2 more\./);
});
});
diff --git a/frontend/src/lib/map/engine.js b/frontend/src/lib/map/engine.js
index 5276b43..44006c7 100644
--- a/frontend/src/lib/map/engine.js
+++ b/frontend/src/lib/map/engine.js
@@ -36,6 +36,8 @@ setWorkerUrl(workerUrl);
* Written here rather than fetched, which is the whole of this engine's network
* behaviour: no style URL, no glyphs, no sprite, no token and no telemetry. The
* only thing it ever asks for is a tile the analyst's own basemap choice named.
+ * A layer that writes text asks for nothing more: with no glyph URL, the engine
+ * draws each character in one of the browser's own fonts.
*/
const EMPTY_STYLE = { version: 8, sources: {}, layers: [] };
diff --git a/frontend/src/lib/map/facade.js b/frontend/src/lib/map/facade.js
index 0c8ce26..b4b8503 100644
--- a/frontend/src/lib/map/facade.js
+++ b/frontend/src/lib/map/facade.js
@@ -293,6 +293,9 @@ export function mapFacade(map, container) {
/** True while `follow` is moving this map. */
following: () => following,
+ /** True while the view moves or has tiles in flight, so a capture now would be partial. */
+ tilesLoading: () => map.isMoving() || !map.areTilesLoaded(),
+
/**
* The drawn pixels, once every visible tile is in.
*
diff --git a/frontend/src/lib/map/facade.test.js b/frontend/src/lib/map/facade.test.js
index 03d915f..10400ea 100644
--- a/frontend/src/lib/map/facade.test.js
+++ b/frontend/src/lib/map/facade.test.js
@@ -427,6 +427,18 @@ describe('capturing the drawn pixels', () => {
}
});
+ it('says whether a capture now would be partial', () => {
+ let moving = false;
+ let loaded = true;
+ const facade = mapFacade(stubMap({ isMoving: () => moving, areTilesLoaded: () => loaded }));
+ expect(facade.tilesLoading()).toBe(false);
+ loaded = false;
+ expect(facade.tilesLoading()).toBe(true);
+ loaded = true;
+ moving = true;
+ expect(facade.tilesLoading()).toBe(true);
+ });
+
it('waits for the map to go idle, and says so when it gave up', async () => {
vi.useFakeTimers();
const { map, once } = capturable({ loaded: false });
diff --git a/frontend/src/lib/map/firePoints.js b/frontend/src/lib/map/firePoints.js
new file mode 100644
index 0000000..41022fd
--- /dev/null
+++ b/frontend/src/lib/map/firePoints.js
@@ -0,0 +1,161 @@
+/**
+ * FIRMS detections, drawn by the map from vector tiles (`engine/firmspoints.py`).
+ *
+ * A picture of squares is stretched with its pixels until the next picture of
+ * the zoom lands, so every square swelled and snapped back at each level, or
+ * had to be hidden while it did. Drawn by the map, a mark keeps its size on
+ * screen through a zoom and stays where it is while the next tiles come, and
+ * grows only once the ground it stands for is bigger than it: `MARK_PX` far
+ * out, the pixel FIRMS measured close in.
+ *
+ * Every zoom and every question comes this way. Close in, the tiles carry
+ * footprints with the marks, and across `HANDOVER` the marks give way to them,
+ * each with its own ring and edge and the ground showing inside. A rolling
+ * window's come from the detections themselves; far out, and for a dated
+ * range, the backend reads the marks off FIRMS's own picture of the tile, and
+ * close in gives each one a square of the sensor's footprint.
+ */
+
+/** The shallowest zoom whose tiles carry the detections themselves, and the
+ * deepest tile there is, as the backend serves them. */
+export const POINTS_MIN_ZOOM = 8;
+export const POINTS_MAX_ZOOM = 13;
+/** The smallest a detection is drawn, on screen: the size FIRMS's pictures use. */
+export const MARK_PX = 7;
+/** Web Mercator metres under one pixel at zoom 0, on the map's 512 px world. */
+const METRES_PER_PX_AT_ZERO = (2 * 20037508.342789244) / 512;
+/** The zooms over which the marks fade out and the footprints in. */
+export const HANDOVER = [11.5, 12];
+/** The deepest zoom a mark's size is worked out for; it is gone by then. */
+const LAST_SIZED_ZOOM = 14;
+
+/** The colours of `engine/firms.py`: FIRMS's "24 h" red over the rest in amber. */
+const RECENT = '#ff3000';
+const EARLIER = '#ffba00';
+const RING = 'rgba(24, 12, 6, 0.86)';
+const RING_PX = 2;
+const colour = ['case', ['==', ['get', 'recent'], 1], RECENT, EARLIER];
+
+/** The one image the marks are drawn with, tinted to either colour. */
+export const SQUARE = 'firms-square';
+
+/**
+ * The tiles' format, in their address. The browser keeps a past range's tiles
+ * for hours, so after a change to what a tile carries the old ones would come
+ * back from its cache beside the new. Raise it with any such change.
+ */
+export const TILE_REVISION = '2';
+
+/** Where the tiles of one question are asked: its sensor and window, and a
+ * dated range's days (`firms.js` `tileParams`). */
+export function marksUrl(params = {}) {
+ return `/api/firms/points/{z}/{x}/{y}?${new URLSearchParams({ ...params, v: TILE_REVISION })}`;
+}
+
+/**
+ * How big a mark is drawn, as an `icon-size`: its footprint on screen, never
+ * under `MARK_PX`. `side` is the footprint's side in Mercator metres, so its
+ * pixels double with every zoom. A stop every half zoom keeps that exact, and
+ * the bend where the footprint outgrows the mark within a tenth of a pixel.
+ */
+export function markSize() {
+ const stops = [];
+ for (let zoom = 0; zoom <= LAST_SIZED_ZOOM; zoom += 0.5) {
+ stops.push(zoom, ['max', 1, ['*', ['get', 'side'], 2 ** zoom / METRES_PER_PX_AT_ZERO / MARK_PX]]);
+ }
+ return ['interpolate', ['exponential', 2], ['zoom'], ...stops];
+}
+
+const fadeIn = (top) => ['interpolate', ['linear'], ['zoom'], HANDOVER[0], 0, HANDOVER[1], top];
+
+/**
+ * The style: footprints under the marks, which fade out over them where a
+ * footprint came with the mark (`foot`), and stay where none did.
+ *
+ * A footprint's ring sits just outside it and its edge just inside, both
+ * offsets from a ring the tile writes clockwise, which is outward to the left.
+ * Every fill is drawn before any edge, so an edge under another square still
+ * shows. Red is drawn over amber in each layer.
+ */
+export const POINT_LAYERS = [
+ {
+ id: 'foot-fill',
+ type: 'fill',
+ source: 'marks',
+ 'source-layer': 'footprints',
+ minzoom: HANDOVER[0],
+ layout: { 'fill-sort-key': ['get', 'recent'] },
+ paint: { 'fill-color': colour, 'fill-opacity': fadeIn(0.35), 'fill-antialias': false },
+ },
+ {
+ id: 'foot-ring',
+ type: 'line',
+ source: 'marks',
+ 'source-layer': 'footprints',
+ minzoom: HANDOVER[0],
+ paint: { 'line-color': RING, 'line-width': RING_PX, 'line-offset': -RING_PX / 2, 'line-opacity': fadeIn(1) },
+ },
+ {
+ id: 'foot-edge',
+ type: 'line',
+ source: 'marks',
+ 'source-layer': 'footprints',
+ minzoom: HANDOVER[0],
+ layout: { 'line-sort-key': ['get', 'recent'] },
+ paint: { 'line-color': colour, 'line-width': 2, 'line-offset': 1, 'line-opacity': fadeIn(1) },
+ },
+ {
+ id: 'mark',
+ type: 'symbol',
+ source: 'marks',
+ 'source-layer': 'marks',
+ layout: {
+ 'icon-image': SQUARE,
+ 'icon-size': markSize(),
+ // every detection is drawn: a fire hidden behind another is still a fire
+ 'icon-allow-overlap': true,
+ 'icon-ignore-placement': true,
+ // squares of ground, so they turn and tilt with it
+ 'icon-rotation-alignment': 'map',
+ 'icon-pitch-alignment': 'map',
+ 'symbol-sort-key': ['get', 'recent'],
+ },
+ paint: {
+ 'icon-color': colour,
+ 'icon-halo-color': RING,
+ 'icon-halo-width': RING_PX,
+ 'icon-opacity': ['interpolate', ['linear'], ['zoom'],
+ HANDOVER[0], 1, HANDOVER[1], ['case', ['==', ['get', 'foot'], 1], 0, 1]],
+ },
+ },
+];
+
+/**
+ * The square as a signed distance field: MapLibre reads alpha 0.75 as the
+ * edge and an eighth less per pixel outwards, which is what lets one image take
+ * either colour and a ring (`icon-halo-*`) of any width up to `spread`.
+ */
+export function squareImage(side = MARK_PX, spread = 4) {
+ const size = side + 2 * spread;
+ const data = new Uint8ClampedArray(size * size * 4);
+ const half = side / 2;
+ for (let y = 0; y < size; y += 1) {
+ for (let x = 0; x < size; x += 1) {
+ const qx = Math.abs(x + 0.5 - size / 2) - half;
+ const qy = Math.abs(y + 0.5 - size / 2) - half;
+ const distance = Math.hypot(Math.max(qx, 0), Math.max(qy, 0)) + Math.min(Math.max(qx, qy), 0);
+ const at = (y * size + x) * 4;
+ data[at] = data[at + 1] = data[at + 2] = 255;
+ data[at + 3] = Math.round(Math.min(1, Math.max(0, 0.75 - distance / 8)) * 255);
+ }
+ }
+ return { width: size, height: size, data };
+}
+
+/** The FIRMS overlay's vector style (`basemap.js`): one source, asked the question. */
+export const FIRE_MARKS = {
+ sources: (params) => ({ marks: marksUrl(params) }),
+ maxZoom: POINTS_MAX_ZOOM,
+ layers: POINT_LAYERS,
+ images: [[SQUARE, squareImage, { sdf: true }]],
+};
diff --git a/frontend/src/lib/map/firePoints.test.js b/frontend/src/lib/map/firePoints.test.js
new file mode 100644
index 0000000..040d987
--- /dev/null
+++ b/frontend/src/lib/map/firePoints.test.js
@@ -0,0 +1,105 @@
+import { describe, expect, it } from 'vitest';
+import {
+ FIRE_MARKS, HANDOVER, MARK_PX, POINT_LAYERS, POINTS_MAX_ZOOM, POINTS_MIN_ZOOM, SQUARE,
+ markSize, marksUrl, squareImage, TILE_REVISION,
+} from './firePoints.js';
+
+/** An `interpolate` expression with exponential base 2, read at one zoom for one feature. */
+function sizeAt(zoom, side) {
+ const [, [, base], , ...stops] = markSize();
+ const at = (i) => {
+ const [, floor, [, [, ], ratio]] = stops[i + 1];
+ return Math.max(floor, side * ratio);
+ };
+ for (let i = 0; i < stops.length - 2; i += 2) {
+ const [z0, z1] = [stops[i], stops[i + 2]];
+ if (zoom >= z0 && zoom <= z1) {
+ const t = (base ** (zoom - z0) - 1) / (base ** (z1 - z0) - 1);
+ return at(i) + (at(i + 2) - at(i)) * t;
+ }
+ }
+ return at(stops.length - 2);
+}
+
+describe('FIRMS marks, drawn by the map', () => {
+ it('asks the app for one question, where the key stays', () => {
+ expect(marksUrl({ sensor: 'modis', window: '48h' })).toBe('/api/firms/points/{z}/{x}/{y}?sensor=modis&window=48h&v=2');
+ // a dated range is asked with its days, the same tiles at every zoom
+ expect(marksUrl({ sensor: 'viirs', window: 'dates', first: '2026-09-01', last: '2026-09-03' }))
+ .toBe('/api/firms/points/{z}/{x}/{y}?sensor=viirs&window=dates&first=2026-09-01&last=2026-09-03&v=2');
+ expect(FIRE_MARKS.sources({ sensor: 'viirs', window: '24h' })).toEqual({
+ marks: '/api/firms/points/{z}/{x}/{y}?sensor=viirs&window=24h&v=2',
+ });
+ expect(POINT_LAYERS.every((layer) => layer.source === 'marks')).toBe(true);
+ });
+
+ it('names the tile format in the address, so a cached tile of an older one is not reused', () => {
+ expect(new URL(marksUrl({ sensor: 'viirs', window: 'dates' }), 'http://x').searchParams.get('v'))
+ .toBe(TILE_REVISION);
+ });
+
+ it('asks the zooms the backend serves', () => {
+ expect([POINTS_MIN_ZOOM, POINTS_MAX_ZOOM]).toEqual([8, 13]);
+ });
+
+ it('keeps a mark the same size on screen until its footprint is bigger', () => {
+ // a 375 m VIIRS pixel is a speck far out, at z8 and at z10: all the 7 px mark
+ expect(sizeAt(3, 375) * MARK_PX).toBeCloseTo(MARK_PX);
+ expect(sizeAt(8, 375) * MARK_PX).toBeCloseTo(MARK_PX);
+ expect(sizeAt(10, 375) * MARK_PX).toBeCloseTo(MARK_PX);
+ // where it outgrows the mark, it grows from there and no sooner
+ expect(Math.abs(sizeAt(10.6, 375) * MARK_PX - (375 * 2 ** 10.6) / 78271.517)).toBeLessThan(0.1);
+ // then it is the ground: 375 m is 19.6 px at z12 on the 512 px world
+ expect(sizeAt(12, 375) * MARK_PX).toBeCloseTo((375 * 2 ** 12) / 78271.517, 1);
+ // and doubles with each zoom, never jumping between two levels
+ const steps = [11, 11.25, 11.5, 11.75, 12].map((zoom) => sizeAt(zoom, 375));
+ for (let i = 1; i < steps.length; i += 1) expect(steps[i] / steps[i - 1]).toBeCloseTo(2 ** 0.25, 2);
+ });
+
+ it('hands a mark over to its footprint across one half zoom, and keeps one that has none', () => {
+ const byId = Object.fromEntries(POINT_LAYERS.map((layer) => [layer.id, layer]));
+ expect(byId.mark.paint['icon-opacity']).toEqual(['interpolate', ['linear'], ['zoom'],
+ HANDOVER[0], 1, HANDOVER[1], ['case', ['==', ['get', 'foot'], 1], 0, 1]]);
+ expect(byId['foot-fill'].paint['fill-opacity']).toEqual(['interpolate', ['linear'], ['zoom'], HANDOVER[0], 0, HANDOVER[1], 0.35]);
+ expect(byId['foot-edge'].paint['line-opacity'].slice(-2)).toEqual([HANDOVER[1], 1]);
+ // a mark read off a picture has no footprint to give way to, so it is drawn at every zoom
+ expect(byId.mark.maxzoom).toBeUndefined();
+ for (const id of ['foot-fill', 'foot-ring', 'foot-edge']) expect(byId[id].minzoom).toBe(HANDOVER[0]);
+ });
+
+ it('draws every detection, red over amber, lying on the ground', () => {
+ const mark = POINT_LAYERS.find((layer) => layer.id === 'mark');
+ expect(mark.layout).toMatchObject({
+ 'icon-image': SQUARE,
+ 'icon-allow-overlap': true,
+ 'icon-ignore-placement': true,
+ 'icon-rotation-alignment': 'map',
+ 'icon-pitch-alignment': 'map',
+ 'symbol-sort-key': ['get', 'recent'],
+ });
+ expect(mark.paint['icon-halo-width']).toBe(2);
+ // footprints under the marks, fills under every edge
+ expect(POINT_LAYERS.map((layer) => layer.id)).toEqual(['foot-fill', 'foot-ring', 'foot-edge', 'mark']);
+ const ring = POINT_LAYERS.find((layer) => layer.id === 'foot-ring');
+ const edge = POINT_LAYERS.find((layer) => layer.id === 'foot-edge');
+ // the ring just outside a clockwise outline, the edge just inside it
+ expect(ring.paint['line-offset']).toBeLessThan(0);
+ expect(edge.paint['line-offset']).toBeGreaterThan(0);
+ });
+
+ it('writes the square as the distance field MapLibre reads', () => {
+ const { width, height, data } = squareImage();
+ expect([width, height]).toEqual([15, 15]);
+ const alpha = (x, y) => data[(y * width + x) * 4 + 3] / 255;
+ // solid inside, 0.75 on the edge, falling an eighth a pixel outwards
+ expect(alpha(7, 7)).toBe(1);
+ expect(alpha(4, 7)).toBeCloseTo(0.75 + 0.5 / 8, 2);
+ expect(alpha(3, 7)).toBeCloseTo(0.75 - 0.5 / 8, 2);
+ expect(alpha(1, 7)).toBeCloseTo(0.75 - 2.5 / 8, 2);
+ // a 2 px ring has room: the field still falls at the image's border
+ expect(alpha(0, 7)).toBeGreaterThan(0);
+ // square, so the same on every side
+ expect(alpha(7, 3)).toBe(alpha(3, 7));
+ expect(alpha(11, 7)).toBe(alpha(3, 7));
+ });
+});
diff --git a/frontend/src/lib/map/firms.js b/frontend/src/lib/map/firms.js
index 0738319..7646bdb 100644
--- a/frontend/src/lib/map/firms.js
+++ b/frontend/src/lib/map/firms.js
@@ -91,3 +91,48 @@ export function summary({ sensor, window, first, last } = {}, sensors = []) {
const end = asDay(last);
return [short, end && end !== start ? `${start} → ${end}` : start].filter(Boolean).join(' · ');
}
+
+/**
+ * What the Layers row says about the key, from `/api/firms/sensors`.
+ *
+ * `keyed` alone said "needs a free key" for three different things. Each now
+ * has its own word and its own way out: no key, a key switched off in
+ * Settings, and a key FIRMS said it does not know. A spent allowance is none
+ * of these, and the layer stays on (`firmsNote`).
+ */
+const KEY_STATES = {
+ missing: { detail: 'needs a free key', title: 'Add a NASA FIRMS key in Settings → Imagery', action: 'Add a FIRMS key' },
+ off: { detail: 'off in Settings', title: 'Switched off in Settings → Imagery', action: 'Turn it on' },
+ refused: { detail: 'key refused', title: 'FIRMS does not know this key. Test it in Settings → Imagery', action: 'Check the key' },
+};
+
+export function keyState({ keyed, state } = {}) {
+ if (keyed) return { usable: true, detail: '', title: '', action: '' };
+ return { usable: false, ...(KEY_STATES[state] ?? KEY_STATES.missing) };
+}
+
+/** A dated range longer than this spends the allowance in a few screens. */
+export const LONG_RANGE_DAYS = 7;
+
+function rangeDays({ first, last } = {}) {
+ const start = asDay(first);
+ if (!start) return 0;
+ const end = asDay(last) || start;
+ return Math.round((Date.parse(`${end}T00:00:00Z`) - Date.parse(`${start}T00:00:00Z`)) / 86_400_000) + 1;
+}
+
+/**
+ * The one sentence the row carries under its controls, or ''.
+ *
+ * In order: the layer paused on a spent allowance, a dated question with no
+ * date yet, a range long enough to spend the allowance, and what the two
+ * colours of a window longer than a day mean.
+ */
+export function firmsNote(choice = {}, paused = null) {
+ if (paused) return 'FIRMS allowance used up. It refills within ten minutes.';
+ if (!askable(choice)) return choice.window === DATED ? 'Pick a date to draw the detections.' : '';
+ if (choice.window === DATED) {
+ return rangeDays(choice) > LONG_RANGE_DAYS ? 'A long range spends the FIRMS allowance in a few screens.' : '';
+ }
+ return choice.window === '24h' ? '' : 'Red: the last 24 hours. Amber: before them.';
+}
diff --git a/frontend/src/lib/map/firms.test.js b/frontend/src/lib/map/firms.test.js
index a858afa..3c143e7 100644
--- a/frontend/src/lib/map/firms.test.js
+++ b/frontend/src/lib/map/firms.test.js
@@ -1,6 +1,8 @@
import { describe, expect, it } from 'vitest';
import {
askable,
+ firmsNote,
+ keyState,
DATED,
lastDayOf,
MAX_RANGE_DAYS,
@@ -11,7 +13,7 @@ import {
} from './firms.js';
const SENSORS = [
- { id: 'viirs', label: 'VIIRS (S-NPP + NOAA-20)' },
+ { id: 'viirs', label: 'VIIRS (S-NPP, NOAA-20, NOAA-21)' },
{ id: 'modis', label: 'MODIS (Terra + Aqua)' },
];
@@ -87,7 +89,7 @@ describe('what the service will answer', () => {
describe('what the row says it is showing', () => {
it('names the instrument without the satellites it is made of', () => {
- // "VIIRS (S-NPP + NOAA-20) · 24 h" does not fit a layer row
+ // "VIIRS (S-NPP, NOAA-20, NOAA-21) · 24 h" does not fit a layer row
expect(summary({ sensor: 'viirs', window: '24h' }, SENSORS)).toBe('VIIRS · 24 h');
});
@@ -104,3 +106,42 @@ describe('what the row says it is showing', () => {
expect(summary({ sensor: 'viirs', window: DATED }, SENSORS)).toBe('VIIRS · pick a date');
});
});
+
+describe('what the row says about the key', () => {
+ it('lets a usable key through without a word', () => {
+ expect(keyState({ keyed: true, state: 'ready' })).toEqual({ usable: true, detail: '', title: '', action: '' });
+ });
+
+ it('tells a missing key from one switched off and one FIRMS refused', () => {
+ expect(keyState({ keyed: false, state: 'missing' }).detail).toBe('needs a free key');
+ expect(keyState({ keyed: false, state: 'off' })).toMatchObject({ usable: false, detail: 'off in Settings', action: 'Turn it on' });
+ expect(keyState({ keyed: false, state: 'refused' })).toMatchObject({ detail: 'key refused', action: 'Check the key' });
+ });
+
+ it('reads an answer without a state as no key', () => {
+ expect(keyState({}).detail).toBe('needs a free key');
+ expect(keyState(undefined).usable).toBe(false);
+ });
+});
+
+describe('the note under the controls', () => {
+ it('puts a paused layer first, whatever else is true', () => {
+ expect(firmsNote({ window: DATED }, { until: '2026-09-26T12:00:00+00:00' })).toMatch(/allowance used up/);
+ });
+
+ it('asks for a date before anything else', () => {
+ expect(firmsNote({ window: DATED })).toBe('Pick a date to draw the detections.');
+ });
+
+ it('warns about a long range and says nothing about a short one', () => {
+ expect(firmsNote({ window: DATED, first: '2026-08-01', last: '2026-08-31' })).toMatch(/long range/);
+ expect(firmsNote({ window: DATED, first: '2026-08-01', last: '2026-08-07' })).toBe('');
+ expect(firmsNote({ window: DATED, first: '2026-08-01' })).toBe('');
+ });
+
+ it('explains the two colours of a window longer than a day', () => {
+ expect(firmsNote({ window: '7d' })).toBe('Red: the last 24 hours. Amber: before them.');
+ expect(firmsNote({ window: '48h' })).toMatch(/Red/);
+ expect(firmsNote({ window: '24h' })).toBe('');
+ });
+});
diff --git a/frontend/src/lib/map/infrastructure.js b/frontend/src/lib/map/infrastructure.js
index 27a0310..a234b90 100644
--- a/frontend/src/lib/map/infrastructure.js
+++ b/frontend/src/lib/map/infrastructure.js
@@ -10,9 +10,8 @@
*
* The style is ours and deliberately small: lines coloured by voltage on Open
* Infrastructure Map's own scale, so a reader who knows that map reads this one,
- * then towers, substations, plants, pipelines and masts. No labels, because
- * the engine loads no glyphs (`engine.js` asks the network for tiles and
- * nothing else). Zooms here are the engine's own, one shallower than the app's.
+ * then towers, substations, plants, pipelines and masts, with no labels. Zooms
+ * here are the engine's own, one shallower than the app's.
*/
const TILES = 'https://openinframap.org/map';
diff --git a/frontend/src/lib/map/placeNames.js b/frontend/src/lib/map/placeNames.js
new file mode 100644
index 0000000..d9ac749
--- /dev/null
+++ b/frontend/src/lib/map/placeNames.js
@@ -0,0 +1,81 @@
+/**
+ * Town, village and hamlet names, drawn from OpenFreeMap's vector tiles.
+ *
+ * Esri's borders name countries, regions and cities, and little under them
+ * wherever its own data is thin: a valley in Yemen reads blank at zoom 13 while
+ * OpenStreetMap holds a name for every hamlet in it. OpenFreeMap serves that
+ * data as OpenMapTiles vector tiles, free, key-less and with no request quota,
+ * and this style reads only its `place` layer.
+ *
+ * The tile paths carry the date of the weekly build and the old build is
+ * removed once a new one lands, so the source is the TileJSON that names the
+ * current one rather than a template.
+ *
+ * Cities and anything larger are left to the borders, which already name them:
+ * both on at once would draw each city twice. What is drawn is `name:latin`,
+ * the name as written when it is Latin and a transliteration otherwise. An
+ * Arabic or Cyrillic name would need the engine's right-to-left plugin, and
+ * none of it is loaded.
+ *
+ * The text is drawn by the browser, in the app's own face: with no glyph URL
+ * the engine renders each character locally, so switching this on fetches
+ * tiles and nothing else. Zooms here are the engine's own, one shallower than
+ * the app's.
+ */
+
+/** Settlement kinds from largest to smallest, which is also who wins a collision. */
+export const PLACE_CLASSES = [
+ 'town',
+ 'village',
+ 'suburb',
+ 'quarter',
+ 'hamlet',
+ 'neighbourhood',
+ 'isolated_dwelling',
+];
+
+const CLASS = ['get', 'class'];
+
+/** The app's sans-serif stack (`--font-sans`), which the engine hands to the browser. */
+const FONT = ['ui-sans-serif', 'system-ui', 'sans-serif'];
+
+export const PLACE_NAMES = {
+ sources: { openmaptiles: { url: 'https://tiles.openfreemap.org/planet' } },
+ maxZoom: 14,
+ layers: [
+ {
+ id: 'label',
+ type: 'symbol',
+ source: 'openmaptiles',
+ 'source-layer': 'place',
+ filter: ['all', ['in', CLASS, ['literal', PLACE_CLASSES]], ['has', 'name:latin']],
+ layout: {
+ 'text-field': ['get', 'name:latin'],
+ 'text-font': FONT,
+ 'text-size': [
+ 'interpolate',
+ ['linear'],
+ ['zoom'],
+ 9,
+ ['match', CLASS, 'town', 12, 'village', 11, 10],
+ 14,
+ ['match', CLASS, 'town', 15, 'village', 14, 12],
+ ],
+ 'text-max-width': 8,
+ 'text-padding': 3,
+ // the list's order, then OSM's own rank inside a kind
+ 'symbol-sort-key': [
+ '+',
+ ['*', 100, ['index-of', CLASS, ['literal', PLACE_CLASSES]]],
+ ['coalesce', ['get', 'rank'], 50],
+ ],
+ },
+ paint: {
+ 'text-color': ['match', CLASS, ['town', 'village'], '#ffffff', '#e2e2e2'],
+ 'text-halo-color': 'rgba(0, 0, 0, 0.85)',
+ 'text-halo-width': 1.4,
+ 'text-halo-blur': 0.4,
+ },
+ },
+ ],
+};
diff --git a/frontend/src/lib/map/placeNames.test.js b/frontend/src/lib/map/placeNames.test.js
new file mode 100644
index 0000000..46d9362
--- /dev/null
+++ b/frontend/src/lib/map/placeNames.test.js
@@ -0,0 +1,69 @@
+import { describe, expect, it } from 'vitest';
+// The engine's own validator and expression evaluator, which ship inside
+// maplibre-gl, so what is asserted is what the engine will do with the style.
+import { createExpression, featureFilter, validateStyleMin } from '@maplibre/maplibre-gl-style-spec';
+import { PLACE_CLASSES, PLACE_NAMES } from './placeNames.js';
+
+const [LABEL] = PLACE_NAMES.layers;
+
+/** A place point as OpenFreeMap's `place` layer serves it. */
+function place(properties) {
+ return { type: 1, properties };
+}
+
+const QUSHAYHI = place({ class: 'village', name: 'قشيحي', 'name:latin': 'Qushayhi', rank: 12 });
+const SAMKAR = place({ class: 'hamlet', name: 'السمكر', 'name:latin': 'As Samkar', rank: 3 });
+const TAIZZ = place({ class: 'city', name: 'تعز', 'name:latin': 'Taizz', rank: 4 });
+
+const shown = (feature, zoom = 12) =>
+ featureFilter(LABEL.filter, 'layers[0].filter').filter({ zoom }, feature);
+const evaluate = (key, feature, zoom = 12) =>
+ createExpression(LABEL.layout[key], `layers[0].layout.${key}`).value.evaluate({ zoom }, feature);
+
+describe('the place names style', () => {
+ it('is one the engine accepts with no glyph URL at all', () => {
+ // the engine draws the characters itself when the style names no glyphs,
+ // so a text layer costs no request beyond its tiles
+ const style = {
+ version: 8,
+ sources: { openmaptiles: { type: 'vector', ...PLACE_NAMES.sources.openmaptiles, maxzoom: PLACE_NAMES.maxZoom } },
+ layers: PLACE_NAMES.layers,
+ };
+ expect(style).not.toHaveProperty('glyphs');
+ expect(validateStyleMin(style)).toEqual([]);
+ });
+
+ it('reads the current build from OpenFreeMap’s TileJSON, over https', () => {
+ // the tile paths carry the build date, and an old build is removed
+ expect(PLACE_NAMES.sources).toEqual({ openmaptiles: { url: 'https://tiles.openfreemap.org/planet' } });
+ expect(LABEL['source-layer']).toBe('place');
+ expect(PLACE_NAMES.maxZoom).toBe(14);
+ });
+
+ it('names villages and hamlets and leaves cities to the borders', () => {
+ expect(shown(QUSHAYHI)).toBe(true);
+ expect(shown(SAMKAR)).toBe(true);
+ expect(shown(TAIZZ)).toBe(false);
+ expect(shown(place({ class: 'country', 'name:latin': 'Yemen' }))).toBe(false);
+ });
+
+ it('writes the Latin name, never the Arabic one the engine could not join up', () => {
+ expect(evaluate('text-field', QUSHAYHI)).toBe('Qushayhi');
+ expect(shown(place({ class: 'village', name: 'قرية' }))).toBe(false);
+ });
+
+ it('keeps the larger place when two names collide', () => {
+ // a lower key is placed first, and a label placed first is the one kept
+ const key = (feature) => evaluate('symbol-sort-key', feature);
+ const town = place({ class: 'town', 'name:latin': 'Al Qaidah', rank: 40 });
+ expect(key(town)).toBeLessThan(key(QUSHAYHI));
+ // a hamlet with a better rank still yields to a village
+ expect(key(QUSHAYHI)).toBeLessThan(key(SAMKAR));
+ expect(PLACE_CLASSES.slice(0, 2)).toEqual(['town', 'village']);
+ });
+
+ it('writes a village larger than a hamlet', () => {
+ const size = (feature) => evaluate('text-size', feature, 13);
+ expect(size(QUSHAYHI)).toBeGreaterThan(size(SAMKAR));
+ });
+});
diff --git a/frontend/src/lib/navigate.js b/frontend/src/lib/navigate.js
index 2ddcf73..881499d 100644
--- a/frontend/src/lib/navigate.js
+++ b/frontend/src/lib/navigate.js
@@ -209,7 +209,7 @@ export function gotoPoint(lat, lon) {
*
* The right-click menu's Open in…: Satellite flies there, Compare and Detect
* move their camera and keep their own pictures and work. A fullscreen map is
- * left first, or the tab it hands over to would open behind it.
+ * left on the way, as every change of tool leaves it (App.svelte).
*/
export function openMapAt(tool, { lat, lon, zoom }) {
if (!Number.isFinite(lat) || !Number.isFinite(lon)) return;
@@ -217,7 +217,6 @@ export function openMapAt(tool, { lat, lon, zoom }) {
if (tool === 'satellite') uiState.gotoCoords = at;
else if (tool === 'compare' || tool === 'detect') uiState.lookAt = { tool, ...at };
else return;
- if (globalThis.document?.fullscreenElement) void document.exitFullscreen?.().catch(() => {});
uiState.tool = tool;
}
diff --git a/frontend/src/lib/state.svelte.js b/frontend/src/lib/state.svelte.js
index cedadee..51e23df 100644
--- a/frontend/src/lib/state.svelte.js
+++ b/frontend/src/lib/state.svelte.js
@@ -24,7 +24,7 @@ export const prefs = $state({
units: 'metric', // 'metric' | 'imperial'
homeView: { lat: 43, lon: 25, zoom: 3 }, // where Satellite opens
mapSync: true, // Satellite, Compare and Detect share one camera
- detectView: { collapsed: false, basemap: 'esri-world-imagery', overlays: ['boundaries'], saved: true },
+ detectView: { collapsed: false, basemap: 'esri-world-imagery', overlays: ['boundaries', 'placenames'], saved: true },
captureScaleNorth: false, // burn a scale bar and a north arrow into captures
postMention: '@GeoConfirmed', // handle a fresh post draft is addressed to
postTarget: 'x', // social composer a fresh post draft starts with
diff --git a/frontend/src/tools/Compare.render.test.js b/frontend/src/tools/Compare.render.test.js
index 7aee0f7..ec29f15 100644
--- a/frontend/src/tools/Compare.render.test.js
+++ b/frontend/src/tools/Compare.render.test.js
@@ -1,6 +1,7 @@
// @vitest-environment happy-dom
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { flushSync, mount, unmount } from 'svelte';
+import { fakeScreen } from '../lib/fullscreen.fixture.js';
const PROVIDERS = [
{
@@ -76,7 +77,7 @@ const get = vi.fn(async (path) => {
return {
keyed: true,
sensors: [
- { id: 'viirs', label: 'VIIRS (S-NPP + NOAA-20)' },
+ { id: 'viirs', label: 'VIIRS (S-NPP, NOAA-20, NOAA-21)' },
{ id: 'modis', label: 'MODIS (Terra + Aqua)' },
],
};
@@ -201,6 +202,10 @@ const drawPictures = vi.fn(async ({ entries, variantFor, onpicture, onprogress }
const composeEvolutionFrame = vi.fn(() => pictureCanvas());
const composeEvolutionSheet = vi.fn(() => pictureCanvas());
vi.mock('../lib/map/evolutionExport.js', () => ({ drawPictures, composeEvolutionFrame, composeEvolutionSheet }));
+// A reading's pixel work needs a real canvas, so a test hands back what one
+// would have found. Untouched, a reading never gets this far here.
+const detectCaptures = vi.fn(async () => { throw new Error('no pixels in this double'); });
+vi.mock('../lib/map/changeCapture.js', () => ({ detectCaptures }));
const { default: Compare } = await import('./Compare.svelte');
@@ -236,6 +241,11 @@ function button(label, root = document) {
return [...root.querySelectorAll('button')].find((entry) => entry.textContent.trim().includes(label));
}
+/** The toolbar's Save, which "Saved" layers and the like would also match. */
+function saveButton() {
+ return [...target.querySelectorAll('.tool-header button')].find((entry) => entry.textContent.trim() === 'Save');
+}
+
/** Start over from the New menu, on one of its presets. */
async function startNew(label = 'Then and now') {
button('New', target).click();
@@ -245,7 +255,8 @@ async function startNew(label = 'Then and now') {
await settle();
}
-async function add(slot, provider = 'Esri World Imagery') {
+/** Most tests here draw, so the rail opens once the pair is whole. */
+async function add(slot, provider = 'Esri World Imagery', { unfold = true } = {}) {
const empty = [...target.querySelectorAll('.empty-slot')].find(
(entry) => entry.querySelector('.slot-letter').textContent === slot
);
@@ -256,6 +267,10 @@ async function add(slot, provider = 'Esri World Imagery') {
.click();
flushSync();
await settle();
+ if (unfold) {
+ target.querySelector('.annotation-rail.folded .rail-strip')?.click();
+ flushSync();
+ }
}
beforeEach(() => {
@@ -294,12 +309,14 @@ describe('Compare', () => {
} finally {
vi.useRealTimers();
}
- expect(target.querySelector('h2').textContent).toBe('Compare');
+ // a pair on screen: the reading modes take the title's place in the one row
+ expect(target.querySelector('h2')).toBeNull();
+ expect(target.querySelector('.tool-header .mode-dock')).not.toBeNull();
expect(target.querySelectorAll('.empty-slot')).toHaveLength(0);
expect(target.querySelectorAll('.surface-shell')).toHaveLength(2);
expect(target.querySelectorAll('.presets')).toHaveLength(0);
const saved = () => post.mock.calls.find(([path]) => path === '/api/cases/case-a/compare/sessions')?.[1];
- button('Save comparison', target).click();
+ saveButton().click();
flushSync();
button('Save comparison', document.querySelector('[role="dialog"]')).click();
await settle();
@@ -313,7 +330,7 @@ describe('Compare', () => {
// no release list: a Wayback A would be World Imagery again
await openFresh();
expect(target.querySelectorAll('.surface-shell')).toHaveLength(1);
- expect(target.querySelector('.surface-label strong').textContent).toBe('B');
+ expect(target.querySelector('.source-card .cmp-letter').textContent).toBe('B');
expect(target.querySelectorAll('.empty-slot')).toHaveLength(1);
});
@@ -323,9 +340,8 @@ describe('Compare', () => {
engines[0].handlers['view-settled']?.({ lat: 40, lon: 3, zoom: 12 });
flushSync();
expect(target.querySelector('.badge')).toBeNull();
- expect(button('Discard', target).disabled).toBe(true);
// …while Save still takes it, a pair at a place being worth keeping
- expect(button('Save comparison', target).disabled).toBe(false);
+ expect(saveButton().disabled).toBe(false);
await startNew();
expect(document.querySelector('[role="alertdialog"]')).toBeNull();
});
@@ -350,17 +366,26 @@ describe('Compare', () => {
expect(engines[1].camera()).toEqual(engines[0].camera());
expect(target.querySelectorAll('.source-card')).toHaveLength(2);
expect(target.querySelectorAll('.source-card button[aria-label="Imagery provider"]')).toHaveLength(2);
- expect(
- target.querySelector('.compare-bar').compareDocumentPosition(target.querySelector('.source-bar')) &
- Node.DOCUMENT_POSITION_FOLLOWING
- ).toBeTruthy();
- // The cards are as wide as the maps they describe, so the seam between A and
- // B is one line: the annotation rail beside the stage narrows both together.
+ // One row above the maps: the modes, the name and the acts share it, and
+ // no bar is left between that row and the stage.
+ const header = target.querySelector('.tool-header');
+ expect(header.querySelector('.mode-dock')).not.toBeNull();
+ expect(button('All dates', header)).toBeTruthy();
+ expect(button('Export', header)).toBeTruthy();
+ expect(target.querySelector('.compare-bar')).toBeNull();
+ // The cards float over the maps they describe, one column per pane, so the
+ // seam between A and B is one line: the annotation rail beside the stage
+ // narrows both together.
const column = target.querySelector('.stage-column');
- expect(target.querySelector('.source-bar').parentElement).toBe(column);
- expect(target.querySelector('.compare-stage').parentElement).toBe(column);
- expect(target.querySelector('.annotation-toolbar').parentElement).toBe(column.parentElement);
- // One camera, so one compass in the bar and none on either surface.
+ const stage = target.querySelector('.compare-stage');
+ expect(target.querySelector('.source-bar').parentElement).toBe(stage);
+ expect(stage.parentElement).toBe(column);
+ expect(target.querySelector('.annotation-rail').parentElement).toBe(column.parentElement);
+ // The place search and the camera ride over the maps, in B's corner.
+ const view = target.querySelector('.source-b .view-col');
+ expect(view.querySelector('.place-search')).not.toBeNull();
+ expect(view.querySelector('.camera-readout')).not.toBeNull();
+ // One camera, so one compass over the stage and none on either surface.
expect(target.querySelectorAll('button[aria-label="Reset to north"]')).toHaveLength(1);
expect(target.querySelector('.surface-shell button[aria-label="Reset to north"]')).toBeNull();
// local-first: Wayback names its releases once it is on screen, but nothing
@@ -435,7 +460,11 @@ describe('Compare', () => {
const footer = target.querySelector('.mode-footer');
expect(footer.querySelector('input[aria-label="Swipe position"]')).not.toBeNull();
expect(footer.querySelector('.difference-bar')).not.toBeNull();
- expect(target.querySelector('.change-legend')).not.toBeNull();
+ const legend = target.querySelector('.change-legend');
+ expect(legend).not.toBeNull();
+ // The legend's swatches are the overlay's own colours, whatever the palette.
+ expect(legend.style.getPropertyValue('--gain')).toBe('rgb(0,229,255)');
+ expect(legend.style.getPropertyValue('--loss')).toBe('rgb(255,0,170)');
// Over both images unless asked otherwise.
const base = (label) => [...target.querySelectorAll('[aria-label="Image under the highlights"] button')]
.find((entry) => entry.textContent.trim() === label);
@@ -454,6 +483,127 @@ describe('Compare', () => {
expect(button('Blink', target).getAttribute('aria-pressed')).toBe('true');
});
+ it('waits out loading tiles, says when a reading is up to date, and drains one the view moved past', async () => {
+ releases = [{ release: 30, date: '2026-09-01' }, { release: 20, date: '2025-09-01' }];
+ await open();
+ await add('A');
+ await add('B', 'Esri Wayback');
+ const pair = engines.slice(-2);
+ let loaded;
+ const tilesIn = new Promise((resolve) => (loaded = resolve));
+ let loading = true;
+ for (const engine of pair) {
+ engine.tilesLoading = () => loading;
+ engine.snapshot.mockImplementation(async () => { await tilesIn; return { canvas: {}, complete: true }; });
+ }
+ // A's first capture gives up with tiles still out, as the engine's wait does.
+ pair[0].snapshot.mockImplementationOnce(async () => ({ canvas: {}, complete: false }));
+ detectCaptures.mockImplementationOnce(async (sources) => ({
+ counts: { gained: 1, lost: 1, changed: 0, quiet: 8 }, zones: [], zoneCount: 0,
+ share: 0.2, coverage: 1, area: 50, frame: sources.a.frame,
+ canvas: { toDataURL: () => 'data:image/png;base64,AA' },
+ }));
+ // Real time never passes on this bench, so the clock is stepped by hand.
+ vi.useFakeTimers();
+ const until = async (check) => {
+ for (let tries = 0; tries < 40 && !check(); tries += 1) { await vi.advanceTimersByTimeAsync(50); flushSync(); }
+ return check();
+ };
+ const read = () => target.querySelector('.difference-bar button.read');
+ const said = () => target.querySelector('.change-legend em')?.textContent.trim() ?? '';
+
+ button('Difference', target).click();
+ flushSync();
+ expect(await until(() => read().textContent.trim() === 'Loading…')).toBe(true);
+ expect(read().disabled).toBe(true);
+ expect(said()).toBe('Waiting for the tiles…');
+
+ // The tiles land: the reading carries on by itself, no "try again".
+ loading = false;
+ loaded();
+ expect(await until(() => read().textContent.trim() === 'Up to date')).toBe(true);
+ expect(read().disabled).toBe(true);
+ expect(said()).toBe('20% highlighted');
+ expect(target.querySelector('.change-map.stale')).toBeNull();
+ expect(toast).not.toHaveBeenCalledWith(expect.stringContaining('tiles'), expect.anything(), expect.anything());
+
+ // Past the held ground, a pair already read follows the camera: once it
+ // rests, the bands are fetched again, with no press of Read.
+ const found = (sources) => ({
+ counts: { gained: 1, lost: 1, changed: 0, quiet: 8 }, zones: [], zoneCount: 0,
+ share: 0.2, coverage: 1, area: 50, frame: sources.a.frame,
+ canvas: { toDataURL: () => 'data:image/png;base64,AA' },
+ });
+ const calls = () => detectCaptures.mock.calls.length;
+ const before = calls();
+ detectCaptures.mockImplementationOnce(async () => ({ needsFetch: true }));
+ detectCaptures.mockImplementationOnce(async (sources) => found(sources));
+ pair[0].handlers['view-settled']({ lat: 40, lon: 3, zoom: 12 });
+ expect(await until(() => calls() === before + 1)).toBe(true);
+ expect(detectCaptures.mock.calls[before][4]).toBe(false);
+ // resting, not waiting on the analyst
+ expect(read().textContent.trim()).toBe('Reading…');
+ expect(await until(() => read().textContent.trim() === 'Up to date')).toBe(true);
+ expect(detectCaptures.mock.calls[before + 1][4]).toBe(true);
+
+ // Something new to read past the held ground waits for Read, and says so everywhere.
+ detectCaptures.mockImplementationOnce(async () => ({ needsFetch: true }));
+ target.querySelector('button[aria-label="Difference settings"]').click();
+ flushSync();
+ button('Preserve fine changes', target).click();
+ flushSync();
+ expect(await until(() => read().textContent.trim() === 'Read' && !read().disabled)).toBe(true);
+ expect(read().classList.contains('due')).toBe(true);
+ expect(said()).toBe('20% highlighted · out of date, press Read');
+ expect(target.querySelector('.change-map').classList.contains('stale')).toBe(true);
+ const waiting = calls();
+ await vi.advanceTimersByTimeAsync(3000);
+ expect(calls()).toBe(waiting);
+ vi.useRealTimers();
+ });
+
+ it('hands an asked-for read overtaken by a move to the reading that takes over, and only that one', async () => {
+ releases = [{ release: 30, date: '2026-09-01' }, { release: 20, date: '2025-09-01' }];
+ await open();
+ await add('A');
+ await add('B', 'Esri Wayback');
+ const pair = engines.slice(-2);
+ for (const engine of pair) {
+ engine.tilesLoading = () => false;
+ engine.snapshot.mockImplementation(async () => ({ canvas: {}, complete: true }));
+ }
+ const found = (sources) => ({
+ counts: { gained: 1, lost: 0, changed: 0, quiet: 9 }, zones: [], zoneCount: 0,
+ share: 0.1, coverage: 1, area: 20, frame: sources.a.frame,
+ canvas: { toDataURL: () => 'data:image/png;base64,AA' },
+ });
+ // The first read's bands are slow to come.
+ detectCaptures.mockImplementationOnce(() => new Promise(() => {}));
+ detectCaptures.mockImplementation(async (sources) => found(sources));
+ vi.useFakeTimers();
+ const until = async (check) => {
+ for (let tries = 0; tries < 40 && !check(); tries += 1) { await vi.advanceTimersByTimeAsync(50); flushSync(); }
+ return check();
+ };
+ const read = () => target.querySelector('.difference-bar button.read');
+
+ // Turned on by hand, so it may fetch; the camera moves before it lands.
+ button('Difference', target).click();
+ flushSync();
+ expect(await until(() => detectCaptures.mock.calls.length === 1)).toBe(true);
+ expect(detectCaptures.mock.calls[0][4]).toBe(true);
+ pair[0].handlers['view-settled']({ lat: 40, lon: 3, zoom: 12 });
+ expect(await until(() => read().textContent.trim() === 'Up to date')).toBe(true);
+ // The reading that took over carried the ask: it did not stop at "press Read".
+ expect(detectCaptures.mock.calls[1][4]).toBe(true);
+
+ // Once landed, the ask is spent: a pan after it follows on what is held.
+ pair[0].handlers['view-settled']({ lat: 40.01, lon: 3, zoom: 12 });
+ expect(await until(() => detectCaptures.mock.calls.length === 3)).toBe(true);
+ expect(detectCaptures.mock.calls[2][4]).toBe(false);
+ vi.useRealTimers();
+ });
+
it('shows the difference side by side with no footer of the view to share', async () => {
await open();
await add('A');
@@ -498,7 +648,7 @@ describe('Compare', () => {
target.querySelector('button[aria-label="Remove imagery A"]').click();
flushSync();
expect(target.querySelectorAll('.surface-shell')).toHaveLength(1);
- expect(target.querySelector('.surface-label strong').textContent).toBe('B');
+ expect(target.querySelector('.source-card .cmp-letter').textContent).toBe('B');
expect(target.querySelectorAll('.mode-btn')).toHaveLength(0);
});
@@ -518,7 +668,7 @@ describe('Compare', () => {
await settle();
// back on the opening pair, which without a release list is B alone
expect(target.querySelectorAll('.surface-shell')).toHaveLength(1);
- expect(target.querySelector('.surface-label strong').textContent).toBe('B');
+ expect(target.querySelector('.source-card .cmp-letter').textContent).toBe('B');
});
it('gives each source its own layers and keeps export choices in one modal', async () => {
@@ -531,7 +681,7 @@ describe('Compare', () => {
const layers = document.querySelector('[role="dialog"]');
expect(layers.getAttribute('aria-label')).toBe('Layers · A / B');
expect(layers.querySelectorAll('.layer-pane')).toHaveLength(2);
- expect(layers.querySelectorAll('.layer-row')).toHaveLength(18);
+ expect(layers.querySelectorAll('.layer-row')).toHaveLength(20);
expect(layers.textContent).toContain('Active fires');
expect(layers.textContent).toContain('Night lights');
expect(layers.textContent).toContain('Saved work');
@@ -695,7 +845,7 @@ describe('Compare', () => {
expect(target.querySelectorAll('.export-frame.readonly')).toHaveLength(1);
output.querySelector('button[aria-label="Close"]').click();
- button('Save comparison', target).click();
+ saveButton().click();
flushSync();
button('Save comparison', document.querySelector('[role="dialog"]')).click();
await settle();
@@ -731,6 +881,57 @@ describe('Compare', () => {
}
);
+ it('starts with the drawing rail folded, and folds it back keeping the tool in hand', async () => {
+ await open();
+ await add('A');
+ await add('B', undefined, { unfold: false });
+ const toolbar = () => target.querySelector('.annotation-rail');
+ // folded until asked: the maps get the width
+ expect(toolbar().classList.contains('folded')).toBe(true);
+ expect(toolbar().querySelector('.rail-strip').textContent.trim()).toBe('Annotations');
+ target.querySelector('button[aria-label="Show the annotation tools"]').click();
+ flushSync();
+ expect(toolbar().classList.contains('folded')).toBe(false);
+ const tools = toolbar().querySelectorAll('button').length;
+ target.querySelector('button[title^="Arrow"]').click();
+ flushSync();
+ target.querySelector('button[aria-label="Hide the annotation tools"]').click();
+ flushSync();
+ expect(toolbar().classList.contains('folded')).toBe(true);
+ // folded, the strip names what it holds and opens it again
+ expect(toolbar().querySelector('.rail-strip').textContent.trim()).toBe('Annotations');
+ expect(target.querySelector('.annotation-toolbar')).toBeNull();
+ // folded, the rail still says what is in hand, and a press puts it down
+ const inHand = toolbar().querySelector('button[aria-pressed="true"]');
+ expect(inHand.title).toBe('Arrow (A)');
+ // the shortcuts still reach every tool while the rail is folded
+ document.dispatchEvent(new KeyboardEvent('keydown', { key: 'r' }));
+ flushSync();
+ expect(toolbar().querySelector('button[aria-pressed="true"]').title).toBe('Box (R)');
+ toolbar().querySelector('button[aria-pressed="true"]').click();
+ flushSync();
+ expect(toolbar().querySelector('button[aria-pressed="true"]')).toBeNull();
+ // `[` brings it back whole, as Detect's `]` does its panel
+ document.dispatchEvent(new KeyboardEvent('keydown', { key: '[' }));
+ flushSync();
+ expect(toolbar().classList.contains('folded')).toBe(false);
+ expect(toolbar().querySelectorAll('button')).toHaveLength(tools);
+ });
+
+ it('opens with the drawing rail folded again after it was left open', async () => {
+ await open();
+ await add('A');
+ await add('B');
+ expect(target.querySelector('.annotation-rail').classList.contains('folded')).toBe(false);
+ unmount(live);
+ live = null;
+ target.remove();
+ await open();
+ await add('A');
+ await add('B', undefined, { unfold: false });
+ expect(target.querySelector('.annotation-rail').classList.contains('folded')).toBe(true);
+ });
+
it('adds a note over the comparison and keeps it in the editable state', async () => {
await open();
await add('A');
@@ -751,7 +952,7 @@ describe('Compare', () => {
expect(target.querySelector('.mark text').textContent).toContain('Before');
expect(target.querySelector('.annotation-toolbar')).not.toBeNull();
expect(target.querySelector('.badge').textContent).toBe('unsaved');
- button('Save comparison', target).click();
+ saveButton().click();
flushSync();
button('Save comparison', document.querySelector('[role="dialog"]')).click();
await settle();
@@ -814,6 +1015,52 @@ describe('Compare', () => {
expect(uiState.lookAt).toEqual({ tool: 'detect', lat: 43.3, lon: 5.4, zoom: 16 });
});
+ it('takes the whole screen with both maps, and reads the way out back from the browser', async () => {
+ const screen = fakeScreen();
+ const full = () => target.querySelector('button[aria-label="Full screen"]');
+ try {
+ await open();
+ await add('A');
+ await add('B');
+ for (const engine of engines) engine.resize.mockClear();
+ full().click();
+ await settle();
+ expect(screen.request).toHaveBeenCalledOnce();
+ expect(document.fullscreenElement).toBe(target.querySelector('.compare-tool'));
+ expect(target.querySelector('button[aria-label="Exit full screen"]').getAttribute('aria-pressed')).toBe('true');
+ // both containers changed size, so both maps are told
+ expect(engines).toHaveLength(2);
+ for (const engine of engines) expect(engine.resize).toHaveBeenCalled();
+ // a map outside the app opens a browser tab, which would drop the screen
+ engines[0].handlers.contextmenu({ lat: 43.3, lon: 5.4, x: 120, y: 90 });
+ flushSync();
+ button('Open in', target.querySelector('[role="menu"]')).click();
+ await settle();
+ const outside = [...target.querySelectorAll('[aria-label="Open this point in"] a')];
+ expect(outside.length).toBeGreaterThan(0);
+ expect(outside.every((link) => !link.hasAttribute('href') && link.getAttribute('aria-disabled') === 'true')).toBe(true);
+ // Esc belongs to the browser, which tells the page only afterwards
+ screen.leave();
+ await settle();
+ expect(full().getAttribute('aria-pressed')).toBe('false');
+ } finally {
+ screen.restore();
+ }
+ });
+
+ it('says so when the browser refuses the screen', async () => {
+ const screen = fakeScreen({ refuse: true });
+ try {
+ await openFresh();
+ target.querySelector('button[aria-label="Full screen"]').click();
+ await settle();
+ expect(toast).toHaveBeenCalledWith('Full screen is not available', 'danger');
+ expect(document.fullscreenElement).toBe(null);
+ } finally {
+ screen.restore();
+ }
+ });
+
it('moves both maps to a point another tab asked about, and keeps its pictures', async () => {
releases = [{ release: 30, date: '2026-09-01' }, { release: 20, date: '2025-06-01' }];
uiState.lookAt = { tool: 'compare', lat: 12.76, lon: 43.65, zoom: 15 };
@@ -859,7 +1106,7 @@ describe('Compare', () => {
await open();
await add('A');
await add('B');
- button('Save comparison', target).click();
+ saveButton().click();
flushSync();
expect(document.querySelector('[role="dialog"]')).not.toBeNull();
button('Save comparison', document.querySelector('[role="dialog"]')).click();
@@ -897,7 +1144,7 @@ describe('Compare', () => {
button('Difference', target).click();
flushSync();
await settle();
- button('Save comparison', target).click();
+ saveButton().click();
flushSync();
button('Save comparison', document.querySelector('[role="dialog"]')).click();
await settle();
@@ -917,21 +1164,20 @@ describe('Compare', () => {
expect(button('Difference', target).getAttribute('aria-pressed')).toBe('true');
});
- it('discards edits back to the saved version, where New would start over', async () => {
+ it('reverts edits back to the saved version, where New would start over', async () => {
await open();
button('Open', target).click();
await settle();
button('Harbour change', document.querySelector('[role="dialog"]')).click();
await settle();
expect(target.querySelector('.badge')).toBeNull();
- expect(button('Discard', target).disabled).toBe(true);
+ expect(button('Revert', target)).toBeUndefined();
button('Fade', target).click();
flushSync();
expect(target.querySelector('.badge').textContent).toBe('unsaved');
- expect(button('Discard', target).disabled).toBe(false);
- button('Discard', target).click();
+ button('Revert', target).click();
flushSync();
const dialog = document.querySelector('[role="alertdialog"]');
expect(dialog.textContent).toContain('Harbour change');
@@ -941,6 +1187,18 @@ describe('Compare', () => {
expect(target.querySelector('.compare-stage').classList.contains('swipe')).toBe(true);
expect(target.querySelectorAll('.surface-shell')).toHaveLength(2);
expect(target.querySelector('.badge')).toBeNull();
+ expect(button('Revert', target)).toBeUndefined();
+ });
+
+ it('offers no Revert on a comparison that was never saved', async () => {
+ await open();
+ await add('A');
+ await add('B', 'Esri Wayback');
+ button('Fade', target).click();
+ flushSync();
+ expect(target.querySelector('.badge').textContent).toBe('unsaved');
+ expect(button('Revert', target)).toBeUndefined();
+ expect(button('Discard', target)).toBeUndefined();
});
});
@@ -993,7 +1251,7 @@ describe('one camera for the map tabs', () => {
expect(took[0].setCamera).toHaveBeenCalledWith(expect.objectContaining({ ...SATELLITE }));
});
- it('keeps a saved comparison on the ground it was saved on', async () => {
+ it('brings a saved comparison along, the move leaving it saved', async () => {
prefs.mapSync = true;
await open();
button('Open', target).click();
@@ -1005,7 +1263,21 @@ describe('one camera for the map tabs', () => {
flushSync();
uiState.tool = 'compare';
flushSync();
- for (const engine of engines) expect(engine.setCamera).not.toHaveBeenCalled();
+ const took = engines.filter((engine) => engine.setCamera.mock.calls.length);
+ expect(took).toHaveLength(1);
+ expect(took[0].setCamera).toHaveBeenCalledWith(expect.objectContaining({ ...SATELLITE }));
+ // the map lands there: looking elsewhere is not an edit to undo…
+ took[0].handlers['view-settled']({ ...SATELLITE });
+ flushSync();
expect(target.querySelector('.badge')).toBeNull();
+ expect(button('Revert', target)).toBeUndefined();
+ // …and Compare does not send the other tabs back to where it was saved
+ expect(uiState.mapView.by).toBe('satellite');
+ // Save still keeps the new ground, and an edit after it still counts
+ expect(saveButton().disabled).toBe(false);
+ button('Fade', target).click();
+ flushSync();
+ expect(target.querySelector('.badge').textContent).toBe('unsaved');
+ expect(button('Revert', target)).toBeDefined();
});
});
diff --git a/frontend/src/tools/Compare.svelte b/frontend/src/tools/Compare.svelte
index e67a69f..dc44e01 100644
--- a/frontend/src/tools/Compare.svelte
+++ b/frontend/src/tools/Compare.svelte
@@ -22,6 +22,7 @@
import { saveRelation } from '../lib/relations.svelte.js';
import { actionsFor, otherMapTools } from '../lib/map/contextMenu.js';
import { openMapAt } from '../lib/navigate.js';
+ import { followFullscreen, toggleFullscreen } from '../lib/fullscreen.js';
import { wrapLon } from '../lib/coords.js';
import {
COMPARE_LAYERS,
@@ -60,6 +61,7 @@
} from '../lib/map/evolution.js';
import { composeEvolutionFrame, composeEvolutionSheet, drawPictures } from '../lib/map/evolutionExport.js';
import {
+ CHANGE_PALETTES,
changeCompatibility,
changeNeedsFrames,
changeSettings,
@@ -137,6 +139,10 @@
let home = $state(null);
let catalogueError = $state('');
let firesKeyed = $state(false);
+ /** Why the fire layer is not usable when it is not: 'missing' | 'off' | 'refused'. */
+ let firesState = $state('missing');
+ /** A spent FIRMS allowance's pause, while it lasts. */
+ let firesPaused = $state(null);
let picking = $state(null); // 'a' | 'b' | null
let mode = $state('side');
let divider = $state(DEFAULT_DIVIDER);
@@ -149,6 +155,11 @@
let searching = $state(false);
let swiping = $state(false);
let stageEl = $state(null);
+ let toolEl = $state(null);
+ let fullscreen = $state(false);
+ // The drawing rail opens folded on every visit, its width given to the
+ // maps, until `[` or its tab opens it.
+ let railFolded = $state(true);
let rotating = $state(null); // { which, x, y } | null
let outputBusy = $state(''); // 'capture' | 'png' | 'gif' | 'copy' | ''
let rightPanel = $state(null); // 'export' | 'layers' | null
@@ -218,6 +229,10 @@
const primeEngine = $derived(a.engine ?? b.engine);
let changeBusy = $state(false);
+ /** A reading is on its way: the settle it follows has not fired yet. */
+ let changePending = $state(false);
+ /** A reading waits for tiles still loading, rather than failing on them. */
+ let changeTiles = $state(false);
let changeError = $state('');
let changeResult = $state(null);
let changeUrl = $state('');
@@ -227,7 +242,9 @@
const changeVisible = $derived(!changeOptions.blink || changeBlinkOn);
const changeOver = (letter) => changeOptions.base === 'both' || changeOptions.base === letter;
const changeOpacity = $derived(changeOptions.opacity);
- const changePalette = $derived(changeOptions.palette);
+ // The legend's swatches come from the palette the overlay is drawn in.
+ const changeSwatches = $derived(Object.entries(CHANGE_PALETTES[changeOptions.palette] ?? CHANGE_PALETTES.directional)
+ .map(([name, [r, g, b]]) => `--${name}: rgb(${r},${g},${b})`).join('; '));
const changeCounts = $derived(changeResult?.counts);
let changeRequest = 0;
let previousCaseId = null;
@@ -340,8 +357,8 @@
const sessionDirty = $derived(
(a.present || b.present) && sessionSignature() !== savedSignature
);
- // A preset as it opened, camera aside. Panning an untouched pair is looking,
- // not work, so leaving it asks nothing; Save still takes it.
+ // A preset as it opened, or a comparison as it was saved, camera aside.
+ // Panning is looking, not work, so leaving asks nothing; Save still takes it.
let pristineSignature = $state(null);
const discardable = $derived(sessionDirty && pairSignature() !== pristineSignature);
let firmsSensors = $state([]);
@@ -451,6 +468,8 @@
})();
return () => {
gone = true;
+ clearTimeout(firesPauseTimer);
+ clearTimeout(firesTroubleTimer);
};
});
@@ -468,10 +487,27 @@
const answer = await api.get('/api/firms/sensors');
firmsSensors = answer.sensors ?? [];
firesKeyed = Boolean(answer.keyed);
+ firesState = answer.state ?? 'missing';
+ firesPaused = answer.paused ?? null;
} catch {
firmsSensors = [];
firesKeyed = false;
+ firesPaused = null;
}
+ // A pause ends on its own; the panes hear it then. Our own backend, once.
+ clearTimeout(firesPauseTimer);
+ if (firesPaused) {
+ const left = Date.parse(firesPaused.until) - Date.now();
+ firesPauseTimer = setTimeout(loadFireCatalogue, Math.max(1000, left + 500));
+ }
+ }
+
+ let firesPauseTimer = null;
+ let firesTroubleTimer = null;
+ /** A FIRMS tile failed on either side: ask our backend why, once per burst. */
+ function fireTrouble() {
+ clearTimeout(firesTroubleTimer);
+ firesTroubleTimer = setTimeout(loadFireCatalogue, 800);
}
function side(which) {
@@ -680,6 +716,8 @@
mode;
a.present;
b.present;
+ fullscreen;
+ railFolded;
void tick().then(() => {
a.engine?.resize();
b.engine?.resize();
@@ -691,11 +729,22 @@
});
});
+ // The whole tool takes the screen, bars and panels with it, so Save and
+ // Export stay in reach.
+ $effect(() => {
+ if (toolEl) return followFullscreen(toolEl, (on) => (fullscreen = on));
+ });
+ function switchFullscreen() {
+ toggleFullscreen(toolEl).catch(() => toast('Full screen is not available', 'danger'));
+ }
+
// Tools stay mounted while hidden so their work survives a tab switch.
$effect(() => {
if (uiState.tool !== 'compare') return;
imagery.refreshUsage();
loadProviders();
+ // a FIRMS key pasted into Settings, or tested back to life there
+ loadFireCatalogue();
void tick().then(() => {
a.engine?.resize();
b.engine?.resize();
@@ -836,7 +885,10 @@
difference = on;
if (!on) return;
if (!changeStatus.methods.includes(changeOptions.method)) changeOptions.method = changeStatus.methods[0];
- void refreshChangeAssist({ fetch: false });
+ // Turning it on by hand asks for a reading, bands included. Queued behind
+ // the flush the switch starts, so the follow-up that flush schedules is the
+ // one this replaces, and not the other way round.
+ queueMicrotask(() => void refreshChangeAssist());
}
function setDividerAt(clientX) {
@@ -909,9 +961,9 @@
return JSON.stringify([sessionName.trim(), sessionSpec()]);
}
- function pairSignature() {
- const { camera, ...pair } = sessionSpec();
- return JSON.stringify([sessionName.trim(), pair]);
+ function pairSignature(spec = sessionSpec(), title = sessionName.trim()) {
+ const { camera, ...pair } = spec;
+ return JSON.stringify([title, pair]);
}
function requestSaveSession() {
@@ -935,7 +987,7 @@
if (caseState.current?.id !== owner.id) return;
sessionName = result.title;
openedSession = { name: result.name, title: result.title };
- pristineSignature = null;
+ pristineSignature = pairSignature(savedSpec, result.title);
savedSignature = JSON.stringify([result.title, savedSpec]);
saveDialog = false;
let previewError = null;
@@ -1031,6 +1083,8 @@
mode = compareMode(spec.mode);
// Difference used to be a mode of its own, laid over the pair side by side.
difference = spec.difference === true || spec.mode === 'change';
+ // A reopened session reads nothing it has not been asked to, bands included.
+ changeReadScope = '';
divider = percentage(spec.divider, DEFAULT_DIVIDER);
opacity = percentage(spec.opacity, DEFAULT_OPACITY);
changeOptions = changeSettings(spec.change_assist);
@@ -1053,6 +1107,7 @@
a.engine?.resize();
b.engine?.resize();
savedSignature = sessionSignature();
+ pristineSignature = pairSignature();
if (difference) void refreshChangeAssist({ fetch: false });
toast(`Opened ${sessionName}`, 'ok');
} catch (error) {
@@ -1097,8 +1152,8 @@
* when this tab shows. One map takes it and the link brings the other along;
* with neither built, the camera they will open on moves.
*
- * A saved comparison keeps the ground it was saved on: its camera is part of
- * what was saved, and a pan made in another tab would leave it unsaved.
+ * A saved comparison follows too: its camera is not an edit (see
+ * `pristineSignature`), and holding it would send the other tabs back to it.
*/
const share = shareView('compare', { state: uiState, enabled: () => prefs.mapSync });
@@ -1106,7 +1161,6 @@
uiState.mapView;
if (uiState.tool !== 'compare' || !home) return;
untrack(() => {
- if (openedSession) return;
const engine = a.engine ?? b.engine;
const next = share.pending(engine ? engine.camera() : { ...view, bearing });
if (!next) return;
@@ -1215,16 +1269,13 @@
}
/**
- * Throw the edits away and keep the work: a comparison that was saved goes
- * back to the version on disk, one that never was goes back to the default
- * pair. New always starts over, which is why it is not an answer to "undo
- * what I just did".
+ * Throw the edits away and keep the work: a saved comparison goes back to the
+ * version on disk. One that never was has nothing to go back to, so New is
+ * its way to start over.
*/
- function requestDiscardChanges() {
- if (!discardable || sessionBusy) return;
- discardTarget = openedSession
- ? { kind: 'revert', name: openedSession.name }
- : { kind: 'new' };
+ function requestRevert() {
+ if (!openedSession || !discardable || sessionBusy) return;
+ discardTarget = { kind: 'revert', name: openedSession.name };
}
function confirmDiscard() {
@@ -1272,28 +1323,41 @@
new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)));
let changeTimer;
+ /** A reading asked for (Read, a choice) that has not landed yet: bands are allowed until it does. */
+ let changeAsked = false;
let changeRenderedKey = $state('');
const detectionKey = $derived(changeKey());
const changeFrames = $derived(changeNeedsFrames(changeSettings(changeOptions), changeStatus));
+ // What Read can honestly say: its move ("due"), the reading's, or nothing left to do.
+ const changeState = $derived(
+ changeTiles ? 'tiles'
+ : changeBusy || changePending ? 'reading'
+ : changeResult && !changeError && changeRenderedKey === detectionKey ? 'current'
+ : 'due');
+
+ /** What a reading reads, the camera aside: the pair and the analysis settings. */
+ function changeScope() {
+ const { opacity, base, blink, zones, ...analysis } = changeSettings(changeOptions);
+ return JSON.stringify([changeSide(a, s2a, wba, shownA, s1a), changeSide(b, s2b, wbb, shownB, s1b), analysis]);
+ }
function changeKey() {
- const { opacity, base, blink, zones, ...analysis } = changeSettings(changeOptions);
- return JSON.stringify([
- changeSide(a, s2a, wba, shownA, s1a),
- changeSide(b, s2b, wbb, shownB, s1b),
- view,
- bearing,
- analysis,
- ]);
+ return JSON.stringify([changeScope(), view, bearing]);
}
+ /** The scope the last reading landed for: once read, a pair's bands follow the camera. */
+ let changeReadScope = '';
+ /** How long the camera rests past the held ground before its bands are fetched again. */
+ const CHANGE_REST_MS = 700;
+
function invalidateChangeAssist() {
changeRenderedKey = '';
if (!difference) return;
- // A reading that follows the camera never spends a request: it runs on the
- // band frames already held, and waits for Run when they no longer reach.
+ // A reading that follows the camera runs on the band frames already held;
+ // past them it waits for the camera to rest (see `refreshChangeAssist`).
clearTimeout(changeTimer);
+ changePending = true;
changeTimer = setTimeout(() => void refreshChangeAssist({ fetch: false }), 180);
}
@@ -1310,11 +1374,26 @@
}
}
+ const tilesLoading = () => [a, b].some((side) => side.engine?.tilesLoading?.());
+ // A map that can say it is loading can be waited on: its capture waits for
+ // the tiles itself, so trying again is never a spin.
+ const canWaitForTiles = () => [a, b].every((side) => typeof side.engine?.tilesLoading === 'function');
+
async function refreshChangeAssist({ fetch = true } = {}) {
+ // This reading replaces the one waiting to follow the camera, which would
+ // otherwise start 180 ms in and throw away a Read still fetching its bands.
+ clearTimeout(changeTimer);
+ changePending = false;
+ // A read that was asked for and then overtaken by a move hands its ask to
+ // the reading that took over: Read reads the view the camera settles on,
+ // where it once spent the request and then threw the answer away.
+ const allowed = fetch || changeAsked;
+ changeAsked = false;
if (!difference || !changeStatus.ok) return;
if (!changeStatus.methods.includes(changeOptions.method)) { changeError = 'Choose a compatible method'; return; }
const key = changeKey();
if (key === changeRenderedKey && changeResult) return;
+ changeAsked = allowed;
const settings = changeSettings(changeOptions);
const sides = [changeSide(a, s2a, wba, shownA, s1a), changeSide(b, s2b, wbb, shownB, s1b)];
const request = ++changeRequest;
@@ -1324,41 +1403,76 @@
await tick();
await twoPaints();
if (request !== changeRequest || key !== changeKey()) return;
- const sources = await sourceCanvases();
- if (request !== changeRequest || key !== changeKey()) return;
- const result = await detectCaptures(sources, settings, sides, changeStatus, fetch);
+ // Tiles in flight are waited out, however long they take: a reading that
+ // gave up on them left the analyst to guess that Read would now work.
+ let sources = null;
+ while (!sources) {
+ changeTiles = tilesLoading();
+ try {
+ sources = await sourceCanvases();
+ } catch (error) {
+ if (!(error instanceof TilesLoading) || !canWaitForTiles()) throw error;
+ }
+ if (request !== changeRequest || key !== changeKey()) return;
+ }
+ changeTiles = false;
+ const result = await detectCaptures(sources, settings, sides, changeStatus, allowed);
if (request !== changeRequest || !difference || key !== changeKey()) return;
- // Nothing held reaches this view: the last reading stays up, marked out
- // of date, until the analyst asks for the frames.
- if (result.needsFetch) return;
+ // Nothing held reaches this view. A pair already read with its bands
+ // follows the camera with them: once it rests, they are fetched again, as
+ // the tiles it just drew were. A new pair, another date or a reopened
+ // session waits for Read, the last reading up and marked out of date.
+ if (result.needsFetch) {
+ if (changeScope() === changeReadScope) {
+ changePending = true;
+ changeTimer = setTimeout(() => void refreshChangeAssist(), CHANGE_REST_MS);
+ }
+ return;
+ }
changeResult = result;
placeChangeMap();
changeUrl = result.canvas.toDataURL('image/png');
changeRenderedKey = key;
+ changeReadScope = changeScope();
} catch (error) {
if (request !== changeRequest) return;
changeResult = null;
changeUrl = '';
changeError = error?.message ?? 'Could not compare these pixels';
} finally {
- if (request === changeRequest) changeBusy = false;
+ if (request === changeRequest) {
+ changeBusy = false;
+ changeTiles = false;
+ changeAsked = false;
+ }
}
}
$effect(() => {
- if (!difference || uiState.tool !== 'compare') { changeRequest++; return; }
+ if (!difference || uiState.tool !== 'compare') {
+ changeRequest++;
+ changePending = false;
+ changeAsked = false;
+ if (!difference) changeReadScope = '';
+ return;
+ }
if (!changeStatus.ok) {
changeRequest += 1;
+ changeAsked = false;
changeResult = null;
changeUrl = '';
changeError = changeStatus.reason;
changeBusy = false;
+ changeTiles = false;
+ changePending = false;
return;
}
detectionKey;
changeRequest++;
changeBusy = false;
+ changeTiles = false;
clearTimeout(changeTimer);
+ changePending = true;
changeTimer = setTimeout(() => void refreshChangeAssist({ fetch: false }), 180);
return () => clearTimeout(changeTimer);
});
@@ -1485,6 +1599,7 @@
if (reading) { setMode(reading.id); return; }
if (key === DIFFERENCE_KEY && (difference || changeStatus.ok)) { setDifference(!difference); return; }
if (key === ' ' && mode === 'blink') { event.preventDefault(); blinkPaused = !blinkPaused; return; }
+ if (key === '[') { railFolded = !railFolded; return; }
}
if ((event.ctrlKey || event.metaKey) && key === 'z') {
event.preventDefault();
@@ -1717,6 +1832,13 @@
return canvas;
}
+ /** A capture taken with tiles still in flight: a reading waits, an export says so. */
+ class TilesLoading extends Error {
+ constructor() {
+ super('Some tiles are still loading. Try again');
+ }
+ }
+
async function sourceCanvases() {
if (!both || !a.ready || !b.ready) {
throw new Error('both maps must be ready before they can be exported');
@@ -1724,7 +1846,7 @@
if (!hasWidget) {
const frames = [surfaceFrame(a), surfaceFrame(b)];
const captures = await Promise.all([a.engine.snapshot(), b.engine.snapshot()]);
- if (captures.some((capture) => !capture.complete)) throw new Error('Some tiles are still loading. Try again');
+ if (captures.some((capture) => !capture.complete)) throw new TilesLoading();
if ([a, b].some((target, index) => JSON.stringify(surfaceFrame(target)) !== JSON.stringify(frames[index]))) {
throw new Error('The map moved during capture. Settle it and try again');
}
@@ -2143,46 +2265,47 @@
}
</script>
-<div class="tool compare-tool" inert={sessionBusy}>
+<div class="tool compare-tool" class:grabbing inert={sessionBusy} bind:this={toolEl}>
+ <!-- One row above the maps. With a pair on screen the reading modes take the
+ title's place, since the tab strip already says which tool this is. -->
<div class="tool-header">
- <h2>Compare</h2>
+ {#if both}
+ <ModeDock {mode} {difference} differenceable={difference || changeStatus.ok}
+ onmode={setMode} ondifference={setDifference} onswap={swapSides} />
+ <button class="btn btn-sm" class:active={stripOpen} disabled={!archive} aria-pressed={stripOpen}
+ onclick={() => (stripOpen = !stripOpen)}
+ title={archive ? 'Every dated picture of this point'
+ : 'Show the same dated archive on A and B to list its pictures'}>
+ <Icon name="clock" size={13} /> All dates
+ </button>
+ {:else}
+ <h2>Compare</h2>
+ {/if}
+ {#if !a.present && !b.present}
+ <span class="sub">Two imagery views, one shared camera</span>
+ {/if}
+ <div class="spacer"></div>
+ <!-- The name sits with the acts that save and discard it. -->
{#if a.present || b.present}
+ {#if discardable}<span class="badge">unsaved</span>{/if}
<input
- class="input session-title"
+ class="input title-input session-title"
bind:value={sessionName}
maxlength="200"
aria-label="Comparison name"
+ title="Rename this comparison"
onkeydown={(event) => event.key === 'Enter' && requestSaveSession()}
/>
- {#if discardable}<span class="badge">unsaved</span>{/if}
- {:else}
- <span class="sub">Two imagery views, one shared camera</span>
- {/if}
- <div class="spacer"></div>
- {#if a.present || b.present}
- <PlaceSearch
- bind:value={coordsText}
- savedRows={[]}
- centre={activeView}
- units={prefs.units}
- {searching}
- listId="compare-suggestions"
- onpick={goToSuggestion}
- onsubmit={goTo}
- />
{/if}
<button class="btn btn-sm" onclick={openSessionList} disabled={!caseState.current || sessionBusy} title="Open a saved comparison">
<Icon name="folderOpen" size={13} /> Open
</button>
- {#if a.present || b.present}
- <button
- class="btn btn-sm"
- onclick={requestDiscardChanges}
- disabled={!discardable || sessionBusy}
- title={openedSession ? 'Go back to the saved version' : 'Throw this comparison away'}
- >
- <Icon name="undo" size={13} /> Discard
+ {#if openedSession && discardable}
+ <button class="btn btn-sm" onclick={requestRevert} disabled={sessionBusy} title="Go back to the saved version">
+ <Icon name="undo" size={13} /> Revert
</button>
+ {/if}
+ {#if a.present || b.present}
<div class="new-wrap" bind:this={newMenuEl}>
<button class="btn btn-sm" onclick={() => (newMenu = !newMenu)} title="Start a new comparison"
aria-expanded={newMenu} aria-haspopup="menu">
@@ -2204,35 +2327,28 @@
{/if}
</div>
{/if}
+ {#if both}
+ <button class="btn btn-sm" onclick={() => toggleRightPanel('export')} disabled={!a.ready || !b.ready || !!outputBusy}>
+ <Icon name="download" size={13} /> Export
+ </button>
+ {/if}
<button
class="btn btn-primary btn-sm"
onclick={requestSaveSession}
disabled={!both || sessionBusy || !sessionDirty}
title="Keep this editable comparison in My work"
>
- <Icon name="save" size={13} /> {sessionBusy ? 'Saving…' : 'Save comparison'}
+ <Icon name="save" size={13} /> {sessionBusy ? 'Saving…' : 'Save'}
</button>
+ <button
+ class="btn btn-sm btn-ghost"
+ aria-pressed={fullscreen}
+ onclick={switchFullscreen}
+ title={fullscreen ? 'Back to the window (Esc)' : 'Compare on the whole screen'}
+ aria-label={fullscreen ? 'Exit full screen' : 'Full screen'}
+ ><Icon name={fullscreen ? 'minimize' : 'maximize'} size={13} /></button>
</div>
- {#if both}
- <div class="compare-bar">
- <ModeDock {mode} {difference} differenceable={difference || changeStatus.ok}
- onmode={setMode} ondifference={setDifference} onswap={swapSides} />
- <button class="btn btn-sm" class:active={stripOpen} disabled={!archive} aria-pressed={stripOpen}
- onclick={() => (stripOpen = !stripOpen)}
- title={archive ? 'Every dated picture of this point'
- : 'Show the same dated archive on A and B to list its pictures'}>
- <Icon name="clock" size={13} /> All dates
- </button>
- <div class="spacer"></div>
- <span class="camera-readout mono">z{Number(view.zoom).toFixed(1)}</span>
- <!-- One camera, so one compass: it turns both maps and resets them. -->
- <Compass {bearing} onbearing={(deg) => primeEngine?.setBearing(deg)} />
- <button class="btn btn-sm" onclick={() => toggleRightPanel('export')} disabled={!a.ready || !b.ready || !!outputBusy}>
- <Icon name="download" size={13} /> Export
- </button>
- </div>
- {/if}
{#if !a.present && !b.present}
<div class="presets">
{#each availablePresets(imagery.providers) as preset}
@@ -2247,6 +2363,7 @@
<div class="compare-workspace">
{#if both}
<AnnotationToolbar
+ bind:collapsed={railFolded}
bind:tool={annotationTool}
selected={editableAnnotation}
canUndo={annotationUndo.length > 0}
@@ -2275,24 +2392,7 @@
/>
{/if}
- <!-- The cards ride over the stage, not over the tool: the annotation rail on
- the left narrows the stage, and a full-width bar put the seam between
- the cards tens of pixels away from the seam between the maps. -->
<div class="stage-column">
- {#if a.present || b.present}
- <div class="source-bar" aria-label="Compared imagery">
- {#if a.present}
- <SourceCard letter="A" {imagery} bind:providerId={a.providerId} s2={s2a} wayback={wba} s1={s1a}
- shown={shownA} dated={a.dated} layerCount={a.overlays.length} layersOpen={rightPanel === 'layers'}
- onlayers={() => toggleRightPanel('layers')} onremove={() => remove('a')} />
- {:else}<button class="source-add" onclick={() => (picking = 'a')}>A · Add imagery</button>{/if}
- {#if b.present}
- <SourceCard letter="B" {imagery} bind:providerId={b.providerId} s2={s2b} wayback={wbb} s1={s1b}
- shown={shownB} dated={b.dated} align="right" layerCount={b.overlays.length} layersOpen={rightPanel === 'layers'}
- onlayers={() => toggleRightPanel('layers')} onremove={() => remove('b')} />
- {:else}<button class="source-add" onclick={() => (picking = 'b')}>B · Add imagery</button>{/if}
- </div>
- {/if}
<div
class="compare-stage"
class:overlay={both && mode !== 'side'}
@@ -2306,10 +2406,51 @@
style:--change-opacity={changeOpacity / 100}
bind:this={stageEl}
>
+ <!-- The cards float over the maps they describe, one column per pane, so
+ the seam between A and B is one line and no bar takes the maps'
+ height. The view's own controls ride in B's corner. -->
+ {#if a.present || b.present}
+ <div class="source-bar" aria-label="Compared imagery">
+ {#if a.present}
+ <SourceCard letter="A" {imagery} bind:providerId={a.providerId} s2={s2a} wayback={wba} s1={s1a}
+ shown={shownA} dated={a.dated} layerCount={a.overlays.length} layersOpen={rightPanel === 'layers'}
+ onlayers={() => toggleRightPanel('layers')} onremove={() => remove('a')} />
+ {:else}<button class="source-add cmp-glass" onclick={() => (picking = 'a')}>A · Add imagery</button>{/if}
+ <div class="source-b">
+ {#if b.present}
+ <SourceCard letter="B" {imagery} bind:providerId={b.providerId} s2={s2b} wayback={wbb} s1={s1b}
+ shown={shownB} dated={b.dated} align="right" layerCount={b.overlays.length} layersOpen={rightPanel === 'layers'}
+ onlayers={() => toggleRightPanel('layers')} onremove={() => remove('b')} />
+ {:else}<button class="source-add cmp-glass" onclick={() => (picking = 'b')}>B · Add imagery</button>{/if}
+ <!-- Stacked in the corner as Detect's column is: where to go, then how
+ the shared camera stands. -->
+ <div class="view-col">
+ <div class="search-chip cmp-glass">
+ <PlaceSearch
+ bind:value={coordsText}
+ savedRows={[]}
+ centre={activeView}
+ units={prefs.units}
+ {searching}
+ listId="compare-suggestions"
+ onpick={goToSuggestion}
+ onsubmit={goTo}
+ />
+ </div>
+ {#if both}
+ <div class="camera-chip cmp-glass">
+ <span class="camera-readout mono" title="Zoom level of both maps">z{Number(view.zoom).toFixed(1)}</span>
+ <!-- One camera, so one compass: it turns both maps and resets them. -->
+ <Compass {bearing} onbearing={(deg) => primeEngine?.setBearing(deg)} />
+ </div>
+ {/if}
+ </div>
+ </div>
+ </div>
+ {/if}
{#if a.present && home}
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div class="surface-shell primary" oncontextmenu={(event) => onOverlayMenu('a', event)}>
- <div class="surface-label"><strong>A</strong></div>
<MapSurface
bind:this={a.surface}
bind:engine={a.engine}
@@ -2336,6 +2477,7 @@
onwidgetload={(meter) => imagery.countLoad(meter)}
onwidgetauthfailure={onWidgetAuthFailure}
onwidgetfailed={(provider, error) => onWidgetFailed('a', provider, error)}
+ onoverlaytrouble={(id) => id === 'firms' && fireTrouble()}
onviewsettled={(next) => onSurfaceSettled('a', next)}
onbearingchange={(next) => onSurfaceBearing('a', next)}
oncontextmenu={(at) => onMapContextMenu('a', at)}
@@ -2349,6 +2491,7 @@
actions={pointActions}
tools={pointTools}
lookup={pointMenu.lookup}
+ {fullscreen}
onpick={onPointMenu}
onclose={closePointMenu}
/>
@@ -2359,6 +2502,7 @@
items={savedWork.rows}
caseId={caseState.current?.id}
coords={savedCoords}
+ {fullscreen}
onopen={openSaved}
onedit={editSaved}
onrefresh={reloadCase}
@@ -2368,7 +2512,7 @@
<!-- The mask is ground, not screen: it is laid on each map through that
map's own frame, so "Both" shows one reading over two pictures. -->
{#if both && difference && changeOver('a') && changeUrl && changeVisible}
- <img class="change-map" src={changeUrl} alt="Pixel-change heatmap over imagery A"
+ <img class="change-map" class:stale={changeState === 'due'} src={changeUrl} alt="Pixel-change heatmap over imagery A"
style:width={`${changeResult.frame.width}px`} style:height={`${changeResult.frame.height}px`}
style:transform={changeTransform.a} />
{/if}
@@ -2405,7 +2549,6 @@
class:blink-hidden={mode === 'blink' && !blinkB}
oncontextmenu={(event) => onOverlayMenu('b', event)}
>
- <div class="surface-label"><strong>B</strong></div>
<MapSurface
bind:this={b.surface}
bind:engine={b.engine}
@@ -2432,6 +2575,7 @@
onwidgetload={(meter) => imagery.countLoad(meter)}
onwidgetauthfailure={onWidgetAuthFailure}
onwidgetfailed={(provider, error) => onWidgetFailed('b', provider, error)}
+ onoverlaytrouble={(id) => id === 'firms' && fireTrouble()}
onviewsettled={(next) => onSurfaceSettled('b', next)}
onbearingchange={(next) => onSurfaceBearing('b', next)}
oncontextmenu={(at) => onMapContextMenu('b', at)}
@@ -2445,6 +2589,7 @@
actions={pointActions}
tools={pointTools}
lookup={pointMenu.lookup}
+ {fullscreen}
onpick={onPointMenu}
onclose={closePointMenu}
/>
@@ -2455,6 +2600,7 @@
items={savedWork.rows}
caseId={caseState.current?.id}
coords={savedCoords}
+ {fullscreen}
onopen={openSaved}
onedit={editSaved}
onrefresh={reloadCase}
@@ -2462,7 +2608,7 @@
{/if}
</MapSurface>
{#if both && difference && changeOver('b') && changeUrl && changeVisible}
- <img class="change-map" src={changeUrl} alt="Pixel-change heatmap over imagery B"
+ <img class="change-map" class:stale={changeState === 'due'} src={changeUrl} alt="Pixel-change heatmap over imagery B"
style:width={`${changeResult.frame.width}px`} style:height={`${changeResult.frame.height}px`}
style:transform={changeTransform.b} />
{/if}
@@ -2528,11 +2674,15 @@
{/if}
{#if both && difference}
- <div class="change-legend" class:colourblind={changePalette === 'colourblind'}>
+ <div class="change-legend" style={changeSwatches}>
<span><i class="gain"></i> Appeared / stronger in B</span>
<span><i class="loss"></i> Disappeared / weaker from A</span>
<span><i class="changed"></i> Other evolution</span>
- {#if changeBusy}<em>Reading…</em>{:else if changeError}<em class="warn">{changeError}</em>{:else if changeCounts}<em class:warn={changeRenderedKey !== detectionKey}>{changeShare(changeCounts)}% highlighted{changeRenderedKey !== detectionKey ? ' · from an earlier read' : ''}</em>{/if}
+ {#if changeState === 'tiles'}<em>Waiting for the tiles…</em>
+ {:else if changeState === 'reading'}<em>Reading…</em>
+ {:else if changeError}<em class="warn">{changeError}</em>
+ {:else if changeState === 'due'}<em class="warn">{changeCounts ? `${changeShare(changeCounts)}% highlighted · out of date, press Read` : 'Not read yet, press Read'}</em>
+ {:else if changeCounts}<em>{changeShare(changeCounts)}% highlighted</em>{/if}
</div>
{/if}
@@ -2552,8 +2702,7 @@
<ModeControl {mode} bind:divider bind:opacity bind:blinkB bind:blinkPaused bind:blinkInterval />
{#if difference}
<DifferenceBar bind:settings={changeOptions} status={changeStatus} result={changeResult}
- busy={changeBusy} error={changeError}
- stale={!!changeResult && changeRenderedKey !== detectionKey}
+ reading={changeState} error={changeError}
onrun={() => refreshChangeAssist()} onzone={visitZone} onanalyzer={saveAsAnalyzer} />
{/if}
</div>
@@ -2698,6 +2847,8 @@
night={a.night}
{firmsSensors}
{firesKeyed}
+ {firesState}
+ {firesPaused}
savedCount={savedWork.rows.length}
ontoggle={(layer) => toggleLayer(a, layer)}
onfirms={(patch) => patchLayer(a, 'firms', patch)}
@@ -2714,6 +2865,8 @@
night={b.night}
{firmsSensors}
{firesKeyed}
+ {firesState}
+ {firesPaused}
savedCount={savedWork.rows.length}
ontoggle={(layer) => toggleLayer(b, layer)}
onfirms={(patch) => patchLayer(b, 'firms', patch)}
@@ -2853,14 +3006,20 @@
<style>
.tool { position: relative; }
+ /* The fullscreen backdrop is black, and the header draws no background of its own. */
+ .tool:fullscreen { background: var(--bg-0); }
.spacer { flex: 1; }
- .tool-header { min-height: 55px; }
- .tool-header :global(.place-search) { width: min(440px, 40vw); }
- .session-title {
- width: min(250px, 22vw);
- height: 30px;
- padding: 4px 8px;
- font-weight: 650;
+ .tool-header { min-height: 48px; padding-block: 6px; gap: 8px; }
+ .tool-header > :global(*) { flex-shrink: 0; }
+ /* The name gives way before any button does, so the row never wraps. */
+ /* The shared title field of Inspect and the composers, so it reads as a name
+ to type over. It gives way before any button does, so the row never wraps. */
+ .tool-header .session-title {
+ flex: 0 1 240px;
+ width: 240px;
+ min-width: 100px;
+ height: 28px;
+ padding: 3px 10px;
}
.badge {
padding: 2px 6px;
@@ -2871,17 +3030,49 @@
text-transform: uppercase;
letter-spacing: .05em;
}
+ /* Two columns set 8px inside the two panes (1px stage padding, 1px seam), so
+ each card sits in its own map's corner. Only the cards take the pointer;
+ the map stays grabbable between them. */
.source-bar {
+ position: absolute;
+ top: 8px;
+ left: 9px;
+ right: 9px;
+ z-index: 650;
display: grid;
grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
- gap: 1px;
- padding: 1px;
- border-bottom: 1px solid var(--border);
- background: var(--border-strong);
+ column-gap: 17px;
+ align-items: start;
+ pointer-events: none;
}
- .source-add { color: var(--text-3); background: var(--bg-1); }
- .compare-bar { display: flex; align-items: center; gap: 12px; padding: 6px 12px; background: var(--bg-1); }
+ .source-bar > :global(*),
+ .source-b > :global(*) { pointer-events: auto; }
+ .source-bar > :global(.source-card) { justify-self: start; }
+ .source-b {
+ grid-column: 2;
+ display: flex;
+ flex-wrap: wrap;
+ align-items: flex-start;
+ gap: 8px;
+ min-width: 0;
+ pointer-events: none;
+ }
+ .source-add { justify-self: start; height: 38px; padding: 0 12px; color: var(--text-2); font-size: var(--fs-sm); }
+ .source-add:hover { color: var(--text-1); border-color: var(--accent); }
+ /* Lifted off the imagery, which can be as dark as the chips themselves. */
+ .source-bar :global(.cmp-glass) { box-shadow: var(--shadow-1); }
+ .view-col { display: flex; flex-direction: column; align-items: flex-end; gap: 6px; margin-left: auto; pointer-events: none; }
+ .view-col > * { pointer-events: auto; }
+ .search-chip { display: flex; width: min(280px, 24vw); padding: 4px; }
+ .search-chip :global(.place-search) { flex: 1; }
+ .camera-chip { display: flex; align-items: center; gap: 4px; padding: 0 0 0 8px; }
+ /* one frame for the pair; a turned camera still rings the compass in amber */
+ .camera-chip :global(.rotate-ctl) { background: transparent; backdrop-filter: none; }
+ .camera-chip :global(.rotate-ctl:not(.turned)) { box-shadow: none; }
.camera-readout { color: var(--text-3); font-size: var(--fs-xs); }
+ /* The dock is drawn for the map; in the header row its segments stand on
+ the row itself, not on a second frame. */
+ .tool-header :global(.mode-dock) { padding: 0; border: 0; background: transparent; box-shadow: none; }
/* Above the stage, which keeps its map layers to itself (see .compare-stage),
so the Difference panel opening upward lies over the highlights. */
.mode-footer { position: relative; z-index: 1; display: flex; flex-wrap: wrap; justify-content: center; align-items: center; gap: 8px; padding: 6px; background: var(--bg-1); }
@@ -2946,22 +3137,6 @@
min-height: 0;
}
.surface-shell { display: flex; overflow: hidden; background: var(--bg-0); }
- .surface-label {
- position: absolute;
- top: 11px;
- left: 11px;
- z-index: 520;
- display: flex;
- align-items: center;
- height: 29px;
- border: 1px solid rgba(255,255,255,.18);
- border-radius: var(--r-sm);
- color: #f2f2f2;
- background: rgba(24,24,24,.88);
- backdrop-filter: blur(6px);
- box-shadow: var(--shadow-1);
- }
- .surface-label strong { padding: 0 9px; font-size: var(--fs-xs); color: var(--accent); }
.empty-slot {
display: flex;
flex-direction: column;
@@ -2992,7 +3167,6 @@
.compare-stage.overlay .surface-shell { background: transparent; }
.compare-stage.overlay .primary { z-index: 1; }
.compare-stage.overlay .secondary { z-index: 2; }
- .compare-stage.overlay .surface-label { display: none; }
.compare-stage.swipe .secondary { clip-path: inset(0 0 0 var(--divider)); }
/* Blend the pixels, not the provider/date controls that explain them. */
.compare-stage.blended .secondary :global(.map),
@@ -3009,6 +3183,12 @@
opacity: var(--change-opacity);
pointer-events: none;
}
+ /* A reading the view has moved past stays for reference, drained of colour
+ so it cannot pass for this view's. */
+ .change-map.stale {
+ opacity: calc(var(--change-opacity) * 0.45);
+ filter: grayscale(1);
+ }
.change-legend {
position: absolute;
z-index: 555;
@@ -3028,15 +3208,14 @@
}
.change-legend span { display: flex; align-items: center; gap: 4px; }
.change-legend i { width: 9px; height: 9px; border-radius: 2px; }
- .change-legend .gain { background: rgb(34,197,94); }
- .change-legend .loss { background: rgb(239,68,68); }
- .change-legend .changed { background: rgb(250,204,21); }
- .change-legend.colourblind .gain { background: rgb(0,114,178); }
- .change-legend.colourblind .loss { background: rgb(230,159,0); }
- .change-legend.colourblind .changed { background: rgb(204,121,167); }
+ .change-legend .gain { background: var(--gain); }
+ .change-legend .loss { background: var(--loss); }
+ .change-legend .changed { background: var(--changed); }
.change-legend em.warn { color: var(--warn); }
.change-legend em { max-width: 260px; overflow: hidden; color: #c4c9cf; font-style: normal; text-overflow: ellipsis; white-space: nowrap; }
- .compare-stage.capturing .surface-label,
+ /* the rail's tab lies over map A's edge, inside the frame being grabbed */
+ .compare-tool.grabbing :global(.rail-tab) { visibility: hidden; }
+ .compare-stage.capturing .source-bar,
.compare-stage.capturing .swipe-line { visibility: hidden; }
.compare-stage.capture-a .secondary,
.compare-stage.capture-b .primary { visibility: hidden; }
@@ -3201,11 +3380,13 @@
.session-open small { color: var(--text-3); font-size: 10px; }
@media (max-width: 900px) {
.tool-header .sub { display: none; }
+ .tool-header { flex-wrap: wrap; }
.compare-stage:not(.overlay) { flex-direction: column; }
.provider-grid { grid-template-columns: 1fr; }
- .source-bar { grid-template-columns: 1fr; }
- .compare-bar { flex-wrap: wrap; }
- .session-title { width: 150px; }
+ /* The panes stack, so the cards do too: each row is one pane's height. */
+ .source-bar { grid-template-columns: minmax(0, 1fr); row-gap: 8px; }
+ .compare-stage:not(.overlay) .source-bar { bottom: 8px; grid-template-rows: 1fr 1fr; row-gap: 17px; }
+ .source-b { grid-column: 1; }
.camera-readout { display: none; }
.layer-columns { height: min(72vh, 720px); grid-template-columns: 1fr; overflow: auto; }
}
diff --git a/frontend/src/tools/Coordinates.svelte b/frontend/src/tools/Coordinates.svelte
index d783821..d06f50c 100644
--- a/frontend/src/tools/Coordinates.svelte
+++ b/frontend/src/tools/Coordinates.svelte
@@ -134,10 +134,6 @@
</script>
<div class="tool">
- <div class="tool-header">
- <h2>Coords &amp; Sky</h2>
- </div>
-
<div class="tool-body">
<form
class="go-form"
diff --git a/frontend/src/tools/Detect.render.test.js b/frontend/src/tools/Detect.render.test.js
index 239c4f9..26beb21 100644
--- a/frontend/src/tools/Detect.render.test.js
+++ b/frontend/src/tools/Detect.render.test.js
@@ -1,6 +1,7 @@
// @vitest-environment happy-dom
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { flushSync, mount, unmount } from 'svelte';
+import { fakeScreen } from '../lib/fullscreen.fixture.js';
const ANALYZERS = {
builtins: [{
@@ -291,6 +292,37 @@ describe('Detect', () => {
expect(target.textContent).toContain('tile');
});
+ it('shows a chosen pass whole, as the run reads it, and says on the chip when it is cloudy', async () => {
+ // Lyman, 2026-09-26: under the run's 30% ceiling Sentinel Hub dropped the
+ // 51% tile and the map stayed black while the day was picked
+ post.mockImplementation(async (path) => (path.endsWith('/acquisitions')
+ ? { dates: [{ date: '2026-09-26', cloud: 51.1, granules: 2, coverage: 1 },
+ { date: '2026-09-19', cloud: 0.7, granules: 4, coverage: 1 }], truncated: false }
+ : {}));
+ try {
+ await open();
+ button('New detection').click(); await settle();
+ starts('One pass').click(); await settle();
+ button('Use current view').click(); await settle();
+ button('Next: What').click(); await settle();
+ button('Next: When').click(); await settle();
+ button('Find passes').click(); await settle();
+ target.querySelector('[aria-label="Use 2026-09-26"] button:last-child').click(); await settle();
+ const [provider, variant] = showBasemap.mock.lastCall;
+ expect(provider.id).toBe('sentinel2');
+ expect(variant).toContain('2026-09-26');
+ expect(variant).not.toContain('CC');
+ const chip = labelled('Leave pass imagery');
+ expect(chip.textContent).toContain('2026-09-26');
+ expect(chip.textContent).toContain('51% cloud');
+ // a clear day says nothing more than its date
+ target.querySelector('[aria-label="Use 2026-09-19"] button:last-child').click(); await settle();
+ expect(labelled('Leave pass imagery').textContent).not.toContain('cloud');
+ } finally {
+ post.mockImplementation(async () => ({}));
+ }
+ });
+
it('opens a saved item the rest of the app asked for', async () => {
await open();
uiState.openAnalyzer = `followups-${WATCH}`;
@@ -350,6 +382,46 @@ describe('Detect', () => {
expect(uiState.gotoCoords).toEqual({ lat: 14.81, lon: 42.95, zoom: 12 });
});
+ it('takes the whole screen with its panel, and reads the way out back from the browser', async () => {
+ const screen = fakeScreen();
+ try {
+ await open();
+ engines[0].resize.mockClear();
+ labelled('Full screen').click(); await settle();
+ expect(screen.request).toHaveBeenCalledOnce();
+ expect(document.fullscreenElement).toBe(target.querySelector('.detect-tool'));
+ expect(labelled('Exit full screen').getAttribute('aria-pressed')).toBe('true');
+ expect(engines[0].resize).toHaveBeenCalled();
+ // a map outside the app opens a browser tab, which would drop the screen
+ rightClick({ lat: 14.81, lon: 42.95, x: 200, y: 150 });
+ starts('Open in').click(); await settle();
+ const outside = [...target.querySelectorAll('[aria-label="Open this point in"] a')];
+ expect(outside.length).toBeGreaterThan(0);
+ expect(outside.every((link) => !link.hasAttribute('href') && link.getAttribute('aria-disabled') === 'true')).toBe(true);
+ // Esc belongs to the browser, which tells the page only afterwards
+ screen.leave(); await settle();
+ expect(labelled('Full screen').getAttribute('aria-pressed')).toBe('false');
+ labelled('Full screen').click(); await settle();
+ labelled('Exit full screen').click(); await settle();
+ expect(screen.exit).toHaveBeenCalledOnce();
+ expect(document.fullscreenElement).toBe(null);
+ } finally {
+ screen.restore();
+ }
+ });
+
+ it('says so when the browser refuses the screen', async () => {
+ const screen = fakeScreen({ refuse: true });
+ try {
+ await open();
+ labelled('Full screen').click(); await settle();
+ expect(toast).toHaveBeenCalledWith('Full screen is not available', 'danger');
+ expect(labelled('Full screen').getAttribute('aria-pressed')).toBe('false');
+ } finally {
+ screen.restore();
+ }
+ });
+
it('looks where another map tab asked, over the case\'s landing frame', async () => {
uiState.lookAt = { tool: 'detect', lat: 12.7615, lon: 43.6571, zoom: 15 };
await open();
diff --git a/frontend/src/tools/Detect.svelte b/frontend/src/tools/Detect.svelte
index e0fcbea..56b78fc 100644
--- a/frontend/src/tools/Detect.svelte
+++ b/frontend/src/tools/Detect.svelte
@@ -20,6 +20,8 @@
import { caseState, dismissToast, prefs, prefsReady, toast, uiState } from '../lib/state.svelte.js';
import { marksToZones, sourceLabel, viewZone, zoneMarks, zoneRing } from '../lib/map/analyzers.js';
import { blinkable } from '../lib/map/detectReview.js';
+ import { ADVISED_MAXCC } from '../lib/map/detectWhen.js';
+ import { DEFAULT_MAXCC } from '../lib/sentinel.js';
import { insideBounds } from '../lib/map/analyzerRules.js';
import { DEFAULT_BLINK_INTERVAL } from '../lib/map/compare.js';
import { createImageryState } from './satellite/state/imagery.svelte.js';
@@ -29,6 +31,7 @@
import { copernicusNeed } from '../lib/copernicusSetup.js';
import { actionsFor, otherMapTools } from '../lib/map/contextMenu.js';
import { openMapAt } from '../lib/navigate.js';
+ import { followFullscreen, toggleFullscreen } from '../lib/fullscreen.js';
import { shareView } from '../lib/map/sharedView.js';
import { COMPARE_SOURCES, comparePair } from '../lib/map/comparePair.js';
import CopernicusNeeded from '../components/CopernicusNeeded.svelte';
@@ -65,7 +68,9 @@
let providerId = $state('esri-world-imagery');
let chosenBasemap = $state('esri-world-imagery');
let collapsed = $state(false);
- let overlays = $state(['boundaries']);
+ let toolEl = $state(null);
+ let fullscreen = $state(false);
+ let overlays = $state(['boundaries', 'placenames']);
let savedVisible = $state(true);
let readingPass = $state(false);
let layersOpen = $state(false);
@@ -77,8 +82,8 @@
* its Copernicus layer and day, but none is remembered as the basemap: Detect
* opens on free imagery every time. */
const PASSES = [SENTINEL, RADAR_ID];
- const OVERLAY_ROWS = [['boundaries', 'Borders'], ['roads', 'Roads'], ['railway', 'Railways'],
- ['power', 'Power lines'], ['seamarks', 'Seamarks'], ['gpstraces', 'GPS traces']];
+ const OVERLAY_ROWS = [['boundaries', 'Borders'], ['placenames', 'Place names'], ['roads', 'Roads'], ['railway', 'Railways'],
+ ['power', 'Power lines'], ['seamarks', 'Sea marks'], ['gpstraces', 'GPS traces']];
const layerRows = $derived([
...OVERLAY_ROWS.map(([id, label]) => ({
id, label, on: overlays.includes(id), toggle: () => {
@@ -182,6 +187,8 @@
const marks = $derived(zoneMarks(zones));
const mapDate = $derived(s2.date || '');
const passChip = $derived(providerId === RADAR_ID ? passLabel(s1.pass) : mapDate);
+ let passCloud = $state(null);
+ const cloudyPass = $derived(providerId !== RADAR_ID && passCloud > ADVISED_MAXCC);
/**
* What Detect needs before a run can fetch anything: a Copernicus key, which
* Sentinel-2 lists once it is in Settings. Said in the middle of the map,
@@ -202,7 +209,7 @@
providerId = chosenBasemap;
// Only the layers still offered: a retired one (Labels) would be sent back
// with the next save and refused.
- overlays = (saved?.overlays ?? ['boundaries']).filter((id) => OVERLAY_ROWS.some(([row]) => row === id));
+ overlays = (saved?.overlays ?? ['boundaries', 'placenames']).filter((id) => OVERLAY_ROWS.some(([row]) => row === id));
savedVisible = saved?.saved ?? true;
prefsLoaded = true;
home = { ...prefs.homeView };
@@ -237,9 +244,19 @@
});
$effect(() => {
collapsed;
+ fullscreen;
void tick().then(() => engine?.resize());
});
+ // The panel comes along to the whole screen, since the review is worked from
+ // it; `]` still folds it away for the map alone.
+ $effect(() => {
+ if (toolEl) return followFullscreen(toolEl, (on) => (fullscreen = on));
+ });
+ function switchFullscreen() {
+ toggleFullscreen(toolEl).catch(() => toast('Full screen is not available', 'danger'));
+ }
+
// The same turn as Satellite and Compare: a middle-drag, or shift and the
// left button, turns the map about the point that was grabbed.
let rotating = $state(null);
@@ -503,9 +520,15 @@
);
}
- /** Put a pass on the map, so the picture is the one the work is about. */
- function showDate({ provider, date, time, layer, maxcc }) {
+ /**
+ * Put a pass on the map, so the picture is the one the work is about. A day is
+ * shown whole, as a run reads it: under the run's ceiling Sentinel Hub would
+ * drop a cloudier tile and leave the map black. Its cloud, when the lookup
+ * knows it, rides on the chip.
+ */
+ function showDate({ provider, date, time, layer, cloud = null }) {
if (!date) { leavePass(); return; }
+ passCloud = provider === RADAR_ID || !Number.isFinite(cloud) ? null : cloud;
if (provider === RADAR_ID) {
// A radar pass is shown by the radar basemap, once Settings has its layer.
if (!imagery.find(RADAR_ID)) return;
@@ -518,7 +541,7 @@
readingPass = true;
providerId = SENTINEL;
if (layer) s2.layer = layer;
- if (maxcc !== undefined && maxcc !== null) s2.setMaxcc(maxcc);
+ s2.setMaxcc(DEFAULT_MAXCC);
s2.date = date ?? '';
}
@@ -546,7 +569,7 @@
</script>
<svelte:window onkeydown={onKey} />
-<div class="detect-tool">
+<div class="detect-tool" bind:this={toolEl}>
<div class="stage">
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div class="surface-shell" oncontextmenu={onOverlayMenu}>
@@ -593,18 +616,21 @@
<button class="cmp-icon" title="Stop blinking" aria-label="Stop blinking" onclick={() => (blinking = false)}><Icon name="x" size={12} /></button>
</div>
{:else if readingPass}
- <button class="pass-chip cmp-glass" title="Return to your basemap" aria-label="Leave pass imagery" onclick={leavePass}>{passChip} <Icon name="x" size={12} /></button>
+ <button class="pass-chip cmp-glass" title="Return to your basemap" aria-label="Leave pass imagery" onclick={leavePass}>{passChip}
+ {#if cloudyPass}<span class="cloudy" title="Ground under cloud is left out of a run">{Math.round(passCloud)}% cloud</span>{/if}
+ <Icon name="x" size={12} /></button>
{/if}
<!-- Which way is up: the same reading every other map in the app shows,
which Detect lost when it turned the surface's own chrome off. -->
<Compass {bearing} onbearing={(deg) => engine?.setBearing(deg)} />
- <div class="ruler cmp-glass">
- <button class="cmp-icon" class:on={measuring} aria-pressed={measuring} aria-label="Measure"
- title="Measure a length (M)" onclick={toggleMeasure}><Icon name="ruler" size={15} /></button>
- {#if measures.length}
- <button class="cmp-icon" aria-label="Clear measures" title="Clear measures" onclick={clearMeasures}><Icon name="trash" size={14} /></button>
- {/if}
- </div>
+ </div>
+ <!-- Under the search and over the zoom buttons, which `controlsTop` pushes down to make room. -->
+ <div class="ruler cmp-glass">
+ <button class="cmp-icon" class:on={measuring} aria-pressed={measuring} aria-label="Measure"
+ title="Measure a length (M)" onclick={toggleMeasure}><Icon name="ruler" size={15} /></button>
+ {#if measures.length}
+ <button class="cmp-icon" aria-label="Clear measures" title="Clear measures" onclick={clearMeasures}><Icon name="trash" size={14} /></button>
+ {/if}
</div>
{#if home}
<MapSurface
@@ -631,7 +657,7 @@
else if (builder?.pinning && !measuring) panel?.pinAt({ lon, lat });
else if (builder && !measuring) void panel?.probeAt({ lon, lat });
}}
- controlsTop={98}
+ controlsTop={108}
{alternate}
alternateOn={showingA}
onusage={() => imagery.refreshUsage()}
@@ -690,6 +716,7 @@
tools={pointTools}
lookup={pointMenu.lookup}
{compareSources}
+ {fullscreen}
onpick={onPointMenu}
onclose={closePointMenu}
/>
@@ -725,6 +752,8 @@
<DetectPanel
bind:this={panel}
bind:collapsed
+ {fullscreen}
+ onfullscreen={switchFullscreen}
bind:manual
caseId={caseState.current?.id}
bind:zones
@@ -767,11 +796,11 @@
.search { position: absolute; top: 12px; left: 12px; z-index: 650; display: flex; width: min(280px, 42%); padding: 4px; }
.search :global(.place-search) { flex: 1; }
.map-choices { position: absolute; top: 12px; right: 12px; z-index: 650; display: grid; justify-items: end; gap: 8px; }
- .layer-picker { padding: 4px 8px; min-width: 112px; max-width: 250px; max-height: 50vh; overflow: auto; }
- .layer-picker :global(.sub-head) { display: flex; align-items: center; gap: 6px; width: 100%; min-height: 22px; font-size: var(--fs-xs); color: var(--text-2); }
+ .layer-picker { padding: 3px 8px; min-width: 112px; max-width: 250px; max-height: 50vh; overflow: auto; }
+ .layer-picker :global(.sub-head) { display: flex; align-items: center; gap: 6px; width: 100%; min-height: 22px; padding: 0 2px; font-size: var(--fs-xs); color: var(--text-2); }
.layer-picker :global(.count) { margin-left: auto; color: var(--text-3); }
.layer-picker :global(.layers) { min-width: 190px; margin-top: 8px; }
- .ruler { display: flex; padding: 2px; }
+ .ruler { position: absolute; top: 66px; left: 12px; z-index: 650; display: flex; padding: 2px; }
.blink-chip { padding: 2px 2px 2px 4px; }
.bench-bar { gap: 4px; padding: 2px 2px 2px 4px; }
.bench-bar .cmp-letter { cursor: pointer; }
@@ -781,6 +810,7 @@
.bench-bar .cmp-icon { width: 22px; height: 22px; }
.blink-chip .cmp-icon { width: 22px; height: 22px; }
.pass-chip { display: flex; align-items: center; gap: 8px; padding: 4px 8px; font-size: var(--fs-xs); }
+ .pass-chip .cloudy { color: var(--warn, #e2a03f); }
/* Over the map and under its own controls, which stay usable around it. */
.need-over {
position: absolute;
diff --git a/frontend/src/tools/Satellite.svelte b/frontend/src/tools/Satellite.svelte
index 25665af..7b572cd 100644
--- a/frontend/src/tools/Satellite.svelte
+++ b/frontend/src/tools/Satellite.svelte
@@ -51,6 +51,8 @@
import {
askable,
DATED as FIRMS_DATED,
+ firmsNote,
+ keyState,
lastDayOf,
summary,
tileParams,
@@ -212,13 +214,15 @@
let railOverlay = $state(false);
/**
* The other key-less reference layers, each simply on or off: Esri's borders
- * and roads, Open Infrastructure Map's power lines, OpenSeaMap's sea marks
- * and OSM's raw GPS traces. Borders start on, because every read of imagery
- * starts with which side of a line it is on; they are map tiles, the network
+ * and roads, OpenFreeMap's place names, Open Infrastructure Map's power
+ * lines, OpenSeaMap's sea marks and OSM's raw GPS traces. Borders and place
+ * names start on, because every read of imagery starts with which side of a
+ * line it is on and what the place is called; they are map tiles, the network
* a map is opened to use. The rest fetch no tile until their switch is pressed.
*/
const refLayers = $state({
boundaries: true,
+ placenames: true,
roads: false,
power: false,
seamarks: false,
@@ -240,6 +244,10 @@
const fires = $state({
on: false,
keyed: false,
+ /** Why it is not usable when it is not: 'missing' | 'off' | 'refused'. */
+ state: 'missing',
+ /** A spent allowance's pause, `{ until, used, of }`, while it lasts. */
+ paused: null,
sensors: [],
sensor: 'viirs',
window: '24h',
@@ -248,6 +256,7 @@
});
const firmsAskable = $derived(askable(fires));
const firmsSummary = $derived(summary(fires, fires.sensors));
+ const firmsKey = $derived(keyState(fires));
/** The archives a right-click can build a pair from. A keyed provider that is
* not configured is left out rather than offered and refused. */
@@ -273,9 +282,27 @@
const answer = await api.get('/api/firms/sensors');
fires.sensors = answer.sensors ?? [];
fires.keyed = Boolean(answer.keyed);
+ fires.state = answer.state ?? 'missing';
+ fires.paused = answer.paused ?? null;
} catch {
fires.keyed = false;
+ fires.paused = null;
}
+ // A pause ends on its own; the row hears it then rather than on the next
+ // failed tile. Our own backend, once, so nothing is polled.
+ clearTimeout(pauseTimer);
+ if (fires.paused) {
+ const left = Date.parse(fires.paused.until) - Date.now();
+ pauseTimer = setTimeout(loadFireSensors, Math.max(1000, left + 500));
+ }
+ }
+
+ let pauseTimer = null;
+ let troubleTimer = null;
+ /** A FIRMS tile failed: ask our backend why, once for the burst a screen makes. */
+ function fireTrouble() {
+ clearTimeout(troubleTimer);
+ troubleTimer = setTimeout(loadFireSensors, 800);
}
/** The two questions the fire layer asks, as rows under its switch. */
@@ -284,7 +311,7 @@
label: 'Sensor',
options: fires.sensors.map((entry) => ({
id: entry.id,
- // "VIIRS (S-NPP + NOAA-20)" does not fit a panel this wide, and the
+ // "VIIRS (S-NPP, NOAA-20, NOAA-21)" does not fit a panel this wide, and the
// instrument is the part being chosen between
label: entry.label.replace(/\s*\(.*\)\s*$/, ''),
title:
@@ -357,6 +384,7 @@
const overlays = $derived(
[
refLayers.boundaries && 'boundaries',
+ refLayers.placenames && baseIsImagery && 'placenames',
refLayers.roads && baseIsImagery && 'roads',
railOverlay && 'railway',
refLayers.power && 'power',
@@ -563,6 +591,8 @@
grid.destroy();
footprint.destroy();
markerSurface?.destroy();
+ clearTimeout(pauseTimer);
+ clearTimeout(troubleTimer);
};
}
@@ -627,10 +657,11 @@
if (fullscreen && !document.fullscreenElement) toggleFullscreen();
}
- // force the roads off whenever the base isn't imagery: a street map already
- // draws them
+ // force the roads and the place names off whenever the base isn't imagery: a
+ // street map already draws them
$effect(() => {
if (!baseIsImagery && refLayers.roads) refLayers.roads = false;
+ if (!baseIsImagery && refLayers.placenames) refLayers.placenames = false;
});
// While the picker is open, a settled pan refreshes its dates. The stale
@@ -1073,12 +1104,17 @@
*/
const armedCursor = $derived(modes[armedMode]?.pointing?.() ? cursorOf(armedMode) : null);
const RAIL = railSections(railEntries());
- /** The rail's inset from the map's top-left corner, shared with the CSS. */
- const RAIL_TOP = 12;
+ /** The search sits in the map's top-left corner and the rail under it, so
+ * the rail's inset follows the search's own height. */
+ let searchHeight = $state(0);
+ const railTop = $derived(12 + searchHeight + 8);
+ /** …and the imagery corner stops short of its width, wrapping rather than
+ * sliding under it on a narrow map. */
+ let searchWidth = $state(0);
/** Its own height, so the engine's zoom buttons stack under it rather than
* behind it — and keep doing so when a tool is added to the rail. */
let railHeight = $state(0);
- const railBottom = $derived(RAIL_TOP + railHeight + 8);
+ const railBottom = $derived(railTop + railHeight + 8);
/** Whether the case has anything the saved layer could draw, on any of its
* three positions — media reads its own index, so one length is not enough. */
@@ -1132,13 +1168,6 @@
* different intentions and used to be the same button.
*/
const layerRows = $derived([
- {
- id: 'railway',
- label: 'OSM railways',
- on: railOverlay,
- title: 'Tracks, sidings and stations, from OpenRailwayMap',
- toggle: () => (railOverlay = !railOverlay),
- },
{
id: 'boundaries',
label: 'Borders',
@@ -1146,6 +1175,17 @@
title: 'Country, region and district borders, from Esri',
toggle: () => (refLayers.boundaries = !refLayers.boundaries),
},
+ {
+ id: 'placenames',
+ label: 'Place names',
+ on: refLayers.placenames,
+ disabled: !baseIsImagery,
+ detail: baseIsImagery ? '' : 'imagery only',
+ title: baseIsImagery
+ ? 'Towns, villages and hamlets, from OpenStreetMap via OpenFreeMap'
+ : 'Only useful over satellite imagery',
+ toggle: () => (refLayers.placenames = !refLayers.placenames),
+ },
{
id: 'roads',
label: 'Roads',
@@ -1155,6 +1195,13 @@
title: baseIsImagery ? 'Road network over the imagery, from Esri' : 'Only useful over satellite imagery',
toggle: () => (refLayers.roads = !refLayers.roads),
},
+ {
+ id: 'railway',
+ label: 'Railways',
+ on: railOverlay,
+ title: 'Tracks, sidings and stations, from OpenRailwayMap',
+ toggle: () => (railOverlay = !railOverlay),
+ },
{
id: 'power',
label: 'Power lines',
@@ -1182,18 +1229,16 @@
label: 'Active fires',
on: fires.on,
disabled: !fires.keyed,
- detail: fires.keyed ? firmsSummary : 'needs a free key',
- title: fires.keyed
- ? 'Thermal detections from NASA FIRMS, live or from the archive'
- : 'Add a NASA FIRMS key in Settings → Imagery',
+ detail: fires.keyed ? firmsSummary : firmsKey.detail,
+ title: fires.keyed ? 'Thermal detections from NASA FIRMS, live or from the archive' : firmsKey.title,
toggle: () => (fires.on = !fires.on),
- // A switch that cannot be pressed says why and where the key goes, on the
- // row itself rather than only on a greyed-out eye nobody hovers.
- actions: fires.keyed ? null : [{ label: 'Add a FIRMS key', quiet: true, run: openImagerySettings }],
+ // A switch that cannot be pressed says why and where to go, on the row
+ // itself rather than only on a greyed-out eye nobody hovers.
+ actions: fires.keyed ? null : [{ label: firmsKey.action, quiet: true, run: openImagerySettings }],
// its two questions — which instrument, and over what — are asked in the
// row rather than in a card of its own floating somewhere
controls: fires.on && fires.keyed ? firmsControls : null,
- note: fires.on && !firmsAskable ? 'Pick a date to draw the detections.' : '',
+ note: fires.on && fires.keyed ? firmsNote(fires, fires.paused) : '',
},
{
id: 'nightlights',
@@ -2102,50 +2147,7 @@
</script>
<div class="tool" class:fullscreen bind:this={toolEl}>
- <div class="tool-header">
- <!-- Two identical windows on a second screen are otherwise impossible to
- tell apart; the first one needs no number and says nothing. -->
- <h2>Satellite{windowNumber ? ` · ${windowNumber}` : ''}</h2>
- <div class="spacer"></div>
- <PlaceSearch
- bind:value={coordsText}
- savedRows={savedWork.rows}
- centre={{ lat: center.lat, lon: center.lon }}
- units={prefs.units}
- {searching}
- onpick={goToSuggestion}
- onsubmit={goTo}
- />
- <!-- What the window does with the tool, not what the tool does with the
- map: these sit with the title rather than among the map's own controls. -->
- <button
- class="btn btn-icon"
- class:on={linked}
- onclick={toggleLink}
- disabled={!peerMaps}
- title={!peerMaps
- ? 'Open a second map tab or the extension map tools to link the views'
- : linked
- ? 'Stop following the other maps'
- : 'Pan and zoom with the other maps'}
- aria-label="Link the view to the other maps"
- ><Icon name="link" size={15} /></button>
- <button
- class="btn btn-icon"
- onclick={detachWindow}
- title="Open this map in a tab of its own, on this view"
- aria-label="Open in a new tab"
- ><Icon name="external" size={15} /></button>
- <button
- class="btn btn-icon"
- class:on={fullscreen}
- onclick={toggleFullscreen}
- title={fullscreen ? 'Exit fullscreen (Esc)' : 'Fullscreen map'}
- aria-label="Toggle fullscreen"
- ><Icon name={fullscreen ? 'minimize' : 'maximize'} size={15} /></button>
- </div>
-
- <div class="body">
+ <div class="body" style:--surface-ctl-reserve={`${12 + searchWidth + 8}px`}>
{#if homeReady}
<MapSurface
bind:this={surface}
@@ -2172,6 +2174,7 @@
onwidgetload={(meter) => imagery.countLoad(meter)}
onwidgetauthfailure={onWidgetAuthFailure}
onwidgetfailed={onWidgetFailed}
+ onoverlaytrouble={(id) => id === 'firms' && fireTrouble()}
onviewsettled={(camera) => share.settled(camera, engine?.maxZoom())}
>
<!-- saved work on the map: navigation only, off by default, session-only.
@@ -2222,10 +2225,58 @@
/>
{/if}
+ <!-- What the window does with the tool, beside the imagery it shows. -->
+ {#snippet beside()}
+ <div class="window-ctl">
+ <button
+ class="btn btn-icon"
+ class:on={linked}
+ onclick={toggleLink}
+ disabled={!peerMaps}
+ title={!peerMaps
+ ? 'Open a second map tab or the extension map tools to link the views'
+ : linked
+ ? 'Stop following the other maps'
+ : 'Pan and zoom with the other maps'}
+ aria-label="Link the view to the other maps"
+ ><Icon name="link" size={15} /></button>
+ <button
+ class="btn btn-icon"
+ onclick={detachWindow}
+ title="Open this map in a tab of its own, on this view"
+ aria-label="Open in a new tab"
+ ><Icon name="external" size={15} /></button>
+ <button
+ class="btn btn-icon"
+ class:on={fullscreen}
+ onclick={toggleFullscreen}
+ title={fullscreen ? 'Exit fullscreen (Esc)' : 'Fullscreen map'}
+ aria-label="Toggle fullscreen"
+ ><Icon name={fullscreen ? 'minimize' : 'maximize'} size={15} /></button>
+ </div>
+ {/snippet}
+
+ <!-- The search floats over the map as Detect's does, above the rail: the
+ tab strip already says which tool this is. -->
+ <div class="map-bar" bind:clientHeight={searchHeight} bind:clientWidth={searchWidth}>
+ <!-- Two identical windows on a second screen are otherwise impossible to
+ tell apart; the first one needs no number and says nothing. -->
+ {#if windowNumber}<span class="window-no mono" title="This map's window">Map {windowNumber}</span>{/if}
+ <PlaceSearch
+ bind:value={coordsText}
+ savedRows={savedWork.rows}
+ centre={{ lat: center.lat, lon: center.lon }}
+ units={prefs.units}
+ {searching}
+ onpick={goToSuggestion}
+ onsubmit={goTo}
+ />
+ </div>
+
<!-- The map's toolbox, and the one slot the armed tool's settings open
in. Only verbs live here; what is *drawn* over the imagery is a layer
and is listed in the panel on the right. -->
- <div class="map-tools">
+ <div class="map-tools" style:top={`${railTop}px`}>
<MapRail
sections={RAIL}
bind:height={railHeight}
@@ -2797,6 +2848,58 @@
:global(.sat-marker) {
filter: drop-shadow(0 1px 2px rgba(0, 0, 0, 0.5));
}
+ .map-bar {
+ position: absolute;
+ top: 12px;
+ left: 12px;
+ /* over the rail (1100), which its suggestions list drops across */
+ z-index: 1150;
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ padding: 4px;
+ border-radius: var(--radius-1);
+ background: rgba(24, 24, 24, 0.88);
+ backdrop-filter: blur(6px);
+ box-shadow: 0 0 0 1px var(--border);
+ }
+ .map-bar :global(.place-search) {
+ width: min(360px, 30vw);
+ }
+ /* no frame of its own: it shares the imagery card (MapSurface's .ctl-row),
+ after a rule, as Compare's source card ends on its own two buttons */
+ .window-ctl {
+ display: flex;
+ align-items: center;
+ gap: 2px;
+ padding-left: 5px;
+ margin-left: 1px;
+ border-left: 1px solid var(--border);
+ }
+ .window-ctl .btn-icon {
+ justify-content: center;
+ width: 28px;
+ height: 28px;
+ padding: 0;
+ color: var(--text-2);
+ background: transparent;
+ border-color: transparent;
+ }
+ .window-ctl .btn-icon:hover:not(:disabled) {
+ color: var(--text-1);
+ background: var(--bg-2);
+ border-color: transparent;
+ }
+ .window-ctl .btn-icon.on {
+ color: var(--accent);
+ background: var(--accent-soft);
+ }
+ .window-no {
+ padding: 0 6px;
+ font-size: var(--fs-xs);
+ color: var(--text-2);
+ white-space: nowrap;
+ }
/* fullscreen: the whole tool covers the viewport, above the app chrome */
.tool.fullscreen {
position: fixed;
@@ -2810,7 +2913,6 @@
buttons — which the rail now stacks on top of rather than beside. */
.map-tools {
position: absolute;
- top: 12px;
left: 12px;
z-index: 1100;
/* the rail sits in flow here, so this box is exactly rail-wide — which is
diff --git a/frontend/src/tools/Satellite.test.js b/frontend/src/tools/Satellite.test.js
index 3f6ddba..bc1453b 100644
--- a/frontend/src/tools/Satellite.test.js
+++ b/frontend/src/tools/Satellite.test.js
@@ -356,8 +356,26 @@ describe('what is laid over the imagery', () => {
expect(source).toContain("refLayers.roads && baseIsImagery && 'roads'");
expect(source).toContain("railOverlay && 'railway'");
const rows = source.slice(source.indexOf('const layerRows = $derived(['));
- expect(rows.slice(0, 900)).toContain("label: 'OSM railways'");
- expect(rows.slice(0, 900)).toContain('toggle: () => (railOverlay = !railOverlay)');
+ expect(rows).toContain('toggle: () => (railOverlay = !railOverlay)');
+ });
+
+ it('lists its layers in the order Compare, Detect and the proof map use', () => {
+ // the plain references first, then the specialist networks, the dated
+ // events, and the case last
+ const rows = source.slice(source.indexOf('const layerRows = $derived(['), source.indexOf('...(sheetPoints'));
+ const labels = [...rows.matchAll(/^ {6}label: '([^']+)'/gm)].map((match) => match[1]);
+ expect(labels).toEqual([
+ 'Borders',
+ 'Place names',
+ 'Roads',
+ 'Railways',
+ 'Power lines',
+ 'Sea marks',
+ 'GPS traces',
+ 'Active fires',
+ 'Night lights',
+ 'Saved work',
+ ]);
});
it('gives the railways no rail seat', () => {
@@ -387,19 +405,31 @@ describe('what is laid over the imagery', () => {
expect(back.slice(0, 700)).toContain('loadFireSensors()');
});
- it('offers the layer disabled, with the reason, when there is no key', () => {
+ it('offers the layer disabled, with the reason, when the key cannot be used', () => {
const rows = source.slice(source.indexOf('const layerRows = $derived(['));
expect(rows).toContain('disabled: !fires.keyed');
- expect(rows).toContain('Add a NASA FIRMS key in Settings → Imagery');
- // said on the row, where it can be read without hovering a greyed switch
- expect(rows).toContain("detail: fires.keyed ? firmsSummary : 'needs a free key'");
- expect(rows).toContain("actions: fires.keyed ? null : [{ label: 'Add a FIRMS key', quiet: true, run: openImagerySettings }]");
+ // said on the row, where it can be read without hovering a greyed switch;
+ // no key, a key switched off and a refused key each say their own thing
+ // (`keyState`, tested in lib/map/firms.test.js)
+ expect(rows).toContain('detail: fires.keyed ? firmsSummary : firmsKey.detail');
+ expect(rows).toContain('actions: fires.keyed ? null : [{ label: firmsKey.action, quiet: true, run: openImagerySettings }]');
+ expect(source).toContain('const firmsKey = $derived(keyState(fires));');
expect(source).toContain("uiState.settingsTab = 'imagery';");
});
+ it('asks its own backend why when a fire tile fails, once for the burst', () => {
+ // the map shows nothing for a failed tile, so the row would never hear
+ // about a spent allowance or a refused key without this
+ expect(source).toContain("onoverlaytrouble={(id) => id === 'firms' && fireTrouble()}");
+ const trouble = source.slice(source.indexOf('function fireTrouble()'));
+ expect(trouble.slice(0, 200)).toContain('clearTimeout(troubleTimer)');
+ expect(trouble.slice(0, 200)).toContain('setTimeout(loadFireSensors');
+ });
+
it('says a layer is for imagery only when the basemap is not imagery', () => {
const rows = source.slice(source.indexOf('const layerRows = $derived(['));
- expect(rows.match(/detail: baseIsImagery \? '' : 'imagery only'/g)).toHaveLength(1);
+ // the roads and the place names, which a street map already draws
+ expect(rows.match(/detail: baseIsImagery \? '' : 'imagery only'/g)).toHaveLength(2);
});
it('asks for no tile until the choice is one the service can answer', () => {
@@ -678,6 +708,37 @@ describe('a map in more than one window', () => {
expect(source).toContain('if (!count) linked = false;');
});
+ it('has no title row: the search floats above the rail, the window buttons beside the imagery', () => {
+ // the tab strip already names the tool, and every row above the map is map lost
+ expect(source).not.toContain('<div class="tool-header">');
+ const bar = source.slice(source.indexOf('<div class="map-bar"'), source.indexOf('<div class="map-tools"'));
+ expect(bar).toContain('<PlaceSearch');
+ // the rail starts under the search, however tall it renders
+ expect(source).toContain('const railTop = $derived(12 + searchHeight + 8);');
+ expect(source).toContain('<div class="map-tools" style:top={`${railTop}px`}>');
+ const beside = source.slice(source.indexOf('{#snippet beside()}'), source.indexOf('{/snippet}', source.indexOf('{#snippet beside()}')));
+ for (const label of ['Link the view to the other maps', 'Open in a new tab', 'Toggle fullscreen']) {
+ expect(beside).toContain(`aria-label="${label}"`);
+ }
+ // on the imagery chip's right, where the corner ends
+ const row = satelliteSources()['satellite/MapSurface.svelte'];
+ const ctl = row.slice(row.indexOf('<div class="ctl-row">'), row.indexOf('</div>', row.indexOf('<div class="ctl-row">')));
+ expect(ctl.indexOf('<ImageryChip')).toBeGreaterThan(-1);
+ expect(ctl.indexOf('{@render beside()}')).toBeGreaterThan(ctl.indexOf('<ImageryChip'));
+ });
+
+ it('dates Sentinel-2 on its chip and again under it, as the radar pass is', () => {
+ const surface = satelliteSources()['satellite/MapSurface.svelte'];
+ const s2Pill = surface.slice(
+ surface.indexOf('{#if s2 && shown.provider?.id === SENTINEL_ID}'),
+ surface.indexOf('{:else if s1 && shown.provider?.id === RADAR_ID}')
+ );
+ // the pill always reads the day, marks a pinned one, and says how it was chosen
+ expect(s2Pill).toContain('{pinnedDay ?? s2.latest ?? \'\'}');
+ expect(s2Pill).toContain('class:exact={!!pinnedDay}');
+ expect(s2Pill).toContain("{s2.latest ? 'latest' : 'most recent'}");
+ });
+
it('opens that tab on the map alone', () => {
// the rail, the case bar and the tab strip are how you get somewhere else,
// and a second screen showing one map is already somewhere (lib/hash.js)
@@ -686,7 +747,7 @@ describe('a map in more than one window', () => {
it('numbers a detached window, and leaves the first one unnumbered', () => {
expect(source).toContain('const windowNumber = readWindowLabel(opening.params)');
- expect(source).toContain('<h2>Satellite{windowNumber ? ` · ${windowNumber}` : \'\'}</h2>');
+ expect(source).toContain('{#if windowNumber}<span class="window-no mono" title="This map\'s window">Map {windowNumber}</span>{/if}');
expect(source).toContain('if (windowNumber) document.title = `Azimut · Map ${windowNumber}`');
});
@@ -740,25 +801,29 @@ describe('one camera for the map tabs', () => {
});
describe('the key-less reference layers', () => {
- it('fetches no tile from any of them until its switch is pressed, borders apart', () => {
+ it('fetches no tile from any of them until its switch is pressed, borders and place names apart', () => {
// local-first: a map not showing power lines asks nobody about power lines.
- // Borders are the exception and are on from the start — they are map tiles,
- // which is the network a map is opened to use.
+ // Borders and place names are the exception and are on from the start —
+ // they are map tiles, which is the network a map is opened to use.
const state = source.slice(
source.indexOf('const refLayers = $state({'),
source.indexOf('const night = $state(')
);
expect(state).toContain('boundaries: true');
- expect(state.replace('boundaries: true', '')).not.toContain('true');
+ expect(state).toContain('placenames: true');
+ expect(state.replace('boundaries: true', '').replace('placenames: true', '')).not.toContain('true');
expect(source).toContain("const night = $state({ on: false, source: 'noaa20', day: lastNight() });");
});
- it('asks for each by id, and the roads only over imagery like the labels', () => {
+ it('asks for each by id, and the roads and the place names only over imagery', () => {
for (const id of ['boundaries', 'power', 'seamarks', 'gpstraces']) {
expect(source).toContain(`refLayers.${id} && '${id}'`);
}
- expect(source).toContain("refLayers.roads && baseIsImagery && 'roads'");
- expect(source).toContain('if (!baseIsImagery && refLayers.roads) refLayers.roads = false;');
+ // a street map already names its villages and draws its roads
+ for (const id of ['roads', 'placenames']) {
+ expect(source).toContain(`refLayers.${id} && baseIsImagery && '${id}'`);
+ expect(source).toContain(`if (!baseIsImagery && refLayers.${id}) refLayers.${id} = false;`);
+ }
});
it('asks GIBS for no night until the choice is one it can answer', () => {
diff --git a/frontend/src/tools/Settings.svelte b/frontend/src/tools/Settings.svelte
index 47d0d18..6cc8552 100644
--- a/frontend/src/tools/Settings.svelte
+++ b/frontend/src/tools/Settings.svelte
@@ -143,7 +143,7 @@
'One key serves both the global and the US/Canada service.',
],
overage:
- 'The limit is 5,000 requests per 10 minutes, which only a layer left on while panning could approach.',
+ 'The limit is 5,000 transactions per 10 minutes, and every day a map tile covers counts, so a long range spends it fastest.',
},
];
diff --git a/frontend/src/tools/compare/AnnotationToolbar.svelte b/frontend/src/tools/compare/AnnotationToolbar.svelte
index 45cea77..1b356e5 100644
--- a/frontend/src/tools/compare/AnnotationToolbar.svelte
+++ b/frontend/src/tools/compare/AnnotationToolbar.svelte
@@ -27,8 +27,11 @@
count = 0,
side = $bindable('both'),
setSide = () => {},
+ collapsed = $bindable(false),
} = $props();
+ const armed = $derived(ANNOTATION_TOOLS.find((entry) => entry.id === tool && entry.id !== 'select'));
+
const contextual = $derived(tool !== 'select' || Boolean(selected));
const fillable = $derived(canFill(selected?.kind ?? tool));
// A note and a stamp are sized by their own number: neither has a line to
@@ -70,7 +73,7 @@
// nothing selected, or deletes what was selected. Drop the panel with them
// rather than leaving it floating over the maps with nothing behind it.
$effect(() => {
- if (!contextual || (open === 'fill' && !fillable) || (open === 'outline' && !outlined)) open = '';
+ if (collapsed || !contextual || (open === 'fill' && !fillable) || (open === 'outline' && !outlined)) open = '';
});
$effect(() => {
@@ -91,6 +94,18 @@
});
</script>
+<div class="annotation-rail" class:folded={collapsed}>
+{#if collapsed}
+ <!-- Folded, the rail gives its width to the maps and keeps a strip that says
+ what it holds, and the tool still in hand, which a press puts down. -->
+ {#if armed}
+ <button class="tool-button active" aria-pressed="true" title={`${armed.label} (${armed.shortcut})`}
+ onclick={() => (tool = 'select')}><Icon name={armed.icon} size={18} /></button>
+ {/if}
+ <button class="rail-strip" title="Show the annotation tools ([)" onclick={() => (collapsed = false)}>
+ <span class="strip-label">Annotations</span>
+ </button>
+{:else}
<aside class="annotation-toolbar" aria-label="Comparison annotation tools">
<button class="tool-button" title="Undo (Ctrl+Z)" disabled={!canUndo} onclick={undo}><Icon name="undo" size={18} /></button>
<button class="tool-button" title="Redo (Ctrl+Shift+Z)" disabled={!canRedo} onclick={redo}><Icon name="redo" size={18} /></button>
@@ -160,6 +175,17 @@
<button class="tool-button" title="Clear all annotations" onclick={clear}><Icon name="reset" size={18} /></button>
{/if}
</aside>
+{/if}
+ <!-- The tab on the map's edge, as a map's side panel has: the same place
+ folds the rail and brings it back. -->
+ <button
+ class="rail-tab"
+ aria-label={collapsed ? 'Show the annotation tools' : 'Hide the annotation tools'}
+ aria-expanded={!collapsed}
+ title={collapsed ? 'Show the annotation tools ([)' : 'Hide the annotation tools ([)'}
+ onclick={() => (collapsed = !collapsed)}
+ ><Icon name={collapsed ? 'chevronRight' : 'chevronLeft'} size={15} /></button>
+</div>
{#if open === 'glyph'}
<div class="flyout glyphs" bind:this={flyoutEl} style:left={flyout.left} style:top={flyout.top} style:bottom={flyout.bottom}>
@@ -271,6 +297,60 @@
font-size: 8px;
line-height: 1;
}
+ .annotation-rail {
+ position: relative;
+ z-index: 610;
+ display: flex;
+ flex: 0 0 auto;
+ }
+ .annotation-rail.folded {
+ flex-direction: column;
+ align-items: center;
+ gap: 4px;
+ width: 26px;
+ padding-top: 6px;
+ border-right: 1px solid var(--border);
+ background: var(--bg-1);
+ }
+ .folded .tool-button { width: 24px; height: 28px; }
+ .rail-strip {
+ flex: 1;
+ align-self: stretch;
+ display: flex;
+ justify-content: center;
+ padding-top: 6px;
+ color: var(--text-3);
+ cursor: pointer;
+ }
+ .rail-strip:hover { color: var(--text-1); background: var(--bg-2); }
+ .strip-label {
+ writing-mode: vertical-rl;
+ transform: rotate(180deg);
+ font-size: var(--fs-xs);
+ font-weight: 600;
+ letter-spacing: .08em;
+ text-transform: uppercase;
+ }
+ /* Half on the rail's edge, half on the map, at mid-height where no map
+ control sits. */
+ .rail-tab {
+ position: absolute;
+ top: 50%;
+ left: 100%;
+ display: grid;
+ place-items: center;
+ width: 20px;
+ height: 48px;
+ transform: translateY(-50%);
+ border: 1px solid var(--border-strong);
+ border-left: 0;
+ border-radius: 0 8px 8px 0;
+ color: var(--text-2);
+ background: var(--bg-1);
+ box-shadow: var(--shadow-1);
+ cursor: pointer;
+ }
+ .rail-tab:hover { color: var(--text-1); background: var(--bg-2); }
.separator {
grid-column: 1 / -1;
justify-self: stretch;
diff --git a/frontend/src/tools/compare/DifferenceBar.svelte b/frontend/src/tools/compare/DifferenceBar.svelte
index c0a402e..0f090cc 100644
--- a/frontend/src/tools/compare/DifferenceBar.svelte
+++ b/frontend/src/tools/compare/DifferenceBar.svelte
@@ -8,9 +8,11 @@
* hangs from its edge: a label that grew on every read moved the panel under
* the pointer. What a read is doing is said in the panel and the map legend.
*
- * The reading follows the camera by itself. What it never does on a pan is
- * spend a request: a method that reads Sentinel-2 bands runs on the frames it
- * holds, and waits for Read once the camera leaves the ground they cover.
+ * The reading follows the camera by itself. A method that reads Sentinel-2
+ * bands runs on the frames it holds, and past the ground they cover fetches
+ * them again once the camera rests, for a pair it has already read.
+ * Read says which of those it is: lit when the next move is the analyst's,
+ * and naming what the reading does otherwise, never a press that does nothing.
*/
import { CHANGE_BASES, CHANGE_METHODS, CHANGE_INDICES, CHANGE_DISPLAYS, CHANGE_CLASSES,
changeNeedsFrames, changeSettings, indexThreshold } from '../../lib/map/changeAssist.js';
@@ -21,9 +23,9 @@
settings = $bindable(),
status,
result = null,
- busy = false,
+ /** due: Read has something to do · reading · tiles: waiting on the maps · current: nothing moved. */
+ reading = 'due',
error = '',
- stale = false,
onrun = () => {},
onzone = () => {},
/** Keep this index reading as a Detect analyzer, to sweep areas with it. */
@@ -36,6 +38,23 @@
// What this reading has to fetch, and therefore whether it can follow the map.
const frames = $derived(changeNeedsFrames(settings, status));
const index = $derived(CHANGE_INDICES.find((entry) => entry.id === settings.index));
+ const busy = $derived(reading === 'reading' || reading === 'tiles');
+ const stale = $derived(!!result && reading === 'due');
+ const due = $derived(runnable && reading === 'due');
+ const READ = {
+ due: ['Read', 'Read the pixels in this view'],
+ reading: ['Reading…', 'Reading the pixels in this view'],
+ tiles: ['Loading…', 'Waiting for the map tiles to load'],
+ current: ['Up to date', 'Nothing moved since the last read'],
+ };
+ const read = $derived(READ[reading] ?? READ.due);
+ // Choosing what to read is asking for it, as the cloud switch is: the reading
+ // runs then, bands included, rather than waiting on a second press of Read.
+ const chosen = () => queueMicrotask(() => onrun());
+ const readTitle = $derived(!status.ok ? status.reason
+ : !runnable ? 'This method needs another imagery source'
+ : reading === 'due' && frames ? 'Read this view, one Sentinel-2 request a side'
+ : read[1]);
// A press anywhere off the strip and its panel closes the panel. The strip
// counts as inside: Read or a base pressed with the settings open is tuning
@@ -78,9 +97,8 @@
>
<Icon name="blink" size={15} />
</button>
- <button class="text-btn read" class:busy disabled={busy || !runnable} onclick={() => onrun()}
- title={runnable ? 'Read the pixels in this view again' : (status.ok ? 'This method needs another imagery source' : status.reason)}>
- {busy ? 'Reading…' : 'Read'}
+ <button class="text-btn read" class:busy class:due disabled={!due} onclick={() => onrun()} title={readTitle}>
+ {runnable ? read[0] : 'Read'}
</button>
<button
class="cmp-icon"
@@ -137,7 +155,7 @@
{#if frames}
<p class="hint">
Reads Sentinel-2 bands, one request a side, kept with a margin around this view.
- Panning inside it costs nothing; past it, press Read.
+ Panning inside it costs nothing; past it, the bands are fetched again once the map rests.
</p>
{/if}
@@ -149,13 +167,13 @@
{#if tab === 'detection'}
<label title="What to compare: colour, edges or a spectral index.">Method
- <select aria-label="Method" bind:value={settings.method}>
+ <select aria-label="Method" bind:value={settings.method} onchange={chosen}>
{#each CHANGE_METHODS as method}<option value={method.id} disabled={!status.methods.includes(method.id)}>{method.label}</option>{/each}
</select>
</label>
{#if settings.method === 'index'}
<label title="The spectral index compared between the two passes.">Index
- <select bind:value={settings.index}>{#each CHANGE_INDICES as entry}<option value={entry.id}>{entry.label} · {entry.hint}</option>{/each}</select>
+ <select bind:value={settings.index} onchange={chosen}>{#each CHANGE_INDICES as entry}<option value={entry.id}>{entry.label} · {entry.hint}</option>{/each}</select>
</label>
{:else}
<label title="Adapt the threshold to this view, or follow the sensitivity.">Threshold
@@ -257,9 +275,15 @@
background: var(--glass-hover);
}
.text-btn:disabled { opacity: 0.4; }
- /* Wide enough for "Reading…", so the strip keeps its width through a read. */
- .text-btn.read { min-width: 70px; text-align: center; }
+ /* One width for every label, so the gear beside it never moves. */
+ .text-btn.read { width: 84px; text-align: center; white-space: nowrap; }
.text-btn.read.busy:disabled { opacity: 0.75; }
+ /* Lit only when pressing it is the next move, in the primary-action amber. */
+ .text-btn.read.due {
+ color: var(--accent-text);
+ background: var(--accent);
+ }
+ .text-btn.read.due:hover { color: var(--accent-text); background: var(--accent-hover); }
.name {
font-size: var(--fs-xs);
letter-spacing: 0.04em;
diff --git a/frontend/src/tools/compare/DifferenceBar.test.js b/frontend/src/tools/compare/DifferenceBar.test.js
index c7ab257..73282d0 100644
--- a/frontend/src/tools/compare/DifferenceBar.test.js
+++ b/frontend/src/tools/compare/DifferenceBar.test.js
@@ -105,6 +105,34 @@ describe('Difference strip', () => {
done();
});
+ it('says what the reading is doing on Read itself, and lights it only when pressing it does something', () => {
+ const result = { share: 0.1, coverage: 1, area: 20, zones: [], zoneCount: 0 };
+ const read = (target) => target.querySelector('button.read');
+ const seen = Object.fromEntries(['due', 'reading', 'tiles', 'current'].map((reading) => {
+ const { target, done } = render({ reading, result });
+ const node = read(target);
+ const shown = [node.textContent.trim(), node.disabled, node.classList.contains('due'), node.title];
+ done();
+ return [reading, shown];
+ }));
+ expect(seen.due).toEqual(['Read', false, true, 'Read the pixels in this view']);
+ expect(seen.reading).toEqual(['Reading…', true, false, 'Reading the pixels in this view']);
+ expect(seen.tiles).toEqual(['Loading…', true, false, 'Waiting for the map tiles to load']);
+ // A press on an up-to-date reading used to do nothing and say nothing.
+ expect(seen.current).toEqual(['Up to date', true, false, 'Nothing moved since the last read']);
+ // What a press will cost is said before it is spent.
+ const bands = render({ reading: 'due', settings: changeSettings({ ignore_clouds: true }) });
+ expect(read(bands.target).title).toBe('Read this view, one Sentinel-2 request a side');
+ bands.done();
+ });
+
+ it('gives Read one width for every label, so the gear beside it never moves', () => {
+ const here = dirname(fileURLToPath(import.meta.url));
+ const source = readFileSync(join(here, 'DifferenceBar.svelte'), 'utf8');
+ expect(source).toMatch(/\.text-btn\.read \{ width: \d+px;/);
+ expect(source).not.toMatch(/\.text-btn\.read \{[^}]*min-width/);
+ });
+
it('blinks the highlights on and off, which only touches the overlay', () => {
const onrun = vi.fn();
const { target, done } = render({ onrun });
@@ -119,7 +147,7 @@ describe('Difference strip', () => {
it('says so in the panel when the highlights are from an earlier read', () => {
const result = { share: 0.1, coverage: 1, area: 20, zones: [], zoneCount: 0 };
- const { target, done } = render({ stale: true, result }, { open: true });
+ const { target, done } = render({ reading: 'due', result }, { open: true });
expect(target.querySelector('.readout').textContent).toContain('From an earlier read');
done();
});
@@ -132,7 +160,7 @@ describe('Difference strip', () => {
const idle = render({}, { open: true });
const before = shape(idle.target);
idle.done();
- const reading = render({ busy: true, error: 'Could not compare these pixels', stale: true }, { open: true });
+ const reading = render({ reading: 'reading', error: 'Could not compare these pixels' }, { open: true });
expect(shape(reading.target)).toEqual(before);
expect(reading.target.querySelector('.readout [role="alert"]').textContent).toBe('Could not compare these pixels');
reading.done();
@@ -184,6 +212,20 @@ describe('Difference strip', () => {
free.done();
});
+ it('reads the view as soon as a method or an index is chosen', async () => {
+ const onrun = vi.fn();
+ const { target, done } = render({ settings: changeSettings({ method: 'index', index: 'nbr' }),
+ status: { ...ready, methods: ['colour', 'index'] }, onrun }, { open: true });
+ const [method, index] = target.querySelectorAll('aside.settings select');
+ index.dispatchEvent(new Event('change', { bubbles: true }));
+ await Promise.resolve();
+ expect(onrun).toHaveBeenCalledTimes(1);
+ method.dispatchEvent(new Event('change', { bubbles: true }));
+ await Promise.resolve();
+ expect(onrun).toHaveBeenCalledTimes(2);
+ done();
+ });
+
it('reads the view as soon as the cloud filter is switched on', async () => {
// The switch says the sky is being read, so it cannot leave an unfiltered
// reading up behind it.
@@ -198,7 +240,7 @@ describe('Difference strip', () => {
it('states the index change it draws the line at', () => {
const { target, done } = render({ settings: changeSettings({ method: 'index', index: 'nbr' }) }, { open: true });
- expect(target.textContent).toContain('NBR moved by 0.25');
+ expect(target.textContent).toContain('NBR moved by 0.19');
done();
});
});
diff --git a/frontend/src/tools/compare/LayerPane.render.test.js b/frontend/src/tools/compare/LayerPane.render.test.js
new file mode 100644
index 0000000..17439f8
--- /dev/null
+++ b/frontend/src/tools/compare/LayerPane.render.test.js
@@ -0,0 +1,45 @@
+import { describe, expect, it } from 'vitest';
+import { render } from 'svelte/server';
+import LayerPane from './LayerPane.svelte';
+
+const FIRES = { id: 'firms', label: 'Active fires', hint: 'Thermal detections from NASA FIRMS' };
+
+function pane(props) {
+ return render(LayerPane, {
+ props: {
+ letter: 'A',
+ present: true,
+ layers: [FIRES],
+ overlays: ['firms'],
+ firms: { sensor: 'viirs', window: '7d', first: '', last: '' },
+ night: {},
+ firmsSensors: [{ id: 'viirs', label: 'VIIRS' }],
+ firesKeyed: true,
+ savedCount: 0,
+ ontoggle: () => {},
+ onfirms: () => {},
+ onnight: () => {},
+ oncopy: () => {},
+ onclear: () => {},
+ ...props,
+ },
+ }).body;
+}
+
+describe('the fire layer on one side of Compare', () => {
+ it('says a refused key is refused rather than missing', () => {
+ const body = pane({ firesKeyed: false, firesState: 'refused' });
+ expect(body).toContain('FIRMS does not know this key');
+ expect(body).not.toContain('Add a NASA FIRMS key');
+ });
+
+ it('keeps its settings and says when a spent allowance refills', () => {
+ const body = pane({ firesPaused: { until: '2026-09-26T12:00:00+00:00', used: 4990, of: 5000 } });
+ expect(body).toContain('Active fires settings for imagery A');
+ expect(body).toContain('FIRMS allowance used up. It refills within ten minutes.');
+ });
+
+ it('explains the two colours of a week', () => {
+ expect(pane({})).toContain('Red: the last 24 hours. Amber: before them.');
+ });
+});
diff --git a/frontend/src/tools/compare/LayerPane.svelte b/frontend/src/tools/compare/LayerPane.svelte
index f2ac4ae..32ec3eb 100644
--- a/frontend/src/tools/compare/LayerPane.svelte
+++ b/frontend/src/tools/compare/LayerPane.svelte
@@ -4,6 +4,8 @@
import Icon from '../../components/Icon.svelte';
import {
DATED as FIRMS_DATED,
+ firmsNote,
+ keyState,
lastDayOf,
today as firmsToday,
WINDOWS as FIRMS_WINDOWS,
@@ -24,6 +26,10 @@
night,
firmsSensors,
firesKeyed,
+ /** Why the fire layer is not usable when it is not (`keyState`). */
+ firesState = 'missing',
+ /** A spent FIRMS allowance's pause, while it lasts. */
+ firesPaused = null,
savedCount,
ontoggle,
onfirms,
@@ -35,9 +41,11 @@
const disabled = (id) =>
!present || (id === 'firms' && !firesKeyed) || (id === 'saved' && !savedCount);
const on = (id) => overlays.includes(id);
+ const fireKey = $derived(keyState({ keyed: firesKeyed, state: firesState }));
+ const fireNote = $derived(firmsNote(firms, firesPaused));
const disabledReason = (id) =>
id === 'firms' && !firesKeyed
- ? 'Add a FIRMS key in Settings'
+ ? fireKey.title
: id === 'saved' && !savedCount
? 'No saved work in this case'
: '';
@@ -143,6 +151,7 @@
</label>
</div>
{/if}
+ {#if fireNote}<p class="baseline">{fireNote}</p>{/if}
</div>
{/if}
diff --git a/frontend/src/tools/compare/ModeDock.svelte b/frontend/src/tools/compare/ModeDock.svelte
index fae851c..1d10fdd 100644
--- a/frontend/src/tools/compare/ModeDock.svelte
+++ b/frontend/src/tools/compare/ModeDock.svelte
@@ -20,6 +20,7 @@
class="mode-btn"
class:on={mode === entry.id}
aria-pressed={mode === entry.id}
+ aria-label={entry.label}
title={`${entry.label} (${entry.key})`}
onclick={() => onmode(entry.id)}
>
@@ -56,7 +57,9 @@
gap: 8px;
padding: 4px 6px;
}
- @media (max-width: 1100px) {
+ /* The dock shares its row with the comparison's name and acts, so the four
+ readings go to their icons first; the tooltips still name them. */
+ @media (max-width: 1400px) {
.mode-btn:not(.difference) span {
display: none;
}
diff --git a/frontend/src/tools/compare/SourceCard.svelte b/frontend/src/tools/compare/SourceCard.svelte
index d927699..77af030 100644
--- a/frontend/src/tools/compare/SourceCard.svelte
+++ b/frontend/src/tools/compare/SourceCard.svelte
@@ -34,7 +34,7 @@
<div class="source-card cmp-glass" class:right={align === 'right'} aria-label={`Imagery ${letter}`}>
<span class="cmp-letter {lower}">{letter}</span>
<div class="chips">
- <ImageryChip {imagery} bind:providerId s2={s2} {wayback} {s1} {shown} dateChip />
+ <ImageryChip {imagery} bind:providerId {s2} {wayback} {s1} {shown} />
</div>
{#if showsDate}
<span class="dated cmp-mono" title={dated.source ? `Acquired around this date (${dated.source})` : 'Acquired around this date'}>
diff --git a/frontend/src/tools/detect/AcquisitionPicker.svelte b/frontend/src/tools/detect/AcquisitionPicker.svelte
index 104e13e..a5112fd 100644
--- a/frontend/src/tools/detect/AcquisitionPicker.svelte
+++ b/frontend/src/tools/detect/AcquisitionPicker.svelte
@@ -11,8 +11,8 @@
* and how much of it was cloud.
*
* The calendar has its place one step up, for where to look: past the year the
- * presets reach, two days picked in it bound the lookup. The catalogue gives at
- * most 100 passes, newest first, so a list it cut short offers the older ones.
+ * presets reach, two days picked in it bound the lookup. The catalogue answers
+ * newest first, five pages at most, so a list it cut short offers the older ones.
*/
import Icon from '../../components/Icon.svelte';
import MonthGrid from '../../components/MonthGrid.svelte';
@@ -117,12 +117,12 @@
{:else if busy}
<p class="hint">Reading the catalogue over your areas…</p>
{:else if !searched}
- <p class="hint">One lookup, billed as one Copernicus request.</p>
+ <p class="hint">One lookup, billed as one Copernicus request, or a few for a long window.</p>
{:else if !list.length}
<p class="warn">No pass reaches these areas in this window. Try a longer one.</p>
{:else}
{#if truncated}
- <p class="warn">The catalogue stopped at 100 passes, so older ones are missing.
+ <p class="warn">The catalogue stopped short, so the oldest passes are missing.
{#if older}<button type="button" class="link" disabled={busy} onclick={onolder}>Older passes</button>{/if}</p>
{/if}
<ul class="list">
@@ -170,7 +170,7 @@
<p class="hint">
<Icon name="info" size={11} />
{radar ? 'A and B must share a track: the same time of day.'
- : 'A pass covers what its swath reached that day, not the whole map.'}
+ : 'Cloud is over the whole 110 km tile, so your area can be clearer or cloudier.'}
</p>
{/if}
</div>
diff --git a/frontend/src/tools/detect/AcquisitionPicker.test.js b/frontend/src/tools/detect/AcquisitionPicker.test.js
index f494442..c6c4197 100644
--- a/frontend/src/tools/detect/AcquisitionPicker.test.js
+++ b/frontend/src/tools/detect/AcquisitionPicker.test.js
@@ -86,7 +86,7 @@ describe('the acquisition picker', () => {
it('says when the catalogue stopped short instead of implying a full list', () => {
const { target, done } = render({ truncated: true });
- expect(target.textContent).toContain('stopped at 100 passes');
+ expect(target.textContent).toContain('stopped short');
done();
});
diff --git a/frontend/src/tools/detect/AreaDates.svelte b/frontend/src/tools/detect/AreaDates.svelte
index aa7fff2..f0b3a72 100644
--- a/frontend/src/tools/detect/AreaDates.svelte
+++ b/frontend/src/tools/detect/AreaDates.svelte
@@ -1,6 +1,9 @@
<script>
import { api } from '../../lib/api.js';
- import { acquisitionQuery, coverageWarning, olderSpan, passKey, withOlder } from '../../lib/map/acquisitions.js';
+ import {
+ acquisitionQuery, cloudWarning, coverageWarning, olderSpan, passKey, withOlder,
+ } from '../../lib/map/acquisitions.js';
+ import { newestLabel, newestLine, newestPick } from '../../lib/map/detectWhen.js';
import AcquisitionPicker from './AcquisitionPicker.svelte';
import DateField from '../../components/DateField.svelte';
@@ -43,9 +46,17 @@
...pair, [letter]: { ...pair[letter], date, time: radar ? time : '' },
date_rule: letter === 'b' && pair.date_rule !== 'latest_previous' ? (date ? 'manual' : 'latest_reference') : pair.date_rule,
});
- if (date) onshow({ ...pairFor(id)[letter], date, ...(radar ? { provider: 'sentinel1', time } : {}) });
+ if (!date) return;
+ const cloud = radar || looking !== id ? null : passes.find((pass) => pass.date === date)?.cloud ?? null;
+ onshow({ ...pairFor(id)[letter], date, cloud, ...(radar ? { provider: 'sentinel1', time } : {}) });
}
const at = (source) => (radar && source?.time ? `${source.time.slice(0, 5)} UTC` : '');
+ /** "Newest" as this area's ceiling makes it, capitalised for a cell. */
+ const newestFor = (pair) => {
+ const label = newestLabel({ maxcc: pair?.b?.maxcc, radar });
+ return label.charAt(0).toUpperCase() + label.slice(1);
+ };
+ const track = (pair) => (radar && !single ? pair?.a?.time ?? '' : '');
</script>
<div class="dates-table">
@@ -67,7 +78,7 @@
<td><DateField day reading={false} label={`Pass for ${zone.name}`} value={pair.b.date}
onchange={(value) => pick(zone.id, 'b', value ?? '')} />
{#if at(pair.b)}<small class="mono">{at(pair.b)}</small>{/if}
- {#if !pair.b.date}<small>Newest pass</small>{:else}<button class="link" onclick={() => pick(zone.id, 'b', '')}>Newest pass</button>{/if}</td>
+ {#if !pair.b.date}<small>{newestFor(pair)}</small>{:else}<button class="link" onclick={() => pick(zone.id, 'b', '')}>{newestFor(pair)}</button>{/if}</td>
{/if}
<td><button class="btn btn-sm" disabled={busy} onclick={() => lookup(zone)} aria-label={`Find passes for ${zone.name}`}>Find passes</button></td>
</tr>
@@ -84,10 +95,15 @@
onlookback={(value) => (lookback = value)} onlook={() => lookup(zones.find((zone) => zone.id === looking))}
onolder={() => lookup(zones.find((zone) => zone.id === looking), true)}
onpick={(letter, entry) => pick(looking, letter, entry.date, entry.time ?? '')} />
+ {#if searched && !baselineOnly && !pair?.b?.date}
+ {@const maxcc = radar ? 100 : pair?.b?.maxcc}
+ <p class="hint">{newestLine(newestPick(passes, { maxcc, radar, track: track(pair) }), { maxcc, radar })}</p>
+ {/if}
{#each [single ? null : pair?.a, pair?.b].filter((source) => source?.date) as source}
- {@const warning = coverageWarning(passes.find((pass) => passKey(pass) === passKey(source)
- || (!source.time && pass.date === source.date)))}
- {#if warning}<p class="warn">{warning}</p>{/if}
+ {@const entry = passes.find((pass) => passKey(pass) === passKey(source) || (!source.time && pass.date === source.date))}
+ {#each [coverageWarning(entry), radar ? '' : cloudWarning(entry, source.maxcc)].filter(Boolean) as warning (warning)}
+ <p class="warn">{warning}</p>
+ {/each}
{/each}
{/if}
diff --git a/frontend/src/tools/detect/DetectPanel.svelte b/frontend/src/tools/detect/DetectPanel.svelte
index 437901a..cc0acce 100644
--- a/frontend/src/tools/detect/DetectPanel.svelte
+++ b/frontend/src/tools/detect/DetectPanel.svelte
@@ -31,6 +31,9 @@
let {
caseId,
collapsed = $bindable(false),
+ /** Whether Detect holds the whole screen, and the way in and out of it. */
+ fullscreen = false,
+ onfullscreen = () => {},
manual = $bindable(null),
zones = $bindable([]),
drawing = $bindable('select'),
@@ -562,6 +565,10 @@
{/each}
<button class="cmp-icon" aria-label="Analyzers" title="Make and tune what detections look for"
onclick={openLibrary}><Icon name="sliders" size={15} /></button>
+ <button class="cmp-icon" class:on={fullscreen} aria-pressed={fullscreen}
+ aria-label={fullscreen ? 'Exit full screen' : 'Full screen'}
+ title={fullscreen ? 'Back to the window (Esc)' : 'Detect on the whole screen'}
+ onclick={onfullscreen}><Icon name={fullscreen ? 'minimize' : 'maximize'} size={15} /></button>
</nav>
<div class="dock-content" hidden={collapsed}>
<div class="new-action" bind:this={newActionEl}>
diff --git a/frontend/src/tools/detect/DetectPanel.test.js b/frontend/src/tools/detect/DetectPanel.test.js
index 6751344..27113f8 100644
--- a/frontend/src/tools/detect/DetectPanel.test.js
+++ b/frontend/src/tools/detect/DetectPanel.test.js
@@ -41,6 +41,13 @@ const button = (text) => [...document.querySelectorAll('button')].find((b) => b.
const starts = (text) => [...document.querySelectorAll('button')].find((b) => b.textContent.trim().startsWith(text));
const labelled = (label) => target.querySelector(`button[aria-label="${label}"]`);
const heading = () => target.querySelector('h3')?.textContent.trim();
+const ceilingSlider = () => target.querySelector('input[aria-label="Maximum cloud cover"]');
+function slide(value) {
+ const slider = ceilingSlider();
+ slider.value = String(value);
+ slider.dispatchEvent(new Event('input', { bubbles: true }));
+ flushSync();
+}
const area = [{ id: 'area', name: 'Area', kind: 'rect', points: [[2, 48], [2.001, 48.001]] }];
const WATCH = 'abcdef123456';
@@ -295,8 +302,9 @@ it('walks a single pass through its steps and runs it once', async () => {
// a pair needs A, and says so in the words of the step
expect(button('Next: Start').disabled).toBe(true);
expect(target.textContent).toContain('Choose A, the picture before.');
- // B is the newest pass until a day is asked for, and then it needs one
- expect(button('Newest pass').getAttribute('aria-checked')).toBe('true');
+ // B is the newest pass under the ceiling until a day is asked for, and the
+ // button says which ceiling rather than promising the newest pass there is
+ expect(button('Newest pass under 30% cloud').getAttribute('aria-checked')).toBe('true');
button('A day I choose').click(); await settle();
const pass = target.querySelector('[aria-label="Day of B"]');
pass.value = '06/09/2026'; pass.dispatchEvent(new Event('input', { bubbles: true })); await settle();
@@ -333,13 +341,13 @@ it('pages back through a pass list the catalogue cut short', async () => {
post.mockResolvedValueOnce({ dates: [{ date: ago(100), cloud: 5, coverage: 1 }, { date: ago(120), cloud: 9, coverage: 1 }],
truncated: false });
button('Find passes').click(); await settle();
- expect(target.textContent).toContain('stopped at 100 passes');
+ expect(target.textContent).toContain('stopped short');
button('Older passes').click(); await settle();
expect(post).toHaveBeenLastCalledWith('/api/satellite/sentinel/acquisitions',
expect.objectContaining({ start: ago(365), end: ago(100) }));
const listed = [...target.querySelectorAll('.passes li strong')].map((node) => node.textContent);
expect(listed).toEqual([ago(10), ago(100), ago(120)]);
- expect(target.textContent).not.toContain('stopped at 100 passes');
+ expect(target.textContent).not.toContain('stopped short');
expect(target.textContent).not.toContain('40% of the areas');
});
@@ -390,7 +398,10 @@ it('asks a routine what each pass compares against, not which day to read', asyn
button('Next: What').click(); await settle();
button('Next: When').click(); await settle();
expect(heading()).toBe('Which images, each run');
- expect(target.textContent).toContain('Each run takes the newest pass as B and compares it with');
+ expect(target.textContent).toContain('Each run takes the newest pass under 30% cloud as B and compares it with');
+ expect(ceilingSlider().value).toBe('30');
+ slide(40);
+ expect(target.textContent).toContain('Each run takes the newest pass under 40% cloud as B');
expect(target.textContent).toContain('The pass before');
expect(target.textContent).toContain('Only the first run');
expect(target.textContent).toContain('Choose A, the picture the first run compares with.');
@@ -399,16 +410,59 @@ it('asks a routine what each pass compares against, not which day to read', asyn
expect(button('B')).toBeUndefined();
button('A').click(); await settle();
button('Next: Start').click(); await settle();
- expect(target.textContent).toContain('Each run: the newest pass against the one before, first against 2026-08-01');
+ expect(target.textContent).toContain('Each run: the newest pass under 40% cloud against the one before, first against 2026-08-01');
button('Save and run the first pass').click(); await settle();
expect(post).toHaveBeenCalledWith('/api/cases/case-a/analysis/followups', expect.objectContaining({
- date_rule: 'latest_previous', zones: area, area_dates: [expect.objectContaining({ a: expect.objectContaining({ date: '2026-08-01' }) })],
+ date_rule: 'latest_previous', zones: area, area_dates: [expect.objectContaining({
+ a: expect.objectContaining({ date: '2026-08-01' }), b: expect.objectContaining({ maxcc: 40 }) })],
}));
expect(post).toHaveBeenCalledWith(`/api/cases/case-a/analysis/followups/${WATCH}/run`, {});
// it lands on the routine's own page, where its runs gather
expect(heading()).toBe('Harbour weekly');
});
+it('says which day the newest pass is and why newer ones were skipped, and reads a cloudier one when asked', async () => {
+ // Lyman, 2026-09-26: the map showed that day's pass, while "newest" took the
+ // 19th without a word; the three newer passes were over the ceiling
+ answer({
+ '/api/compare/analyzers': catalogue({ builtins: [structuredClone(vessels), structuredClone(recipe)] }),
+ '/api/cases/case-a/analysis/zones/aaaaaaaaaaaa': { id: 'aaaaaaaaaaaa', title: 'Port', zones: area },
+ });
+ post.mockImplementation(async (path) => (path.endsWith('/acquisitions')
+ ? { dates: [
+ { date: '2026-09-26', cloud: 51.1, granules: 2, coverage: 1 },
+ { date: '2026-09-24', cloud: 82.2, granules: 2, coverage: 1 },
+ { date: '2026-09-22', cloud: 89.2, granules: 2, coverage: 1 },
+ { date: '2026-09-19', cloud: 0.7, granules: 4, coverage: 1 },
+ ], truncated: false }
+ : { id: RUN, status: 'queued', input: {}, results: [], total: 1, progress: 0 }));
+ const onshow = vi.fn();
+ await open({ opening: 'zones-aaaaaaaaaaaa', onshow });
+ button('Next: What').click(); await settle();
+ button('Next: When').click(); await settle();
+ button('Find passes').click(); await settle();
+ expect(target.textContent).toContain(
+ 'Now 2026-09-19. Newer: 2026-09-26 (51% cloud), 2026-09-24 (82% cloud), 2026-09-22 (89% cloud).');
+ // the ceiling sits beside "newest": raised, it takes the 26th and says what that costs
+ slide(60);
+ expect(button('Newest pass under 60% cloud')).toBeDefined();
+ expect(target.textContent).toContain('Now 2026-09-26, looked up again when the run starts.');
+ expect(target.textContent).toContain('Above 30%, the pass taken can be mostly cloud');
+ slide(30);
+ expect(target.textContent).not.toContain('Above 30%');
+ // the analyst has the last word: the cloudier pass is offered, and read
+ target.querySelector('[aria-label="Use 2026-09-26"] button').click(); await settle();
+ expect(target.textContent).toContain('2026-09-26 is 51% cloud over its tile. It is read anyway');
+ // the map is handed its cloud, and a chosen day needs no ceiling
+ expect(onshow).toHaveBeenLastCalledWith(expect.objectContaining({ date: '2026-09-26', cloud: 51.1 }));
+ expect(ceilingSlider()).toBe(null);
+ button('Next: Start').click(); await settle();
+ button('Run this pass').click(); await settle();
+ expect(post).toHaveBeenCalledWith('/api/cases/case-a/analysis/runs', expect.objectContaining({
+ area_dates: [expect.objectContaining({ date_rule: 'manual', b: expect.objectContaining({ date: '2026-09-26' }) })],
+ }));
+});
+
it('reads the newest pass for a one-image sweep unless a day is asked for', async () => {
answer({
'/api/compare/analyzers': catalogue({ builtins: [structuredClone(vessels), structuredClone(recipe)] }),
@@ -422,7 +476,7 @@ it('reads the newest pass for a one-image sweep unless a day is asked for', asyn
button('Next: When').click(); await settle();
expect(heading()).toBe('Which image');
// the newest pass is a whole answer, so the step can be passed as it opens
- expect(target.textContent).toContain('Looked up when the run starts, under the cloud ceiling.');
+ expect(target.textContent).toContain('The newest pass under 30% cloud, looked up when the run starts.');
expect(target.querySelector('[aria-label="Day of A"]')).toBe(null);
expect(button('Next: Start').disabled).toBe(false);
button('A day I choose').click(); await settle();
@@ -481,11 +535,16 @@ it('asks a routine of one image for nothing but its picture', async () => {
button('Next: What').click(); await settle();
button('Next: When').click(); await settle();
expect(heading()).toBe('Which image, each run');
- expect(target.textContent).toContain('Each run reads the newest pass over the area, under the cloud ceiling.');
+ expect(target.textContent).toContain('Each run reads the newest pass under 30% cloud over the area.');
expect(button('Find passes')).toBeUndefined();
+ // its one question is the cloud ceiling, right there, with a word above 30%
+ expect(target.textContent).not.toContain('Above 30%');
+ slide(45);
+ expect(target.textContent).toContain('Each run reads the newest pass under 45% cloud over the area.');
+ expect(target.textContent).toContain('Above 30%, the pass taken can be mostly cloud, and ground under cloud is left out.');
expect(button('Next: Start').disabled).toBe(false);
button('Next: Start').click(); await settle();
- expect(target.textContent).toContain('Each run: the newest pass');
+ expect(target.textContent).toContain('Each run: the newest pass under 45% cloud');
expect(post).not.toHaveBeenCalled();
});
@@ -507,7 +566,7 @@ it('holds a routine to one fixed picture when asked', async () => {
const day = target.querySelector('[aria-label="Day of A"]');
day.value = '01/08/2026'; day.dispatchEvent(new Event('input', { bubbles: true })); await settle();
button('Next: Start').click(); await settle();
- expect(target.textContent).toContain('Each run: the newest pass against 2026-08-01');
+ expect(target.textContent).toContain('Each run: the newest pass under 30% cloud against 2026-08-01');
button('Save without running').click(); await settle();
expect(post).toHaveBeenCalledWith('/api/cases/case-a/analysis/followups', expect.objectContaining({
date_rule: 'latest_reference',
diff --git a/frontend/src/tools/detect/DetectWizard.svelte b/frontend/src/tools/detect/DetectWizard.svelte
index 9ce9a4d..1a24eae 100644
--- a/frontend/src/tools/detect/DetectWizard.svelte
+++ b/frontend/src/tools/detect/DetectWizard.svelte
@@ -28,7 +28,7 @@
import { plural } from '../../lib/map/detections.js';
import { recipeCapability } from '../../lib/map/analyzerRules.js';
import { openCopernicusSettings } from '../../lib/navigate.js';
- import { uniform, whenNeed, whenSummary } from '../../lib/map/detectWhen.js';
+ import { ADVISED_MAXCC, uniform, whenNeed, whenSummary } from '../../lib/map/detectWhen.js';
import AnalyzerSettings from './AnalyzerSettings.svelte';
import AnalyzerSize from './AnalyzerSize.svelte';
import WhenStep from './WhenStep.svelte';
@@ -60,7 +60,7 @@
onareas = async () => {},
} = $props();
- const EMPTY_SOURCE = { provider: 'sentinel2', date: '', layer: 'TRUE_COLOR', maxcc: 30 };
+ const EMPTY_SOURCE = { provider: 'sentinel2', date: '', layer: 'TRUE_COLOR', maxcc: ADVISED_MAXCC };
const STEPS = [[1, 'Where'], [2, 'What'], [3, 'When'], [4, 'Start']];
const SIZE_NAMES = { small: 'Small', medium: 'Medium', large: 'Large', all: 'All sizes' };
@@ -138,7 +138,7 @@
: zones.length === 1 ? `${recipe.name} · ${zones[0].name}`
: `${recipe.name} · ${plural(zones.length, 'area')}`
);
- const timing = $derived(whenSummary({ single: isSingle, routine, against, pairs, radar }));
+ const timing = $derived(whenSummary({ single: isSingle, routine, against, pairs, radar, maxcc: b.maxcc }));
/** A detection saved against Wayback reopens undated, which is what it is
* for Copernicus. A radar run's sources keep their day and pass time; the
@@ -414,6 +414,7 @@
</section>
{:else if step === 3}
<WhenStep {zones} bind:pairs {routine} single={isSingle} sensor={capability.sensor} {followupId}
+ maxcc={radar ? 100 : b.maxcc} onmaxcc={radar ? null : (value) => setPicture({ maxcc: value })}
bind:against bind:chooseB bind:lookup {onshow} />
{#if radar}
{#if !routine}
@@ -423,15 +424,12 @@
{/if}
{:else}
<details>
- <summary>Picture and cloud ceiling</summary>
+ <summary>{routine ? 'Picture' : 'Picture and local images'}</summary>
<label title="Image used for review">Picture
<select value={b.layer} onchange={(e) => setPicture({ layer: e.currentTarget.value })}>
<option value="TRUE_COLOR">True colour</option><option value="FALSE_COLOR">False colour</option><option value="SWIR">SWIR</option>
</select>
</label>
- <label title="Reject scenes above this cloud ceiling">Maximum cloud cover · {b.maxcc}%
- <input type="range" min="0" max="100" value={b.maxcc} oninput={(e) => setPicture({ maxcc: Number(e.currentTarget.value) })} />
- </label>
{#if !routine}
<label class="check" title="Use cached or retained frames without downloading">
<input type="checkbox" bind:checked={offline} /> Use local images only
diff --git a/frontend/src/tools/detect/WhenStep.svelte b/frontend/src/tools/detect/WhenStep.svelte
index 76e7724..08b5374 100644
--- a/frontend/src/tools/detect/WhenStep.svelte
+++ b/frontend/src/tools/detect/WhenStep.svelte
@@ -3,8 +3,11 @@
* Which imagery a detection reads, asked in the order it is decided.
*
* A one pass names A, the picture before, and B, the one to look in, which
- * is the newest pass unless a day is chosen. A routine names no B: each run
- * looks the newest pass up itself, so this only asks what it compares with.
+ * is the newest pass under the cloud ceiling unless a day is chosen, and says
+ * which day that is once the passes are looked up. A chosen day is read
+ * whatever its cloud. A routine names no B: each run looks the newest pass up
+ * itself, so this only asks what it compares with. The ceiling's slider sits
+ * wherever "newest" picks, and says what a ceiling over 30% costs.
* The passes over the areas are listed under the question, because picking
* from what exists beats typing a day that may have no picture.
*
@@ -14,8 +17,14 @@
*/
import { untrack } from 'svelte';
import { api } from '../../lib/api.js';
- import { acquisitionQuery, areaKey, coverageWarning, olderSpan, passKey, withOlder } from '../../lib/map/acquisitions.js';
- import { areaLine, setSide, shadowWarning, sharedSide, uniform, withRule } from '../../lib/map/detectWhen.js';
+ import {
+ acquisitionQuery, areaKey, cloudWarning, coverageWarning, olderSpan, passKey, withOlder,
+ } from '../../lib/map/acquisitions.js';
+ import {
+ areaLine, ceilingWarning, newestLabel, newestLine, newestPick, setSide, shadowWarning, sharedSide, uniform,
+ withRule,
+ } from '../../lib/map/detectWhen.js';
+ import { isoDay } from '../../lib/sentinel.js';
import AcquisitionPicker from './AcquisitionPicker.svelte';
import AreaDates from './AreaDates.svelte';
import DateField from '../../components/DateField.svelte';
@@ -32,6 +41,10 @@
against = $bindable('previous'),
/** A one pass reads B on a day of its own rather than the newest pass. */
chooseB = $bindable(false),
+ /** The cloud ceiling "newest" is chosen under. A chosen day ignores it. */
+ maxcc = 100,
+ /** Sets the ceiling; without it (radar) no slider is shown. */
+ onmaxcc = null,
/** The last lookup, held by the wizard so stepping back does not pay for it twice. */
lookup = $bindable(null),
onshow = () => {},
@@ -50,7 +63,8 @@
let generation = 0;
const key = $derived(areaKey(zones));
- const fresh = $derived(lookup?.key === key ? lookup : null);
+ // a list looked up another day has missed that day's passes
+ const fresh = $derived(lookup?.key === key && lookup?.day === isoDay(new Date()) ? lookup : null);
const a = $derived(sharedSide(pairs, 'a'));
const b = $derived(sharedSide(pairs, 'b'));
const same = $derived(uniform(pairs));
@@ -66,13 +80,20 @@
: waived ? 'Used until a run has finished; then each run compares with the one before.'
: 'Only the first run; after it, each run compares with the one before.'
);
- const cloudy = $derived(radar ? '' : ', under the cloud ceiling');
+ const newest = $derived(newestLabel({ maxcc, radar }));
+ const Newest = $derived(newest.charAt(0).toUpperCase() + newest.slice(1));
+ // which day "newest" takes now, by the rule the run applies at launch
+ const newestNow = $derived(fresh ? newestPick(fresh.list, { maxcc, radar, track: radar && !single ? a?.time ?? '' : '' }) : null);
+ const newestNote = $derived(newestNow ? newestLine(newestNow, { maxcc, radar }) : `The ${newest}, looked up when the run starts.`);
const warnings = $derived(!fresh ? [] : [single ? null : a, routine ? null : b]
.filter((side) => side?.date)
- .map((side) => coverageWarning(fresh.list.find((pass) => passKey(pass) === passKey(side)
- || (!side.time && pass.date === side.date))))
+ .map((side) => fresh.list.find((pass) => passKey(pass) === passKey(side) || (!side.time && pass.date === side.date)))
+ .flatMap((entry) => [coverageWarning(entry), radar ? '' : cloudWarning(entry, maxcc)])
.filter(Boolean));
const shadows = $derived(shadowWarning(pairs, zones, { single, radar }));
+ // the slider sits where the ceiling is in play: wherever "newest" picks B
+ const ceiling = $derived(!radar && !!onmaxcc);
+ const ceilingNote = $derived(ceilingWarning(maxcc));
const look = () => search(lookback, false);
const lookOlder = () => search(olderSpan(lookback, fresh?.list), true);
@@ -86,19 +107,22 @@
acquisitionQuery(zones, span, new Date(), sensor));
if (mine !== generation) return;
const list = more ? withOlder(fresh?.list, found.dates) : found.dates ?? [];
- lookup = { key, lookback, list, truncated: !!found.truncated };
+ lookup = { key, day: isoDay(new Date()), lookback, list, truncated: !!found.truncated };
} catch (e) { if (mine === generation) error = e.message; }
finally { if (mine === generation) busy = false; }
}
- /** One pass on one side of every area, shown on the map as it is chosen. */
+ /** One pass on one side of every area, shown on the map as it is chosen,
+ * with its cloud when the lookup knows it. */
function pick(letter, date, time = '') {
pairs = setSide(pairs, letter, date, time, radar);
if (letter === 'b' && date) chooseB = true;
- if (date && pairs.length) onshow({ ...pairs[0][letter], date, ...(radar ? { provider: 'sentinel1', time } : {}) });
+ if (!date || !pairs.length) return;
+ const cloud = radar ? null : fresh?.list.find((pass) => pass.date === date)?.cloud ?? null;
+ onshow({ ...pairs[0][letter], date, cloud, ...(radar ? { provider: 'sentinel1', time } : {}) });
}
- function newest() {
+ function takeNewest() {
chooseB = false;
pairs = setSide(pairs, 'b', '', '', radar);
}
@@ -111,15 +135,25 @@
const time = (side) => (radar && side?.time ? `${side.time.slice(0, 5)} UTC` : '');
</script>
+{#snippet ceilingRow()}
+ <label class="ceiling" title="The newest pass is taken under this">
+ <span>Maximum cloud cover · {maxcc}%</span>
+ <input type="range" min="0" max="100" value={maxcc} aria-label="Maximum cloud cover"
+ oninput={(e) => onmaxcc(Number(e.currentTarget.value))} />
+ </label>
+ {#if ceilingNote}<p class="warn" role="note">{ceilingNote}</p>{/if}
+{/snippet}
+
<section class="step" aria-label="Which imagery">
<h3>{heading}</h3>
{#if routine && single}
- <p class="lead">Each run reads the newest pass over {ground}{cloudy}.</p>
- <p class="hint">Nothing to choose now. When you run it, you can keep the newest pass or name another.</p>
+ <p class="lead">Each run reads the {newest} over {ground}.</p>
+ <p class="hint">Nothing to choose now. When you run it, you can keep that pass or name another.</p>
+ {#if ceiling}{@render ceilingRow()}{/if}
{:else}
{#if routine}
- <p class="lead">Each run takes the newest pass as B and compares it with</p>
+ <p class="lead">Each run takes the {newest} as B and compares it with</p>
<div class="options" role="radiogroup" aria-label="What each run compares with">
{#each AGAINST as [value, title, detail] (value)}
<button type="button" role="radio" class="option" class:on={against === value}
@@ -128,6 +162,7 @@
</button>
{/each}
</div>
+ {#if ceiling}{@render ceilingRow()}{/if}
{/if}
<div class="slots">
@@ -151,7 +186,7 @@
<div class="body">
{#if !single}<span class="k">After</span>{/if}
<div class="cmp-seg" role="radiogroup" aria-label={single ? 'Which image' : 'Which picture B is'}>
- <button type="button" role="radio" class:on={!chooseB} aria-checked={!chooseB} onclick={newest}>Newest pass</button>
+ <button type="button" role="radio" class:on={!chooseB} aria-checked={!chooseB} onclick={takeNewest}>{Newest}</button>
<button type="button" role="radio" class:on={chooseB} aria-checked={chooseB} onclick={() => (chooseB = true)}>A day I choose</button>
</div>
{#if chooseB}
@@ -162,7 +197,8 @@
</div>
<small>Type it, or pick it in the passes below.</small>
{:else}
- <small>Looked up when the run starts{cloudy}.</small>
+ {#if ceiling}{@render ceilingRow()}{/if}
+ <small>{newestNote}</small>
{/if}
</div>
</div>
@@ -249,6 +285,8 @@
.cmp-seg { justify-self: start; }
.passes-title { display: flex; flex-wrap: wrap; gap: 6px; align-items: baseline; margin: 2px 0 0; font-size: var(--fs-xs); }
.passes-title span { color: var(--text-3); font-size: 10.5px; }
+ .ceiling { display: grid; gap: 3px; color: var(--text-2); font-size: var(--fs-xs); }
+ .ceiling input { width: 100%; }
.link { color: var(--accent); font-size: var(--fs-xs); }
.warn { margin: 0; color: var(--warn, #e2a03f); font-size: 10.5px; line-height: 1.35; }
.dates { display: grid; gap: 3px; margin: 0; padding: 0; list-style: none; }
diff --git a/frontend/src/tools/proof/PointMapDialog.render.test.js b/frontend/src/tools/proof/PointMapDialog.render.test.js
index f2db878..8379d50 100644
--- a/frontend/src/tools/proof/PointMapDialog.render.test.js
+++ b/frontend/src/tools/proof/PointMapDialog.render.test.js
@@ -62,7 +62,7 @@ vi.mock('../../lib/map/engine.js', () => ({
const setOverlay = vi.fn();
vi.mock('../../lib/map/basemap.js', () => ({
- OVERLAY_IDS: ['roads', 'boundaries', 'railway', 'power', 'seamarks', 'gpstraces'],
+ OVERLAY_IDS: ['roads', 'boundaries', 'placenames', 'railway', 'power', 'seamarks', 'gpstraces'],
createBasemaps: vi.fn(() => ({
show: vi.fn(),
setOverlay,
@@ -155,11 +155,12 @@ describe('moving a proof point on the map', () => {
expect(onpick).not.toHaveBeenCalled();
});
- it('offers the reference layers, the borders already on for their place names', async () => {
+ it('offers the reference layers, the borders and the place names already on', async () => {
await open();
expect(setOverlay).toHaveBeenCalledWith('boundaries', true, null);
expect(setOverlay).toHaveBeenCalledWith('railway', false, undefined);
+ expect(setOverlay).toHaveBeenCalledWith('placenames', true, null);
button('Layers').click();
flushSync();
@@ -168,6 +169,7 @@ describe('moving a proof point on the map', () => {
);
expect(names).toEqual([
'Borders',
+ 'Place names',
'Roads',
'Railways',
'Power lines',
@@ -181,6 +183,13 @@ describe('moving a proof point on the map', () => {
.click();
await settle();
expect(setOverlay).toHaveBeenCalledWith('railway', true, null);
+
+ // the village names come off like any other layer
+ [...document.querySelectorAll('.layers button')]
+ .find((entry) => entry.getAttribute('aria-label') === 'Place names')
+ .click();
+ await settle();
+ expect(setOverlay).toHaveBeenCalledWith('placenames', false, undefined);
});
it('checks a point before a save, handing it back without closing', async () => {
diff --git a/frontend/src/tools/proof/PointMapDialog.svelte b/frontend/src/tools/proof/PointMapDialog.svelte
index 4cfdf42..71b815e 100644
--- a/frontend/src/tools/proof/PointMapDialog.svelte
+++ b/frontend/src/tools/proof/PointMapDialog.svelte
@@ -50,8 +50,8 @@
} = $props();
const PIN = 'point';
- /** Only the roads read wrongly over a street basemap, which draws its own. */
- const IMAGERY_ONLY = new Set(['roads']);
+ /** The roads and the place names read wrongly over a street basemap, which draws its own. */
+ const IMAGERY_ONLY = new Set(['roads', 'placenames']);
const REFERENCE = COMPARE_LAYERS.filter((layer) => layer.group === 'reference');
const imagery = createImageryState({ api });
@@ -63,8 +63,8 @@
// Where the pin starts: the opening camera, read once. The dialog is opened on
// one row and closed on it, so a later view would be a different question.
let at = $state(untrack(() => ({ lat: view.lat, lon: view.lon })));
- // The borders carry the place names, which is what finding a spot needs.
- let on = $state(['boundaries']);
+ // The borders and the place names, which are what finding a spot needs.
+ let on = $state(['boundaries', 'placenames']);
let layersOpen = $state(false);
let surface = null;
diff --git a/frontend/src/tools/satellite/AddedLayers.render.test.js b/frontend/src/tools/satellite/AddedLayers.render.test.js
index 00cb6a9..19c66dc 100644
--- a/frontend/src/tools/satellite/AddedLayers.render.test.js
+++ b/frontend/src/tools/satellite/AddedLayers.render.test.js
@@ -110,7 +110,7 @@ describe('a row', () => {
it('says a stale snapshot is stale, and marks it for the eye', () => {
show({ rows: [followed({ stale: true, checked_at: '2020-01-01T00:00:00Z' })] });
- expect(text()).toContain('stale');
+ expect(text()).toContain('out of date');
expect(document.querySelector('.stale')).toBeTruthy();
});
diff --git a/frontend/src/tools/satellite/ImageryChip.svelte b/frontend/src/tools/satellite/ImageryChip.svelte
index 2c34720..9f1c149 100644
--- a/frontend/src/tools/satellite/ImageryChip.svelte
+++ b/frontend/src/tools/satellite/ImageryChip.svelte
@@ -40,9 +40,6 @@
s1 = null,
/** What it is actually showing — a billed base steps aside when paused. */
shown,
- /** Open the Sentinel-2 picker from a dated chip, as Wayback's already is.
- * Compare asks for it: its card has a layers button of its own. */
- dateChip = false,
} = $props();
let menuOpen = $state(false);
@@ -121,7 +118,6 @@
<SentinelPicker
bind:menuEl={s2MenuEl}
{s2}
- {dateChip}
{maxccLabel}
{monthLabel}
{monthGrid}
@@ -183,7 +179,9 @@
display: flex;
align-items: center;
justify-content: flex-end;
- flex-wrap: wrap;
+ /* when it has to split, the provider keeps the top line and the usage and
+ date drop under it */
+ flex-wrap: wrap-reverse;
gap: 6px;
}
.chip-wrap {
diff --git a/frontend/src/tools/satellite/MapStatusBar.svelte b/frontend/src/tools/satellite/MapStatusBar.svelte
index 0acba41..d8d04ce 100644
--- a/frontend/src/tools/satellite/MapStatusBar.svelte
+++ b/frontend/src/tools/satellite/MapStatusBar.svelte
@@ -34,7 +34,6 @@
<div class="status">
<div class="readouts card">
<button class="hud-coords mono" onclick={copy} title="Copy coordinates">
- <Icon name="crosshair" size={13} />
{coords}
<span class="z">z{zoom}</span>
{#if pinned}<span class="pin-tag">pin</span>{/if}
diff --git a/frontend/src/tools/satellite/MapSurface.svelte b/frontend/src/tools/satellite/MapSurface.svelte
index 70f24f4..94fd486 100644
--- a/frontend/src/tools/satellite/MapSurface.svelte
+++ b/frontend/src/tools/satellite/MapSurface.svelte
@@ -97,9 +97,13 @@
onwidgetload = () => {},
onwidgetauthfailure = () => {},
onwidgetfailed = () => {},
+ /** A tile of an overlay failed, by overlay id, for the tool that offers it. */
+ onoverlaytrouble = () => {},
/** The settled camera and the turn, for a parent that shares them. */
onviewsettled = () => {},
onbearingchange = () => {},
+ /** Controls the tool puts beside the imagery chip, on its right. */
+ beside,
children,
} = $props();
@@ -193,6 +197,7 @@
onWidgetLoad: (provider) => onwidgetload(provider.meter),
onWidgetAuthFailure: onwidgetauthfailure,
onWidgetFailed: onwidgetfailed,
+ onOverlayTrouble: (id) => onoverlaytrouble(id),
});
basemaps.setZoomCeiling(zoomCeiling);
showBasemap();
@@ -326,16 +331,24 @@
which is what lets two surfaces sit side by side each saying its own. -->
{#if chrome}
<div class="surface-ctl">
- <ImageryChip {imagery} bind:providerId {s2} {wayback} {s1} {shown} />
+ {#if beside}
+ <div class="ctl-row">
+ <ImageryChip {imagery} bind:providerId {s2} {wayback} {s1} {shown} />
+ {@render beside()}
+ </div>
+ {:else}
+ <ImageryChip {imagery} bind:providerId {s2} {wayback} {s1} {shown} />
+ {/if}
<!-- …and when the pixels under the crosshair were taken. Under the provider
rather than in the opposite corner: it describes that same picture, and
the corner it used to sit in is the instrument's, where the scale bracket
reads. -->
{#if s2 && shown.provider?.id === SENTINEL_ID}
- <!-- Sentinel-2 says what it is showing: a pinned day is the window the tiles
- were rendered from; otherwise the layer's default renders the most
- recent pass, which the calendar lookup has already named. -->
+ <!-- The date is the picker's chip too, and it is said again here, as the
+ radar's pass is: one line reading the day, how it was chosen and what
+ is drawn from it. A pinned day is the window the tiles were rendered
+ from; otherwise the layer's default renders the most recent pass. -->
<span
class="date-pill mono"
class:exact={!!pinnedDay}
@@ -474,6 +487,9 @@
flex-direction: column;
align-items: flex-end;
gap: 8px;
+ /* stops short of whatever the tool floats in the opposite corner (Satellite's
+ search), so a narrow map wraps the chips instead of hiding them under it */
+ max-width: calc(100% - 12px - var(--surface-ctl-reserve, 12px));
/* the column is only as wide as its widest control, so the map stays
grabbable everywhere the controls are not */
pointer-events: none;
@@ -481,4 +497,42 @@
.surface-ctl > :global(*) {
pointer-events: auto;
}
+ /* One card for the picture and what the window does with it, as Compare's
+ source card holds its side: the chips inside lose their own boxes. */
+ .ctl-row {
+ /* its blur is a stacking context that shuts its menus in, so the card
+ itself has to sit over the date pill and the compass below it */
+ position: relative;
+ z-index: 1;
+ display: flex;
+ align-items: flex-start;
+ gap: 2px;
+ max-width: 100%;
+ padding: 3px;
+ border-radius: var(--radius-1);
+ background: rgba(24, 24, 24, 0.88);
+ backdrop-filter: blur(6px);
+ box-shadow: 0 0 0 1px var(--border);
+ }
+ .ctl-row > :global(.chip-row) {
+ min-width: 0;
+ gap: 2px;
+ }
+ .ctl-row :global(.chip) {
+ height: 28px;
+ background: transparent;
+ box-shadow: none;
+ backdrop-filter: none;
+ }
+ .ctl-row :global(.chip:hover),
+ .ctl-row :global(.chip.on) {
+ color: var(--text-1);
+ background: var(--bg-2);
+ }
+ .ctl-row :global(.pill) {
+ margin: 0 2px;
+ background: rgba(255, 255, 255, 0.06);
+ box-shadow: none;
+ backdrop-filter: none;
+ }
</style>
diff --git a/frontend/src/tools/satellite/SentinelPicker.svelte b/frontend/src/tools/satellite/SentinelPicker.svelte
index 1ed820f..c7aff50 100644
--- a/frontend/src/tools/satellite/SentinelPicker.svelte
+++ b/frontend/src/tools/satellite/SentinelPicker.svelte
@@ -12,13 +12,6 @@
monthGrid,
cloudClass,
cloudLabel,
- /**
- * Open from a dated chip rather than a layers icon, the way the Wayback
- * picker beside it does. Compare's source card carries its own layers
- * button, and two identical icons in one card said nothing about which of
- * them held the date.
- */
- dateChip = false,
} = $props();
// What the tiles are dated: the pinned pass, or the one "most recent" resolved
@@ -33,27 +26,19 @@
</script>
<div class="s2-wrap" bind:this={menuEl}>
- {#if dateChip}
- <button
- class="chip"
- class:on={s2.menuOpen}
- onclick={s2.toggleMenu}
- title={s2.date ? `Sentinel-2 pass of ${s2.date}` : 'Sentinel-2 layer and date'}
- aria-label="Sentinel-2 layer and date"
- aria-expanded={s2.menuOpen}
- >
- <Icon name="clock" size={13} />
- <span class="mono">{chipDate || 'Most recent'}</span>
- </button>
- {:else}
- <button
- class="btn btn-icon"
- class:on={s2.menuOpen}
- onclick={s2.toggleMenu}
- title="Sentinel-2 layer and date"
- aria-label="Sentinel-2 layer and date"
- ><Icon name="layers" size={14} /></button>
- {/if}
+ <!-- Opened from a dated chip, as the Wayback and Sentinel-1 pickers are: the
+ date is what you look for, and a layers icon hid it behind a click. -->
+ <button
+ class="chip"
+ class:on={s2.menuOpen}
+ onclick={s2.toggleMenu}
+ title={s2.date ? `Sentinel-2 pass of ${s2.date}` : 'Sentinel-2 layer and date'}
+ aria-label="Sentinel-2 layer and date"
+ aria-expanded={s2.menuOpen}
+ >
+ <Icon name="clock" size={13} />
+ <span class="mono">{chipDate || 'Most recent'}</span>
+ </button>
{#if s2.menuOpen}
<div class="s2-menu card">
<div class="menu-row">
diff --git a/frontend/src/tools/satellite/SentinelPicker.test.js b/frontend/src/tools/satellite/SentinelPicker.test.js
index 116bb61..b40a9fa 100644
--- a/frontend/src/tools/satellite/SentinelPicker.test.js
+++ b/frontend/src/tools/satellite/SentinelPicker.test.js
@@ -93,31 +93,26 @@ describe('SentinelPicker date safety', () => {
});
describe('SentinelPicker trigger', () => {
- it('is a layers icon on a map surface, which has no layers button of its own', () => {
- const { body } = render(SentinelPicker, { props: props({ s2: { menuOpen: false } }) });
- expect(body).toMatch(/<button[^>]*class="btn btn-icon[^"]*"/);
- expect(body).not.toContain('Most recent');
- });
-
- it('carries the pinned pass as a dated chip when Compare asks for one', () => {
+ it('carries the pinned pass as a dated chip, as Wayback and Sentinel-1 do', () => {
const { body } = render(SentinelPicker, {
- props: props({ s2: { menuOpen: false, date: '2025-04-11' }, dateChip: true }),
+ props: props({ s2: { menuOpen: false, date: '2025-04-11' } }),
});
expect(body).toMatch(/<button[^>]*class="chip[^"]*"/);
+ expect(body).not.toContain('btn-icon');
expect(body).toContain('2025-04-11');
expect(body).toContain('Sentinel-2 pass of 2025-04-11');
});
it('dates the chip by the pass "most recent" resolved to', () => {
const { body } = render(SentinelPicker, {
- props: props({ s2: { menuOpen: false, date: '', latest: '2025-03-28' }, dateChip: true }),
+ props: props({ s2: { menuOpen: false, date: '', latest: '2025-03-28' } }),
});
expect(body).toContain('2025-03-28');
});
it('says "Most recent" while no pass has come back', () => {
const { body } = render(SentinelPicker, {
- props: props({ s2: { menuOpen: false }, dateChip: true }),
+ props: props({ s2: { menuOpen: false } }),
});
expect(body).toContain('Most recent');
});
diff --git a/src/azimut/api/analyzers.py b/src/azimut/api/analyzers.py
index 7339391..e2e0b9c 100644
--- a/src/azimut/api/analyzers.py
+++ b/src/azimut/api/analyzers.py
@@ -409,7 +409,8 @@ def add_manual(case_id: str, ident: str, body: ManualCandidate) -> dict[str, Any
parts = []
for ty in range(top // size, (bottom - 1) // size + 1):
for tx in range(left // size, (right - 1) // size + 1):
- keys = [engine._key(stored(Source, s), z, tx, ty, None) for s in sources]
+ keys = [engine._key(stored(Source, s), z, tx, ty, None, saved.get("engine_version", 4))
+ for s in sources]
if not all(key in saved["frames"] for key in keys):
continue
px, py = max(left, tx * size), max(top, ty * size)
diff --git a/src/azimut/api/compare.py b/src/azimut/api/compare.py
index a1ef919..4285298 100644
--- a/src/azimut/api/compare.py
+++ b/src/azimut/api/compare.py
@@ -56,7 +56,7 @@ from .satellite import locate_on_save, saved_changed
router = APIRouter(prefix="/api", tags=["compare"])
OVERLAYS = frozenset({
- "boundaries", "roads", "railway", "power", "seamarks", "gpstraces",
+ "boundaries", "placenames", "roads", "railway", "power", "seamarks", "gpstraces",
"firms", "nightlights", "saved",
})
MAX_FRAME_BYTES = 24_000_000
diff --git a/src/azimut/api/ingest.py b/src/azimut/api/ingest.py
index 01cd716..319bbc1 100644
--- a/src/azimut/api/ingest.py
+++ b/src/azimut/api/ingest.py
@@ -55,6 +55,7 @@ from .. import __version__, config
from ..engine import (
extinstall,
firms,
+ firmspoints,
geo,
mapsites,
media as media_engine,
@@ -69,6 +70,7 @@ from .satellite import (
GridSaveIn,
apply_grid_marks,
firms_answer,
+ firms_drawn,
firms_key,
firms_sensors,
get_search_grid,
@@ -666,11 +668,12 @@ def firms_image(
) -> Response:
"""Active fire detections over one rectangle of ground, as a picture.
- The app's own map draws FIRMS as tiles (``/api/firms/tiles``). The panel
- over Google or Yandex has no tile grid of its own, so it asks for the whole
- of what it can see at once and lays that over the map — which is also one
- request per settled view rather than a dozen, and the FIRMS allowance is
- counted in requests.
+ The app's own map draws FIRMS from vector tiles (``/api/firms/points``). The
+ panel over Google or Yandex has no tile grid of its own, so it asks for the
+ whole of what it can see at once and lays that over the map — which is also
+ one request per settled view rather than a dozen, and the FIRMS allowance is
+ counted in requests. Close in, the picture is drawn from the same points as
+ the map's tiles.
Same key, same guard, same reason as the app's route: NASA puts the
MAP_KEY in the path, so it never crosses into a page.
@@ -680,10 +683,18 @@ def firms_image(
raise HTTPException(status_code=404, detail="no FIRMS key saved")
if north <= south or east <= west:
raise HTTPException(status_code=422, detail="the rectangle has no area")
+ bounds = firms.bounds_of(south, west, north, east)
+ try:
+ firms.sensor(sensor)
+ drawn = firmspoints.drawn_here(window, bounds, width)
+ except KeyError as exc:
+ raise HTTPException(status_code=422, detail=str(exc)) from exc
+ if drawn:
+ return firms_drawn(key, sensor_id=sensor, window=window, bounds=bounds, width=width, height=height)
try:
url = firms.image_url(
key,
- bounds=firms.bounds_of(south, west, north, east),
+ bounds=bounds,
width=width,
height=height,
sensor_id=sensor,
@@ -691,9 +702,11 @@ def firms_image(
first=first,
last=last,
)
+ mark = firms.mark_px(sensor, bounds, width)
+ max_age = firms.cache_seconds(window, first, last, today=datetime.now(timezone.utc).date())
except (KeyError, ValueError) as exc:
raise HTTPException(status_code=422, detail=str(exc)) from exc
- return firms_answer(url)
+ return firms_answer(key, url, mark=mark, max_age=max_age)
@router.get("/firms/sensors", dependencies=[Depends(require_token)])
diff --git a/src/azimut/api/satellite.py b/src/azimut/api/satellite.py
index 98f43d7..ad66835 100644
--- a/src/azimut/api/satellite.py
+++ b/src/azimut/api/satellite.py
@@ -7,9 +7,13 @@ import math
import os
import re
import tempfile
+import threading
+import time
+from collections import OrderedDict
+from concurrent.futures import Future, ThreadPoolExecutor
# Aliased: this module already imports the ``time`` module for tile timing, and
# the sky routes need the datetime classes of the same names.
-from datetime import date as calendar_date, datetime, time as wall_clock, timezone
+from datetime import date as calendar_date, datetime, time as wall_clock, timedelta, timezone
from pathlib import Path
from typing import Any, Literal
@@ -24,6 +28,7 @@ from ..engine.analysis_models import Zone
from ..engine import (
cities,
firms,
+ firmspoints,
geo,
google_tiles,
localtime,
@@ -281,16 +286,20 @@ def sentinel_dates(
"free tier is used; enable the override in Settings to keep going",
)
try:
- found = sentinel.dates(instance, lat, lon, start, end, collection=collection)
+ found = sentinel.dates(instance, lat, lon, start, end, collection=collection,
+ on_request=_count_sentinel_request)
except ValueError as exc:
- config.record_usage("sentinelhub", 1)
raise HTTPException(status_code=422, detail=str(exc)) from exc
except Exception as exc:
raise HTTPException(status_code=502, detail=f"date lookup failed: {tiles.upstream_failure(exc)}") from exc
- config.record_usage("sentinelhub", 1)
return {"dates": found, "start": start, "end": end}
+def _count_sentinel_request() -> None:
+ """One catalogue page asked of Sentinel Hub, on its meter."""
+ config.record_usage("sentinelhub", 1)
+
+
class AcquisitionQuery(BaseModel):
"""The drawn areas a sweep would cover, and the window to look in."""
@@ -311,7 +320,8 @@ def sentinel_acquisitions(body: AcquisitionQuery) -> dict[str, Any]:
run, that is a number on a row; discovered after it, it is a sweep paid for
in tiles that found nothing.
- User-triggered only. Billed as one request on the sentinelhub meter.
+ User-triggered only. Billed as one request a catalogue page on the
+ sentinelhub meter, which is one for most windows.
"""
instance = _sentinel_instance()
if config.usage_blocked("sentinelhub"):
@@ -323,13 +333,12 @@ def sentinel_acquisitions(body: AcquisitionQuery) -> dict[str, Any]:
try:
found = sentinel.acquisitions(
instance, [list(zone.ring()) for zone in body.zones], body.start, body.end,
- collection=body.collection,
+ collection=body.collection, on_request=_count_sentinel_request,
)
except ValueError as exc:
raise HTTPException(status_code=422, detail=str(exc)) from exc
except Exception as exc:
raise HTTPException(status_code=502, detail=f"pass lookup failed: {tiles.upstream_failure(exc)}") from exc
- config.record_usage("sentinelhub", 1)
return {**found, "start": body.start, "end": body.end}
@@ -633,9 +642,84 @@ def tile_proxy(provider_id: str, z: int, x: int, y: int) -> Response:
raise HTTPException(status_code=404, detail="no imagery at this location/zoom")
-#: What FIRMS means by the placard it draws instead of detections. Its own
-#: wording, which covers both ways a key stops working.
-FIRMS_REFUSED = "FIRMS did not accept this key, or the account is over its limit"
+#: The three things a placard can turn out to mean, once the key-status
+#: endpoint has said which (``firms.allowance``).
+FIRMS_SPENT = "FIRMS allowance used up (5,000 per 10 minutes); it refills within ten minutes"
+FIRMS_REFUSED = "FIRMS does not know this key"
+FIRMS_UNSURE = "FIRMS turned this picture down without saying why; try again in a moment"
+#: How long one answer from the key-status endpoint stands for the tiles of a
+#: burst: a screen that hits the placard hits it a dozen times at once.
+FIRMS_VERDICT_SECONDS = 15
+
+_firms_lock = threading.Lock()
+#: One status question at a time, held apart from ``_firms_lock`` so a tile
+#: checking the pause never waits on NASA's answer to somebody else's placard.
+_firms_asking = threading.Lock()
+#: ``(monotonic, verdict)`` of the last status question.
+_firms_verdict: tuple[float, str] | None = None
+#: While a spent allowance pauses the layer: when it ends, on both clocks, and
+#: the count FIRMS gave. Memory only: a restart forgets it, and FIRMS's own
+#: ten minutes will have passed by then or be about to.
+_firms_pause: dict[str, Any] = {}
+
+
+def firms_paused() -> dict[str, Any] | None:
+ """The pause a spent allowance put on the layer, while it lasts."""
+ with _firms_lock:
+ if _firms_pause and _firms_pause["until"] > time.monotonic():
+ return {"until": _firms_pause["until_utc"], "used": _firms_pause["used"],
+ "of": _firms_pause["of"]}
+ _firms_pause.clear()
+ return None
+
+
+def _firms_ask(key: str) -> str:
+ """'spent', 'refused' or 'unsure', from the key-status endpoint."""
+ try:
+ answer = _client().get(firms.STATUS_URL, params={"MAP_KEY": key}, timeout=10)
+ except Exception:
+ return "unsure"
+ if answer.status_code in (401, 403):
+ config.record_provider_status("firms", False, firms.status_error(answer.text))
+ return "refused"
+ count = firms.allowance(answer.text) if answer.status_code == 200 else None
+ if not count or not firms.spent(*count):
+ # a count far from the limit means the window turned over meanwhile,
+ # or the refusal was something else: nothing to pause for
+ return "unsure"
+ with _firms_lock:
+ _firms_pause.update(
+ until=time.monotonic() + firms.PAUSE_SECONDS,
+ until_utc=(datetime.now(timezone.utc) + timedelta(seconds=firms.PAUSE_SECONDS))
+ .isoformat(timespec="seconds"),
+ used=count[0], of=count[1],
+ )
+ return "spent"
+
+
+def _firms_refusal(key: str) -> HTTPException:
+ """What a refusal meant, asked of the one endpoint that can say.
+
+ The WMS's placard reads "invalid key *or* spent allowance" and is the same
+ bytes either way, and the area API's refusals are a sentence nobody
+ promised to keep. The key-status endpoint costs no transaction and answers a key
+ it knows with its count, so a spent allowance pauses the layer instead of
+ filing a good key as dead. Only a key it says it does not know is
+ benched; a failure to ask says nothing about the key and benches nothing.
+ """
+ global _firms_verdict
+ with _firms_asking:
+ memo = _firms_verdict
+ if memo and time.monotonic() - memo[0] < FIRMS_VERDICT_SECONDS:
+ verdict = memo[1]
+ else:
+ verdict = _firms_ask(key)
+ _firms_verdict = (time.monotonic(), verdict)
+ if verdict == "spent":
+ return HTTPException(status_code=429, detail=FIRMS_SPENT)
+ if verdict == "refused":
+ return HTTPException(status_code=502, detail=FIRMS_REFUSED)
+ return HTTPException(status_code=502, detail=FIRMS_UNSURE)
def firms_key() -> str | None:
@@ -654,17 +738,38 @@ def firms_key() -> str | None:
return (settings.get("api_keys") or {}).get("firms")
+def firms_state() -> str:
+ """Why the layer can or cannot be asked, as the Layers row says it.
+
+ ``keyed`` alone read "no key" for three different things: no key, a key
+ switched off in Settings, and a key FIRMS refused. Each wants a different
+ word and a different way out. FIRMS's own sentence stays with the verdict
+ in Settings, where the key is.
+ """
+ settings = config.load_settings()
+ if not (settings.get("api_keys") or {}).get("firms"):
+ return "missing"
+ if not settings.get("providers_enabled", {}).get("firms", True):
+ return "off"
+ if config.provider_key_bad("firms", settings):
+ return "refused"
+ return "ready"
+
+
@router.get("/firms/sensors")
def firms_sensors() -> dict[str, Any]:
"""What the fire layer can be asked, and whether it can be asked at all.
- Read on mount by the Layers panel, so it touches no network: the sensors
- and the windows are a catalogue, and ``keyed`` is a look at settings.json.
+ Read on mount by the Layers panel, and again when a tile fails, so it
+ touches no network: the sensors and the windows are a catalogue, the state
+ is a look at settings.json, and ``paused`` is what the last refusal said.
A layer nobody can use says so with the reason rather than failing on the
first tile.
"""
return {
"keyed": bool(firms_key()),
+ "state": firms_state(),
+ "paused": firms_paused(),
"sensors": [{"id": s.id, "label": s.label} for s in firms.SENSORS],
"windows": list(firms.WINDOWS),
"max_zoom": firms.MAX_ZOOM,
@@ -672,8 +777,8 @@ def firms_sensors() -> dict[str, Any]:
}
[email protected]("/firms/tiles/{z}/{x}/{y}")
-def firms_tile(
[email protected]("/firms/points/{z}/{x}/{y}")
+def firms_points(
z: int,
x: int,
y: int,
@@ -682,66 +787,209 @@ def firms_tile(
first: str = "",
last: str = "",
) -> Response:
- """One tile of active fire detections, proxied so the key stays here.
-
- FIRMS puts the MAP_KEY in the *path*, so a tile URL the browser could build
- would publish it in the page, in the network log and in a screenshot of
- either. Everything else is this endpoint translating the map's z/x/y into
- the bounding box a WMS wants (``engine/firms.py``).
-
- Never cached to disk: the live layers are what is burning now, refreshed
- upstream every fifteen minutes, and a cached fire is a lie with a timestamp.
+ """One vector tile of active fire detections, which the map draws itself.
+
+ The map draws every mark, at every zoom, so a square keeps its size through
+ a zoom and never waits blown up or hidden for the next level. From
+ ``firmspoints.MIN_ZOOM`` in, a rolling window is cut from the points
+ fetched for its cell once, footprints and all. Farther out, and for a dated
+ range, the marks are read off FIRMS's own picture of the tile, one request
+ a tile as before (``firmspoints.picture_tile``).
+
+ FIRMS puts the MAP_KEY in the *path*, so a URL the browser could build would
+ publish it in the page, in the network log and in a screenshot of either:
+ the key stays here. Never cached to disk: the live layers are what is
+ burning now, and a cached fire is a lie with a timestamp.
"""
- if z < 0 or firms.too_deep(z):
- raise HTTPException(
- status_code=422,
- detail=f"FIRMS source tiles use zooms 0 through {firms.MAX_ZOOM}",
- )
+ if not 0 <= z <= firmspoints.MAX_ZOOM:
+ raise HTTPException(status_code=422, detail=f"FIRMS tiles come in zooms 0 through {firmspoints.MAX_ZOOM}")
grid = 1 << z
if not (0 <= x < grid) or not (0 <= y < grid):
raise HTTPException(status_code=422, detail="tile coordinates out of range")
+ try:
+ firms.sensor(sensor)
+ except KeyError as exc:
+ raise HTTPException(status_code=422, detail=str(exc)) from exc
key = firms_key()
if not key:
raise HTTPException(status_code=404, detail="no FIRMS key saved")
+ exact = window in firmspoints.DAYS_BACK and z >= firmspoints.MIN_ZOOM
try:
- url = firms.tile_url(
- key, sensor_id=sensor, window=window, z=z, x=x, y=y, first=first, last=last
- )
- except (KeyError, ValueError) as exc:
+ url = "" if exact else firms.tile_url(
+ key, sensor_id=sensor, window=window, z=z, x=x, y=y, first=first, last=last, mark=1)
+ max_age = firms.cache_seconds(window, first, last, today=datetime.now(timezone.utc).date())
+ except ValueError as exc:
raise HTTPException(status_code=422, detail=str(exc)) from exc
- return firms_answer(url)
+ if firms_paused():
+ raise HTTPException(status_code=429, detail=FIRMS_SPENT)
+ if exact:
+ points = _firms_points_for(key, sensor, window, firms.tile_bounds(z, x, y))
+ body = firmspoints.tile(points, z, x, y, window=window, now=datetime.now(timezone.utc))
+ else:
+ try:
+ body = firmspoints.picture_tile(firms_picture(key, url), z, x, y, sensor_id=sensor)
+ except (OSError, ValueError) as exc:
+ raise HTTPException(status_code=502, detail="FIRMS sent a picture that could not be read") from exc
+ # The browser may hold a live tile for a few minutes, long enough for a pan
+ # back and short of FIRMS's own fifteen, and a past range for hours.
+ return Response(
+ content=body,
+ media_type="application/vnd.mapbox-vector-tile",
+ headers={"Cache-Control": f"private, max-age={max_age}"},
+ )
-def firms_answer(url: str) -> Response:
- """Fetch one FIRMS picture and hand it on, or say what FIRMS said.
+def firms_picture(key: str, url: str) -> bytes:
+ """One FIRMS picture, or what FIRMS said instead.
- Shared with the extension's own route (``api/ingest.py``): the two ask for
- different rectangles and want exactly the same handling of a refusal, and
- FIRMS refuses by answering 200 with an XML report in the body.
+ Shared by the map's far tiles and the extension's picture (``api/ingest.py``):
+ they ask for different rectangles and want exactly the same handling of a
+ refusal, and FIRMS refuses by answering 200 with an XML report in the body.
+ While a spent allowance pauses the layer nothing is asked at all: each
+ refused picture would only add to the count that refused it.
"""
+ if firms_paused():
+ raise HTTPException(status_code=429, detail=FIRMS_SPENT)
try:
- response = httpx.get(url, headers={"User-Agent": tiles.USER_AGENT}, timeout=20)
+ response = _client().get(url)
except Exception as exc:
raise HTTPException(status_code=502, detail=f"FIRMS unreachable: {tiles.upstream_failure(exc)}") from exc
if response.status_code >= 400 or "xml" in response.headers.get("content-type", ""):
raise HTTPException(
status_code=502, detail=firms.service_error(response.text) or "FIRMS refused the request"
)
- # A key FIRMS will not accept comes back as 200 and a picture saying so.
- # Nothing in the answer is an error, so without this the map would tile that
- # placard across the ground. It is an auth-shaped verdict and nothing else,
- # which is what lets it bench the layer the way a dead basemap key is
- # benched: the Layers row goes back to "add a key", with the reason.
+ # A key FIRMS will not accept, and an allowance spent, both come back as 200
+ # and the same picture saying so. Nothing in the answer is an error, so
+ # without this the map would draw that placard's pixels as fires.
if firms.is_placard(response.content):
- config.record_provider_status("firms", False, FIRMS_REFUSED)
- raise HTTPException(status_code=502, detail=FIRMS_REFUSED)
+ raise _firms_refusal(key)
+ return response.content
+
+
+def firms_answer(key: str, url: str, *, mark: int, max_age: int) -> Response:
+ """The extension's picture far out: FIRMS's own, dressed to read over imagery."""
+ content = firms_picture(key, url)
+ try:
+ picture = firms.dress(content, mark)
+ except (OSError, ValueError) as exc:
+ raise HTTPException(status_code=502, detail="FIRMS sent a picture that could not be read") from exc
+ return Response(
+ content=picture,
+ media_type="image/png",
+ headers={"Cache-Control": f"private, max-age={max_age}"},
+ )
+
+
+#: The points behind the drawn tiles (``engine/firmspoints.py``) by source, cell
+#: and day: when they stop being true, and the points. Least recently drawn
+#: first, and never more than ``FIRMS_POINTS_CAP`` rows in all, about 24 MB,
+#: where a week over a burning region is a few hundred thousand. Memory only:
+#: a restart asks again, which a live window would soon do anyway.
+FIRMS_POINTS_CAP = 1_000_000
+_firms_points: OrderedDict[tuple[str, tuple[int, int], calendar_date], tuple[float, firmspoints.Points]] = OrderedDict()
+_firms_rows = 0
+_firms_points_lock = threading.Lock()
+#: One fetch of the same days of the same cell at a time. The tiles of a screen
+#: want the same cells at once, and each would otherwise pay for them.
+_firms_flights: dict[tuple[str, tuple[int, int], calendar_date, int], Future[None]] = {}
+#: The satellites, cells and stretches of days of a screen fetched side by
+#: side, and no more at once than the connection pool keeps warm.
+_firms_pool = ThreadPoolExecutor(max_workers=8, thread_name_prefix="firms")
+
+
+def _firms_missing(source: str, cell: tuple[int, int], days: list[calendar_date]) -> list[calendar_date]:
+ """The days of a cell not held, or held past their time."""
+ clock = time.monotonic()
+ with _firms_points_lock:
+ return [day for day in days
+ if (held := _firms_points.get((source, cell, day))) is None or held[0] <= clock]
+
+
+def _firms_store(source: str, cell: tuple[int, int], found: dict[calendar_date, firmspoints.Points]) -> None:
+ global _firms_rows
+ now = datetime.now(timezone.utc)
+ clock = time.monotonic()
+ with _firms_points_lock:
+ for day, points in found.items():
+ old = _firms_points.pop((source, cell, day), None)
+ if old:
+ _firms_rows -= len(old[1])
+ _firms_points[(source, cell, day)] = (clock + firmspoints.fresh_seconds(day, now), points)
+ _firms_rows += len(points)
+ while _firms_rows > FIRMS_POINTS_CAP and len(_firms_points) > 1:
+ _, (_, gone) = _firms_points.popitem(last=False)
+ _firms_rows -= len(gone)
+
+
+def _firms_fetch(key: str, source: str, cell: tuple[int, int], start: calendar_date, count: int) -> None:
+ """Ask the area API for ``count`` days of a cell from ``start``."""
+ try:
+ response = _client().get(firmspoints.area_url(key, source, cell, start, count), timeout=30)
+ except Exception as exc:
+ raise HTTPException(status_code=502, detail=f"FIRMS unreachable: {tiles.upstream_failure(exc)}") from exc
+ if response.status_code != 200 or not firmspoints.is_table(response.text):
+ raise _firms_refusal(key)
+ _firms_store(source, cell, firmspoints.parse(
+ response.text, [start + timedelta(days=n) for n in range(count)]))
+
+
+def _firms_flights_for(key: str, source: str, cell: tuple[int, int], days: list[calendar_date]) -> list[Future[None]]:
+ """The fetches that bring a cell these days: those under way, and new ones."""
+ flights = []
+ with _firms_points_lock:
+ for start, count in firmspoints.runs(days):
+ flight = _firms_flights.get((source, cell, start, count))
+ if flight is None or flight.done():
+ flight = _firms_pool.submit(_firms_fetch, key, source, cell, start, count)
+ _firms_flights[(source, cell, start, count)] = flight
+ flights.append(flight)
+ for done in [name for name, flight in _firms_flights.items() if flight.done()]:
+ del _firms_flights[done]
+ return flights
+
+
+def _firms_points_for(
+ key: str, sensor_id: str, window: str, bounds: tuple[float, float, float, float]
+) -> firmspoints.Points:
+ """Every point a picture may draw, fetched once for all the pictures after it.
+
+ Every source, cell and stretch of days missing is asked at once, and a
+ picture waits for them all: a picture short of one satellite would look
+ whole and not be.
+ """
+ days = firmspoints.days_for(window, datetime.now(timezone.utc))
+ wanted = [(source, cell) for source in firmspoints.SOURCES[sensor_id] for cell in firmspoints.cells_for(bounds)]
+ flights = [flight for source, cell in wanted if (missing := _firms_missing(source, cell, days))
+ for flight in _firms_flights_for(key, source, cell, missing)]
+ for flight in flights:
+ flight.result()
+ parts = []
+ with _firms_points_lock:
+ for source, cell in wanted:
+ for day in days:
+ held = _firms_points.get((source, cell, day))
+ if held:
+ _firms_points.move_to_end((source, cell, day))
+ parts.append(held[1])
+ return firmspoints.Points.join(parts)
+
+
+def firms_drawn(
+ key: str, *, sensor_id: str, window: str, bounds: tuple[float, float, float, float], width: int, height: int
+) -> Response:
+ """The extension's picture close in, drawn here from the same points the map's tiles are cut from.
+
+ The pause holds here as it does for the WMS: a spent allowance asks nothing.
+ """
+ if firms_paused():
+ raise HTTPException(status_code=429, detail=FIRMS_SPENT)
+ points = _firms_points_for(key, sensor_id, window, bounds)
+ picture = firmspoints.render(points, bounds, width, height, sensor_id=sensor_id, window=window,
+ now=datetime.now(timezone.utc))
return Response(
- content=response.content,
+ content=picture,
media_type="image/png",
- # The browser may hold a picture for a few minutes — long enough for a
- # pan back, short enough that a live layer is still live. FIRMS itself
- # updates every fifteen.
- headers={"Cache-Control": "private, max-age=300"},
+ headers={"Cache-Control": f"private, max-age={firms.LIVE_CACHE_SECONDS}"},
)
diff --git a/src/azimut/config.py b/src/azimut/config.py
index aa8b14e..afb5f70 100644
--- a/src/azimut/config.py
+++ b/src/azimut/config.py
@@ -51,7 +51,9 @@ DEFAULT_SETTINGS: dict[str, Any] = {
# The Copernicus layer Detect's radar methods read: one the user added to
# their configuration with Sentinel-1 as its source. Empty until found.
"sentinel1_layer": "",
- "detect_view": {"collapsed": False, "basemap": "esri-world-imagery", "overlays": ["boundaries"], "saved": True},
+ "detect_view": {
+ "collapsed": False, "basemap": "esri-world-imagery", "overlays": ["boundaries", "placenames"], "saved": True,
+ },
# Schema version this build writes. Read back through _settings_schema() so
# a future breaking rename is migrated rather than silently dropped.
"schema": SETTINGS_SCHEMA,
diff --git a/src/azimut/engine/analysis_models.py b/src/azimut/engine/analysis_models.py
index ca34d25..944c218 100644
--- a/src/azimut/engine/analysis_models.py
+++ b/src/azimut/engine/analysis_models.py
@@ -107,15 +107,16 @@ def stored(model: type[M], data: Any) -> M:
#: Map layers that no longer exist. A saved preference or a settings backup that
#: still names one drops it rather than being refused: CARTO's labels went when
-#: their tiles began asking for a key, and the borders already name places.
+#: their tiles began asking for a key, and the place names now come from
+#: OpenFreeMap under an id of their own.
RETIRED_OVERLAYS = frozenset({"labels"})
class DetectPrefs(Model):
collapsed: bool = False
basemap: str = Field(default="esri-world-imagery", max_length=120, pattern=r"^[a-zA-Z0-9_-]+$")
- overlays: list[Literal["boundaries", "roads", "railway", "power", "seamarks", "gpstraces"]] = Field(
- default=["boundaries"], max_length=6)
+ overlays: list[Literal["boundaries", "placenames", "roads", "railway", "power", "seamarks", "gpstraces"]] = (
+ Field(default=["boundaries", "placenames"], max_length=7))
saved: bool = True
@field_validator("overlays", mode="before")
diff --git a/src/azimut/engine/analyzers.py b/src/azimut/engine/analyzers.py
index e3fb7d1..4243a59 100644
--- a/src/azimut/engine/analyzers.py
+++ b/src/azimut/engine/analyzers.py
@@ -77,7 +77,10 @@ PAD = 32
# Bumped when a product's layout changes, so a frame kept from an older run is
# never decoded as a newer one.
PRODUCT_VERSION = 2
-ENGINE_VERSION = 4
+# 5: a day is read whatever its tile's cloud cover. The ceiling picks the newest
+# pass and no longer filters the read, so a frame a v4 run kept under the same
+# source may be a blank one, and is not reused (``_key``).
+ENGINE_VERSION = 5
LOCK = threading.RLock()
KINDS = {"areas": "analysis-area", "zones": "analysis-zones", "followups": "analysis-follow-up", "runs": "analysis-run"}
ACTIVE = {"queued", "running"}
@@ -541,24 +544,35 @@ def check_active(case: Case, ident: str) -> None:
raise workqueue.JobCancelled() from exc
-def _key(source: Source, z: int, x: int, y: int, product: str | None) -> str:
+def _key(source: Source, z: int, x: int, y: int, product: str | None,
+ engine: int = ENGINE_VERSION) -> str:
+ """The name one frame is kept under, for the engine version of its run.
+
+ Up to v4 a Sentinel-2 day was read under its source's cloud ceiling, and
+ Sentinel Hub drops a whole tile above it: a day chosen over the ceiling came
+ back blank. From v5 a day is read whole, so a source with a ceiling names
+ its frames apart, and an older run still finds its own under the old name.
+ """
parts: list[Any] = [source.model_dump(), z, x, y, product]
if product:
parts.append(PRODUCT_VERSION)
+ if engine >= 5 and source.maxcc < sentinel.DEFAULT_MAXCC:
+ parts.append("whole-day")
return hashlib.sha256(json.dumps(parts, sort_keys=True).encode()).hexdigest()[:32]
def picture_cache_id(source: Source) -> str:
"""The tile-cache folder a source's review picture lives in.
- Sentinel-2's is the basemap's own variant, so a picture read for a sweep is
- a tile the map can reuse. Sentinel-1's is rendered by us for one pass, and
- its time rides in the name without the colons Windows refuses in a folder.
+ Sentinel-2's is the basemap's own variant for that day read whole, so a
+ picture read for a sweep is a tile the map can reuse. Sentinel-1's is
+ rendered by us for one pass, and its time rides in the name without the
+ colons Windows refuses in a folder.
"""
if source.provider == "sentinel1":
return (f"sentinel1~{source.layer}~{source.date}~{source.time.replace(':', '') or 'day'}"
f"~picture~v{PRODUCT_VERSION}")
- return sentinel.variant_id("sentinel2", source.layer, source.date, source.date, source.maxcc)
+ return sentinel.variant_id("sentinel2", source.layer, source.date, source.date, sentinel.DEFAULT_MAXCC)
def product_cache_id(source: Source, product: str) -> str:
@@ -566,7 +580,7 @@ def product_cache_id(source: Source, product: str) -> str:
if source.provider == "sentinel1":
return (f"sentinel1~{source.layer}~{source.date}~{source.time.replace(':', '') or 'day'}"
f"~{product}~v{PRODUCT_VERSION}")
- variant = sentinel.variant_id("sentinel2", source.layer, source.date, source.date, source.maxcc)
+ variant = sentinel.variant_id("sentinel2", source.layer, source.date, source.date, sentinel.DEFAULT_MAXCC)
return f"{variant}~{product}~v{PRODUCT_VERSION}"
@@ -637,7 +651,7 @@ def frame(case: Case, run: dict[str, Any], source: Source, x: int, y: int,
"""One tile's picture, or its band product with PAD pixels of context."""
z, size = GRID
edge = size + 2 * PAD if product else size
- key = _key(source, z, x, y, product)
+ key = _key(source, z, x, y, product, run.get("engine_version", ENGINE_VERSION))
frame_rel = layout.analysis_asset_rel(run["id"], key)
name = frame_rel.rsplit("/", 1)[-1]
destination = case.resolve_inside(frame_rel)
@@ -661,18 +675,21 @@ def frame(case: Case, run: dict[str, Any], source: Source, x: int, y: int,
raise ValueError("Sentinel Hub usage limit reached; review Settings")
instance = _instance()
radar = source.provider == "sentinel1"
+ # A day is read whole, whatever its tile's cloud cover: the ceiling
+ # chose the day, and passed on as MAXCC it would blank a day the analyst
+ # picked over it. The sky byte masks the clouds pixel by pixel.
if product or radar:
# A radar picture is ours too: there is no true colour to borrow,
# so the review composite is rendered like a product, unpadded.
try:
raw = sentinel.band_frame(instance, _box(z, x, y, PAD if product else 0), edge, edge,
source.date, product or "sar-picture",
- 100 if radar else source.maxcc, layer=source.layer,
+ sentinel.DEFAULT_MAXCC, layer=source.layer,
time=source.time)
finally:
config.record_usage("sentinelhub", 1)
else:
- url = sentinel.wmts_url(source.layer, source.date, source.date, source.maxcc)
+ url = sentinel.wmts_url(source.layer, source.date, source.date, sentinel.DEFAULT_MAXCC)
url = url.replace("{key}", instance)
with httpx.stream("GET", tiles.tile_url(url, z, x, y, 1), timeout=30) as response:
if response.status_code == 404:
@@ -1566,11 +1583,9 @@ def _lookup(body: RunInput, start: str, end: str) -> list[dict[str, Any]]:
instance = (config.load_settings().get("api_keys") or {}).get("sentinelhub")
if not instance or config.usage_blocked("sentinelhub"):
raise ValueError("Copernicus is unavailable or its usage limit is reached")
- try:
- found = sentinel.acquisitions(instance, [list(zone.ring()) for zone in body.zones],
- start, end, collection=recipe_sensor(body.recipe))
- finally:
- config.record_usage("sentinelhub", 1)
+ found = sentinel.acquisitions(instance, [list(zone.ring()) for zone in body.zones],
+ start, end, collection=recipe_sensor(body.recipe),
+ on_request=lambda: config.record_usage("sentinelhub", 1))
return list(found["dates"])
@@ -1867,7 +1882,7 @@ def sweep_area(case: Case, run: dict[str, Any], body: RunInput) -> tuple[list[di
asked += int(inside.sum())
imaged += int((inside & (picture_a[:, :, 3] > 0) & (picture_b[:, :, 3] > 0)).sum())
sources = [body.b] if single else [body.a, body.b]
- keys = [_key(source, z, x, y, None) for source in sources]
+ keys = [_key(source, z, x, y, None, run["engine_version"]) for source in sources]
results.extend(_candidates(reading, body.recipe.phenomenon, x, y, part, keys))
if len(results) > MAX_RESULTS * 4:
raise ValueError("too many fragments; lower the sensitivity or use smaller areas")
diff --git a/src/azimut/engine/firms.py b/src/azimut/engine/firms.py
index 34fcbe6..8c4cc88 100644
--- a/src/azimut/engine/firms.py
+++ b/src/azimut/engine/firms.py
@@ -10,13 +10,13 @@ archive, which is the same layers asked with a ``TIME``.
Three decisions are recorded here because none is obvious from the URLs:
-- **WMS, not the CSV API.** FIRMS offers both. The CSV would let the app draw
- its own marks — clickable, styled by confidence — but a bbox of detections is
- unbounded in a way a tile is not, and it would need paging, a zoom floor and a
- cap before it drew anything. The WMS is a raster layer, which the map already
- knows how to stack (``lib/map/basemap.js``), and one screen is one request
- per tile whatever is burning. Drawing our own marks is the upgrade, not the
- starting point.
+- **WMS far out, the points close in.** A bbox of detections is unbounded in a
+ way a tile is not: a continent's burning week is hundreds of thousands of
+ points, where the WMS is one picture per tile whatever is burning. So out
+ from z8, and for a dated range, this module asks the WMS, and the squares
+ of its picture are read back into points. From z8 in, a rolling window
+ comes from the area API's points, one fetch per cell for every zoom under
+ it. Either way the map draws the marks itself (``engine/firmspoints.py``).
- **The key never reaches the browser.** FIRMS puts the MAP_KEY *in the path*,
so a direct tile URL would publish it in the page source, in the network log,
and in any screenshot of either. It is proxied like every other keyed
@@ -26,32 +26,42 @@ Three decisions are recorded here because none is obvious from the URLs:
is the projection the tile grid is already in — no reprojection, just the
four numbers of the tile's own square.
-Rate limit, from FIRMS: 5000 transactions per 10 minutes, and a long date range
-counts as more than one. Nothing here polls, and a layer that is off asks for
-nothing, so a single analyst never approaches it — but it is why this must not
-grow a refresh timer without a reason.
+Rate limit, from FIRMS: 5000 transactions per 10 minutes, and every day a
+picture covers is counted, per satellite in the layer (measured 2026-09). One tile
+of the last 24 hours on the combined VIIRS layer is three, one tile of a 31-day
+range is ninety-three, so one screen of a long range spends more than a quarter
+of the allowance. Three things keep a session inside it: tiles of 512 px, a
+quarter of the requests 256 px would be; a past range the browser may keep for
+hours (``cache_seconds``); and a refusal read for what it is (``allowance``),
+so a spent allowance pauses the layer rather than filing the key as dead.
+Nothing here polls, and it must not grow a refresh timer.
"""
from __future__ import annotations
import hashlib
+import io
+import json
import math
import re
from dataclasses import dataclass
from datetime import date, timedelta
+from PIL import Image, ImageFilter
+
WMS_BASE = "https://firms.modaps.eosdis.nasa.gov/mapserver/wms/fires"
# The whole of Web Mercator, in metres: the tile grid's own square.
WORLD = 20037508.342789244
-TILE_SIZE = 256
+# A tile a quarter the count of 256 px ones for the same screen, and FIRMS
+# counts requests: the same ground, a quarter of the allowance.
+TILE_SIZE = 512
# FIRMS serves detections from the last seven days as its own layers, and
# anything older through the archive. Asking the archive for a range longer
# than this is refused upstream, so it is refused here with a reason.
MAX_RANGE_DAYS = 31
-# Past this the detections are a smear of identical squares: FIRMS draws a
-# fixed-size symbol per detection, and VIIRS resolves 375 m. The layer stops
-# being asked for rather than drawing a screen of overlapping marks.
-MAX_ZOOM = 14
+# Past this a tile would hold the same detections, which the map draws at any
+# deeper zoom from the deepest one. At 13 a VIIRS square is already 20 px or more.
+MAX_ZOOM = 13
@dataclass(frozen=True)
@@ -69,17 +79,19 @@ class Sensor:
id: str
label: str
layer: str
+ #: The ground one detection stands for, which is what its square is drawn as.
+ footprint_m: float
SENSORS: tuple[Sensor, ...] = (
# The default, and the reason to prefer it: VIIRS resolves 375 m where MODIS
# resolves 1 km, so a single burning building is a mark rather than a blur.
- Sensor(id="viirs", label="VIIRS (S-NPP + NOAA-20)", layer="fires_viirs"),
- Sensor(id="viirs_snpp", label="VIIRS Suomi-NPP", layer="fires_viirs_snpp"),
- Sensor(id="viirs_noaa20", label="VIIRS NOAA-20", layer="fires_viirs_noaa20"),
+ Sensor(id="viirs", label="VIIRS (S-NPP, NOAA-20, NOAA-21)", layer="fires_viirs", footprint_m=375),
+ Sensor(id="viirs_snpp", label="VIIRS Suomi-NPP", layer="fires_viirs_snpp", footprint_m=375),
+ Sensor(id="viirs_noaa20", label="VIIRS NOAA-20", layer="fires_viirs_noaa20", footprint_m=375),
# 1 km, and on orbit since 1999: the only one that can answer a question
# about a fire older than VIIRS itself.
- Sensor(id="modis", label="MODIS (Terra + Aqua)", layer="fires_modis"),
+ Sensor(id="modis", label="MODIS (Terra + Aqua)", layer="fires_modis", footprint_m=1000),
)
# The rolling windows FIRMS serves as layers of their own, by the suffix it
@@ -109,6 +121,42 @@ def is_placard(content: bytes) -> bool:
return hashlib.sha256(content).hexdigest() == PLACARD_SHA256
+#: How long a spent allowance pauses the layer before it asks again. The count
+#: fell back to zero in one go after ten quiet minutes (measured 2026-09), so
+#: the allowance returns within ten minutes, and a minute between tries spares
+#: each screen its dozen refusals.
+PAUSE_SECONDS = 60
+
+
+#: How near the limit a count has to be for a refusal to mean it was spent: a
+#: little over two of the dearest pictures, 31 days of the combined VIIRS layer
+#: at 93. FIRMS refuses a picture whose cost would carry the count past it.
+SPENT_MARGIN = 200
+
+
+def spent(used: int, limit: int) -> bool:
+ """Whether a count this close to its limit explains a refusal."""
+ return used + SPENT_MARGIN >= limit
+
+
+def allowance(body: str) -> tuple[int, int] | None:
+ """``(used, limit)`` from the key-status answer, or None when it is not one.
+
+ The placard says "invalid key *or* spent allowance" in one picture, the
+ same bytes either way (verified 2026-09). The status endpoint tells them
+ apart: a key it knows gets JSON with its count, even mid-refusal, and a key
+ it does not gets a 403 and a sentence.
+ """
+ try:
+ data = json.loads(body or "")
+ used, limit = data["current_transactions"], data["transaction_limit"]
+ except (ValueError, KeyError, TypeError):
+ return None
+ if not all(isinstance(n, int) and not isinstance(n, bool) for n in (used, limit)):
+ return None
+ return used, limit
+
+
def sensor(sensor_id: str) -> Sensor:
"""The sensor asked for, or a ``KeyError`` naming what is on offer."""
for entry in SENSORS:
@@ -193,6 +241,49 @@ def tile_bounds(z: int, x: int, y: int) -> tuple[float, float, float, float]:
return (left, top - span, left + span, top)
+# How a detection is drawn. FIRMS's default is a 5 px square in a dull red,
+# which reads on a plain map and sinks into imagery; its WMS takes a symbol, a
+# size and a colour per layer in the path, and `dress` adds the dark ring.
+SYMBOL = "square"
+#: The last 24 hours, and the rest of a longer window under them. FIRMS's own
+#: KML draws the newest red and the older toward yellow, so this keeps its
+#: convention: a fire still burning reads apart from what burned days ago.
+RECENT_RGB = (255, 48, 0)
+EARLIER_RGB = (255, 186, 0)
+#: The smallest square a detection is drawn as: far out a 375 m pixel is a
+#: speck, and a detection still has to be seen.
+MARK_MIN_PX = 7
+MARK_MAX_PX = 1000 # FIRMS's own ceiling for SIZE
+
+
+def drawn_layers(sensor_id: str, window: str) -> list[tuple[str, tuple[int, int, int]]]:
+ """The layers one picture is drawn from, lowest first, with their colours.
+
+ A window longer than a day adds the last 24 hours over it, which FIRMS
+ counts as one more day. A dated range is one colour: "the newest" of an
+ archive question is not a thing the question asked.
+ """
+ layer = layer_name(sensor_id, window)
+ if window in WINDOWS and window != "24h":
+ return [(layer, EARLIER_RGB), (layer_name(sensor_id, "24h"), RECENT_RGB)]
+ return [(layer, RECENT_RGB)]
+
+
+def mark_px(sensor_id: str, bounds: tuple[float, float, float, float], width: int) -> int:
+ """How many pixels one detection's square covers in this picture.
+
+ Its footprint on the ground, as far as the zoom shows it, and never smaller
+ than a mark still seen far out. Mercator stretches the ground by 1/cos of
+ the latitude, and the imagery under the squares with it, so they stretch too.
+ """
+ left, bottom, right, top = bounds
+ per_px = (right - left) / max(1, width)
+ middle = (bottom + top) / 2
+ lat = math.degrees(2 * math.atan(math.exp(middle * math.pi / WORLD)) - math.pi / 2)
+ ground = sensor(sensor_id).footprint_m / max(0.01, math.cos(math.radians(lat)))
+ return max(MARK_MIN_PX, min(MARK_MAX_PX, round(ground / per_px)))
+
+
def image_url(
key: str,
*,
@@ -203,19 +294,32 @@ def image_url(
window: str = "24h",
first: str = "",
last: str = "",
+ mark: int | None = None,
) -> str:
"""A GetMap for one square of ground, with the key where FIRMS puts it.
Pure, so the shape of the request is read off a test rather than off a
fire: `test_firms.py` asserts the bbox, the projection and the date range
- without asking NASA anything.
+ without asking NASA anything. The drawing rides in the path, after the key:
+ layers, symbols, sizes and colours, one entry per layer. ``mark`` sets the
+ square's size in pixels instead of the footprint's: the map's own marks are
+ read off a picture of 1 px squares (``firmspoints.picture_tile``).
"""
left, bottom, right, top = bounds
+ layers = drawn_layers(sensor_id, window)
+ size = mark or mark_px(sensor_id, bounds, width)
+ names = ",".join(name for name, _ in layers)
+ style = "/".join([
+ names,
+ ",".join(SYMBOL for _ in layers),
+ ",".join(str(size) for _ in layers),
+ ",".join("+".join(str(c) for c in rgb) for _, rgb in layers),
+ ])
query = [
"SERVICE=WMS",
"VERSION=1.3.0",
"REQUEST=GetMap",
- f"LAYERS={layer_name(sensor_id, window)}",
+ f"LAYERS={names}",
"FORMAT=image/png",
"TRANSPARENT=TRUE",
"CRS=EPSG:3857",
@@ -226,7 +330,7 @@ def image_url(
if window not in WINDOWS:
start, end = window_range(first, last)
query.append(f"TIME={start.isoformat()}/{end.isoformat()}")
- return f"{WMS_BASE}/{key}/?{'&'.join(query)}"
+ return f"{WMS_BASE}/{key}/{style}/?{'&'.join(query)}"
def tile_url(
@@ -240,12 +344,13 @@ def tile_url(
first: str = "",
last: str = "",
size: int = TILE_SIZE,
+ mark: int | None = None,
) -> str:
"""…and the one a map tile is: the same request over the tile's own square.
- The app's map is a grid of these. The extension asks for one image over the
- whole of somebody else's map instead, because it has no tile grid to hang
- them on — one screen, one request.
+ The app's map is a grid of these, turned into its own marks. The extension
+ asks for one image over the whole of somebody else's map instead, because it
+ has no tile grid to hang them on — one screen, one request.
"""
return image_url(
key,
@@ -256,12 +361,78 @@ def tile_url(
window=window,
first=first,
last=last,
+ mark=mark,
)
-def too_deep(zoom: int) -> bool:
- """Past the zoom where a detection mark still means one detection."""
- return zoom > MAX_ZOOM
+#: The ring laid around every mark, so a red square reads on red soil and a
+#: yellow one on sand.
+RING_RGBA = (24, 12, 6, 220)
+RING_PX = 2
+#: From this size a square is a footprint more than a mark, and a solid one
+#: would hide the ground it is about: its edge stays solid, its inside shows
+#: the ground through this much colour.
+FOOTPRINT_PX = 16
+FOOTPRINT_FILL = 0.35
+EDGE_PX = 2
+
+
+def dress(content: bytes, mark: int) -> bytes:
+ """A FIRMS picture made to read over imagery, as a PNG.
+
+ A picture with nothing in it goes back as it came.
+ """
+ with Image.open(io.BytesIO(content)) as source:
+ image = source.convert("RGBA")
+ if not image.getchannel("A").getbbox():
+ return content
+ buffer = io.BytesIO()
+ dressed(image, mark).save(buffer, "PNG")
+ return buffer.getvalue()
+
+
+def dressed(image: Image.Image, mark: int) -> Image.Image:
+ """Marks in an RGBA picture, each patch of them ringed dark.
+
+ A mark ``FOOTPRINT_PX`` or bigger, which is a footprint seen close, keeps a
+ solid edge and lets the ground show inside, the way FIRMS's own footprints
+ are drawn. The picture holds no more than pixels, so the ring and the edge
+ go round a patch, not each square in it: the points drawn here
+ (``engine/firmspoints.py``) give every square its own from the zoom where
+ that shows.
+ """
+ import numpy as np
+
+ alpha = image.getchannel("A")
+ pixels = np.asarray(image, dtype=np.float32) / 255
+ colour, cover = pixels[..., :3], pixels[..., 3]
+ ring = np.asarray(alpha.filter(ImageFilter.MaxFilter(2 * RING_PX + 1)), dtype=np.float32) / 255
+ if mark >= FOOTPRINT_PX:
+ inside = np.asarray(alpha.filter(ImageFilter.MinFilter(2 * EDGE_PX + 1)), dtype=np.float32) / 255
+ cover = cover - inside * (1 - FOOTPRINT_FILL)
+ outline = np.clip(ring - pixels[..., 3], 0, 1) * (RING_RGBA[3] / 255)
+ shade = np.array(RING_RGBA[:3], dtype=np.float32) / 255
+ total = cover + outline * (1 - cover)
+ mixed = (colour * cover[..., None] + shade * (outline * (1 - cover))[..., None]) / np.maximum(
+ total, 1e-6
+ )[..., None]
+ out = np.dstack([mixed, total])
+ return Image.fromarray(np.round(out * 255).astype(np.uint8))
+
+
+#: How long the browser may keep a picture. A live window is what is burning
+#: now, and FIRMS refreshes it every fifteen minutes. A range that ended before
+#: yesterday is history: a detection filed late has landed by then.
+LIVE_CACHE_SECONDS = 300
+PAST_CACHE_SECONDS = 6 * 3600
+
+
+def cache_seconds(window: str, first: str = "", last: str = "", *, today: date) -> int:
+ """How long a picture of this window stays true."""
+ if window in WINDOWS:
+ return LIVE_CACHE_SECONDS
+ _, end = window_range(first, last)
+ return PAST_CACHE_SECONDS if end < today - timedelta(days=1) else LIVE_CACHE_SECONDS
def service_error(body: str) -> str:
diff --git a/src/azimut/engine/firmspoints.py b/src/azimut/engine/firmspoints.py
new file mode 100644
index 0000000..73a26d2
--- /dev/null
+++ b/src/azimut/engine/firmspoints.py
@@ -0,0 +1,435 @@
+"""FIRMS detections as the vector tiles the map draws, and the points behind them.
+
+Far out, and for a dated range, a tile's marks are read off FIRMS's own
+picture of it (``picture_tile``): a continent's week is more points than a
+laptop should hold, and the WMS draws it in one picture a tile. From
+``MIN_ZOOM`` in, a rolling window comes from the area API, which hands over the
+points of a whole cell of ground at once, and every tile over that cell, at
+every zoom, is cut from memory (``tile``). Measured 2026-09-27:
+
+- **The allowance.** The area API counts 2 transactions per day and satellite,
+ whatever the size of the box. A week of the combined VIIRS layer over one
+ cell is 48, about two WMS tiles, and every zoom under it is then free, where
+ the WMS counts every tile of every zoom again.
+- **The map draws them.** The app's map gets vector tiles (``tile``) and draws
+ each mark itself, every frame, so a square keeps its size through a zoom. A
+ picture's squares grow with its pixels until the next picture lands.
+- **Each square its own.** A picture holds pixels, so an outline could only go
+ round a whole cluster. Drawn from points, every footprint keeps its own edge.
+
+The extension lays one picture over somebody else's map, so it gets the same
+marks drawn into a PNG (``render``).
+
+The windows are FIRMS's own, by UTC day and not by the hour: "24 h" is
+yesterday and today, "7 days" today and the seven before (matched pixel for
+pixel against the WMS, 2026-09-27). Counted by the hour, the day's main pass
+fell out of "24 h" before the next one was filed, and squares vanished at the
+zoom where the WMS hands over.
+
+Only a rolling window comes from the points. A dated range may reach back past
+the near-real-time files into the archive's other files, and a long one is many
+more points, so its marks are read off the WMS at every zoom. Nothing here
+touches the network: the route fetches (``api/satellite.py``), this module
+plans, reads and draws.
+"""
+
+from __future__ import annotations
+
+import csv
+import io
+import math
+from collections.abc import Iterable
+from dataclasses import dataclass
+from datetime import date, datetime, timedelta, timezone
+
+import numpy as np
+from PIL import Image, ImageDraw
+
+from . import firms, mvt
+
+AREA_BASE = "https://firms.modaps.eosdis.nasa.gov/api/area/csv"
+#: From this zoom in, a tile is drawn here. Out from it a screen covers enough
+#: ground that a burning season is hundreds of thousands of points.
+MIN_ZOOM = 8
+#: Metres of Web Mercator per pixel at ``MIN_ZOOM`` on a 512 px tile. The
+#: extension's picture has no zoom, only this, so both routes ask it.
+COARSEST_M_PER_PX = 2 * firms.WORLD / ((1 << MIN_ZOOM) * firms.TILE_SIZE)
+#: The ground one fetch covers, in degrees. The API costs the same for any box,
+#: so a cell is as big as a dense week can be without weighing megabytes.
+CELL_DEG = 4
+#: A picture over more cells than this is too far out for points.
+MAX_CELLS = 12
+#: The area API answers at most this many days a request (``[1..5]``).
+MAX_DAY_RANGE = 5
+#: The deepest vector tile. Past it the map draws the z13 tile bigger, which a
+#: vector tile allows without losing an edge: its marks are drawn, not stretched.
+MAX_ZOOM = firms.MAX_ZOOM
+#: From this zoom a tile carries each detection's footprint as well as its mark:
+#: the map crosses from one to the other where a mark reaches footprint size.
+FOOTPRINT_ZOOM = 11
+#: How far past its border a tile keeps a footprint, in tile units: enough for
+#: the edge drawn along the border to join the next tile's.
+BUFFER = 16
+#: The side a mark's size is rounded to, in Mercator metres. Marks of one size
+#: and one colour are one feature of the tile, however many there are.
+SIZE_STEP_M = 25
+#: A picture's pixels are thinned to one mark per square of this many: 7 px
+#: marks three pixels apart already overlap, so the rest would be drawn under
+#: them, and a burning continent stays thousands of marks, not tens of thousands.
+THIN_PX = 3
+#: How opaque a pixel of FIRMS's 1 px squares has to be to count: it spreads
+#: each detection over the pixels it straddles.
+PAINTED_ALPHA = 96
+#: The rolling windows, as the UTC days before today they reach back, the way
+#: FIRMS's layers count them.
+DAYS_BACK: dict[str, int] = {"24h": 1, "48h": 2, "72h": 3, "7d": 7}
+#: The window whose detections are drawn red over the rest.
+RECENT = "24h"
+#: The near-real-time files behind each sensor. The combined VIIRS layer is the
+#: three satellites (checked pixel for pixel against the WMS, 2026-09).
+SOURCES: dict[str, tuple[str, ...]] = {
+ "viirs": ("VIIRS_SNPP_NRT", "VIIRS_NOAA20_NRT", "VIIRS_NOAA21_NRT"),
+ "viirs_snpp": ("VIIRS_SNPP_NRT",),
+ "viirs_noaa20": ("VIIRS_NOAA20_NRT",),
+ "modis": ("MODIS_NRT",),
+}
+#: How far past a tile's edge a detection can still reach into it: half the
+#: widest MODIS pixel at the edge of its swath, 4.8 km.
+REACH_M = 2500
+
+
+@dataclass(frozen=True)
+class Points:
+ """Detections as columns: where, how big a pixel, and when (UTC seconds)."""
+
+ lon: np.ndarray
+ lat: np.ndarray
+ scan: np.ndarray
+ track: np.ndarray
+ seen: np.ndarray
+
+ def __len__(self) -> int:
+ return int(self.lon.size)
+
+ @staticmethod
+ def empty() -> Points:
+ f = np.zeros(0, dtype=np.float32)
+ return Points(f, f, f, f, np.zeros(0, dtype=np.int64))
+
+ @staticmethod
+ def join(parts: Iterable[Points]) -> Points:
+ parts = [p for p in parts if len(p)]
+ if not parts:
+ return Points.empty()
+ return Points(*(np.concatenate([getattr(p, name) for p in parts])
+ for name in ("lon", "lat", "scan", "track", "seen")))
+
+
+def drawn_here(window: str, bounds: tuple[float, float, float, float], width: int) -> bool:
+ """Is this picture drawn from points rather than asked of the WMS?"""
+ left, _, right, _ = bounds
+ fine = (right - left) / max(1, width) <= COARSEST_M_PER_PX * (1 + 1e-9)
+ return window in DAYS_BACK and fine and len(cells_for(bounds)) <= MAX_CELLS
+
+
+def _degrees(x: float, y: float) -> tuple[float, float]:
+ """``(lon, lat)`` of a point in Web Mercator metres."""
+ lon = x / firms.WORLD * 180
+ lat = math.degrees(2 * math.atan(math.exp(y * math.pi / firms.WORLD)) - math.pi / 2)
+ return lon, lat
+
+
+def cells_for(bounds: tuple[float, float, float, float]) -> list[tuple[int, int]]:
+ """The cells a picture draws from, with the reach of a pixel past its edge."""
+ left, bottom, right, top = bounds
+ west, south = _degrees(left, bottom)
+ east, north = _degrees(right, top)
+ pad = REACH_M / 111_320
+ reach = pad / max(0.05, math.cos(math.radians(max(abs(south), abs(north)))))
+ xs = range(math.floor(max(-180.0, west - reach) / CELL_DEG),
+ math.floor(min(179.999, east + reach) / CELL_DEG) + 1)
+ ys = range(math.floor(max(-90.0, south - pad) / CELL_DEG),
+ math.floor(min(89.999, north + pad) / CELL_DEG) + 1)
+ return [(cx, cy) for cy in ys for cx in xs]
+
+
+def cell_box(cell: tuple[int, int]) -> str:
+ """One cell as the area API's ``west,south,east,north``."""
+ cx, cy = cell
+ west, south = cx * CELL_DEG, cy * CELL_DEG
+ return f"{west},{south},{min(180, west + CELL_DEG)},{min(90, south + CELL_DEG)}"
+
+
+def days_for(window: str, now: datetime) -> list[date]:
+ """The UTC days a rolling window holds, oldest first."""
+ today = now.astimezone(timezone.utc).date()
+ return [today - timedelta(days=n) for n in range(DAYS_BACK[window], -1, -1)]
+
+
+def since(window: str, now: datetime) -> int:
+ """The first second of a window, UTC midnight of its first day."""
+ first = days_for(window, now)[0]
+ return int(datetime(first.year, first.month, first.day, tzinfo=timezone.utc).timestamp())
+
+
+def runs(days: Iterable[date]) -> list[tuple[date, int]]:
+ """Days as the fewest requests: consecutive stretches, five days at most."""
+ out: list[tuple[date, int]] = []
+ for day in sorted(set(days)):
+ if out and out[-1][0] + timedelta(days=out[-1][1]) == day and out[-1][1] < MAX_DAY_RANGE:
+ out[-1] = (out[-1][0], out[-1][1] + 1)
+ else:
+ out.append((day, 1))
+ return out
+
+
+def area_url(key: str, source: str, cell: tuple[int, int], start: date, count: int) -> str:
+ """One request: a source's detections over a cell, ``count`` days from ``start``."""
+ return f"{AREA_BASE}/{key}/{source}/{cell_box(cell)}/{count}/{start.isoformat()}"
+
+
+def fresh_seconds(day: date, now: datetime) -> int:
+ """How long a day's points stay true: a day still being filed, or history."""
+ return firms.LIVE_CACHE_SECONDS if day >= now.date() - timedelta(days=1) else firms.PAST_CACHE_SECONDS
+
+
+def is_table(text: str) -> bool:
+ """Is this the CSV, rather than a sentence saying why not?"""
+ return (text or "").lstrip().startswith("latitude,")
+
+
+def parse(text: str, days: Iterable[date]) -> dict[date, Points]:
+ """The rows of one answer, filed by day, with every day asked present.
+
+ A day that answered no rows is a day with no fires, and is kept as that so
+ it is not asked again. Rows are read by their header, since MODIS and VIIRS
+ name their brightness columns differently.
+ """
+ if not is_table(text):
+ raise ValueError("FIRMS did not answer with a table")
+ rows: dict[date, list[tuple[float, float, float, float, int]]] = {day: [] for day in days}
+ reader = csv.DictReader(io.StringIO(text))
+ for row in reader:
+ try:
+ day = date.fromisoformat(row["acq_date"])
+ clock = int(row["acq_time"])
+ seen = datetime(day.year, day.month, day.day, clock // 100, clock % 100, tzinfo=timezone.utc)
+ entry = (float(row["longitude"]), float(row["latitude"]), float(row["scan"]),
+ float(row["track"]), int(seen.timestamp()))
+ except (KeyError, TypeError, ValueError):
+ continue
+ rows.setdefault(day, []).append(entry)
+ out: dict[date, Points] = {}
+ for day, entries in rows.items():
+ if not entries:
+ out[day] = Points.empty()
+ continue
+ table = np.array(entries, dtype=np.float64)
+ out[day] = Points(table[:, 0].astype(np.float32), table[:, 1].astype(np.float32),
+ table[:, 2].astype(np.float32), table[:, 3].astype(np.float32),
+ table[:, 4].astype(np.int64))
+ return out
+
+
+def _mercator(lon: np.ndarray, lat: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
+ clamped = np.clip(lat.astype(np.float64), -firms.LAT_LIMIT, firms.LAT_LIMIT)
+ x = firms.WORLD * lon.astype(np.float64) / 180
+ y = firms.WORLD * np.log(np.tan(np.radians(45 + clamped / 2))) / math.pi
+ return x, y
+
+
+def _grow(mask: np.ndarray, rx: int, ry: int) -> np.ndarray:
+ """Every set pixel grown into a (2rx+1) x (2ry+1) rectangle around it."""
+ wide = mask.copy()
+ for d in range(1, rx + 1):
+ wide[:, d:] |= mask[:, :-d]
+ wide[:, :-d] |= mask[:, d:]
+ tall = wide.copy()
+ for d in range(1, ry + 1):
+ tall[d:, :] |= wide[:-d, :]
+ tall[:-d, :] |= wide[d:, :]
+ return tall
+
+
+def _png(image: Image.Image) -> bytes:
+ buffer = io.BytesIO()
+ image.save(buffer, "PNG")
+ return buffer.getvalue()
+
+
+def render(
+ points: Points,
+ bounds: tuple[float, float, float, float],
+ width: int,
+ height: int,
+ *,
+ sensor_id: str,
+ window: str,
+ now: datetime,
+) -> bytes:
+ """One picture of the detections in a window, as a PNG, the WMS's look kept.
+
+ FIRMS's "24 h" is red over the rest in amber, as the WMS layers are
+ stacked. A mark smaller than ``FOOTPRINT_PX`` is a solid square of the
+ zoom's size with a ring round each patch, exactly the WMS picture dressed.
+ From there each detection is its own footprint, scan by track as FIRMS
+ measured it, drawn oldest first with its own ring and edge, so a square
+ under another still shows where it ends.
+ """
+ left, bottom, right, top = bounds
+ across, down = (right - left) / width, (top - bottom) / height
+ keep = points.seen >= since(window, now)
+ x, y = _mercator(points.lon[keep], points.lat[keep])
+ px, py = (x - left) / across, (top - y) / down
+ seen = points.seen[keep]
+ recent = seen >= since(RECENT, now)
+ mark = firms.mark_px(sensor_id, bounds, width)
+ if mark < firms.FOOTPRINT_PX:
+ return _png(_squares(px, py, recent, mark, width, height))
+ stretch = 1 / np.maximum(0.01, np.cos(np.radians(points.lat[keep].astype(np.float64))))
+ half_w = np.maximum(firms.MARK_MIN_PX, points.scan[keep] * 1000 * stretch / across) / 2
+ half_h = np.maximum(firms.MARK_MIN_PX, points.track[keep] * 1000 * stretch / down) / 2
+ image = Image.new("RGBA", (width, height), (0, 0, 0, 0))
+ ring, edge = firms.RING_PX, firms.EDGE_PX
+ fill = round(255 * firms.FOOTPRINT_FILL)
+ for i in np.argsort(seen, kind="stable"):
+ x0 = math.floor(px[i] - half_w[i]) - ring
+ y0 = math.floor(py[i] - half_h[i]) - ring
+ x1 = math.ceil(px[i] + half_w[i]) + ring
+ y1 = math.ceil(py[i] + half_h[i]) + ring
+ if x1 < 0 or y1 < 0 or x0 >= width or y0 >= height:
+ continue
+ rgb = firms.RECENT_RGB if recent[i] else firms.EARLIER_RGB
+ # Each square on its own and laid over the rest: drawn straight onto
+ # the picture, its see-through inside would replace the edges under it.
+ square = Image.new("RGBA", (x1 - x0 + 1, y1 - y0 + 1), (0, 0, 0, 0))
+ draw = ImageDraw.Draw(square)
+ draw.rectangle((0, 0, x1 - x0, y1 - y0), outline=firms.RING_RGBA, width=ring)
+ draw.rectangle((ring, ring, x1 - x0 - ring, y1 - y0 - ring), fill=(*rgb, fill), outline=(*rgb, 255), width=edge)
+ image.alpha_composite(square, dest=(max(0, x0), max(0, y0)), source=(max(0, -x0), max(0, -y0)))
+ return _png(image)
+
+
+def _squares(px: np.ndarray, py: np.ndarray, recent: np.ndarray, mark: int, width: int, height: int) -> Image.Image:
+ """Solid squares of one size, ringed as ``firms.dressed`` rings the WMS's.
+
+ Drawn on a margin wider than a square and its ring, then cut back, so a
+ square across the tile's edge gets its ring on both tiles.
+ """
+ pad = mark + 2 * firms.RING_PX + 2
+ wide, high = width + 2 * pad, height + 2 * pad
+ canvas = np.zeros((high, wide, 4), dtype=np.uint8)
+ half = mark // 2
+ for chosen, rgb in ((~recent, firms.EARLIER_RGB), (recent, firms.RECENT_RGB)):
+ cx = np.floor(px[chosen]).astype(np.int64) + pad
+ cy = np.floor(py[chosen]).astype(np.int64) + pad
+ inside = (cx >= 0) & (cx < wide) & (cy >= 0) & (cy < high)
+ if not inside.any():
+ continue
+ centres = np.zeros((high, wide), dtype=bool)
+ centres[cy[inside], cx[inside]] = True
+ canvas[_grow(centres, half, half)] = (*rgb, 255)
+ image = Image.fromarray(canvas)
+ if canvas[..., 3].any():
+ image = firms.dressed(image, mark)
+ return image.crop((pad, pad, pad + width, pad + height))
+
+
+def tile(points: Points, z: int, x: int, y: int, *, window: str, now: datetime) -> bytes:
+ """One vector tile of the detections in a window, for the map to draw.
+
+ Layer ``marks`` is a point per detection, grouped by colour (``recent``) and
+ by the side of its footprint in Mercator metres (``side``), which the map
+ turns into a size on screen at every zoom; ``foot`` says the footprint
+ comes too, so close in the mark can give way to it. A point belongs to the
+ one tile its centre is in, so no mark is drawn twice. From
+ ``FOOTPRINT_ZOOM``, layer ``footprints`` adds the rectangles, scan by track,
+ in every tile they reach into: the map cuts a fill and an edge at the
+ tile's border.
+ """
+ left, bottom, right, top = firms.tile_bounds(z, x, y)
+ keep = points.seen >= since(window, now)
+ lat = points.lat[keep].astype(np.float64)
+ mx, my = _mercator(points.lon[keep], lat)
+ scale = mvt.EXTENT / (right - left)
+ tx, ty = (mx - left) * scale, (top - my) * scale
+ recent = points.seen[keep] >= since(RECENT, now)
+ stretch = 1 / np.maximum(0.01, np.cos(np.radians(lat)))
+ scan = points.scan[keep] * 1000 * stretch
+ track = points.track[keep] * 1000 * stretch
+ side = np.maximum(1, np.round(np.sqrt(scan * track) / SIZE_STEP_M)).astype(np.int64) * SIZE_STEP_M
+ inside = (tx >= 0) & (tx < mvt.EXTENT) & (ty >= 0) & (ty < mvt.EXTENT)
+ marks = mvt.Layer("marks")
+ for flag in (False, True):
+ chosen = inside & (recent == flag)
+ for size in np.unique(side[chosen]):
+ group = chosen & (side == size)
+ marks.points(np.round(tx[group]), np.round(ty[group]),
+ {"recent": int(flag), "side": int(size), "foot": 1})
+ layers = [marks]
+ if z >= FOOTPRINT_ZOOM:
+ half_w, half_h = scan * scale / 2, track * scale / 2
+ x0, x1, y0, y1 = tx - half_w, tx + half_w, ty - half_h, ty + half_h
+ near = (x1 > -BUFFER) & (x0 < mvt.EXTENT + BUFFER) & (y1 > -BUFFER) & (y0 < mvt.EXTENT + BUFFER)
+ footprints = mvt.Layer("footprints")
+ for flag in (False, True):
+ group = near & (recent == flag)
+ left_px, top_px, right_px, bottom_px = (
+ np.clip(np.round(v[group]), -mvt.EXTENT, 2 * mvt.EXTENT) for v in (x0, y0, x1, y1))
+ footprints.rectangles(left_px, top_px, right_px, bottom_px, {"recent": int(flag)})
+ layers.append(footprints)
+ return mvt.encode(layers)
+
+
+def picture_tile(content: bytes, z: int, x: int, y: int, *, sensor_id: str) -> bytes:
+ """The marks of one FIRMS picture of 1 px squares, as a vector tile.
+
+ Far out and for a dated range the detections come as FIRMS draws them, one
+ picture a tile, and the map still draws the marks itself, so they keep
+ their size through a zoom here too. FIRMS spreads a detection over the
+ pixels it straddles, so each square of ``THIN_PX`` pixels becomes one mark
+ at the opacity-weighted middle of what is painted in it, red if any of it
+ is. Its size is the sensor's footprint, since a picture does not say
+ FIRMS's measured one. From ``FOOTPRINT_ZOOM`` a square of that size comes
+ with each mark (``foot``), so a dated range hands over to see-through
+ footprints like a rolling window. A picture knows only its own tile, so a
+ footprint across its border is cut there.
+ """
+ with Image.open(io.BytesIO(content)) as source:
+ rgba = np.asarray(source.convert("RGBA"))
+ height, width = rgba.shape[:2]
+ alpha = rgba[..., 3].astype(np.float64)
+ ys, xs = np.nonzero(alpha >= PAINTED_ALPHA)
+ if not ys.size:
+ return b""
+ weight = alpha[ys, xs]
+ red = rgba[ys, xs, 1] < (firms.RECENT_RGB[1] + firms.EARLIER_RGB[1]) / 2
+ across = -(-width // THIN_PX)
+ _, block = np.unique((ys // THIN_PX) * across + xs // THIN_PX, return_inverse=True)
+ total = np.bincount(block, weights=weight)
+ mark_x = np.bincount(block, weights=weight * (xs + 0.5)) / total * (mvt.EXTENT / width)
+ mark_y = np.bincount(block, weights=weight * (ys + 0.5)) / total * (mvt.EXTENT / height)
+ recent = np.bincount(block, weights=red.astype(np.float64)) > 0
+ left, bottom, right, top = firms.tile_bounds(z, x, y)
+ _, lat = _degrees((left + right) / 2, (bottom + top) / 2)
+ side = firms.sensor(sensor_id).footprint_m / max(0.01, math.cos(math.radians(lat)))
+ side = max(1, round(side / SIZE_STEP_M)) * SIZE_STEP_M
+ foot = z >= FOOTPRINT_ZOOM
+ mark_x = np.clip(np.floor(mark_x), 0, mvt.EXTENT - 1)
+ mark_y = np.clip(np.floor(mark_y), 0, mvt.EXTENT - 1)
+ marks = mvt.Layer("marks")
+ for flag in (False, True):
+ chosen = recent == flag
+ marks.points(mark_x[chosen], mark_y[chosen], {"recent": int(flag), "side": int(side), "foot": int(foot)})
+ layers = [marks]
+ if foot:
+ half = side * mvt.EXTENT / (right - left) / 2
+ footprints = mvt.Layer("footprints")
+ for flag in (False, True):
+ chosen = recent == flag
+ left_px, top_px, right_px, bottom_px = (
+ np.clip(np.round(v[chosen]), -mvt.EXTENT, 2 * mvt.EXTENT)
+ for v in (mark_x - half, mark_y - half, mark_x + half, mark_y + half))
+ footprints.rectangles(left_px, top_px, right_px, bottom_px, {"recent": int(flag)})
+ layers.append(footprints)
+ return mvt.encode(layers)
diff --git a/src/azimut/engine/maplayers.py b/src/azimut/engine/maplayers.py
index b2e4f9c..dae3b1f 100644
--- a/src/azimut/engine/maplayers.py
+++ b/src/azimut/engine/maplayers.py
@@ -1112,10 +1112,16 @@ def _kml_rings(polygon: Element) -> Iterator[list[list[float]]]:
yield points
+#: Space around a tuple's commas. The spec writes `lon,lat` with none, but NASA
+#: FIRMS writes `7.31866000, 52.46726000`, and splitting that on whitespace
+#: leaves two halves that are neither a point.
+_KML_COMMA = re.compile(r"\s*,\s*")
+
+
def _kml_points(text: str) -> list[list[float]]:
"""`lon,lat[,alt]` tuples, whitespace-separated. Altitude is dropped."""
points: list[list[float]] = []
- for chunk in str(text or "").split():
+ for chunk in _KML_COMMA.sub(",", str(text or "")).split():
parts = chunk.split(",")
if len(parts) < 2:
continue
@@ -1552,7 +1558,7 @@ SPEC_VERSION = 1
#: the day it was dropped in, for as long as the case lives. Bumped whenever a
#: change here would give the same bytes a different reading; the next request
#: for that layer reparses the snapshot already on disk.
-PARSE_VERSION = 3
+PARSE_VERSION = 4
#: Where that stamp is written. A GeoJSON object may carry members it does not
#: define, and this one is written first so the check reads the head of the file
diff --git a/src/azimut/engine/mvt.py b/src/azimut/engine/mvt.py
new file mode 100644
index 0000000..a785f3b
--- /dev/null
+++ b/src/azimut/engine/mvt.py
@@ -0,0 +1,161 @@
+"""Mapbox Vector Tiles, written for the two shapes the app serves.
+
+The map draws a vector tile itself, every frame, so a mark keeps its size on
+screen through a zoom where a picture's pixels would be stretched until the
+next picture lands. The format is protobuf (the Mapbox Vector Tile
+specification 2.1), and the app only ever writes points and axis-aligned
+rectangles, so a hundred lines of encoding stand in for a protobuf library.
+
+Coordinates are the tile's own, 0 to ``EXTENT`` from the top-left corner. A
+feature here is many points or many rectangles sharing their properties,
+written as one MultiPoint or one MultiPolygon: a burning week is tens of
+thousands of detections, and one feature each would make the tile mostly
+headers. The geometry is encoded with numpy, a whole feature at a time.
+"""
+
+from __future__ import annotations
+
+import struct
+from dataclasses import dataclass, field
+
+import numpy as np
+
+EXTENT = 4096
+
+_MOVE_TO, _LINE_TO, _CLOSE_PATH = 1, 2, 7
+_POINT, _POLYGON = 1, 3
+
+
+def _varint(value: int) -> bytes:
+ out = bytearray()
+ while True:
+ byte = value & 0x7F
+ value >>= 7
+ if value:
+ out.append(byte | 0x80)
+ else:
+ out.append(byte)
+ return bytes(out)
+
+
+def _varints(values: np.ndarray) -> bytes:
+ """Many unsigned ints as packed varints, all at once."""
+ values = values.astype(np.uint64, copy=False)
+ if not values.size:
+ return b""
+ width = np.ones(values.size, dtype=np.int64)
+ for shift in range(7, 64, 7):
+ width += values >= (np.uint64(1) << np.uint64(shift))
+ out = np.zeros(int(width.sum()), dtype=np.uint8)
+ start = np.concatenate([[0], np.cumsum(width)[:-1]])
+ rest = values.copy()
+ for k in range(int(width.max())):
+ live = width > k
+ more = width > k + 1
+ byte = (rest[live] & np.uint64(0x7F)).astype(np.uint8)
+ byte[more[live]] |= 0x80
+ out[start[live] + k] = byte
+ rest[live] >>= np.uint64(7)
+ return out.tobytes()
+
+
+def _zigzag(values: np.ndarray) -> np.ndarray:
+ signed = values.astype(np.int64, copy=False)
+ return ((signed << 1) ^ (signed >> 63)).astype(np.uint64)
+
+
+def _field(number: int, payload: bytes) -> bytes:
+ """A length-delimited field: an embedded message, a string or packed ints."""
+ return _varint(number << 3 | 2) + _varint(len(payload)) + payload
+
+
+def _command(command: int, count: int) -> int:
+ return command | count << 3
+
+
+def points_geometry(xs: np.ndarray, ys: np.ndarray) -> bytes:
+ """A MultiPoint: one MoveTo carrying every point, each a step from the last."""
+ xs, ys = np.asarray(xs, dtype=np.int64), np.asarray(ys, dtype=np.int64)
+ steps = np.empty(2 * xs.size, dtype=np.int64)
+ steps[0::2] = np.diff(xs, prepend=0)
+ steps[1::2] = np.diff(ys, prepend=0)
+ return _varint(_command(_MOVE_TO, xs.size)) + _varints(_zigzag(steps))
+
+
+def rectangles_geometry(x0: np.ndarray, y0: np.ndarray, x1: np.ndarray, y1: np.ndarray) -> bytes:
+ """A MultiPolygon of rectangles, each ring clockwise on screen as an outer ring must be.
+
+ A ring is MoveTo its top-left corner, LineTo the other three, ClosePath.
+ The cursor carries on from the last ring's last corner.
+ """
+ x0, y0 = np.asarray(x0, dtype=np.int64), np.asarray(y0, dtype=np.int64)
+ x1, y1 = np.asarray(x1, dtype=np.int64), np.asarray(y1, dtype=np.int64)
+ n = x0.size
+ # corners: top-left, top-right, bottom-right, bottom-left
+ cx = np.stack([x0, x1, x1, x0], axis=1)
+ cy = np.stack([y0, y0, y1, y1], axis=1)
+ flat_x, flat_y = cx.reshape(-1), cy.reshape(-1)
+ dx = np.diff(flat_x, prepend=0).reshape(n, 4)
+ dy = np.diff(flat_y, prepend=0).reshape(n, 4)
+ ring = np.empty((n, 11), dtype=np.uint64)
+ ring[:, 0] = _command(_MOVE_TO, 1)
+ ring[:, 1], ring[:, 2] = _zigzag(dx[:, 0]), _zigzag(dy[:, 0])
+ ring[:, 3] = _command(_LINE_TO, 3)
+ for k in range(1, 4):
+ ring[:, 2 * k + 2], ring[:, 2 * k + 3] = _zigzag(dx[:, k]), _zigzag(dy[:, k])
+ ring[:, 10] = _command(_CLOSE_PATH, 1)
+ return _varints(ring.reshape(-1))
+
+
+Value = int | float | str
+
+
+@dataclass
+class Layer:
+ """One named layer: its features, and the keys and values they share."""
+
+ name: str
+ features: list[tuple[int, bytes, dict[str, Value]]] = field(default_factory=list)
+
+ def points(self, xs: np.ndarray, ys: np.ndarray, properties: dict[str, Value]) -> None:
+ if len(xs):
+ self.features.append((_POINT, points_geometry(xs, ys), properties))
+
+ def rectangles(self, x0: np.ndarray, y0: np.ndarray, x1: np.ndarray, y1: np.ndarray,
+ properties: dict[str, Value]) -> None:
+ if len(x0):
+ self.features.append((_POLYGON, rectangles_geometry(x0, y0, x1, y1), properties))
+
+ def encode(self) -> bytes:
+ keys: dict[str, int] = {}
+ values: dict[tuple[type, Value], int] = {}
+ body = [_varint(15 << 3) + _varint(2), _field(1, self.name.encode())]
+ for kind, geometry, properties in self.features:
+ tags = []
+ for key, value in properties.items():
+ tags.append(keys.setdefault(key, len(keys)))
+ tags.append(values.setdefault((type(value), value), len(values)))
+ feature = (_field(2, b"".join(_varint(t) for t in tags))
+ + _varint(3 << 3) + _varint(kind) + _field(4, geometry))
+ body.append(_field(2, feature))
+ body += [_field(3, key.encode()) for key in keys]
+ body += [_field(4, _value(value)) for _, value in values]
+ body.append(_varint(5 << 3) + _varint(EXTENT))
+ return b"".join(body)
+
+
+def _value(value: Value) -> bytes:
+ if isinstance(value, bool):
+ return _varint(7 << 3) + _varint(int(value))
+ if isinstance(value, int):
+ if value >= 0:
+ return _varint(5 << 3) + _varint(value)
+ return _varint(6 << 3) + _varint(int(_zigzag(np.array([value]))[0]))
+ if isinstance(value, float):
+ return _varint(3 << 3 | 1) + struct.pack("<d", value)
+ return _field(1, str(value).encode())
+
+
+def encode(layers: list[Layer]) -> bytes:
+ """A tile of these layers. A layer with nothing in it is left out."""
+ return b"".join(_field(3, layer.encode()) for layer in layers if layer.features)
diff --git a/src/azimut/engine/sentinel.py b/src/azimut/engine/sentinel.py
index 983dbf0..b877f9a 100644
--- a/src/azimut/engine/sentinel.py
+++ b/src/azimut/engine/sentinel.py
@@ -228,6 +228,11 @@ _BBOX_PAD = 0.005
# is "up to 100 granules" rather than "100 dates" — the caller sees how many
# dates that collapsed to.
_MAX_FEATURES = 100
+# How many pages of that one lookup reads before it says it was cut. Granules
+# come newest first (checked 2026-09 over Lyman), so a cut drops the oldest, and
+# five pages hold a year over a point or a season over an area several tiles
+# wide. Each page is one request on the meter.
+_MAX_PAGES = 5
# How many points stand in for a drawn area when measuring how much of it a
# day's granules really cover. Sampling keeps this to the geometry already
@@ -895,15 +900,18 @@ def _passes(
*,
collection: str = "sentinel2",
get: Callable[..., Any] | None = None,
-) -> tuple[dict[str, dict[str, Any]], int]:
- """One WFS query, collapsed to per-pass entries and the samples each covers.
+ on_request: Callable[[], object] | None = None,
+) -> tuple[dict[str, dict[str, Any]], bool]:
+ """One WFS lookup, collapsed to per-pass entries and the samples each covers,
+ and whether the catalogue still had more when it stopped.
A Sentinel-2 entry is a day. A Sentinel-1 entry is one pass, so a morning
and an evening look on the same day stay two, and each carries its time.
- A WFS query is billed as one request (~0.01 PU, versus a tile's 1 PU), so
- the caller counts it on the meter — cheap, but not free, and the meter never
- lies by omission.
+ The lookup reads up to ``_MAX_PAGES`` pages of ``_MAX_FEATURES``. Each page
+ is billed as one request (~0.01 PU, versus a tile's 1 PU), so ``on_request``
+ is called once a page, sent or failed: cheap, but not free, and the meter
+ never lies by omission.
Raises httpx.HTTPError / ValueError upward: a date list that failed must not
read as "no imagery here".
@@ -930,16 +938,29 @@ def _passes(
# the instance's filter would hide passes we never said we hid.
"MAXCC": str(DEFAULT_MAXCC),
}
- response = fetch(
- f"{BASE}/wfs/{instance}", params=params,
- headers={"User-Agent": USER_AGENT}, timeout=15,
- )
- if response.status_code == 400 and radar and "not found" in response.text.lower():
- raise ValueError(
- "this Copernicus instance has no Sentinel-1 layer; add one in its configuration"
- )
- response.raise_for_status()
- features = (response.json() or {}).get("features") or []
+ features: list[dict[str, Any]] = []
+ truncated = True
+ for page in range(_MAX_PAGES):
+ if page:
+ params["FEATURE_OFFSET"] = str(page * _MAX_FEATURES)
+ try:
+ response = fetch(
+ f"{BASE}/wfs/{instance}", params=params,
+ headers={"User-Agent": USER_AGENT}, timeout=15,
+ )
+ finally:
+ if on_request:
+ on_request()
+ if response.status_code == 400 and radar and "not found" in response.text.lower():
+ raise ValueError(
+ "this Copernicus instance has no Sentinel-1 layer; add one in its configuration"
+ )
+ response.raise_for_status()
+ chunk = (response.json() or {}).get("features") or []
+ features.extend(chunk)
+ if len(chunk) < _MAX_FEATURES:
+ truncated = False
+ break
by_pass: dict[str, dict[str, Any]] = {}
for feature in features:
@@ -965,7 +986,7 @@ def _passes(
# the granule that actually covers the area may be the clearer of two
if cloud is not None and (entry["cloud"] is None or cloud < entry["cloud"]):
entry["cloud"] = cloud
- return by_pass, len(features)
+ return by_pass, truncated
def _listed(entry: dict[str, Any], lon: float, collection: str) -> dict[str, Any]:
@@ -984,6 +1005,7 @@ def dates(
*,
collection: str = "sentinel2",
get: Callable[..., Any] | None = None,
+ on_request: Callable[[], object] | None = None,
) -> list[dict[str, Any]]:
"""Acquisition dates over a point, newest first.
@@ -998,7 +1020,8 @@ def dates(
share attached.
"""
box = (lon - _BBOX_PAD, lat - _BBOX_PAD, lon + _BBOX_PAD, lat + _BBOX_PAD)
- found, _ = _passes(instance, box, [(lon, lat)], start, end, collection=collection, get=get)
+ found, _ = _passes(instance, box, [(lon, lat)], start, end, collection=collection, get=get,
+ on_request=on_request)
return sorted(
(_listed(e, lon, collection) for e in found.values()),
key=lambda entry: (entry["date"], entry.get("time", "")), reverse=True,
@@ -1056,6 +1079,7 @@ def acquisitions(
*,
collection: str = "sentinel2",
get: Callable[..., Any] | None = None,
+ on_request: Callable[[], object] | None = None,
) -> dict[str, Any]:
"""Acquisitions over drawn areas, newest first.
@@ -1065,8 +1089,9 @@ def acquisitions(
290 km-wide swaths, so an area wider than one of them has *no* single day
that covers it, and pinned to one date half the sweep reads nodata.
- ``truncated`` says the WFS hit its feature ceiling, so older passes in the
- window are missing and the window wants narrowing.
+ ``truncated`` says the catalogue still had more after ``_MAX_PAGES`` pages,
+ so the oldest passes in the window are missing and the window wants
+ narrowing.
"""
if not rings:
raise ValueError("no area to look up")
@@ -1078,7 +1103,8 @@ def acquisitions(
min(180.0, max(b[2] for b in boxes) + _BBOX_PAD),
min(90.0, max(b[3] for b in boxes) + _BBOX_PAD),
)
- found, features = _passes(instance, box, samples, start, end, collection=collection, get=get)
+ found, truncated = _passes(instance, box, samples, start, end, collection=collection, get=get,
+ on_request=on_request)
middle = (box[0] + box[2]) / 2
listed = sorted(
({**_listed(entry, middle, collection),
@@ -1086,7 +1112,7 @@ def acquisitions(
for entry in found.values()),
key=lambda entry: (entry["date"], entry.get("time", "")), reverse=True,
)
- return {"dates": listed, "truncated": features >= _MAX_FEATURES}
+ return {"dates": listed, "truncated": truncated}
def coverage(
diff --git a/tests/analyzerfixture.py b/tests/analyzerfixture.py
index cfbda38..9fc2857 100644
--- a/tests/analyzerfixture.py
+++ b/tests/analyzerfixture.py
@@ -56,8 +56,7 @@ def _png(pixels):
def put_picture(source, tile=SENTINEL_TILE, shade=40):
parsed = Source.model_validate(source)
z, x, y = tile
- tilecache.put(sentinel.variant_id("sentinel2", parsed.layer, parsed.date, parsed.date,
- parsed.maxcc),
+ tilecache.put(analyzers.picture_cache_id(parsed),
z, x, y, _png(np.full((512, 512, 3), shade, np.uint8)), "image/png")
diff --git a/tests/mvtread.py b/tests/mvtread.py
new file mode 100644
index 0000000..4c3475c
--- /dev/null
+++ b/tests/mvtread.py
@@ -0,0 +1,139 @@
+"""A Mapbox Vector Tile reader, enough to check what ``engine/mvt.py`` wrote.
+
+Written from the specification rather than borrowed from the encoder, so a
+test that reads a tile back is two implementations agreeing, not one agreeing
+with itself.
+"""
+
+from __future__ import annotations
+
+import struct
+from collections.abc import Iterator
+from typing import Any
+
+
+def _varint(buf: bytes, i: int) -> tuple[int, int]:
+ shift = value = 0
+ while True:
+ byte = buf[i]
+ i += 1
+ value |= (byte & 0x7F) << shift
+ if not byte & 0x80:
+ return value, i
+ shift += 7
+
+
+def _fields(buf: bytes) -> Iterator[tuple[int, Any]]:
+ """``(field number, value)`` of every field of one message."""
+ i = 0
+ while i < len(buf):
+ key, i = _varint(buf, i)
+ number, wire = key >> 3, key & 7
+ if wire == 0:
+ value, i = _varint(buf, i)
+ elif wire == 1:
+ value = buf[i:i + 8]
+ i += 8
+ elif wire == 2:
+ size, i = _varint(buf, i)
+ value = buf[i:i + size]
+ i += size
+ elif wire == 5:
+ value = buf[i:i + 4]
+ i += 4
+ else:
+ raise ValueError(f"wire type {wire}")
+ yield number, value
+
+
+def _packed(buf: bytes) -> list[int]:
+ out, i = [], 0
+ while i < len(buf):
+ value, i = _varint(buf, i)
+ out.append(value)
+ return out
+
+
+def _unzig(n: int) -> int:
+ return (n >> 1) ^ -(n & 1)
+
+
+def _value(buf: bytes) -> Any:
+ for number, value in _fields(buf):
+ if number == 1:
+ return value.decode()
+ if number == 2:
+ return struct.unpack("<f", value)[0]
+ if number == 3:
+ return struct.unpack("<d", value)[0]
+ if number in (4, 5):
+ return value
+ if number == 6:
+ return _unzig(value)
+ if number == 7:
+ return bool(value)
+ return None
+
+
+def geometry(commands: list[int]) -> list[list[tuple[int, int]]]:
+ """The parts of one geometry: each MoveTo starts one, LineTo extends it."""
+ x = y = i = 0
+ parts: list[list[tuple[int, int]]] = []
+ while i < len(commands):
+ command, count = commands[i] & 7, commands[i] >> 3
+ i += 1
+ if command == 7: # ClosePath: the ring ends where it began
+ continue
+ for _ in range(count):
+ x += _unzig(commands[i])
+ y += _unzig(commands[i + 1])
+ i += 2
+ if command == 1:
+ parts.append([(x, y)])
+ else:
+ parts[-1].append((x, y))
+ return parts
+
+
+def read(tile: bytes) -> dict[str, dict[str, Any]]:
+ """Every layer of a tile by name, its features decoded."""
+ layers: dict[str, dict[str, Any]] = {}
+ for number, body in _fields(tile):
+ assert number == 3, "a tile holds layers and nothing else"
+ layer: dict[str, Any] = {"name": None, "keys": [], "values": [], "raw": [], "extent": None, "version": None}
+ for field, value in _fields(body):
+ if field == 1:
+ layer["name"] = value.decode()
+ elif field == 2:
+ layer["raw"].append(value)
+ elif field == 3:
+ layer["keys"].append(value.decode())
+ elif field == 4:
+ layer["values"].append(_value(value))
+ elif field == 5:
+ layer["extent"] = value
+ elif field == 15:
+ layer["version"] = value
+ features = []
+ for raw in layer.pop("raw"):
+ tags: list[int] = []
+ kind = None
+ commands: list[int] = []
+ for field, value in _fields(raw):
+ if field == 2:
+ tags = _packed(value)
+ elif field == 3:
+ kind = value
+ elif field == 4:
+ commands = _packed(value)
+ properties = {layer["keys"][tags[k]]: layer["values"][tags[k + 1]] for k in range(0, len(tags), 2)}
+ features.append({"type": kind, "properties": properties, "parts": geometry(commands)})
+ layer["features"] = features
+ layers[layer["name"]] = layer
+ return layers
+
+
+def ring_area(ring: list[tuple[int, int]]) -> float:
+ """Twice the signed area by the surveyor's formula, positive for an outer ring."""
+ closed = ring + ring[:1]
+ return float(sum(x0 * y1 - x1 * y0 for (x0, y0), (x1, y1) in zip(closed, closed[1:], strict=False)))
diff --git a/tests/test_analyzers.py b/tests/test_analyzers.py
index 956927e..873818f 100644
--- a/tests/test_analyzers.py
+++ b/tests/test_analyzers.py
@@ -9,7 +9,7 @@ from PIL import Image
from azimut import config, layout
from azimut.api import analyzers as analyzers_api
-from azimut.engine import analyzers, tilecache, workqueue
+from azimut.engine import analyzers, sentinel, tilecache, workqueue
from azimut.engine.analysis_models import (
BUILTINS,
METHODS,
@@ -17,6 +17,7 @@ from azimut.engine.analysis_models import (
Parameters,
Recipe,
RunInput,
+ Source,
Zone,
)
from azimut.workspace import Case
@@ -78,6 +79,64 @@ def run(client, case, body):
# -- runs, review and evidence ------------------------------------------------------
+def test_a_day_is_read_whole_whatever_its_tile_s_cloud(client, scenario, monkeypatch):
+ """Sentinel Hub drops a whole tile above MAXCC, so a day picked over the
+ ceiling used to come back blank and the sweep read nothing. The ceiling
+ only chooses the newest pass now; the sky byte keeps the clouds out."""
+ from analyzerfixture import _png
+
+ case, body = scenario
+ body["offline"] = False
+ assert body["b"]["maxcc"] < sentinel.DEFAULT_MAXCC
+ client.put("/api/settings/keys", json={"sentinelhub": "INSTANCE"})
+ monkeypatch.setattr(analyzers.tilecache, "get", lambda *args, **kwargs: None)
+ read, pictures = [], []
+
+ def band_frame(instance, box, width, height, day, product, maxcc, **kwargs):
+ read.append(maxcc)
+ return _png(surface())
+
+ class Stream:
+ status_code = 200
+
+ def __init__(self, url):
+ pictures.append(url)
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *exc):
+ return False
+
+ def raise_for_status(self):
+ return None
+
+ def iter_bytes(self):
+ yield _png(np.full((512, 512, 3), 40, np.uint8))
+
+ monkeypatch.setattr(analyzers.sentinel, "band_frame", band_frame)
+ monkeypatch.setattr(analyzers.httpx, "stream", lambda method, url, **kwargs: Stream(url))
+ saved = run(client, case, body)
+ assert saved["status"] == "ready", saved
+ assert read and set(read) == {sentinel.DEFAULT_MAXCC}
+ assert pictures and all(f"MAXCC={sentinel.DEFAULT_MAXCC}" in url for url in pictures)
+
+
+def test_a_frame_an_older_run_kept_under_a_ceiling_is_not_taken_for_a_whole_day():
+ ceiling = Source(date="2026-05-04", maxcc=30)
+ # an older run finds its own frames under the name it kept them by…
+ assert analyzers._key(ceiling, 13, 1, 2, None, 4) == analyzers._key(ceiling, 13, 1, 2, None, 3)
+ # …and a new run never reuses one, which may be the blank a ceiling made
+ assert analyzers._key(ceiling, 13, 1, 2, None, 4) != analyzers._key(ceiling, 13, 1, 2, None)
+ assert analyzers._key(ceiling, 13, 1, 2, "surface", 4) != analyzers._key(ceiling, 13, 1, 2, "surface")
+ # a source that never had a ceiling read the whole day already
+ whole = Source(date="2026-05-04", maxcc=100)
+ assert analyzers._key(whole, 13, 1, 2, None, 4) == analyzers._key(whole, 13, 1, 2, None)
+ # and the cache a sweep shares with the map is the day read whole
+ assert analyzers.picture_cache_id(ceiling) == analyzers.picture_cache_id(whole)
+
+
+
def test_local_run_keeps_frames_and_review_without_network(client, scenario):
case, body = scenario
saved = run(client, case, body)
@@ -1170,7 +1229,7 @@ def test_an_automatic_date_rule_takes_the_newest_pass_that_covers_the_whole_area
client.put("/api/settings/keys", json={"sentinelhub": "inst-uuid"})
asked = {}
- def acquisitions(instance, rings, start, end, collection="sentinel2"):
+ def acquisitions(instance, rings, start, end, collection="sentinel2", **kwargs):
asked.update(instance=instance, rings=rings, start=start, end=end)
return {"dates": [
{"date": "2026-05-20", "cloud": 5.0, "granules": 1, "coverage": 0.61},
diff --git a/tests/test_compare_api.py b/tests/test_compare_api.py
index 359b304..1af12eb 100644
--- a/tests/test_compare_api.py
+++ b/tests/test_compare_api.py
@@ -785,7 +785,7 @@ def test_a_session_saved_with_the_retired_labels_layer_saves_without_it(client):
cid = _case(client, "Retired labels")
spec = _spec()
spec["a"]["overlays"] = ["labels", "roads", "labels"]
- everything = ["labels", "boundaries", "roads", "railway", "power", "seamarks",
+ everything = ["labels", "boundaries", "placenames", "roads", "railway", "power", "seamarks",
"gpstraces", "firms", "nightlights", "saved"]
spec["b"]["overlays"] = everything
res = _save(client, cid, "Before the key", spec=spec)
diff --git a/tests/test_detect_rework.py b/tests/test_detect_rework.py
index b8333a7..89fb709 100644
--- a/tests/test_detect_rework.py
+++ b/tests/test_detect_rework.py
@@ -94,8 +94,9 @@ def test_each_track_resolves_its_own_pass_and_only_the_missing_area_fails(client
client.put("/api/settings/keys", json={"sentinelhub": "test-instance"})
calls = []
first_lon = body["zones"][0]["points"][0][0]
- def lookup(instance, rings, start, end, collection="sentinel2"):
+ def lookup(instance, rings, start, end, collection="sentinel2", on_request=None):
calls.append(rings)
+ on_request() # one catalogue page, on the meter
assert len(rings) == 1
first = rings[0][0][0] == first_lon
return {"dates": [] if partial and not first else [{"date": "2026-05-11" if first else "2026-05-13",
diff --git a/tests/test_firms.py b/tests/test_firms.py
index 74fc20b..c088605 100644
--- a/tests/test_firms.py
+++ b/tests/test_firms.py
@@ -8,13 +8,17 @@ anything, and the route tests stub the one call that would.
from __future__ import annotations
import hashlib
+import io
+from datetime import date
from urllib.parse import parse_qs, urlparse
import httpx
import pytest
+from PIL import Image
from azimut import config
from azimut.engine import firms
+from mvtread import read
# -- the layer a question names ------------------------------------------------
@@ -70,17 +74,66 @@ def _query(url: str) -> dict[str, list[str]]:
def test_the_key_goes_in_the_path_where_firms_wants_it():
url = firms.tile_url("KEY123", z=3, x=4, y=2)
- assert url.startswith(f"{firms.WMS_BASE}/KEY123/?")
+ assert url.startswith(f"{firms.WMS_BASE}/KEY123/")
# …and nowhere else: a key repeated in the query is a key logged twice
assert "KEY123" not in urlparse(url).query
+def _style(url: str) -> list[list[str]]:
+ """The drawing FIRMS reads from the path: layers, symbols, sizes, colours."""
+ path = urlparse(url).path
+ return [part.split(",") for part in path.split("/KEY/", 1)[1].strip("/").split("/")]
+
+
+def test_the_drawing_rides_in_the_path_one_entry_per_layer():
+ layers, symbols, sizes, colours = _style(firms.tile_url("KEY", z=6, x=40, y=22))
+ assert layers == ["fires_viirs_24"]
+ assert symbols == ["square"]
+ assert sizes == [str(firms.MARK_MIN_PX)]
+ assert colours == ["+".join(str(c) for c in firms.RECENT_RGB)]
+ # the layers FIRMS draws are the layers the query names
+ assert _query(firms.tile_url("KEY", z=6, x=40, y=22))["LAYERS"] == ["fires_viirs_24"]
+
+
+def test_a_window_longer_than_a_day_lays_the_last_24_hours_over_it():
+ layers, symbols, sizes, colours = _style(firms.tile_url("KEY", window="7d", z=6, x=40, y=22))
+ # lowest first: FIRMS draws the list in order, so the newest lands on top
+ assert layers == ["fires_viirs_7", "fires_viirs_24"]
+ assert colours == ["+".join(str(c) for c in firms.EARLIER_RGB), "+".join(str(c) for c in firms.RECENT_RGB)]
+ assert len(symbols) == len(sizes) == 2
+
+
+def test_a_dated_range_is_drawn_in_one_colour():
+ url = firms.tile_url("KEY", window="dates", first="2026-08-01", last="2026-08-09", z=6, x=40, y=22)
+ assert _style(url)[0] == ["fires_viirs"]
+
+
+def test_far_out_a_detection_is_a_mark_seen_whatever_its_footprint():
+ assert firms.mark_px("viirs", firms.tile_bounds(3, 4, 2), firms.TILE_SIZE) == firms.MARK_MIN_PX
+
+
+def test_close_in_a_detection_is_its_footprint_on_the_ground():
+ # z13 over Lyman: a 512 px tile is 4.9 km of Mercator, and the 375 m pixel
+ # is stretched by 1/cos(49°) with the imagery under it
+ x, y = 4956, 2814
+ near = firms.mark_px("viirs", firms.tile_bounds(13, x, y), firms.TILE_SIZE)
+ assert 55 <= near <= 62
+ # MODIS sees a kilometre, and says so
+ assert firms.mark_px("modis", firms.tile_bounds(13, x, y), firms.TILE_SIZE) > 2 * near
+
+
+def test_the_same_footprint_is_drawn_bigger_where_mercator_stretches_the_ground():
+ equator = firms.mark_px("viirs", firms.tile_bounds(13, 4096, 4095), firms.TILE_SIZE)
+ north = firms.mark_px("viirs", firms.tile_bounds(13, 4096, 2600), firms.TILE_SIZE)
+ assert north > equator
+
+
def test_a_tile_is_a_getmap_in_the_projection_the_grid_is_already_in():
query = _query(firms.tile_url("K", z=5, x=8, y=11))
assert query["REQUEST"] == ["GetMap"]
assert query["CRS"] == ["EPSG:3857"]
assert query["TRANSPARENT"] == ["TRUE"]
- assert query["WIDTH"] == ["256"] and query["HEIGHT"] == ["256"]
+ assert query["WIDTH"] == [str(firms.TILE_SIZE)] and query["HEIGHT"] == [str(firms.TILE_SIZE)]
# six decimals in the URL is a micrometre on the ground, and keeps the
# address readable
corners = [float(n) for n in query["BBOX"][0].split(",")]
@@ -131,9 +184,68 @@ def test_only_one_date_form_reaches_a_public_service(bad):
firms.parse_day(bad)
-def test_the_zoom_guard_stops_where_a_mark_stops_meaning_one_detection():
- assert not firms.too_deep(firms.MAX_ZOOM)
- assert firms.too_deep(firms.MAX_ZOOM + 1)
+# -- the picture ---------------------------------------------------------------
+
+
+def _png(image) -> bytes:
+ buffer = io.BytesIO()
+ image.save(buffer, "PNG")
+ return buffer.getvalue()
+
+
+def _pixels(content: bytes):
+ with Image.open(io.BytesIO(content)) as image:
+ return image.convert("RGBA").load()
+
+
+def test_an_empty_picture_goes_back_as_it_came():
+ empty = _png(Image.new("RGBA", (64, 64), (0, 0, 0, 0)))
+ assert firms.dress(empty, firms.MARK_MIN_PX) == empty
+
+
+def test_a_mark_gets_a_dark_ring_that_reads_on_any_ground():
+ image = Image.new("RGBA", (64, 64), (0, 0, 0, 0))
+ image.paste((*firms.RECENT_RGB, 255), (30, 30, 37, 37))
+ dressed = _pixels(firms.dress(_png(image), firms.MARK_MIN_PX))
+ # the mark keeps its colour…
+ assert dressed[33, 33] == (*firms.RECENT_RGB, 255)
+ # …the pixel beside it is the ring: dark and nearly opaque
+ ring = dressed[31 - firms.RING_PX, 33]
+ assert max(ring[:3]) < 40 and ring[3] > 200
+ # …and a little further out the ground is left alone
+ assert dressed[30 - firms.RING_PX - 2, 33][3] == 0
+
+
+def test_a_footprint_seen_close_keeps_its_edge_and_shows_the_ground_inside():
+ image = Image.new("RGBA", (96, 96), (0, 0, 0, 0))
+ image.paste((*firms.RECENT_RGB, 255), (20, 20, 60, 60))
+ dressed = _pixels(firms.dress(_png(image), 40))
+ assert dressed[20, 40][3] == 255 # the edge
+ inside = dressed[40, 40]
+ assert inside[:3] == firms.RECENT_RGB
+ assert abs(inside[3] - round(255 * firms.FOOTPRINT_FILL)) <= 1
+
+
+def test_a_live_window_is_kept_minutes_and_a_past_range_hours():
+ today = date(2026, 9, 26)
+ assert firms.cache_seconds("24h", today=today) == firms.LIVE_CACHE_SECONDS
+ assert firms.cache_seconds("7d", today=today) == firms.LIVE_CACHE_SECONDS
+ # a range that reaches yesterday may still gain a late detection
+ assert firms.cache_seconds("dates", "2026-09-20", "2026-09-25", today=today) == firms.LIVE_CACHE_SECONDS
+ assert firms.cache_seconds("dates", "2026-09-01", "2026-09-24", today=today) == firms.PAST_CACHE_SECONDS
+
+
+# -- what a refusal meant --------------------------------------------------------
+
+
+def test_the_count_is_read_off_the_status_answer():
+ body = '{ "transaction_limit" : 5000, "current_transactions": 4911, "transaction_interval" : "10 minutes" }'
+ assert firms.allowance(body) == (4911, 5000)
+
+
[email protected]("body", ["", "MAP_KEY is invalid", '{"current_transactions": "12"}', "[1, 2]"])
+def test_anything_else_is_not_a_count(body):
+ assert firms.allowance(body) is None
def test_a_refusal_is_read_back_as_the_sentence_it_contains():
@@ -148,82 +260,137 @@ def test_a_refusal_is_read_back_as_the_sentence_it_contains():
# -- the route -----------------------------------------------------------------
[email protected](autouse=True)
+def a_fresh_firms_memory(monkeypatch):
+ """No test inherits the pause or the verdict the previous one left."""
+ from azimut.api import satellite
+
+ monkeypatch.setattr(satellite, "_firms_verdict", None)
+ monkeypatch.setattr(satellite, "_firms_rows", 0)
+ satellite._firms_pause.clear()
+ satellite._firms_points.clear()
+ satellite._firms_flights.clear()
+ yield
+ satellite._firms_pause.clear()
+ satellite._firms_points.clear()
+
+
+def _answer_png() -> bytes:
+ image = Image.new("RGBA", (firms.TILE_SIZE, firms.TILE_SIZE), (0, 0, 0, 0))
+ image.paste((*firms.RECENT_RGB, 255), (100, 100, 107, 107))
+ return _png(image)
+
+
+def _upstream(monkeypatch, handler):
+ """FIRMS behind a fake transport: every route asks through the pooled client."""
+ from azimut.api import satellite
+
+ asked: list[httpx.Request] = []
+
+ def record(request: httpx.Request) -> httpx.Response:
+ asked.append(request)
+ return handler(request)
+
+ monkeypatch.setattr(satellite, "_tile_client", httpx.Client(transport=httpx.MockTransport(record)))
+ return asked
+
+
+def _is_status(request: httpx.Request) -> bool:
+ return str(request.url).startswith(firms.STATUS_URL)
+
+
+def _never(request: httpx.Request) -> httpx.Response:
+ raise AssertionError(f"asked FIRMS for {request.url}")
+
+
def test_the_layer_says_it_needs_a_key_before_anything_is_drawn(client):
answer = client.get("/api/firms/sensors").json()
assert answer["keyed"] is False
+ assert answer["state"] == "missing"
# …and the catalogue is there either way, so the panel can be built
assert {s["id"] for s in answer["sensors"]} >= {"viirs", "modis"}
assert answer["max_zoom"] == firms.MAX_ZOOM
def test_a_tile_without_a_key_is_a_404_rather_than_a_request(client):
- assert client.get("/api/firms/tiles/3/4/2").status_code == 404
+ assert client.get("/api/firms/points/3/4/2").status_code == 404
-def test_a_saved_key_lights_the_layer_up(client):
+def test_a_saved_key_lights_the_layer_up(client, monkeypatch):
client.put("/api/settings/keys", json={"firms": "KEY123"})
- assert client.get("/api/firms/sensors").json()["keyed"] is True
+ # read on mount and after every failed tile, so it must never phone NASA
+ _upstream(monkeypatch, _never)
+ answer = client.get("/api/firms/sensors").json()
+ assert answer["keyed"] is True
+ assert answer["state"] == "ready"
+ assert answer["paused"] is None
def test_a_key_switched_off_withholds_the_layer_without_deleting_it(client):
client.put("/api/settings/keys", json={"firms": "KEY123"})
client.put("/api/settings/prefs", json={"providers_enabled": {"firms": False}})
- assert client.get("/api/firms/sensors").json()["keyed"] is False
- assert client.get("/api/firms/tiles/3/4/2").status_code == 404
- # the key is still there, which is the whole difference from deleting it
+ answer = client.get("/api/firms/sensors").json()
+ assert answer["keyed"] is False
+ # the row says "off", not "no key": the key is still there
+ assert answer["state"] == "off"
+ assert client.get("/api/firms/points/3/4/2").status_code == 404
assert config.load_settings()["api_keys"]["firms"] == "KEY123"
def test_a_tile_deeper_than_the_layer_draws_is_refused_with_a_reason(client):
client.put("/api/settings/keys", json={"firms": "KEY123"})
- answer = client.get(f"/api/firms/tiles/{firms.MAX_ZOOM + 1}/0/0")
+ answer = client.get(f"/api/firms/points/{firms.MAX_ZOOM + 1}/0/0")
assert answer.status_code == 422
assert str(firms.MAX_ZOOM) in answer.json()["detail"]
[email protected]("path", ["/api/firms/tiles/-1/0/0", "/api/firms/tiles/3/8/0"])
[email protected]("path", ["/api/firms/points/-1/0/0", "/api/firms/points/3/8/0"])
def test_invalid_tile_coordinates_are_refused_before_key_lookup(client, monkeypatch, path):
- def never(*args, **kwargs):
- raise AssertionError("asked FIRMS for invalid tile coordinates")
-
- monkeypatch.setattr(httpx, "get", never)
+ _upstream(monkeypatch, _never)
assert client.get(path).status_code == 422
def test_a_date_the_service_would_refuse_never_reaches_it(client, monkeypatch):
client.put("/api/settings/keys", json={"firms": "KEY123"})
-
- def never(*args, **kwargs):
- raise AssertionError("asked FIRMS for a range it refuses")
-
- monkeypatch.setattr(httpx, "get", never)
+ _upstream(monkeypatch, _never)
answer = client.get(
- "/api/firms/tiles/3/4/2",
+ "/api/firms/points/3/4/2",
params={"window": "dates", "first": "2026-01-01", "last": "2026-06-01"},
)
assert answer.status_code == 422
-def test_a_tile_comes_back_as_a_png_with_the_key_left_behind(client, monkeypatch):
+def test_a_far_tile_is_read_off_firms_picture_into_marks_with_the_key_left_behind(client, monkeypatch):
client.put("/api/settings/keys", json={"firms": "KEY123"})
- asked = {}
-
- def fake_get(url, **kwargs):
- asked["url"] = url
- return httpx.Response(
- 200,
- content=b"\x89PNG\r\n\x1a\n",
- headers={"content-type": "image/png"},
- request=httpx.Request("GET", url),
- )
-
- monkeypatch.setattr(httpx, "get", fake_get)
- answer = client.get("/api/firms/tiles/3/4/2", params={"sensor": "modis", "window": "48h"})
+ asked = _upstream(
+ monkeypatch, lambda request: httpx.Response(200, content=_answer_png(), headers={"content-type": "image/png"})
+ )
+ answer = client.get("/api/firms/points/3/4/2", params={"sensor": "modis", "window": "48h"})
assert answer.status_code == 200
- assert answer.headers["content-type"] == "image/png"
- assert "fires_modis_48" in asked["url"]
+ assert answer.headers["content-type"] == "application/vnd.mapbox-vector-tile"
+ # FIRMS's own picture of the tile, squares of one pixel so each is a place
+ assert "fires_modis_48" in str(asked[0].url)
+ assert "/square,square/1,1/" in str(asked[0].url)
+ # the red square painted at 100-107 px comes back as red marks there
+ marks = [(x, y, feature["properties"]) for feature in read(answer.content)["marks"]["features"]
+ for [(x, y)] in feature["parts"]]
+ assert marks and all(100 * 8 <= x < 107 * 8 and 100 * 8 <= y < 107 * 8 for x, y, _ in marks)
+ assert {properties["recent"] for _, _, properties in marks} == {1}
+ # no footprint comes with a picture's marks, so they never give way to one
+ assert {properties["foot"] for _, _, properties in marks} == {0}
+ assert answer.headers["cache-control"] == f"private, max-age={firms.LIVE_CACHE_SECONDS}"
# the browser asked our own address; the credential stayed on this side
assert "KEY123" not in str(answer.request.url)
+ assert b"KEY123" not in answer.content
+
+
+def test_a_past_range_may_be_kept_by_the_browser_for_hours(client, monkeypatch):
+ client.put("/api/settings/keys", json={"firms": "KEY123"})
+ _upstream(monkeypatch, lambda request: httpx.Response(200, content=_answer_png(), headers={"content-type": "image/png"}))
+ answer = client.get(
+ "/api/firms/points/3/4/2", params={"window": "dates", "first": "2026-01-01", "last": "2026-01-09"}
+ )
+ assert answer.headers["cache-control"] == f"private, max-age={firms.PAST_CACHE_SECONDS}"
#: Stands in for the 28 KB picture FIRMS really draws. What matters is the
@@ -231,6 +398,9 @@ def test_a_tile_comes_back_as_a_png_with_the_key_left_behind(client, monkeypatch
#: refusal placard into the repo.
PLACARD = b"placard"
+SPENT = '{ "transaction_limit" : 5000, "current_transactions": 4911, "transaction_interval" : "10 minutes" }'
+UNKNOWN_KEY = "MAP_KEY is invalid or your have exceeded your transaction/time limit. Please try again later."
+
def test_the_refusal_picture_is_recognised_for_what_it_is(monkeypatch):
monkeypatch.setattr(firms, "PLACARD_SHA256", hashlib.sha256(PLACARD).hexdigest())
@@ -238,44 +408,130 @@ def test_the_refusal_picture_is_recognised_for_what_it_is(monkeypatch):
assert not firms.is_placard(b"\x89PNG\r\n\x1a\n a real tile")
-def test_a_placard_is_refused_rather_than_tiled_over_the_ground(client, monkeypatch):
- # FIRMS answers a key it rejects with 200 and a picture saying so, so
- # nothing in the HTTP answer says anything is wrong
- client.put("/api/settings/keys", json={"firms": "KEY123"})
+def _placard_then(monkeypatch, status: httpx.Response | Exception):
+ """A tile answered with the placard, and the status endpoint with ``status``."""
monkeypatch.setattr(firms, "PLACARD_SHA256", hashlib.sha256(PLACARD).hexdigest())
- monkeypatch.setattr(
- httpx,
- "get",
- lambda url, **kw: httpx.Response(
- 200,
- content=PLACARD,
- headers={"content-type": "image/png"},
- request=httpx.Request("GET", url),
- ),
- )
- answer = client.get("/api/firms/tiles/3/4/2")
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ if _is_status(request):
+ if isinstance(status, Exception):
+ raise status
+ return status
+ return httpx.Response(200, content=PLACARD, headers={"content-type": "image/png"})
+
+ return _upstream(monkeypatch, handler)
+
+
+def test_a_spent_allowance_pauses_the_layer_and_leaves_the_key_alone(client, monkeypatch):
+ client.put("/api/settings/keys", json={"firms": "KEY123"})
+ asked = _placard_then(monkeypatch, httpx.Response(200, text=SPENT))
+
+ answer = client.get("/api/firms/points/3/4/2")
+ assert answer.status_code == 429
+ assert "allowance" in answer.json()["detail"]
+ # the key is fine, and nothing says otherwise
+ assert "firms" not in config.load_settings().get("provider_status", {})
+ state = client.get("/api/firms/sensors").json()
+ assert state["keyed"] is True and state["state"] == "ready"
+ assert state["paused"]["used"] == 4911 and state["paused"]["of"] == 5000
+
+ # while paused, a tile is refused here: asking would only add to the count,
+ # and saying so asks nothing either
+ before = len(asked)
+ assert client.get("/api/firms/points/3/4/3").status_code == 429
+ assert client.get("/api/firms/sensors").json()["paused"]
+ assert len(asked) == before
+
+
+def test_only_a_count_near_the_limit_explains_a_refusal():
+ assert firms.spent(4911, 5000) # a 31-day picture costs 93
+ assert firms.spent(5000, 5000)
+ assert not firms.spent(12, 5000)
+
+
+def test_a_count_far_from_the_limit_pauses_nothing(client, monkeypatch):
+ # the ten minutes turned over between the picture and the question, or the
+ # refusal was something else: saying "allowance used up" would be untrue
+ client.put("/api/settings/keys", json={"firms": "KEY123"})
+ _placard_then(monkeypatch, httpx.Response(200, text=SPENT.replace("4911", "12")))
+ answer = client.get("/api/firms/points/3/4/2")
assert answer.status_code == 502
- assert "key" in answer.json()["detail"]
+ assert "allowance" not in answer.json()["detail"]
+ state = client.get("/api/firms/sensors").json()
+ assert state["paused"] is None and state["state"] == "ready"
-def test_that_refusal_benches_the_layer_the_way_a_dead_basemap_key_is_benched(client, monkeypatch):
+def test_the_pause_ends_on_its_own(client, monkeypatch):
+ from azimut.api import satellite
+
client.put("/api/settings/keys", json={"firms": "KEY123"})
- monkeypatch.setattr(firms, "PLACARD_SHA256", hashlib.sha256(PLACARD).hexdigest())
- monkeypatch.setattr(
- httpx,
- "get",
- lambda url, **kw: httpx.Response(
- 200,
- content=PLACARD,
- headers={"content-type": "image/png"},
- request=httpx.Request("GET", url),
- ),
+ _placard_then(monkeypatch, httpx.Response(200, text=SPENT))
+ client.get("/api/firms/points/3/4/2")
+ satellite._firms_pause["until"] = 0 # a minute later
+ assert client.get("/api/firms/sensors").json()["paused"] is None
+
+
+def test_a_key_the_service_does_not_know_benches_the_layer(client, monkeypatch):
+ client.put("/api/settings/keys", json={"firms": "KEY123"})
+ _placard_then(monkeypatch, httpx.Response(403, text=UNKNOWN_KEY))
+
+ answer = client.get("/api/firms/points/3/4/2")
+ assert answer.status_code == 502
+ assert answer.json()["detail"] == "FIRMS does not know this key"
+ # the Layers row says the key was refused instead of asking for a thousand
+ # more placards, and Settings keeps FIRMS's own sentence
+ state = client.get("/api/firms/sensors").json()
+ assert state["keyed"] is False
+ assert state["state"] == "refused"
+ verdict = config.load_settings()["provider_status"]["firms"]
+ assert verdict["ok"] is False and verdict["detail"].startswith("MAP_KEY is invalid")
+
+
+def test_a_status_question_that_fails_says_nothing_about_the_key(client, monkeypatch):
+ client.put("/api/settings/keys", json={"firms": "KEY123"})
+ _placard_then(monkeypatch, httpx.ConnectError("offline"))
+
+ answer = client.get("/api/firms/points/3/4/2")
+ assert answer.status_code == 502
+ assert client.get("/api/firms/sensors").json()["state"] == "ready"
+ assert client.get("/api/firms/sensors").json()["paused"] is None
+
+
+def test_a_burst_of_placards_asks_the_status_question_once(client, monkeypatch):
+ client.put("/api/settings/keys", json={"firms": "KEY123"})
+ asked = _placard_then(monkeypatch, httpx.Response(200, text="not a count"))
+ for y in range(3):
+ assert client.get(f"/api/firms/points/3/4/{y}").status_code == 502
+ assert sum(_is_status(request) for request in asked) == 1
+
+
+def test_a_new_key_clears_the_refusal(client, monkeypatch):
+ client.put("/api/settings/keys", json={"firms": "KEY123"})
+ _placard_then(monkeypatch, httpx.Response(403, text=UNKNOWN_KEY))
+ client.get("/api/firms/points/3/4/2")
+ client.put("/api/settings/keys", json={"firms": "KEY456"})
+ assert client.get("/api/firms/sensors").json()["state"] == "ready"
+
+
+def test_the_extension_route_is_paused_and_dressed_the_same_way(client, monkeypatch):
+ client.put("/api/settings/keys", json={"firms": "KEY123"})
+ token = client.post("/api/settings/ingest-token").json()["ingest_token"]
+ headers = {"X-Azimut-Token": token}
+ # far enough out that the WMS draws it; close in, the points do (test_firms_points.py)
+ box = {"south": 44, "west": 30, "north": 54, "east": 45, "width": 512, "height": 512}
+ asked = _upstream(
+ monkeypatch, lambda request: httpx.Response(200, content=_answer_png(), headers={"content-type": "image/png"})
)
- client.get("/api/firms/tiles/3/4/2")
- # the Layers row goes back to "add a key", with the reason, instead of
- # asking for a thousand more placards
- assert client.get("/api/firms/sensors").json()["keyed"] is False
- assert config.load_settings()["provider_status"]["firms"]["ok"] is False
+ answer = client.get("/api/ingest/firms", params=box, headers=headers)
+ assert answer.status_code == 200
+ assert _pixels(answer.content)[100 - firms.RING_PX, 103][3] > 200
+ assert "/square/" in str(asked[0].url)
+
+ from azimut.api import satellite
+
+ satellite._firms_pause.update(until=float("inf"), until_utc="2026-09-26T12:00:00+00:00", used=4990, of=5000)
+ assert client.get("/api/ingest/firms", params=box, headers=headers).status_code == 429
+ assert len(asked) == 1
def test_the_key_test_asks_the_service_about_the_key_rather_than_using_it(client, monkeypatch):
@@ -323,17 +579,15 @@ def test_a_refusal_is_repeated_in_the_service_s_own_words():
def test_a_service_exception_is_reported_with_what_it_said(client, monkeypatch):
client.put("/api/settings/keys", json={"firms": "BAD"})
-
- def fake_get(url, **kwargs):
- return httpx.Response(
+ _upstream(
+ monkeypatch,
+ lambda request: httpx.Response(
200,
content=b"<ServiceExceptionReport><ServiceException>Invalid MAP_KEY"
b"</ServiceException></ServiceExceptionReport>",
headers={"content-type": "text/xml"},
- request=httpx.Request("GET", url),
- )
-
- monkeypatch.setattr(httpx, "get", fake_get)
- answer = client.get("/api/firms/tiles/3/4/2")
+ ),
+ )
+ answer = client.get("/api/firms/points/3/4/2")
assert answer.status_code == 502
assert "Invalid MAP_KEY" in answer.json()["detail"]
diff --git a/tests/test_firms_points.py b/tests/test_firms_points.py
new file mode 100644
index 0000000..38996e5
--- /dev/null
+++ b/tests/test_firms_points.py
@@ -0,0 +1,613 @@
+"""FIRMS detections from the area API's points, close in.
+
+The plan (which cells, which days, how few requests), the reading of an answer,
+the vector tiles the map draws and the extension's picture are pure and tested
+without NASA; a tile is read back with ``mvtread``, written from the
+specification apart from the encoder. The route tests put FIRMS behind a fake
+transport, as ``test_firms.py`` does, and count what was asked: the whole point
+is asking once for many tiles.
+"""
+
+from __future__ import annotations
+
+import io
+import math
+import threading
+from datetime import date, datetime, timedelta, timezone
+
+import httpx
+import numpy as np
+import pytest
+from PIL import Image
+
+from azimut.engine import firms, firmspoints
+from mvtread import read, ring_area
+
+NOW = datetime(2026, 9, 27, 11, 40, tzinfo=timezone.utc)
+HEADER = "latitude,longitude,bright_ti4,scan,track,acq_date,acq_time,satellite,instrument,confidence,version,bright_ti5,frp,daynight"
+MODIS_HEADER = "latitude,longitude,brightness,scan,track,acq_date,acq_time,satellite,instrument,confidence,version,bright_t31,frp,daynight"
+UNKNOWN_KEY = "MAP_KEY is invalid or your have exceeded your transaction/time limit. Please try again later."
+
+
+def _tile(lat: float, lon: float, z: int) -> tuple[int, int]:
+ n = 1 << z
+ x = int((lon + 180) / 360 * n)
+ y = int((1 - math.asinh(math.tan(math.radians(lat))) / math.pi) / 2 * n)
+ return x, y
+
+
+def _row(lat: float, lon: float, seen: datetime, scan: float = 0.4, track: float = 0.4) -> str:
+ return f"{lat},{lon},330.1,{scan},{track},{seen:%Y-%m-%d},{seen:%H%M},N20,VIIRS,n,2.0NRT,290.5,3.2,D"
+
+
+def _pixels(content: bytes):
+ with Image.open(io.BytesIO(content)) as image:
+ return np.asarray(image.convert("RGBA"))
+
+
+def _points(*rows: tuple[float, float, datetime, float, float]) -> firmspoints.Points:
+ lat, lon, seen, scan, track = zip(*rows, strict=True)
+ return firmspoints.Points(
+ np.array(lon, dtype=np.float32), np.array(lat, dtype=np.float32),
+ np.array(scan, dtype=np.float32), np.array(track, dtype=np.float32),
+ np.array([int(s.timestamp()) for s in seen], dtype=np.int64),
+ )
+
+
+def _at(bounds, width, lat, lon) -> tuple[int, int]:
+ """Where a point lands in a picture, as (row, column)."""
+ left, bottom, right, top = bounds
+ x, y = firms.mercator(lat, lon)
+ return int((top - y) / (top - bottom) * width), int((x - left) / (right - left) * width)
+
+
+# -- which pictures, which cells, which days -----------------------------------
+
+
+def test_a_close_tile_of_a_live_window_is_drawn_here():
+ x, y = _tile(48.95, 37.8, firmspoints.MIN_ZOOM)
+ close = firms.tile_bounds(firmspoints.MIN_ZOOM, x, y)
+ assert firmspoints.drawn_here("7d", close, firms.TILE_SIZE)
+ assert firmspoints.drawn_here("24h", firms.tile_bounds(13, *_tile(48.95, 37.8, 13)), firms.TILE_SIZE)
+
+
+def test_a_far_tile_or_a_dated_range_stays_with_the_wms():
+ far = firms.tile_bounds(firmspoints.MIN_ZOOM - 1, *_tile(48.95, 37.8, firmspoints.MIN_ZOOM - 1))
+ assert not firmspoints.drawn_here("7d", far, firms.TILE_SIZE)
+ close = firms.tile_bounds(10, *_tile(48.95, 37.8, 10))
+ assert not firmspoints.drawn_here("dates", close, firms.TILE_SIZE)
+
+
+def test_a_picture_over_too_many_cells_stays_with_the_wms():
+ # fine enough pixels, but a very wide picture: the extension's biggest
+ wide = firms.bounds_of(40, 20, 52, 45)
+ assert not firmspoints.drawn_here("24h", wide, 20_000)
+
+
+def test_a_tile_draws_from_the_cells_it_touches_and_a_pixel_s_reach_past_them():
+ inside = firms.bounds_of(-6.5, 29.2, -6.0, 29.7)
+ assert firmspoints.cells_for(inside) == [(7, -2)]
+ across = firms.bounds_of(-6.5, 31.8, -6.0, 32.3)
+ assert firmspoints.cells_for(across) == [(7, -2), (8, -2)]
+ # a MODIS pixel centred just across the line still reaches in
+ near = firms.bounds_of(-6.5, 31.5, -6.0, 31.99)
+ assert firmspoints.cells_for(near) == [(7, -2), (8, -2)]
+
+
+def test_a_cell_is_asked_as_west_south_east_north():
+ assert firmspoints.cell_box((7, -2)) == "28,-8,32,-4"
+ assert firmspoints.cell_box((44, 22)) == "176,88,180,90"
+
+
+def test_a_rolling_window_is_whole_utc_days_as_firms_counts_them():
+ # matched pixel for pixel against the WMS layers, 2026-09-27: "24 h" held
+ # the previous day's main pass, 25 hours old, and nothing of the day before
+ assert firmspoints.days_for("24h", NOW) == [date(2026, 9, 26), date(2026, 9, 27)]
+ assert firmspoints.days_for("48h", NOW)[0] == date(2026, 9, 25)
+ assert firmspoints.days_for("72h", NOW)[0] == date(2026, 9, 24)
+ week = firmspoints.days_for("7d", NOW)
+ assert week[0] == date(2026, 9, 20) and week[-1] == date(2026, 9, 27) and len(week) == 8
+ assert firmspoints.since("24h", NOW) == int(datetime(2026, 9, 26, tzinfo=timezone.utc).timestamp())
+ # a minute past midnight it is still yesterday and today, not one minute of either
+ late = datetime(2026, 9, 27, 0, 1, tzinfo=timezone.utc)
+ assert firmspoints.days_for("24h", late) == [date(2026, 9, 26), date(2026, 9, 27)]
+
+
+def test_days_are_asked_in_the_fewest_requests_and_five_at_most():
+ week = firmspoints.days_for("7d", NOW)
+ assert firmspoints.runs(week) == [(date(2026, 9, 20), 5), (date(2026, 9, 25), 3)]
+ gap = [date(2026, 9, 20), date(2026, 9, 21), date(2026, 9, 24), date(2026, 9, 24)]
+ assert firmspoints.runs(gap) == [(date(2026, 9, 20), 2), (date(2026, 9, 24), 1)]
+ assert firmspoints.runs([]) == []
+
+
+def test_a_request_names_the_source_the_box_the_days_and_the_first_day():
+ url = firmspoints.area_url("KEY", "VIIRS_SNPP_NRT", (7, -2), date(2026, 9, 20), 5)
+ assert url == f"{firmspoints.AREA_BASE}/KEY/VIIRS_SNPP_NRT/28,-8,32,-4/5/2026-09-20"
+
+
+def test_the_combined_viirs_layer_is_its_three_satellites():
+ assert firmspoints.SOURCES["viirs"] == ("VIIRS_SNPP_NRT", "VIIRS_NOAA20_NRT", "VIIRS_NOAA21_NRT")
+ assert set(firmspoints.SOURCES) == {s.id for s in firms.SENSORS}
+
+
+def test_a_day_still_being_filed_is_kept_minutes_and_an_older_one_hours():
+ assert firmspoints.fresh_seconds(date(2026, 9, 27), NOW) == firms.LIVE_CACHE_SECONDS
+ assert firmspoints.fresh_seconds(date(2026, 9, 26), NOW) == firms.LIVE_CACHE_SECONDS
+ assert firmspoints.fresh_seconds(date(2026, 9, 25), NOW) == firms.PAST_CACHE_SECONDS
+
+
+# -- reading an answer -----------------------------------------------------------
+
+
+def test_an_answer_is_filed_by_day_with_every_day_asked_present():
+ seen = datetime(2026, 9, 21, 12, 12, tzinfo=timezone.utc)
+ text = "\n".join([HEADER, _row(-6.99, 29.71, seen, 0.36, 0.57), "garbage,row", ""])
+ found = firmspoints.parse(text, [date(2026, 9, 20), date(2026, 9, 21)])
+ assert set(found) == {date(2026, 9, 20), date(2026, 9, 21)}
+ # a day with no row is a day with no fires, held as that
+ assert len(found[date(2026, 9, 20)]) == 0
+ day = found[date(2026, 9, 21)]
+ assert len(day) == 1
+ assert day.lat[0] == pytest.approx(-6.99) and day.lon[0] == pytest.approx(29.71)
+ assert day.scan[0] == pytest.approx(0.36) and day.track[0] == pytest.approx(0.57)
+ assert day.seen[0] == int(seen.timestamp())
+
+
+def test_modis_is_read_by_its_own_header():
+ seen = datetime(2026, 9, 25, 0, 5, tzinfo=timezone.utc)
+ row = f"-6.94,29.48,324.8,1.23,1.1,{seen:%Y-%m-%d},0005,Aqua,MODIS,77,6.1NRT,297.5,18.4,N"
+ found = firmspoints.parse(f"{MODIS_HEADER}\n{row}\n", [date(2026, 9, 25)])
+ assert found[date(2026, 9, 25)].seen[0] == int(seen.timestamp())
+
+
+def test_a_sentence_is_not_a_table():
+ assert not firmspoints.is_table("Invalid MAP_KEY.")
+ with pytest.raises(ValueError):
+ firmspoints.parse("Invalid MAP_KEY.", [date(2026, 9, 25)])
+
+
+# -- the drawing ------------------------------------------------------------------
+
+
+def test_far_in_a_detection_is_a_solid_square_red_or_amber_with_a_ring():
+ z = firmspoints.MIN_ZOOM
+ bounds = firms.tile_bounds(z, *_tile(-6.3, 29.4, z))
+ recent = (-6.3, 29.4, NOW - timedelta(hours=2), 0.4, 0.4)
+ earlier = (-6.2, 29.3, NOW - timedelta(days=3), 0.4, 0.4)
+ gone = (-6.4, 29.5, NOW - timedelta(days=9), 0.4, 0.4)
+ image = _pixels(firmspoints.render(_points(recent, earlier, gone), bounds, 512, 512,
+ sensor_id="viirs", window="7d", now=NOW))
+ row, col = _at(bounds, 512, -6.3, 29.4)
+ assert tuple(image[row, col]) == (*firms.RECENT_RGB, 255)
+ row2, col2 = _at(bounds, 512, -6.2, 29.3)
+ assert tuple(image[row2, col2]) == (*firms.EARLIER_RGB, 255)
+ # the ring, just past the square
+ half = firms.mark_px("viirs", bounds, 512) // 2
+ assert image[row, col + half + 1][3] > 150 and image[row, col + half + 1][0] < 80
+ # older than the window: not drawn
+ row3, col3 = _at(bounds, 512, -6.4, 29.5)
+ assert image[row3, col3][3] == 0
+
+
+def test_a_24_hour_window_draws_yesterday_and_today_as_firms_does():
+ # the regression: counted by the hour, yesterday's main pass fell out of
+ # "24 h" before today's was filed, and squares vanished past z8
+ z = 9
+ bounds = firms.tile_bounds(z, *_tile(-6.3, 29.4, z))
+ yesterday = (-6.3, 29.4, NOW - timedelta(hours=25), 0.4, 0.4)
+ before = (-6.25, 29.35, NOW - timedelta(days=2), 0.4, 0.4)
+ image = _pixels(firmspoints.render(_points(yesterday, before), bounds, 512, 512,
+ sensor_id="viirs", window="24h", now=NOW))
+ row, col = _at(bounds, 512, -6.3, 29.4)
+ assert tuple(image[row, col]) == (*firms.RECENT_RGB, 255)
+ row, col = _at(bounds, 512, -6.25, 29.35)
+ assert image[row, col][3] == 0
+
+
+def test_a_square_across_a_tile_s_edge_is_drawn_on_both_tiles():
+ z = 9
+ x, y = _tile(-6.3, 29.4, z)
+ left, bottom, right, top = firms.tile_bounds(z, x, y)
+ lon, lat = firmspoints._degrees(right, (bottom + top) / 2)
+ point = _points((lat, lon - 1e-4, NOW - timedelta(hours=1), 0.4, 0.4))
+ here = _pixels(firmspoints.render(point, (left, bottom, right, top), 512, 512, sensor_id="viirs", window="24h", now=NOW))
+ there = _pixels(firmspoints.render(point, firms.tile_bounds(z, x + 1, y), 512, 512,
+ sensor_id="viirs", window="24h", now=NOW))
+ assert here[256, 511][3] == 255 and there[256, 0][3] == 255
+
+
+def test_close_in_every_footprint_keeps_its_own_edge_under_another():
+ # The regression: the WMS picture has pixels, not squares, so an edge went
+ # round the whole patch and the squares inside it lost theirs.
+ z = 13
+ bounds = firms.tile_bounds(z, *_tile(-6.3, 29.4, z))
+ left, bottom, right, top = bounds
+ lower_lon, lat = firmspoints._degrees((left + right) / 2, (bottom + top) / 2)
+ upper_lon, _ = firmspoints._degrees((left + right) / 2 + 250, (bottom + top) / 2) # half a pixel east
+ lower = (lat, lower_lon, NOW - timedelta(days=2), 0.5, 0.5)
+ upper = (lat, upper_lon, NOW - timedelta(hours=1), 0.5, 0.5)
+ image = _pixels(firmspoints.render(_points(lower, upper), bounds, 512, 512, sensor_id="viirs", window="7d", now=NOW))
+ assert firms.mark_px("viirs", bounds, 512) >= firms.FOOTPRINT_PX
+ row, centre = _at(bounds, 512, lat, lower_lon)
+ # across the pair, four solid edges: each square's two, the lower one's east
+ # edge still there under the upper one, which the WMS picture lost
+ solid = image[row, :, 3] == 255
+ edges = [c for c in range(1, 512) if solid[c] and not solid[c - 1]]
+ assert len(edges) == 4
+ assert tuple(image[row, edges[1]][:3]) == firms.RECENT_RGB
+ assert image[row, edges[2]][3] == 255 and tuple(image[row, edges[2]][:3]) != firms.RECENT_RGB
+ # and the ground shows inside a footprint where no edge crosses it
+ assert image[row, (edges[0] + edges[1]) // 2][3] < 160
+
+
+def test_close_in_a_footprint_is_the_pixel_firms_measured():
+ z = 13
+ bounds = firms.tile_bounds(z, *_tile(-6.3, 29.4, z))
+ left, bottom, right, top = bounds
+ lon, lat = firmspoints._degrees((left + right) / 2, (bottom + top) / 2)
+ wide = _points((lat, lon, NOW - timedelta(hours=1), 0.8, 0.4))
+ image = _pixels(firmspoints.render(wide, bounds, 512, 512, sensor_id="viirs", window="24h", now=NOW))
+ rows, cols = np.nonzero(image[..., 3])
+ assert (cols.max() - cols.min()) / (rows.max() - rows.min()) == pytest.approx(2, rel=0.15)
+
+
+# -- the vector tiles the map draws ---------------------------------------------------
+
+
+def _week_around(lat: float, lon: float, n: int = 40, spread: float = 0.2) -> firmspoints.Points:
+ """Detections scattered around a place over the last week, a few of them recent."""
+ rng = np.random.default_rng(7)
+ rows = []
+ for i in range(n):
+ seen = NOW - timedelta(hours=float(rng.uniform(1, 160)))
+ scan, track = float(rng.uniform(0.35, 0.8)), float(rng.uniform(0.35, 0.7))
+ rows.append((lat + float(rng.uniform(-spread, spread)), lon + float(rng.uniform(-spread, spread)),
+ seen, scan, track))
+ return _points(*rows)
+
+
+def _marks(tile: bytes) -> list[tuple[int, int, dict]]:
+ layer = read(tile).get("marks", {"features": []})
+ return [(x, y, feature["properties"]) for feature in layer["features"] for [(x, y)] in feature["parts"]]
+
+
+def test_a_tile_is_a_vector_tile_the_map_can_read():
+ z = 9
+ x, y = _tile(-6.3, 29.4, z)
+ body = firmspoints.tile(_week_around(-6.3, 29.4), z, x, y, window="7d", now=NOW)
+ layers = read(body)
+ assert set(layers) == {"marks"} # footprints only from FOOTPRINT_ZOOM
+ assert layers["marks"]["extent"] == 4096 and layers["marks"]["version"] == 2
+ # every feature is many points of one colour and one size
+ for feature in layers["marks"]["features"]:
+ assert feature["type"] == 1
+ assert set(feature["properties"]) == {"recent", "side", "foot"}
+ assert feature["properties"]["foot"] == 1
+ assert feature["properties"]["side"] % firmspoints.SIZE_STEP_M == 0
+
+
+def test_every_detection_is_one_mark_in_the_one_tile_its_centre_is_in():
+ z = 10
+ x, y = _tile(-6.3, 29.4, z)
+ left, bottom, right, top = firms.tile_bounds(z, x, y)
+ lon, lat = firmspoints._degrees((left + right) / 2, (bottom + top) / 2)
+ points = _week_around(lat, lon, n=60, spread=0.4)
+ seen = 0
+ for dx in range(-2, 3):
+ for dy in range(-2, 3):
+ seen += len(_marks(firmspoints.tile(points, z, x + dx, y + dy, window="7d", now=NOW)))
+ # the whole scatter fits in these 25 tiles, and no mark is drawn twice
+ assert seen == 60
+
+
+def test_a_mark_lands_where_its_detection_is_and_says_its_colour_and_size():
+ z = 11
+ x, y = _tile(-6.3, 29.4, z)
+ left, bottom, right, top = bounds = firms.tile_bounds(z, x, y)
+ lon, lat = firmspoints._degrees(left + (right - left) * 0.3, top - (top - bottom) * 0.6)
+ recent = _points((lat, lon, NOW - timedelta(hours=26), 0.64, 0.36))
+ [(mx, my, properties)] = _marks(firmspoints.tile(recent, z, x, y, window="7d", now=NOW))
+ assert (mx, my) == (round(0.3 * 4096), round(0.6 * 4096))
+ assert properties["recent"] == 1
+ # the side of a square of the same area, stretched as Mercator stretches it
+ side = math.sqrt(0.64 * 0.36) * 1000 / math.cos(math.radians(lat))
+ assert abs(properties["side"] - side) <= firmspoints.SIZE_STEP_M / 2
+ older = _points((lat, lon, NOW - timedelta(days=3), 0.64, 0.36))
+ assert _marks(firmspoints.tile(older, z, x, y, window="7d", now=NOW))[0][2]["recent"] == 0
+ assert bounds # the same square the pictures use
+
+
+def test_close_in_a_tile_carries_each_footprint_into_every_tile_it_reaches():
+ z = firmspoints.FOOTPRINT_ZOOM
+ x, y = _tile(-6.3, 29.4, z)
+ left, bottom, right, top = firms.tile_bounds(z, x, y)
+ # on the east border, so half of it lies in the next tile
+ lon, lat = firmspoints._degrees(right, (bottom + top) / 2)
+ point = _points((lat, lon - 1e-6, NOW - timedelta(hours=2), 0.5, 0.5))
+ here = read(firmspoints.tile(point, z, x, y, window="24h", now=NOW))
+ there = read(firmspoints.tile(point, z, x + 1, y, window="24h", now=NOW))
+ [ring_here] = [ring for feature in here["footprints"]["features"] for ring in feature["parts"]]
+ [ring_there] = [ring for feature in there["footprints"]["features"] for ring in feature["parts"]]
+ # an outer ring each, clockwise on screen, reaching across the border
+ assert ring_area(ring_here) > 0 and ring_area(ring_there) > 0
+ assert max(px for px, _ in ring_here) > 4096 and min(px for px, _ in ring_there) < 0
+ # the mark itself is in one tile only
+ assert len(_marks(firmspoints.tile(point, z, x, y, window="24h", now=NOW))) == 1
+ assert "marks" not in there
+ # a footprint is scan by track: here as wide as it is tall
+ xs, ys = [px for px, _ in ring_here], [py for _, py in ring_here]
+ assert (max(xs) - min(xs)) == pytest.approx(max(ys) - min(ys), abs=2)
+
+
+def test_a_tile_with_nothing_in_it_is_empty():
+ assert firmspoints.tile(firmspoints.Points.empty(), 9, 300, 260, window="24h", now=NOW) == b""
+
+
+# -- the route ----------------------------------------------------------------------
+
+
[email protected](autouse=True)
+def a_fresh_firms_memory(monkeypatch):
+ """No test inherits the points, the pause or the verdict of the one before."""
+ from azimut.api import satellite
+
+ monkeypatch.setattr(satellite, "_firms_verdict", None)
+ monkeypatch.setattr(satellite, "_firms_rows", 0)
+ satellite._firms_pause.clear()
+ satellite._firms_points.clear()
+ satellite._firms_flights.clear()
+ yield
+ satellite._firms_pause.clear()
+ satellite._firms_points.clear()
+ satellite._firms_flights.clear()
+
+
+def _is_area(request: httpx.Request) -> bool:
+ return str(request.url).startswith(firmspoints.AREA_BASE)
+
+
+def _area_answer(rows: list[tuple[float, float, datetime]], source: str = ""):
+ """An area API that answers each request with the rows of the days it asked,
+ for every satellite or only the one named."""
+
+ def answer(request: httpx.Request) -> httpx.Response:
+ *_, count, start = str(request.url).split("/")
+ first = date.fromisoformat(start)
+ days = {first + timedelta(days=n) for n in range(int(count))}
+ mine = not source or f"/{source}/" in str(request.url)
+ body = [HEADER] + [_row(lat, lon, seen) for lat, lon, seen in rows if mine and seen.date() in days]
+ return httpx.Response(200, text="\n".join(body) + "\n", headers={"content-type": "text/csv"})
+
+ return answer
+
+
+def _upstream(monkeypatch, handler):
+ from azimut.api import satellite
+
+ asked: list[httpx.Request] = []
+
+ def record(request: httpx.Request) -> httpx.Response:
+ asked.append(request)
+ return handler(request)
+
+ monkeypatch.setattr(satellite, "_tile_client", httpx.Client(transport=httpx.MockTransport(record)))
+ return asked
+
+
+LYMAN = (48.98, 37.80)
+
+
+def _points_path(z: int, place=LYMAN) -> str:
+ return f"/api/firms/points/{z}/{'/'.join(map(str, _tile(*place, z)))}"
+
+
+def test_a_close_tile_is_cut_from_the_points_and_the_next_zooms_ask_nothing(client, monkeypatch):
+ client.put("/api/settings/keys", json={"firms": "KEY123"})
+ now = datetime.now(timezone.utc)
+ asked = _upstream(monkeypatch, _area_answer([(*LYMAN, now - timedelta(minutes=5))], "VIIRS_NOAA20_NRT"))
+ z = firmspoints.MIN_ZOOM
+ answer = client.get(_points_path(z), params={"window": "24h"})
+ assert answer.status_code == 200
+ assert answer.headers["content-type"] == "application/vnd.mapbox-vector-tile"
+ assert answer.headers["cache-control"] == f"private, max-age={firms.LIVE_CACHE_SECONDS}"
+ assert b"KEY123" not in answer.content
+ # one request per satellite for FIRMS's two days, all through the area API
+ assert len(asked) == 3 and all(_is_area(request) for request in asked)
+ assert all("/KEY123/" in str(request.url) and "/36,48,40,52/" in str(request.url) for request in asked)
+ [(x, y, properties)] = _marks(answer.content)
+ assert properties["recent"] == 1
+ left, bottom, right, top = firms.tile_bounds(z, *_tile(*LYMAN, z))
+ mx, my = firms.mercator(*LYMAN)
+ assert (x, y) == (round((mx - left) / (right - left) * 4096), round((top - my) / (top - bottom) * 4096))
+ # zooming in over the same cell is cut from what is held
+ for deeper in range(z + 1, firmspoints.MAX_ZOOM + 1):
+ assert client.get(_points_path(deeper), params={"window": "24h"}).status_code == 200
+ assert len(asked) == 3
+
+
+def test_tiles_come_for_the_zooms_the_map_asks_and_the_questions_firms_answers(client, monkeypatch):
+ _upstream(monkeypatch, _never)
+ # no key: nothing to ask with
+ assert client.get(_points_path(9)).status_code == 404
+ client.put("/api/settings/keys", json={"firms": "KEY123"})
+ for path, params in [
+ (_points_path(firmspoints.MAX_ZOOM + 1), {}), # the map draws z13 bigger
+ (_points_path(9), {"sensor": "landsat"}),
+ (_points_path(9), {"window": "dates", "first": "2026-01-01", "last": "2026-06-01"}), # too long
+ ("/api/firms/points/9/600/0", {}), # off the grid
+ ]:
+ assert client.get(path, params=params).status_code == 422, (path, params)
+
+
+def _never(request: httpx.Request) -> httpx.Response:
+ raise AssertionError(f"asked FIRMS for {request.url}")
+
+
+def test_far_out_and_for_a_date_the_marks_come_off_firms_picture(client, monkeypatch):
+ client.put("/api/settings/keys", json={"firms": "KEY123"})
+ empty = io.BytesIO()
+ Image.new("RGBA", (512, 512), (0, 0, 0, 0)).save(empty, "PNG")
+ asked = _upstream(monkeypatch, lambda request: httpx.Response(
+ 200, content=empty.getvalue(), headers={"content-type": "image/png"}))
+ far = client.get(_points_path(firmspoints.MIN_ZOOM - 1), params={"window": "24h"})
+ dated = client.get(_points_path(10), params={"window": "dates", "first": "2026-09-01", "last": "2026-09-03"})
+ for answer in (far, dated):
+ assert answer.status_code == 200
+ assert answer.headers["content-type"] == "application/vnd.mapbox-vector-tile"
+ assert answer.content == b"" # nothing burning in the picture, nothing in the tile
+ # one WMS picture each, and not a point asked of the area API
+ assert len(asked) == 2 and all(str(r.url).startswith(firms.WMS_BASE) for r in asked)
+ assert "TIME=2026-09-01/2026-09-03" in str(asked[1].url)
+
+
+def test_a_picture_of_one_px_squares_becomes_one_mark_per_detection():
+ # FIRMS spreads a square of one pixel over the pixels it straddles
+ picture = Image.new("RGBA", (512, 512), (0, 0, 0, 0))
+ picture.putpixel((201, 300), (*firms.EARLIER_RGB, 140))
+ picture.putpixel((202, 300), (*firms.EARLIER_RGB, 140))
+ picture.putpixel((40, 60), (*firms.RECENT_RGB, 255))
+ picture.putpixel((41, 61), (*firms.RECENT_RGB, 60)) # a faint fringe does not count
+ buffer = io.BytesIO()
+ picture.save(buffer, "PNG")
+ z, x, y = 5, 18, 12
+ tile = read(firmspoints.picture_tile(buffer.getvalue(), z, x, y, sensor_id="viirs"))
+ marks = sorted((mx, my, feature["properties"]["recent"]) for feature in tile["marks"]["features"]
+ for [(mx, my)] in feature["parts"])
+ # the straddling pair is one amber mark at their middle, the red one where it is
+ assert marks == [(40 * 8 + 4, 60 * 8 + 4, 1), (202 * 8, 300 * 8 + 4, 0)]
+ # sized as the sensor's footprint: a picture does not say FIRMS's measured one
+ [side] = {feature["properties"]["side"] for feature in tile["marks"]["features"]}
+ left, bottom, right, top = firms.tile_bounds(z, x, y)
+ _, lat = firmspoints._degrees((left + right) / 2, (bottom + top) / 2)
+ assert abs(side - 375 / math.cos(math.radians(lat))) <= firmspoints.SIZE_STEP_M / 2
+
+
+def test_close_in_a_picture_s_marks_hand_over_to_see_through_footprints():
+ # a dated range comes off FIRMS's picture at every zoom, so close in it
+ # needs footprints too, or its marks stay solid where a rolling window's fade
+ picture = Image.new("RGBA", (512, 512), (0, 0, 0, 0))
+ picture.putpixel((256, 256), (*firms.RECENT_RGB, 255))
+ buffer = io.BytesIO()
+ picture.save(buffer, "PNG")
+ z = firmspoints.FOOTPRINT_ZOOM
+ x, y = _tile(-6.3, 29.4, z)
+ tile = read(firmspoints.picture_tile(buffer.getvalue(), z, x, y, sensor_id="viirs"))
+ [mark] = tile["marks"]["features"]
+ assert mark["properties"]["foot"] == 1
+ [feature] = tile["footprints"]["features"]
+ assert feature["properties"] == {"recent": 1}
+ [ring] = feature["parts"]
+ assert ring_area(ring) > 0
+ # a square of the mark's side, centred on the mark
+ left, _, right, _ = firms.tile_bounds(z, x, y)
+ width = mark["properties"]["side"] * 4096 / (right - left)
+ xs, ys = [px for px, _ in ring], [py for _, py in ring]
+ assert max(xs) - min(xs) == pytest.approx(width, abs=2)
+ assert max(ys) - min(ys) == pytest.approx(width, abs=2)
+ [[(mx, my)]] = mark["parts"]
+ assert (min(xs) + max(xs)) / 2 == pytest.approx(mx, abs=1)
+ # farther out there is no footprint to hand over to
+ far = read(firmspoints.picture_tile(buffer.getvalue(), z - 1, x // 2, y // 2, sensor_id="viirs"))
+ assert set(far) == {"marks"} and far["marks"]["features"][0]["properties"]["foot"] == 0
+
+
+def test_a_live_day_is_asked_again_after_its_minutes_and_an_older_one_is_not(client, monkeypatch):
+ from azimut.api import satellite
+
+ client.put("/api/settings/keys", json={"firms": "KEY123"})
+ asked = _upstream(monkeypatch, _area_answer([]))
+ params = {"window": "7d", "sensor": "modis"}
+ assert client.get(_points_path(9), params=params).status_code == 200
+ assert len(asked) == 2 # eight days, five and three
+ clock = satellite.time.monotonic() + firms.LIVE_CACHE_SECONDS + 1
+ monkeypatch.setattr(satellite.time, "monotonic", lambda: clock)
+ assert client.get(_points_path(9), params=params).status_code == 200
+ # only yesterday and today went stale, and they are one request
+ today = datetime.now(timezone.utc).date()
+ assert len(asked) == 3
+ assert str(asked[-1].url).endswith(f"/2/{today - timedelta(days=1)}")
+
+
+def test_the_points_held_stay_under_their_cap(monkeypatch):
+ from azimut.api import satellite
+
+ monkeypatch.setattr(satellite, "FIRMS_POINTS_CAP", 3)
+ two = _points((1.0, 1.0, NOW, 0.4, 0.4), (1.0, 1.1, NOW, 0.4, 0.4))
+ satellite._firms_store("VIIRS_SNPP_NRT", (0, 0), {date(2026, 9, 26): two})
+ satellite._firms_store("VIIRS_SNPP_NRT", (0, 0), {date(2026, 9, 27): two})
+ # the least recently drawn day went to make room
+ assert list(satellite._firms_points) == [("VIIRS_SNPP_NRT", (0, 0), date(2026, 9, 27))]
+ assert satellite._firms_rows == 2
+
+
+def test_the_tiles_of_one_screen_fetch_a_cell_once(monkeypatch):
+ from azimut.api import satellite
+
+ release = threading.Event()
+ answer = _area_answer([])
+
+ def slow(request: httpx.Request) -> httpx.Response:
+ release.wait(5)
+ return answer(request)
+
+ asked = _upstream(monkeypatch, slow)
+ bounds = firms.tile_bounds(9, *_tile(*LYMAN, 9))
+ done = []
+ workers = [threading.Thread(target=lambda: done.append(
+ satellite._firms_points_for("KEY", "viirs", "24h", bounds))) for _ in range(4)]
+ for worker in workers:
+ worker.start()
+ threading.Event().wait(0.2)
+ release.set()
+ for worker in workers:
+ worker.join(5)
+ assert len(done) == 4
+ assert len(asked) == 3
+
+
+def test_a_refusal_from_the_area_api_is_read_through_the_status_endpoint(client, monkeypatch):
+ client.put("/api/settings/keys", json={"firms": "KEY123"})
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ if str(request.url).startswith(firms.STATUS_URL):
+ return httpx.Response(200, json={"transaction_limit": 5000, "current_transactions": 4990})
+ return httpx.Response(403, text="Exceeding allowed transaction limit")
+
+ asked = _upstream(monkeypatch, handler)
+ tile = _points_path(9)
+ answer = client.get(tile)
+ assert answer.status_code == 429
+ assert client.get("/api/firms/sensors").json()["state"] == "ready"
+ # paused: the next tile asks nobody
+ before = len(asked)
+ assert client.get(tile).status_code == 429
+ assert len(asked) == before
+
+
+def test_a_key_the_area_api_does_not_know_benches_the_layer(client, monkeypatch):
+ client.put("/api/settings/keys", json={"firms": "KEY123"})
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ if str(request.url).startswith(firms.STATUS_URL):
+ return httpx.Response(403, text=UNKNOWN_KEY)
+ return httpx.Response(400, text="Invalid MAP_KEY.")
+
+ _upstream(monkeypatch, handler)
+ answer = client.get(_points_path(9))
+ assert answer.status_code == 502
+ assert client.get("/api/firms/sensors").json()["state"] == "refused"
+
+
+def test_the_extension_close_in_gets_the_same_drawing(client, monkeypatch):
+ client.put("/api/settings/keys", json={"firms": "KEY123"})
+ token = client.post("/api/settings/ingest-token").json()["ingest_token"]
+ now = datetime.now(timezone.utc)
+ asked = _upstream(monkeypatch, _area_answer([(*LYMAN, now - timedelta(hours=1))]))
+ box = {"south": 48.9, "west": 37.7, "north": 49.1, "east": 37.9, "width": 800, "height": 600}
+ answer = client.get("/api/ingest/firms", params=box, headers={"X-Azimut-Token": token})
+ assert answer.status_code == 200
+ assert asked and all(_is_area(request) for request in asked)
+ image = _pixels(answer.content)
+ assert image.shape == (600, 800, 4)
+ assert image[..., 3].max() == 255
diff --git a/tests/test_map_layers.py b/tests/test_map_layers.py
index 4f7cd69..6f6d171 100644
--- a/tests/test_map_layers.py
+++ b/tests/test_map_layers.py
@@ -167,6 +167,26 @@ def test_a_kml_folder_is_a_legend_category():
assert summary["categories"][0]["kinds"] == ["line", "point"]
+def test_a_coordinate_with_space_after_its_comma_is_still_a_point():
+ """NASA FIRMS writes its fire points as `7.31866000, 52.46726000`. Split on
+ whitespace alone that is two halves and no point, and the whole feed was
+ refused as holding nothing to draw."""
+ firms = (
+ '<kml xmlns="http://www.opengis.net/kml/2.2"><Document>'
+ "<Folder><name> Fire Points List </name>"
+ "<Placemark><name>VIIRS FIRE</name>"
+ "<Point><coordinates> 7.31866000, 52.46726000</coordinates></Point></Placemark>"
+ "<Placemark><name>Line</name><LineString><coordinates>"
+ "1.0 , 2.0 ,0 3.0,4.0</coordinates></LineString></Placemark>"
+ "</Folder></Document></kml>"
+ ).encode()
+
+ features = maplayers.parse(firms, filename="J1_VIIRS_C2_Europe_24h.kml")["geojson"]["features"]
+
+ assert features[0]["geometry"] == {"type": "Point", "coordinates": [7.31866, 52.46726]}
+ assert features[1]["geometry"]["coordinates"] == [[1.0, 2.0], [3.0, 4.0]]
+
+
def test_a_kml_colour_is_honoured_through_its_style_map():
"""`aabbggrr` with the alpha dropped, and the *normal* half of a StyleMap —
which is the one Google writes and the one the map draws."""
diff --git a/tests/test_mvt.py b/tests/test_mvt.py
new file mode 100644
index 0000000..8124e5f
--- /dev/null
+++ b/tests/test_mvt.py
@@ -0,0 +1,71 @@
+"""The vector tile encoder, read back by a reader written from the specification."""
+
+from __future__ import annotations
+
+import numpy as np
+
+from azimut.engine import mvt
+from mvtread import _fields, _packed, geometry, read, ring_area
+
+
+def test_many_varints_are_written_as_each_one_would_be():
+ values = [0, 1, 127, 128, 300, 16383, 16384, 2**21, 2**35, 2**63 - 1]
+ assert mvt._varints(np.array(values, dtype=np.uint64)) == b"".join(mvt._varint(v) for v in values)
+ assert mvt._varints(np.array([], dtype=np.uint64)) == b""
+
+
+def test_a_step_back_is_zigzagged_to_a_small_number():
+ steps = np.array([0, -1, 1, -2, 2, -4096, 4096])
+ assert mvt._zigzag(steps).tolist() == [0, 1, 2, 3, 4, 8191, 8192]
+
+
+def test_points_come_back_where_they_were_put():
+ xs, ys = np.array([10, 4000, 4000, 0]), np.array([20, 5, 4095, 0])
+ commands = _packed(mvt.points_geometry(xs, ys))
+ # one MoveTo for all of them
+ assert commands[0] == 1 | 4 << 3
+ assert geometry(commands) == [[(10, 20)], [(4000, 5)], [(4000, 4095)], [(0, 0)]]
+
+
+def test_rectangles_come_back_as_outer_rings():
+ x0, y0 = np.array([0, -50]), np.array([0, 100])
+ x1, y1 = np.array([10, 4200]), np.array([30, 180])
+ parts = geometry(_packed(mvt.rectangles_geometry(x0, y0, x1, y1)))
+ assert parts == [[(0, 0), (10, 0), (10, 30), (0, 30)], [(-50, 100), (4200, 100), (4200, 180), (-50, 180)]]
+ # clockwise on screen, which is what makes each one filled rather than a hole
+ assert all(ring_area(ring) > 0 for ring in parts)
+
+
+def test_a_layer_says_its_name_extent_and_version_and_shares_its_values():
+ layer = mvt.Layer("marks")
+ layer.points(np.array([1]), np.array([2]), {"recent": 1, "side": 375})
+ layer.points(np.array([3]), np.array([4]), {"recent": 1, "side": 400})
+ tile = read(mvt.encode([layer]))
+ marks = tile["marks"]
+ assert (marks["extent"], marks["version"]) == (mvt.EXTENT, 2)
+ assert [f["properties"] for f in marks["features"]] == [{"recent": 1, "side": 375}, {"recent": 1, "side": 400}]
+ # "recent: 1" is written once for both features
+ assert marks["keys"] == ["recent", "side"] and marks["values"] == [1, 375, 400]
+
+
+def test_every_kind_of_value_reads_back_as_itself():
+ layer = mvt.Layer("kinds")
+ properties = {"count": 7, "below": -3, "ratio": 0.25, "name": "fire", "on": True}
+ layer.points(np.array([0]), np.array([0]), properties)
+ [feature] = read(mvt.encode([layer]))["kinds"]["features"]
+ assert feature["properties"] == properties
+ # a bool is not the int 1, even when both are in one layer
+ both = mvt.Layer("both")
+ both.points(np.array([0]), np.array([0]), {"a": 1})
+ both.points(np.array([0]), np.array([0]), {"a": True})
+ assert [f["properties"]["a"] for f in read(mvt.encode([both]))["both"]["features"]] == [1, True]
+
+
+def test_a_layer_with_nothing_in_it_is_left_out():
+ empty, full = mvt.Layer("empty"), mvt.Layer("full")
+ empty.points(np.array([], dtype=np.int64), np.array([], dtype=np.int64), {"recent": 0})
+ full.points(np.array([5]), np.array([6]), {"recent": 0})
+ assert set(read(mvt.encode([empty, full]))) == {"full"}
+ assert mvt.encode([empty]) == b""
+ # and a tile is layers and nothing else
+ assert [number for number, _ in _fields(mvt.encode([full]))] == [3]
diff --git a/tests/test_radar_detect.py b/tests/test_radar_detect.py
index aae30bc..64e103c 100644
--- a/tests/test_radar_detect.py
+++ b/tests/test_radar_detect.py
@@ -439,7 +439,7 @@ def test_a_radar_run_without_its_layer_says_where_to_set_it(client, radar_case):
def test_a_typed_day_is_pinned_to_the_pass_on_the_other_sides_track(client, radar_case, monkeypatch):
asked = []
- def acquisitions(instance, rings, start, end, collection="sentinel2"):
+ def acquisitions(instance, rings, start, end, collection="sentinel2", **kwargs):
asked.append((start, end, collection))
return {"dates": [
{"date": DAY_B, "time": "17:33:02", "cloud": None, "coverage": 1.0},
diff --git a/tests/test_sentinel.py b/tests/test_sentinel.py
index 8690ca1..c99cfb1 100644
--- a/tests/test_sentinel.py
+++ b/tests/test_sentinel.py
@@ -391,6 +391,64 @@ def test_acquisitions_says_when_the_catalogue_stopped_short():
assert sentinel.acquisitions("inst-uuid", [area], "2026-05-01", "2026-05-31", get=get)["truncated"]
+def _paged(pages):
+ """A catalogue that answers ``pages`` in turn, by FEATURE_OFFSET."""
+ asked = []
+
+ def get(url, params=None, **kwargs):
+ offset = int(params.get("FEATURE_OFFSET", 0))
+ asked.append(offset)
+ return _response(url, {"features": pages[offset // sentinel._MAX_FEATURES]})
+
+ return get, asked
+
+
+def test_a_full_page_is_followed_by_the_next_until_one_is_short():
+ """Granules come newest first, so the first 100 of a long window are its
+ newest weeks: stopping there lost the oldest passes, silently for a point."""
+ area = _rect(2.0, 48.0, 2.5, 48.5)
+ newer = [_granule(f"2026-05-{day:02d}", 1.5, 47.5, 3.0, 49.5) for day in range(31, 1, -1)] * 4
+ older = [_granule("2026-04-30", 1.5, 47.5, 3.0, 49.5)]
+ get, asked = _paged([newer[:100], older])
+ metered = []
+
+ found = sentinel.acquisitions("inst-uuid", [area], "2026-04-01", "2026-05-31", get=get,
+ on_request=lambda: metered.append(1))
+ assert asked == [0, 100]
+ assert len(metered) == 2 # each page a request on the meter
+ assert not found["truncated"]
+ assert found["dates"][-1]["date"] == "2026-04-30"
+
+
+def test_a_lookup_stops_after_its_last_page_and_says_it_was_cut():
+ crowd = [_granule("2026-05-01", 1.5, 47.5, 3.0, 49.5)] * sentinel._MAX_FEATURES
+ get, asked = _paged([crowd] * (sentinel._MAX_PAGES + 2))
+ found = sentinel.acquisitions("inst-uuid", [_rect(2.0, 48.0, 2.5, 48.5)], "2026-05-01", "2026-05-31", get=get)
+ assert len(asked) == sentinel._MAX_PAGES
+ assert found["truncated"]
+
+
+def test_a_point_lookup_pages_too():
+ first = [{"properties": {"date": f"2026-05-{1 + i % 28:02d}", "cloudCoverPercentage": 5.0}}
+ for i in range(sentinel._MAX_FEATURES)]
+ last = [{"properties": {"date": "2026-04-02", "cloudCoverPercentage": 5.0}}]
+ get, asked = _paged([first, last])
+ found = sentinel.dates("inst-uuid", 48.0, 2.0, "2026-04-01", "2026-05-31", get=get)
+ assert asked == [0, 100]
+ assert found[-1]["date"] == "2026-04-02"
+
+
+def test_a_failed_page_is_still_counted():
+ def get(url, params=None, **kwargs):
+ return _response(url, text="busy", status=503)
+
+ metered = []
+ with pytest.raises(httpx.HTTPStatusError):
+ sentinel.dates("inst-uuid", 48.0, 2.0, "2026-05-01", "2026-05-31", get=get,
+ on_request=lambda: metered.append(1))
+ assert metered == [1]
+
+
@pytest.mark.parametrize("start,end", [
("2026-13-01", "2026-05-31"), ("2026-05-01", "not-a-date"), ("2026-05-31", "2026-05-01"),
])
diff --git a/tests/test_settings_api.py b/tests/test_settings_api.py
index d00124b..3845eae 100644
--- a/tests/test_settings_api.py
+++ b/tests/test_settings_api.py
@@ -1118,3 +1118,15 @@ def test_detect_prefs_drop_the_retired_labels_layer(client):
)
assert saved.status_code == 200, saved.text
assert saved.json()["detect_view"]["overlays"] == ["boundaries", "roads"]
+
+
+def test_detect_opens_with_the_borders_and_the_place_names(client):
+ assert client.get("/api/settings").json()["detect_view"]["overlays"] == ["boundaries", "placenames"]
+
+
+def test_detect_prefs_keep_the_place_names(client):
+ # Every layer Detect lists can be remembered, the place names included.
+ everything = ["boundaries", "placenames", "roads", "railway", "power", "seamarks", "gpstraces"]
+ saved = client.put("/api/settings/prefs", json={"detect_view": {"overlays": everything}})
+ assert saved.status_code == 200, saved.text
+ assert saved.json()["detect_view"]["overlays"] == everything