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

Give Detect its own tab, read Sentinel-1 radar, and prepare 0.3.1 (#84)

OsintMeThatd738f7ef7619
diff --git a/README.md b/README.md
index 05970ab..1b501c1 100644
--- a/README.md
+++ b/README.md
@@ -60,10 +60,11 @@ to fix a point on the map.*
| **Files** | Every saved artifact in one Finder-style view of your folders, not just media: select several, drag them into a folder, search across the lot. |
| **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** | A scratch workspace over any photo or video: frame adjustments, editable crop, sharpest-frame capture, hand-made collage with per-piece warp/scale/rotate, auto-stitch to solve a panorama's layout, and ELA hints. Nothing enters the case until you save. |
-| **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) and editable AOI grids for area review. Esri/OSM by default, plus the Esri Wayback archive and Sentinel-2 with a date calendar and a cloud-ceiling slider; 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, blink or assisted change reading. Ground-anchored notes, shapes and measurements follow both maps. Editable sessions and rendered previews stay in the case; attributed PNG/GIF copies go to exports. |
+| **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. |
+| **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 and narrows down when a change appeared. 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. |
| **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. |
-| **Geo Proof** | Start a named proof from a reusable house style, or from a published post whose pictures become its panels. Compose case panels in a grid or free layout, annotate with colored shapes, fills, symbols, freehand and text, state every place and every source the proof argues, and export `proof.png` plus a re-editable spec. |
+| **Geo Proof** | Start a named proof from a reusable house style, or from a published post whose pictures become its panels. Compose case panels in a grid or free layout, turn or crop them, annotate with colored shapes, fills, symbols, numbered markers, blur boxes, freehand and text, state every place and every source the proof argues, and export `proof.png` plus a re-editable spec. |
| **Geo Report** | Turn a proof into a prepared thread for X or Bluesky: coordinates, plus code, attribution, target-specific character counts, media, and a structured Markdown case note with linked evidence. |
| **Notebook** | Tabbed Markdown notes with local media, Mermaid diagrams, linked case evidence, broken-reference markers, and PDF export of one note or a whole selection. |
@@ -74,27 +75,26 @@ extension, and cross-platform binaries with a bundled ffmpeg.
Every tool works one-shot (a scratch session, no setup) or inside a case, a
plain directory holding the whole investigation.
-## New in v0.3.0
-
-A new map with much more on it, and Azimut's tools drawn over other map sites.
-
-- The map runs on MapLibre, with modes in one rail, layers in a side panel and a
- status line. Right-click the ground to copy, save, measure, read the sky or open
- the point's imagery history.
-- **Esri Wayback** as a basemap, narrowed to the releases that changed the point
- and dated by when the picture was taken.
-- Key-less overlays (borders, roads, railways, power lines, sea marks, GPS
- traces), NASA FIRMS fires and VIIRS night lights for a chosen day.
-- Several map tabs sharing one camera, with saved points and grid sweeps synced
- live between them.
-- Captures can carry a scale bar and a north arrow, and a place's uncertainty can
- be traced as a shape.
-- The capture extension draws measure, saved points, sun and moon, search grids,
- fires and case media over third-party map sites, and updates from Settings.
- Firefox gets a signed, self-updating add-on.
-- Geo Report fills the X or Bluesky composer with the whole thread, and Reverse
- Search drops the picture straight into the engine's uploader.
-- The app opens on a case Home, and `?` opens a Guide on the current tool.
+## New in v0.3.1
+
+Detect sweeps an area for what appeared, and the map takes layers made elsewhere.
+
+- **Detect**, a tab of its own, sweeps drawn areas of Sentinel-2 for vessels, fires and
+ flares, construction, small spots, surface change, burn scars, vegetation loss
+ or new water. Candidates come strongest first, and only one you keep becomes a
+ case pin.
+- Difference and Detect share one Sentinel-2 cloud and shadow mask.
+- Radar: five Sentinel-1 analyzers (vessels, any change, razed buildings, new
+ structures, floods) see through cloud and at night, and Sentinel-1 passes are a
+ basemap in Satellite, Compare and Detect.
+- A candidate opens in Compare with one press, and All dates in Compare narrows
+ down between which two pictures a change appeared.
+- Open KML, KMZ, GeoJSON and GPX files or a public My Maps as map layers, and add
+ a GeoConfirmed conflict. A dated layer narrows to a period.
+- Proofs turn and crop their images, stamp numbered markers and blur boxes, and
+ carry a sentence and the date their material was taken.
+- To-do lists on Home, one date field across the app, a claim filed from where
+ you are, and Reverse Search from a Media Library row or an Inspect frame.
- Existing cases open unchanged, and older bundles still import.
## Cases on disk
@@ -298,7 +298,7 @@ tag, with credentials from the AMO developer hub:
```bash
export AMO_JWT_ISSUER=... AMO_JWT_SECRET=...
python3 scripts/sign_extension.py # signs, writes packaging/updates.json
-gh release upload v0.3.0 dist-xpi/azimut-capture-0.3.0.xpi
+gh release upload v0.3.1 dist-xpi/azimut-capture-0.3.1.xpi
```
Then commit `packaging/updates.json`. That file is what
@@ -365,7 +365,7 @@ wheel + Windows/Linux/macOS binaries, attaches them to a GitHub release, and
publishes to PyPI. **Don't publish by hand.**
```bash
-git tag v0.3.0 && git push origin v0.3.0
+git tag v0.3.1 && git push origin v0.3.1
```
One-time setup: register the repo as a
diff --git a/docs/IMAGERY_PROVIDERS.md b/docs/IMAGERY_PROVIDERS.md
index 028fa12..bc70884 100644
--- a/docs/IMAGERY_PROVIDERS.md
+++ b/docs/IMAGERY_PROVIDERS.md
@@ -31,6 +31,7 @@
| **Google Satellite** | yes | **session token** | yes (flattened+attributed only) | **NO** | dynamic copyright from viewport endpoint |
| **Google Satellite (Maps JS)** | yes | key in script URL⁴ | screen crops only (user-initiated grab, attribution burned) | n/a (widget) | `Map data © Google` + the widget's own credits |
| **Sentinel-2 (Sentinel Hub)** | yes | instance ID in URL³ | yes | yes | `© Copernicus Sentinel data {year}` |
+| **Sentinel-1 radar (Sentinel Hub)** | yes, plus a radar layer | instance ID in URL³ | yes | yes | `© Copernicus Sentinel data {year}` |
¹ Display + static-image capture with attribution is permitted; plan-level
caching/redistribution limits vary, so the cache stays modest (30-day TTL) and
@@ -341,6 +342,67 @@ assumption.
[Quotas](https://documentation.dataspace.copernicus.eu/Quotas.html) ·
[PU definition](https://documentation.dataspace.copernicus.eu/APIs/SentinelHub/Overview/ProcessingUnit.html)
+## Sentinel-1 comes through a layer the user adds
+
+Radar is the same account, the same quota and the same configuration instance, but
+an instance serves no Sentinel-1 until one of its layers reads it: the WFS answers
+`TYPENAME=DSS3 not found!` for an instance built from the Sentinel-2 template
+(verified 2026-09). The user adds a layer in the Configuration Utility with
+Sentinel-1 GRD as its source, IW mode, VV+VH polarisation, High resolution, any
+orbit direction, orthorectification on, gamma0 and no speckle filter; the form
+refuses to save until Data processing names a predefined product or a script,
+which Azimut replaces anyway. The app shows that form field by field
+(`lib/copernicusSetup.js`). Orthorectification doubles a request's processing
+units and a speckle filter doubles them again; terrain gamma0 multiplies them by
+2.5 (Copernicus PU rules, 2026-09). The processing a layer sets (backscatter coefficient, orthorectification, DEM)
+cannot be overridden from an OGC request; only the evalscript can, and ours
+replaces the layer's.
+
+Nothing in GetCapabilities says which layer reads which collection. WFS
+GetCapabilities does list one feature type per collection the layers use, free,
+which says whether any radar layer exists. **Find** (`POST
+/api/satellite/sentinel1/layer`) then asks each layer the Sentinel-2 templates do
+not ship, at most six, with an 8 × 8 render that reads `VV` and `VH` over the North
+Sea off Rotterdam: a Sentinel-2 layer answers 400 and the service's sentence says
+why. One request per probe, on the meter. The first layer that answers is kept as
+`sentinel1_layer` in settings.json, carried by the backup, and forgotten when the
+instance id changes. It can also be named and checked by hand.
+
+- **A pass is a day and a time.** Sentinel-1 passes a place at dawn flying south
+ and at dusk flying north, so one day can hold two looks from opposite sides.
+ Radar lookups (`collection=sentinel1`) group granules by pass rather than by
+ day, name a pass by the UTC time of its first slice (the WFS `time` field, or
+ the sensing start in the product name), and derive the direction from the
+ local solar hour. Requests carry `TIME` as twenty minutes either side of that
+ time (`sentinel.pass_window`), which holds one pass and nothing else.
+- **One track compares with itself.** A relative orbit repeats to the second every
+ twelve days, whichever satellite flies it; the neighbouring track that also sees
+ a place passes about eight minutes off (Dover 2025: orbits 132 and 59 at 17:49
+ and 17:41). Two passes within four minutes of each other in the day are one
+ track (`sentinel.same_track`), and Detect, Difference and the pickers hold a
+ pair to it.
+- **The basemap** is `sentinel1`, offered once `sentinel1_layer` is set. A pass
+ rides on the id as `sentinel1~2026-05-14~054210` (no colons: the id is a cache
+ folder), a day alone as `sentinel1~2026-05-14`, and the plain id is the most
+ recent pass. It is drawn in the review composite: VV red from -22 to 2 dB, VH
+ green from -30 to -6 dB, their difference blue from 0 to 15 dB.
+- **Detect's radar product** (`sar`) carries VV and VH in decibels, a fifth of one
+ per step from -35 dB, the first byte never zero where the radar saw something.
+ The review picture (`sar-picture`) is rendered by WMS like a product, since
+ there is no true colour to borrow.
+- **The water mask** (`water`) is a Sentinel-2 product read beside a radar vessel
+ sweep: the scene class of the least cloudy pass of the year before the pass's
+ month (`PRIORITY=leastCC`), water, land, or unknown where that pass saw cloud,
+ shadow or snow. Dry desert is as radar-dark as calm sea in both polarisations,
+ and without it the radar alone put 72 candidates on Port Sudan's town and sand.
+
+Calibration used no quota: the scenes were read key-less from Microsoft Planetary
+Computer's `sentinel-1-rtc` and `sentinel-2-l2a` collections and encoded in the
+products' byte layout. Those are terrain-flattened gamma0; a layer left at the
+Sentinel Hub default reads ellipsoid gamma0, which differs little over sea and
+flat ground and more on slopes, which is one more reason to ask for
+orthorectification.
+
## Google is not a static `{key}` URL
It needs a session token, minted and refreshed transparently before the rest of the
diff --git a/docs/RELEASE_NOTES.md b/docs/RELEASE_NOTES.md
index a7224fd..365f784 100644
--- a/docs/RELEASE_NOTES.md
+++ b/docs/RELEASE_NOTES.md
@@ -1,78 +1,112 @@
-# Azimut v0.3.0
+# Azimut v0.3.1
Azimut is a local OSINT workspace: media, geolocation work, proofs and notes in
one portable case folder, on your own machine.
-This release rebuilds the map and gives it much more to show, and lets the
-capture extension draw Azimut's own tools over other map sites.
-
-## A new map
-
-The Satellite map now runs on MapLibre. Your providers, captures and map rotation
-work as before, including the Google basemap.
-
-- The screen is laid out again: modes in one rail, layers in the right panel,
- imagery in the map corner, and your position in a status line underneath.
-- Right-click the ground to copy that point in every format, look it up, save it,
- measure from it, read the sun and moon there, open its imagery history, or open
- it on another map site.
-- **Esri Wayback** is a basemap now. Pick any World Imagery release, or list only
- the releases that brought a new picture of the point you are looking at. The
- chip gives the date the picture was taken, which is often long before the
- release.
-- Stack overlays that need no key: borders, roads, railways, power lines, sea
- marks and GPS traces. Add NASA FIRMS fire detections (with a free FIRMS key in
- Settings) and VIIRS night lights for a day you pick. FIRMS detections remain
- visible as enlarged squares when you zoom past their native detail.
-- Filter the pins drawn on the map by kind and by folder.
-- Open the map in several tabs. The view is in the address, two tabs can share one
- camera, and a point saved or a grid swept in one appears at once in the others.
-- A capture can carry a scale bar and a north arrow.
-- Trace a place's uncertainty as a shape around its pin, for a quay or a treeline
- that a circle describes badly.
-
-## Capture extension
-
-- On a 2D map site, the extension can now draw Azimut's tools over the page:
- measure, the case's saved points, sun and moon, a search grid that opens in the
- app afterwards, NASA FIRMS fires, and floating windows holding the case's own
- pictures and videos.
-- The scale is read from what each site writes in its address bar, checked site by
- site in a real browser. On a view the tools cannot work with, such as Street View
- or a tilted 3D camera, they switch off and say which view they need.
-- Geo Report fills the X or Bluesky composer with the whole thread, one box per
- post with its pictures attached. Posting stays your click.
-- Reverse Search puts the picture straight into the Lens, Yandex, Bing or TinEye
- uploader, so one press runs the search.
-- On Chrome, Edge and Brave, updating the extension is a button in Settings.
- Firefox gets a signed add-on that updates itself, and Settings tells you when
- your copy is out of step with the app.
-- Mastodon is no longer a Geo Report target. A draft saved for it opens on X.
+This release sweeps an area for what appeared, and puts maps made
+elsewhere on yours.
+
+## Detect
+
+- **Detect** is a new tab under Map. Draw one or more areas on
+ Sentinel-2 and it sweeps them at full resolution for vessels, fires and gas
+ flares, construction, small spots, any surface change, burn scars, vegetation
+ loss or new water. You can also copy an analyzer and tune your own.
+- Ask for a small, medium or large target instead of setting thresholds. The
+ areas are priced in Copernicus requests before anything is fetched.
+- **Find passes** lists the dates your areas really have, with how much of them
+ each pass covered and how cloudy it was. A finished run says how much it read,
+ so "nothing found" and "never looked" stay apart.
+- Candidates come strongest first, one at a time. **Keep as a pin** files one
+ with its own evidence crop; nothing else reaches the case.
+- Areas can be saved with the case. A watch keeps an analyzer, its areas and a
+ date rule together, and **Run again** repeats the sweep.
+- Detect needs Copernicus credentials in Settings.
+
+## Compare
+
+- Compare opens on a Wayback release from a year ago against today's World
+ Imagery, with no key needed. **New** offers the other starting pairs.
+- "Change assist" is now **Difference**. Its cloud switch uses the same
+ Sentinel-2 cloud and shadow mask as Detect instead of guessing from the
+ picture, so a white roof is no longer taken for a cloud.
+- MNDWI and BSI join the spectral indices. An index draws its line at a stated
+ change, so panning no longer moves it.
+- Tone matching is off by default on a Sentinel-2 pair.
+- Difference is a switch beside the four views rather than a view of its own:
+ its highlights lie over side by side, swipe, fade or blink, on A, B or both.
+ They can blink.
+- Right-click the ground for the point menu.
+- Right-click a point on the Satellite map to open Compare on its last two
+ Wayback pictures or its last two Copernicus passes.
+- An export frame sets what an export shows. Numbered markers and blur boxes can
+ be stamped on the ground.
+- On a turned map, boxes and ellipses are drawn along the screen, and any shape
+ turns from the grip above it. The export frame keeps its shape when the
+ camera turns, and exports upright as drawn.
+- Difference's settings stay put through a read, lie over the highlights, and
+ close on a click outside them.
+
+## Layers from elsewhere
+
+- Open a KML, KMZ, GeoJSON or GPX file as a map layer, or follow a public Google
+ My Maps or map URL. It keeps its own colours and, if you ask, its own icons,
+ with a legend that filters and a search that jumps to a feature. A layer lives
+ in the case and travels in bundles; its features never become case entities.
+- Add a **GeoConfirmed** conflict over a span of days or dates, or its whole
+ history, optionally only the current view. Events carry GeoConfirmed's own
+ icons, are grouped by faction, and link to their sources and geolocation.
+- Narrow a dated layer (GeoConfirmed, timestamped KML, GPX waypoints) to a period
+ dragged on a strip of its events or picked on a calendar.
+- Added layers start switched off after a reload, so a layer heavy enough to
+ crash the tab cannot do it twice.
+- The map panel opens on its Layers tab. Its Saved tab shows one position at a
+ time: Media, then Places, then Captures. Media draws the case's photos and
+ videos where a relation, a GPS reading or a proof places them, and plays them
+ beside the imagery.
+
+## Proofs
+
+- Turn or crop a panel or an overlay without touching its source. Annotations
+ stay on the same pixels.
+- Stamp numbered markers, counted per colour, and blur boxes that hide what is
+ under them.
+- A proof can carry one sentence, used as its notes and to write the post, and
+ the date its material was taken. That date shows on the Timeline and is stated
+ for the original footage, never for a frame cut from it.
+- Place any point of a proof on a map instead of typing it. Each panel keeps its
+ own point.
## Elsewhere
-- The app opens on **Home**: what is left to do in the case, what was filed
- recently, and the case's points on a small map. With no case open, it explains
- what Azimut is and helps you start one.
-- A **Guide** with one section per tool and a few worked examples. The `?` in the
- top bar opens it on the tool you are using.
-- New case folders keep the name you typed, spaces, accents and non-Latin scripts
- included, instead of a lowercase ASCII version of it.
-- The Media Library no longer lists satellite captures and extension screenshots by
- default. Satellite's Saved panel is where they live, and the library's switch
- still shows them.
-- Auto-stitch sizes the collage canvas to the panorama instead of shrinking it to
- fit, and you can set the canvas size by hand.
-- In Geo Proof, a shape you just drew stays selected so you can restyle it straight
- away. The stamp tool stays in hand for marking several things in a row.
-- Sheets are listed newest first.
+- **To-do lists** on Home: named lists of tasks with a progress count, saved with
+ the case and carried in bundles.
+- One date field across the app. Type a day, a month, a year, a time or a range,
+ or build it from a calendar with how sure you are. It says what it understood.
+- File a claim straight from Details, a Board row or a Graph node, with that
+ entity already filled in.
+- Send a picture to Reverse Search from a Media Library row (**Open in…**), or an
+ Inspect frame as cropped, saved or not.
+- A claim is called a claim everywhere. Every icon button has a tooltip, a layer
+ that cannot be switched on says why, Home lists recent work first, and Coords &
+ Sky opens on the point the map is showing.
+- Over another map site, the extension's points tool draws one position at a
+ time, like the app. Its media windows take files up to 512 MB.
## Fixes
-- Thumbnails and metadata enrichment no longer stop for the rest of the session
- when the background worker dies unexpectedly.
-- Naming a proof's first point, or marking it as the camera position, is now saved
- when its coordinate field was left empty.
+- Geo Report's map links read as site names, in the app and in the saved
+ Markdown note, instead of internal ids.
+- A tab left open across an update no longer asks for interface files that are
+ gone.
+- A video's thumbnail no longer goes missing when the background worker reaches
+ it before the file's details are written.
+- The Guide describes Inspect's actual tabs, and sends you to the Layers tab for
+ overlays.
+- On Windows, moving the workspace or saving settings no longer fails when an
+ antivirus or the search indexer briefly holds the file.
+- The Wayback map no longer slows down while you pan. Its picker lists every
+ release, and **Changes here** reads a point's history only when you press it.
## Install or upgrade
@@ -86,11 +120,10 @@ On Intel Macs (macOS 14 or newer), install the Python package instead:
The downloads are unsigned, so your system will warn you the first time. The
README explains the prompt for each platform.
-Firefox users download the signed `azimut-capture-0.3.0.xpi` attached to this
-release, then open `about:addons` and choose the gear menu → **Install Add-on
-From File**. Pair it with the token shown in Settings → Capture extension.
-Chrome, Edge and Brave users install or update the extension from that same
-Settings page.
+The capture extension changed in this release. Chrome, Edge and Brave users
+update it from Settings → Capture extension. Firefox updates the signed add-on by
+itself; a new install uses `azimut-capture-0.3.1.xpi` attached to this release,
+opened from `about:addons` → gear menu → **Install Add-on From File**.
Your existing cases open as they are. No export, migration or manual step is
needed, and older case bundles still import.
diff --git a/docs/SPEC.md b/docs/SPEC.md
index 46dff3c..0d62282 100644
--- a/docs/SPEC.md
+++ b/docs/SPEC.md
@@ -59,7 +59,7 @@ azimut/ # everything Azimut owns; the rest of the folder is yours
.drafts/ # post drafts
.inspect/ # saved Inspect session specs
.compare/ # saved Compare session specs
- .analysis/ # Detect areas, watches, runs and the frames behind their results
+ .analysis/ # Detect areas, saved detections, runs and the frames behind their results
.search/ # saved Grid Search state
.layers/ # added map layers: spec + source as received + its icons; .cache/ is derived
.trash/ # recoverable artifact payloads, in numbered slots
@@ -174,11 +174,13 @@ proof for publication.
| ✅ **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. |
| ✅ **Media on the map** | Draws the case's located photos and videos where a relation, a GPS reading or a proof puts them, opens the Map panel, the home map and the extension on them, and plays the stack in the panel beside the imagery. |
-| ✅ **Imagery Wayback** | Browses every Esri World Imagery release, narrowed to the ones that changed the point, and dates the pixels apart from the release. |
+| ✅ **Imagery Wayback** | Browses every Esri World Imagery release, narrowed on request to the ones that changed the point, and dates the pixels apart from the release. |
| ✅ **Satellite Compare** | Aligns and annotates two dated views, assists matched-product change reading, saves editable sessions and files or exports attributed PNG/GIF outputs. |
-| ✅ **Compare Detect** | Sweeps drawn areas of Copernicus Sentinel-2 at native resolution for vessels, fires and flares, construction, small spots, burn scars, vegetation loss and new water, at a small, medium or large target size; candidates come strongest first, one at a time, and only a kept one becomes a case pin. |
+| ✅ **Detect sweep** | Native Sentinel-2 detectors, mask footprints, manual candidates and Keep / Dismiss / Pin review with PNG evidence stamped with its dates and point. |
| ✅ **Passes over an area** | Picks Detect's Copernicus dates from the passes the drawn areas really have, each with the share of them its swath reached, and reports what a finished run actually swept. |
| ✅ **Cloud & shadow filter** | One click in Difference and Detect, both on Sentinel-2's scene classification: unsure edges taken, classified "clouds" too small to be one dropped, and shadows cast away from the sun, including the ones the classification read as water. |
+| ✅ **Difference over any view** | A switch beside Compare's four views, offered on a matched pair only, laying its highlights on A, B or both (the default). |
+| ✅ **Detect** | Map-first tab, collapsible dock, shared case areas reshaped in place, an A/B When step with per-area dates, one-off and routine runs grouped in Saved, repeat notices and explicit SAT layer snapshots. |
| ✅ **Capture scale & north** | Adds a scale bar and true-north needle to app and extension captures when resolution and heading are known. |
| ✅ **Footprint tracing** | Traces a place's uncertainty as a polygon around its pin, in place of the radius. |
| ✅ **Extension map tools** | Draws measure, the case's points one position at a time, sun and moon, search grids and case media over third-party maps, calibrated per site by a replayable command. |
@@ -186,12 +188,17 @@ proof for publication.
| ✅ **Site hand-offs** | Fills the X or Bluesky composer with a prepared thread and uploads a case picture straight into Lens, Yandex, Bing or TinEye. |
| ✅ **Home & Guide** | Opens on a case dashboard or a front door when no case is open, and `?` opens the Guide on the current tab. |
| ✅ **Case to-do lists** | Named lists on Home with editable tasks, checkboxes, progress counts and case-bundle persistence. |
-| ✅ **Compare from the ground** | Right-clicking a point opens Compare on the last two Esri Wayback pictures of it, or on its last two Copernicus passes. |
+| ✅ **Compare from the ground** | Right-clicking a point opens Compare on the last two Esri Wayback pictures of it, its last two Copernicus passes, or its last two radar passes of one track. |
| ✅ **Marks that number and hide** | Stamps numbered markers counting a series per colour, and blur boxes that redraw the picture under them, on a proof's panels and on a comparison's ground alike. |
| ✅ **A date in one field** | Reads a day, a month, a year, a time or a range from one line of text, or builds one from a calendar with its marks of doubt, and says what it understood. |
| ✅ **Words that hold still** | One name for a Claim on every surface, a tooltip on every icon, a stated reason on a layer that cannot be switched on, the recent work first on Home, and Coords & Sky opening on the point the map is on. |
| ✅ **A picture sent to Reverse Search** | Opens Reverse Search on a Media Library file, from a row's Open in… menu, or on an Inspect frame as it is cropped, saved or not. |
| ✅ **A claim from where you are** | Files a claim from Details, a Board row or a Graph node with the entity already seated, asking a count and a condition where its family calls for them and writing the sentence from the fields. |
+| ✅ **Radar Detect** | Five Sentinel-1 analyzers (vessels, any change, razed buildings, new structures, floods) through the user's own radar layer, calibrated on real scenes, held to one track. |
+| ✅ **Sentinel-1 basemap** | Radar passes as a dated basemap in Satellite, Compare and Detect, named by day, UTC time and direction. |
+| ✅ **All dates** | Lists every dated picture of the point in Compare and narrows down, a question at a time, between which two a change appeared. |
+| ✅ **Copernicus where it is needed** | Detect and Compare say in the middle of the tool what Copernicus still lacks, with the free account, the Sentinel-2 configuration and the Sentinel-1 layer form field by field. |
+| ✅ **A candidate in Compare** | Opens a Detect candidate in Compare on the passes that found it, or against high-resolution imagery for a thing present on one pass. |
---
@@ -312,6 +319,8 @@ stops making sense.
- **In-app OSINT assistant:** local chat and vision suggestions for analyst confirmation, with no cloud or API key by default.
- **Geographic playback:** step through dated case items on the map instead of showing one fixed Timeline window.
- **More on the home page:** the case's own notes beside the tiles, and panels the analyst arranges rather than a fixed grid. Each has to earn its place there rather than beside Board, Graph and Timeline, which already read the case.
+- **Radar damage from a stack of passes:** the pixel-wise t-test (PWTT) over a year of passes before and weeks after, which two passes cannot match.
+- **Oil slicks by radar:** dark patches on the sea near anchorages and lanes, which Sentinel-1 shows through cloud.
- **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.
## 8. Explicit non-goals
diff --git a/docs/STORAGE_AND_PERFORMANCE.md b/docs/STORAGE_AND_PERFORMANCE.md
index 4b5f39a..a70f296 100644
--- a/docs/STORAGE_AND_PERFORMANCE.md
+++ b/docs/STORAGE_AND_PERFORMANCE.md
@@ -109,7 +109,7 @@ for a case to fit under it on Windows, and names it as a warning elsewhere.
.drafts/ # post drafts
.inspect/ # saved Inspect session specs
.compare/ # saved Compare session specs
- .analysis/ # saved areas, watches, runs and the frames behind their results
+ .analysis/ # saved areas, saved detections, runs and the frames behind their results
.search/ # saved Grid Search state
.trash/ # deleted artifacts grouped by delete action, in numbered slots
```
diff --git a/docs/UI.md b/docs/UI.md
index 8ab4a3b..6ba6b80 100644
--- a/docs/UI.md
+++ b/docs/UI.md
@@ -23,7 +23,7 @@ in `frontend/src/lib/workspaces.js` and appear as tabs, never as new rail entrie
| **Case** (topbar) | Board, Graph, Timeline, Sheet | v5: Orchestrator |
| **Sources** | Media Library, Files, Reverse Search | Channel Monitor, Evidence Locker |
| **Examine** | Inspect (Selection / Frame / Collage / Analyze) | Edit Provenance, Shot contact sheet, OCR, Image Compare, Hints, Sky Clock, audio |
-| **Map** | Satellite, Compare, Coords & Sky | Imagery Wayback, Event layers, Ground Imagery, Measures, Viewshed, OSM Query, Map Board |
+| **Map** | Satellite, Compare, Detect, Coords & Sky | Imagery Wayback, Event layers, Ground Imagery, Measures, Viewshed, OSM Query, Map Board |
| **Compose** | Geo Proof, Geo Report, Notebook | Report Builder, GIF maker |
**Case is not on the rail.** The rail reads as a sequence of stages, and the case is
@@ -1219,52 +1219,88 @@ remote ids in provenance instead of appending them to the visible name.
## Map
-**Compare assembles two imagery views on one camera.** It starts with empty A/B
-slots and loads tiles only after a source or a starting pair is chosen. Each
+**Compare assembles two imagery views on one camera.** It opens on the home view
+with a key-less pair: an Esri Wayback release published a year or more back on A,
+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
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. The
+for Wayback and for Sentinel-2, 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
side's FIRMS period, VIIRS night and saved case work.
-The mode dock holds two kinds of choice, in two named groups. **View**: 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. **Analysis**: **Difference** and
-**Detect**, each marked when it cannot run yet — Difference when the two sides are
-not a matched pair, Detect when Copernicus credentials are missing — with the
-reason as its tooltip and, for Detect, at the head of its own panel beside a way
-into Settings. Detect still opens, because the areas and runs already saved are
-read there. Keys 1–6 switch modes; Space pauses blink. Dragging, zooming or rotating either
+The mode 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.
+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.
-Each computing mode owns the same column beside the stage: the maps narrow rather
-than being covered, and the dock above is the only switch between the two. Leaving
-the mode closes the column.
+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
+the starting pairs once the radar layer is set. Compare works without
+Copernicus, so nothing is said until a Copernicus road is asked for: the
+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
+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
+Wayback releases that changed the point, free. A press shows a picture on B,
+Alt-press or its own A button shows it on A. A Sentinel-2 day over the cloud
+ceiling and a radar pass off the pair's track are greyed. **Show pictures** draws
+each one small from the tile proxy, priced before it is pressed and cached once
+read, and a view that moved says so rather than refreshing on its own.
+
+**Date it** answers "between which two pictures did this appear". With a picture
+without the thing on A and one with it on B, A the older, it shows the middle
+picture between them on B and asks: *It is there*, *Not yet*, or *Can't tell* for
+cloud or a look that settles nothing. Each answer halves what is left, so a year
+of passes takes a handful of looks, and Undo takes one back. It ends on a
+sentence to copy — absent on one date, present on the next, and how many
+pictures between them could not tell.
+
+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
+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.
Colour, structure and brightness methods read captured pixels in a worker.
+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 footer as an earlier read, until Run. A changed view must be run again before
+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.
-These viewport captures depend on display resolution and zoom. Use **Detect**
-for a fixed analysis grid across camera changes.
-**Highlights over** sits above the tabs and says what the reading is laid on: A
-alone, B alone, or both images side by side with the same mask on each — the one
-arrangement that shows what a change went *from* and *to* at the same time. The
-eye beside the title hides the overlay, and **Blink** flashes it on and off,
-because a thin highlight over busy imagery is easier to catch moving than still.
-**Clouds & shadows** sits beside it, one click, because cloud is the first thing
+These viewport captures depend on display resolution and zoom. Use the Detect
+tab for a fixed analysis grid across camera changes.
+The strip's **A / B / Both** says which images carry the highlights, in any view;
+Both is the default, because it shows what a change went *from* and *to* at the
+same time. **Blink** flashes the highlights on and off, because a thin highlight
+over busy imagery is easier to catch moving than still. Turning Difference off
+in the dock takes the highlights away.
+**Clouds & shadows** opens first in the settings, one click, because cloud is the first thing
that goes wrong in a reading. It gives Detect's answer, not a guess: Sentinel-2's
scene classification, grown into the unsure pixels around a real cloud, with
classified "clouds" too small to be one ignored and each cloud cast away from the
@@ -1288,104 +1324,6 @@ area and selectable change zones describe the result, each zone carrying the sam
strength word a Detect candidate does: how far past the line it got. These are candidate pixel
changes for inspection, not confirmed changes to objects.
-**Detect** sweeps a drawn area of Copernicus Sentinel-2 at native resolution and
-keeps what it found. Every detector measures reflectance bands, which a rendered
-picture has already stretched away, so Wayback has nothing to give it. Setup reads
-as three numbered steps, in the order the work happens: an area, the imagery, then
-what to look for.
-
-Step 1 draws rectangles, polygons or circles, or takes the current view as a
-rectangle in one click, and prices the result before anything is fetched: ground
-area, native tiles, Copernicus requests and roughly how long. Each date costs two
-requests a tile, the picture reviewed and the bands measured. A named area set can be
-saved for this case and reused. An area is grabbed by its edge: dragging inside
-one pans the map as it would anywhere else, a click on the edge shows its corner
-handles, and a press that does not travel selects without nudging the geometry.
-Handles and outlines are projected from the ground, so they stay on it through a
-pan, a zoom or a turn.
-
-Step 2 and the stage share one imagery between them, so what is on screen is what
-a run would sweep. On arrival the maps lead, because what is above the stage is
-usually what you came to analyze. From the first change made here — or straight
-away when the maps show anything but Sentinel-2 — the direction reverses and
-the maps follow this step; the A/B source cards step aside while Detect is on, so
-there is one place to choose imagery rather than two. An analyzer that reads one
-date shows one map, because there is no pair to compare. The run is blocked, with
-the reason, until each image it needs is named.
-
-On Copernicus, dates are picked from the passes the drawn areas actually have,
-not from a calendar. **Find passes** asks the catalogue once, over the whole set
-of areas at once, and lists what came back newest first with the two facts that
-decide between them: how much of the areas that day's swath reached, and how much
-of it was cloud. Sentinel-2 flies 290 km swaths on a five-day revisit, so a wide
-area can have no single day covering all of it; a partial date can still be
-chosen, and the panel says what share will be left unswept before the run rather
-than after it. A finished run reports the share it really read, so "nothing
-found" and "never looked" stay different answers. The lookup is billed as one
-Copernicus request and never runs on its own.
-
-Step 3 picks the analyzer. Eight ship built in, for big things and small ones:
-vessels, fires and gas flares, construction and earthworks, small spots (impacts,
-burn marks, vehicles), any surface change, burn scars, vegetation loss, and
-flooding or new water. Each reads its own band product, and each was tuned on real
-scenes rather than synthetic ones: rough sea under glint, a dense anchorage under
-cumulus, oil fires and wildfires, bright roofs, a construction site across seven
-months, dry-season pastures. Vessels stand out from their own patch of sea in near
-*and* short-wave infrared, which a breaking wave does not, and a candidate joined to
-bulk land is a coast. What counts as sea comes from the water index or from the
-classification, either one is enough: under sun glint the index alone read a whole
-strait as dry. Fires take the published short-wave ratios on B8A, which
-shares B12's grid. Construction is ground that moved the same way in every band
-while its vegetation held; a small spot changed while the ring of ground around it
-did not, that ring read with a hole in its middle so the spot cannot sit in its own
-background and over measured ground only, so a granule edge raises nothing; a burn has to end dark, which a dried pasture does not.
-
-**Small**, **Medium**, **Large** and **All** under the analyzer set the target
-size as a whole: floor and ceiling area, cleanup and grouping together, since a
-small target needs no cleanup that would erase it. What the chosen one accepts is
-written under the buttons in ground terms — a mark outside that band is found and
-then dropped, which reads as "nothing found" unless it is said. **All** sets no
-floor and no ceiling, for the mark that falls between two bands. Tuning any of
-those by hand leaves no size selected. The **Clouds & shadows** switch reads Sentinel-2's classification, grows a
-real cloud into the unsure pixels touching it, ignores classified "clouds" too small
-to be one (white hulls and roofs), and casts each cloud away from the sun to find the
-shadows the classification missed. The fire detector offers no switch: its band
-ratios reject cloud already. Thresholds and the analyzer itself open from links
-rather than sitting in the way. The **+** beside the analyzer starts one of your
-own, either as a copy of the one in hand or from scratch; a built-in can be read
-and copied but never written over, and an analyzer of your own can be saved,
-renamed or removed from there. The library is shared by every case.
-
-A **watch** keeps an analyzer, its areas and a date rule together, and
-**Run again** in Saved launches a fresh pass — a weekly harbour review is that
-button, not a background schedule.
-
-**Run** explicitly starts a bounded, cancellable job, up to 4096 native tiles.
-The native analysis grid is independent of map zoom. Opening the panel or
-reopening a saved run reads local state only. Offline runs read only the tile cache and the frames earlier runs
-kept, and a finished run keeps only the tiles that found something — so an
-offline rerun covers what the cache still holds, not the whole of a past sweep.
-Resolving the latest date requires a provider request at run time. Runs preserve their own input snapshots,
-candidate evidence and review state. A finished run keeps the frames of the tiles
-that produced a candidate and drops the rest, so a case grows with what was found
-rather than with how much was swept.
-
-What a sweep produces is a list of candidates, strongest first, and nothing else
-reaches the case on its own. Each says how strong it is in a word (weak, clear or
-strong: how far past its threshold it got) and what was measured in units a reader
-can check, such as "6.2× brighter than the water around it" or "NBR 0.61 → −0.28".
-A candidate that crosses a tile edge is one candidate with one picture, stitched
-from the tiles it touches. Review them one at a time: **Keep as a pin** files that one candidate,
-with its own copy of the evidence and its provenance, and is the single act that
-writes to the case; **Dismiss** takes it off the map. Either verdict moves to the
-next candidate still waiting, and a running tally says how many are left. Keeping
-can be undone, which sends the pin and its evidence to Trash. Evidence is enlarged
-by a whole-number factor with no interpolation, so a candidate a dozen pixels
-across can be read without pretending to detail the sensor never recorded. Each
-result layer has its own eye control, and the one under review wears a ring on the
-map. Areas and candidates belong to Detect and are drawn only there; a kept
-candidate is a pin, and pins show wherever case work shows.
-
Annotations store longitude/latitude points and stay on their ground through pan,
zoom and rotation. Notes, arrows, boxes, ellipses, lines, freehand strokes, distance
measures, polygons, **numbered markers and symbols** can belong to A, B or both.
@@ -1398,6 +1336,10 @@ with a double-click or Enter; Escape cancels. Select a mark to move it or edit i
double-click a note to edit its text, and use Undo/Redo for annotation changes. A
selected mark shows its corner handles, so its geometry is corrected where it was
drawn rather than deleted and redrawn; a note is dragged whole and has none.
+A box or an ellipse drawn on a turned map runs along that screen, not along north,
+and keeps the bearing it was drawn at. Any selected shape but a note or a stamp
+also shows a round grip above it: drag it to turn the shape about its centre,
+with Shift snapping to 15°.
Every mark carries a wide invisible band along its outline, because a four-pixel
arrow is a target nobody hits twice. The wheel still belongs to the map wherever
the pointer is: the marks are drawn over it rather than in it, and a zoom that
@@ -1418,12 +1360,13 @@ offers for its own rails are left out rather than shown dead.
**Save comparison** writes the editable version-2 session under `.compare/` and
updates its rendered media preview in My work (PNG, or GIF for blink). A preview
used by a derived proof is preserved when a later save creates new pixels.
-**Open** restores the sources, layers, camera, reading mode, blink speed, detection
-settings, annotations and the optional export frame; Detect is a place to work rather
-than a way to read the pair, so a session saved from it reopens side by side and its runs
-stay in the case. Export writes an attributed PNG, blink GIF or divider-sweep GIF to the
+**Open** restores the sources, layers, camera, view, the Difference switch, blink speed,
+detection settings, annotations and the optional export frame; a session saved while
+Difference was a view of its own reopens side by side with Difference on. Export writes an attributed PNG, blink GIF or divider-sweep GIF to the
shared Views destination; an optional ground-anchored frame cuts any of the three to the
-chosen area, while Full view remains the default. Copy current PNG uses the clipboard.
+chosen area, while Full view remains the default. The frame keeps the bearing it was
+drawn at: turning the camera turns it with the ground rather than reshaping it, and
+the export comes out upright as it was drawn, once all four corners are in view. Copy current PNG uses the clipboard.
Exports include projected annotations, a scale bar and north arrow. 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.
@@ -1565,6 +1508,14 @@ which it is (`lib/map/tools.js`) rather than adding a button somewhere.
property of that map and not of the tool, which is what lets two surfaces sit
side by side each saying its own.
+**Sentinel-1 radar** is a basemap once Settings → Imagery has found the radar
+layer of the analyst's Copernicus configuration. Its chip names a pass by its day
+and its UTC time, with an arrow for the way the satellite flew: dawn passes fly
+south, dusk passes north, and the two see a place from opposite sides. The picker
+reads a month of passes at the crosshair when it opens, one request a month, and
+keeps what it read. The picture is the dual-polarisation composite Detect reviews
+radar candidates on: water dark blue, vegetation grey-green, walls and hulls white.
+
A capture can carry a **scale bar and a north arrow**, ticked in the capture
menu: the bar bottom-left in the analyst's own units, the needle top-right,
turned so it points at true north on a map that was rotated. Off until asked
@@ -1802,31 +1753,29 @@ holds something Save has not taken, since the panel opens on what the case holds
**Esri Wayback is a basemap of every World Imagery release.** Picking it puts a
chip beside the provider naming the release on screen, and the chip opens a
slider through time, oldest left, with a step either way and the list under it.
-The list opens on **Changes here**, and so does the slider: only the releases
-that brought a new picture of the tile under the crosshair. Esri's tilemap says
-which release a tile really comes from, and walking it backwards shortlists the
-candidates; a picture Esri published again, re-encoded or re-coloured, is folded
-into its first publication by comparing the tiles themselves, then the
-acquisition date and satellite their metadata states. Each row carries its
-release date and, beside it, when the picture was taken; the pill under the chip
-dates the pixels on screen the same way. Narrowed to changes, the newest release
-is named by the change it shows rather than by a date no row carries. **Every
-release** lists all of them, where neighbours often look identical because
-nothing changed there.
-
-**Opening the picker once makes the history follow the map.** Every view that
-settles over another tile reads that tile's history from then on, picker open or
-shut — gating that on the picker *staying* open was the bug behind a picker that
-re-opened on wherever the analyst had been before. A tile already read costs
-nothing, and a tile Esri refused is left alone until **Refresh** is pressed, so
-panning never hammers a service that is down. A first history takes some seconds
-(Esri's metadata service is slow) and the picker offers nothing while it comes,
-since every release is not what *Changes here* was asked for; the changes it
-already has stay on the slider while the next tile's are read. **The chip itself
-says it is waiting**, spinner and all, because both reads run with the picker shut
-and a basemap that answers nothing for ten seconds without saying so reads as a
-broken one. A history that
-fails falls back to every release, which is the honest answer to not knowing.
+The list opens on **Every release**, dated by publication from the one release
+list Esri serves; the pill under the chip dates the pixels on screen, one
+metadata request for the release showing. Neighbours often look identical,
+because Esri republishes a mosaic where nothing changed.
+
+**Changes here narrows the list to the releases that brought a new picture of
+the tile under the crosshair.** Esri's tilemap says which release a tile really
+comes from, and walking it backwards shortlists the candidates; a picture Esri
+published again, re-encoded or re-coloured, is folded into its first publication
+by comparing the tiles themselves, then the acquisition date and satellite their
+metadata states. Each row then carries, beside its release date, when the
+picture was taken. Narrowed to changes, the newest release is named by the
+change it shows rather than by a date no row carries. **Imagery history here**
+on the point menu reads the same history at the point right-clicked.
+
+**A history is read only when asked for.** The walk is dozens of requests and
+takes some seconds, so a moving map never starts one: a history that no longer
+describes the tile under the crosshair says so, keeps its changes on the slider,
+and offers **Read here**. A tile already read costs nothing for the session.
+The picker offers nothing while a first history comes, since every release is not
+what *Changes here* asked for, and **the chip itself says it is waiting**,
+spinner and all, because the picker can be shut meanwhile. A history that fails
+falls back to every release, which is the honest answer to not knowing.
The release rides on the provider id (`esri-wayback~64776`), so tiles are cached
and captures credited under it.
@@ -1841,8 +1790,9 @@ or a zoom that moves the ground from under it.
**Compare here…** asks an archive which two pictures of *this point* are the
last two, and opens Compare on the pair: Esri Wayback for the two releases that
-changed it, Copernicus for the two most recent passes over it, the second only
-where a key for it is in Settings. The lookup happens before the tab changes, so
+changed it, Copernicus for the two most recent passes over it, and Copernicus
+radar for the newest pass and the one before it on the same track. The last two
+are offered only where Settings has what they need. The lookup happens before the tab changes, so
an archive that holds nothing to compare says so on the map instead of costing
the view. It says it is working for as long as it takes rather than for a guessed
few seconds: the walk through Esri's releases is slow, and a message that went out
@@ -1910,6 +1860,267 @@ without a reload, and the same the other way round. A sweep worked from both
keeps both hands' marks: what is written is the cells that were marked, never the
grid around them. A grid discarded elsewhere closes here and says so.
+## Detect
+
+**Detect sweeps ground and comes back to it.** It is its own tab rather than a
+mode of Compare, because it is a different job: Compare reads two pictures side
+by side, while Detect watches an area of Copernicus Sentinel-2 or Sentinel-1 over time. One map
+is enough for that — a candidate's evidence is the before/after picture the column
+shows, not a second surface — so the map is the ground you draw on and the pass you
+are about to read, and the column beside it holds the work. Every detector measures
+reflectance or backscatter, which a rendered picture has already stretched away, so
+only Copernicus feeds it: Sentinel-2 for the optical analyzers, Sentinel-1 for the
+radar ones.
+
+Without a Copernicus key, Detect says so in the middle of its map: the account is
+free, the recipe is there in two parts — the Sentinel-2 configuration whose ID is
+the key, which brings its layers with it, and the Sentinel-1 layer added to it by
+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. A case
+with no area opens on the home view. The search, the compass and SAT's
+imagery/layer controls float over the map. There is no Detect header or
+full-width bottom strip. Attribution stays in the map's corner and the scale stays
+at bottom left; provider usage is a small chip beside the imagery selector. A pass
+date appears only while reading that pass, and run status stays in the panel.
+Leaving a pass restores the chosen basemap.
+
+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 `]`
+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
+map's own layer list, beside Saved work.
+
+Areas belong to the case. Each has a name, colour and polygon; its map label
+appears when there is room, in the area's own colour. An area is grabbed by its
+outline, like a drawn mark in Compare: inside it the map is still the map, so the
+wheel zooms, a drag pans, and a middle- or shift-drag turns it about the point
+grabbed, as on every other map in the app. Pressing an outline opens Areas, where
+a row reads as the map draws it: colour, name, ground area and how many routines
+use it. Pressing the row frames it, the eye hides it, and renaming, recolouring
+or reshaping opens from the row's pencil rather than sitting in it. **Reshape on
+the map** frames the area and puts its corners under the pointer; the panel says
+how many routines watch it, since a routine reads its areas when it runs and its
+next run sweeps the new shape, while a finished run froze its own copy and keeps
+the ground it swept. **Save as a new area** leaves the old one, and the routines
+on it, as they were. The tab also draws or takes the current view, shows every
+area at once, and deletes. Deleting an area used by a routine lists the routines
+that must release it first. A routine and a one-off run can share an area.
+Older routines migrate their embedded zones to shared areas on first read.
+
+The list holds two kinds, and **New detection** asks which before asking anything
+else, because the answer changes every question after it:
+
+- a **one pass** sweeps each area's chosen or latest pass, once. It appears in
+ **Saved**, under **One passes**, below the runs of each routine gathered under
+ its name. Every finished run is drawn on the map from the start; the eye beside
+ its trash hides or shows it, the one on a group's heading does the whole group,
+ and showing frames the ground it covers. The layers button beside them snapshots
+ what was kept or pinned into a SAT layer, a routine's heading into its one layer;
+ a run with nothing kept says so and stays greyed. A group folds shut from its heading.
+- a **routine** is a place you come back to. It keeps its areas, its analyzer and
+ what each pass compares against; it is run again whenever there is a new pass,
+ and it remembers what it found.
+
+A routine's card carries what it is for, its analyzer, its areas, its rule and
+where its last run stands: the day of the pass it swept and how many candidates
+are still to review, or how far a working one got. The play button opens the launch
+table, **Run all** queues idle routines with their saved rules, and the title
+opens the routine's own page. **Analyzers** is where the things a detection looks
+for are made.
+
+An open routine or run is drawn once, in each area's own colour, by the same
+read-only overlay the list uses; the editable canvas belongs to the wizard and the
+Areas tab. Hovering a routine draws its areas heavier.
+
+A routine's page leads with **Findings**: every candidate it has kept, as a pin or
+just here, newest run first, each marked **Pinned** or **Kept here** and a press
+away from the evidence it came from. **Runs** beside it lists its passes, each
+opening its own review. **Run routine** opens a floating table with a row for each
+area, its A and its B (the newest pass by default), each read and written as the
+app's own day-first date field. One button queues the run, naming what it covers.
+The page also offers **Export as layer**, editing and deletion.
+
+Either kind is built one step at a time: **Where**, **What**, **When**, then
+**Start**. Only the current step shows, the next one opens once this one has what
+it needs, and the reason it is not ready yet is written under the Next button.
+Editing a routine opens on the last step, which reads the whole thing back with
+each line a way into its step. Both kinds carry a name and a line saying what they
+are for, and that line travels with every run they make.
+
+**Where** offers the case's own areas first, as chips in their colours that toggle
+in and out of the detection; drawing rectangles, polygons or circles, or taking the
+current view as a rectangle, is for ground the case does not watch yet. It prices
+the result before anything is fetched: ground area, native tiles, Copernicus
+requests and roughly how long. Each date costs two requests a tile, the picture
+reviewed and the bands measured. A radar vessel sweep adds one for the Sentinel-2 water
+classification it is judged against. One-off drawings stay temporary unless **Save as area** is pressed;
+saving a routine promotes its drawings. Legacy area sets remain readable. An area is grabbed by its edge: dragging inside
+one pans the map as it would anywhere else, a click on the edge shows its corner
+handles, and a press that does not travel selects without nudging the geometry.
+Handles and outlines are projected from the ground, so they stay on it through a
+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,
+**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,
+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…**
+opens the per-area table for areas far enough apart to sit under different swaths,
+and the step then lists each area's days. The last step reads the choice back in
+one line. A radar pass is a day and a UTC time,
+since Sentinel-1 can see a place twice in a day from opposite directions: the list
+shows each pass with its time and direction, and A and B must share
+a track, so the rows on the other track are closed to the pair. A day typed by
+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. 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.
+
+**What** picks the analyzer from a list grouped by what it looks for — vessels,
+fires and burns, water and floods, buildings and earthworks, vegetation and small
+marks, any change — with radar first where it reads the same thing better, and
+your own after them. Each built-in says in brackets how far its reading can be
+trusted, from what calibration showed: *reliable* (the published test, or a
+contrast few false hits survive), *approximate* (right more often than not, with
+known look-alikes) or *rough* (a lead to check). Radar vessels are reliable and
+optical ones approximate, since a hull answers the radar through cloud and glint
+alike; two radar passes read damage roughly. An analyzer that cannot run yet
+carries a key and *set up*: all of them without a Copernicus key, the radar ones
+until Settings has found their layer. It can still be picked and read about, and
+the step says what is missing with a way to Settings. Eight ship built in, for big things and small ones:
+vessels, fires and gas flares, construction and earthworks, small spots (impacts,
+burn marks, vehicles), any surface change, burn scars, vegetation loss, and
+flooding or new water. Each reads its own band product, and each was tuned on real
+scenes rather than synthetic ones: rough sea under glint, a dense anchorage under
+cumulus, oil fires and wildfires, bright roofs, a construction site across seven
+months, dry-season pastures. Vessels stand out from their own patch of sea in near
+*and* short-wave infrared, which a breaking wave does not, and a candidate joined to
+bulk land is a coast. What counts as sea comes from the water index or from the
+classification, either one is enough: under sun glint the index alone read a whole
+strait as dry. Fires take the published short-wave ratios on B8A, which
+shares B12's grid. Construction is ground that moved the same way in every band
+while its vegetation held; a small spot changed while the ring of ground around it
+did not, that ring read with a hole in its middle so the spot cannot sit in its own
+background and over measured ground only, so a granule edge raises nothing; a burn has to end dark, which a dried pasture does not.
+
+Five radar analyzers read Sentinel-1 through the layer Settings → Imagery found,
+and see through cloud and at night: vessels, any radar change, damaged or razed
+buildings, new structures and vehicles, and flooding. They were calibrated on real
+scenes: the Singapore anchorage, the Dover Strait, the North Sea in the October
+2023 storms, the Belgian wind farms, the Bosphorus, Port Sudan's desert coast, the
+May 2023 Emilia-Romagna floods and Gaza City before and after late 2023. A hull
+has to stand out of the sea around it in both polarisations, which a strong
+target's ghosts and sea spikes do not, and a weak return beside a much stronger one
+is taken for its sidelobe. What counts as sea is Sentinel-2's own water class on
+the clearest pass of the year before, because dry desert is as radar-dark as calm
+water; the radar decides only where that pass saw cloud. A radar change is the
+power of both polarisations averaged over the size's window and compared between
+two passes of one track; *bright* ground is ground that answered like walls on the
+side that had them, and *water* is ground that went as dark as calm water. Two
+passes only flag where to look: the razed-buildings analyzer says so, and the
+flood one starts at Large, since a flood is fields wide. Without the radar layer
+the wizard says where to find it and stops before its dates.
+
+**Small**, **Medium**, **Large** and **All** under the analyzer set the target
+size as a whole: floor and ceiling area, cleanup and grouping together, since a
+small target needs no cleanup that would erase it. What the chosen one accepts is
+written under the buttons in ground terms — a mark outside that band is found and
+then dropped, which reads as "nothing found" unless it is said. **All** sets no
+floor and no ceiling, for the mark that falls between two bands. Tuning any of
+those by hand leaves no size selected. The **Clouds & shadows** switch reads Sentinel-2's classification, grows a
+real cloud into the unsure pixels touching it, ignores classified "clouds" too small
+to be one (white hulls and roofs), and casts each cloud away from the sun to find the
+shadows the classification missed. The fire detector offers no switch: its band
+ratios reject cloud already. Thresholds open from a link rather than sitting in
+the way, and tuning them there changes this detection only.
+
+**Analyzers** lists the built-ins and your own, shared by every case. An analyzer
+is one calibrated method and how picky it is, so one of your own starts as a copy
+of the closest built-in: **New analyzer** asks what to start from, and the copy
+keeps that method while its name, sizes, thresholds, candidate label and colour
+become yours. A built-in opens read-only with **Copy to tune**; your own can be
+edited or removed from the list. A detection being built keeps its place while the
+library is open, and an analyzer saved from there comes back picked.
+
+**Start** names it, says what it is for, and runs it: **Run this pass** for a one
+pass, **Save and run the first pass** for a routine, which can also be saved
+without running. Every run explicitly starts a bounded,
+cancellable job, up to 4096 native tiles, and joins the case's queue: runs go one
+after another, and only the same detection twice at once is refused. A run keeps
+going whichever tool is open. While one is queued or running, the top bar carries
+**Detect** with its progress, and one press returns to it; when it settles a toast
+says what it found, with **Review** to open the results. Between tiles the sweep
+lets the case's other queued work through, so a thumbnail never waits out a sweep.
+Nothing runs on its own: a weekly harbour review is a press on its card, not a
+background schedule.
+
+Before queueing, exact repeats of the same area, recipe, parameters and resolved
+dates offer **Open** and **Run anyway**. Overlapping dates do not trigger this
+notice. Dismissals are not remembered across runs and candidates are not deduplicated.
+
+The native analysis grid is independent of map zoom. Opening the panel or
+reopening its results reads local state. Offline runs use cached and retained
+frames and require explicit dates. Runs preserve their input snapshots and review
+state. Review pictures are retained over the whole swept area so a missed candidate
+can be added later; measured band frames are retained only for tiles with results.
+
+What a sweep produces is a list of candidates, strongest first, and nothing else
+reaches the case on its own. Each says how strong it is in a word (weak, clear or
+strong: how far past its threshold it got) and what was measured in units a reader
+can check, such as "6.2× brighter than the water around it" or "NBR 0.61 → −0.28".
+A candidate that crosses a tile edge is one candidate with one picture, stitched
+from the tiles it touches. New candidates use the detector mask's simplified
+outline; merged components retain their parts as a MultiPolygon. The bounding
+box still drives crops, sizing and merge tests. Existing results keep their
+stored rectangle geometry.
+
+Opening a run puts the map on the candidate the panel is about, close enough to
+read it, and every step through the queue moves it again. Review has a fixed-height
+preview and a fixed footer: Keep, Dismiss and Pin remain under the pointer as
+candidates change or details scroll. **K**, **D** and **P** are those three
+verdicts from the keyboard and the arrows walk the queue. **Compare** under the
+facts opens the candidate in Compare, framed close: a change on the two passes that
+found it, and a thing present on one pass — a hull, a fire — against today's
+high-resolution picture, where a platform or a flare stack is still standing and a
+ship is not. Nothing is fetched to decide it; the candidate names its passes. Chips above the candidate
+narrow that queue to what is still to review, what was kept, or what was pinned. **Keep** marks the
+candidate in its run without creating a place or image. **Dismiss** removes it
+from the run. **Pin** opens the standard dialog for a name, optional description,
+after-only image and Point/Area geometry. Single-image methods default to after-only
+and Point; change methods default to paired images and Area. Pinning creates a
+place and a PNG in Files. The picture says on its face when and where: each image
+carries its letter and its date (a radar pass its UTC time), and the foot holds the
+point's coordinates and the imagery's attribution, so the file still reads after
+the run is gone. Undo sends those copies to Trash. Evidence is enlarged
+by a whole-number factor with no interpolation, so a candidate a dozen pixels
+across can be read without pretending to detail the sensor never recorded. The
+candidate under review wears a ring on the map. **Add candidate** records a point or polygon on a successfully read area,
+with `origin: manual`, the same pass pair, preview and verdicts. Manual candidates
+have dashed map outlines and a Manual label.
+
+**Export as layer** is an explicit snapshot of kept and pinned candidates only.
+A routine updates one SAT layer, with a category per effective pass date; a one-off
+run has its own layer. Re-exporting a date replaces its category. Older dates are
+lighter and newer dates darker on a blue ramp. Features carry the name, description,
+pass date, detector, area and run id. Exported layers survive deletion of their runs.
+
+
## Geo Proof
A proof is composed of panels: case images, each carrying its source. Two things
diff --git a/extension/manifest.json b/extension/manifest.json
index 8dd472c..075418a 100644
--- a/extension/manifest.json
+++ b/extension/manifest.json
@@ -1,7 +1,7 @@
{
"manifest_version": 3,
"name": "Azimut Capture",
- "version": "0.3.0",
+ "version": "0.3.1",
"description": "File into Azimut: screenshot the map you are looking at (coordinates from the URL), save any other page as a bookmark, fill a social composer with a thread the app prepared, or open a reverse-image engine with a picture from the case.",
"permissions": ["activeTab", "scripting", "storage", "notifications"],
"host_permissions": [
diff --git a/frontend/e2e/app.fixture.js b/frontend/e2e/app.fixture.js
index 98a4c68..f30e179 100644
--- a/frontend/e2e/app.fixture.js
+++ b/frontend/e2e/app.fixture.js
@@ -1072,6 +1072,12 @@ export async function installAppFixture(page, options = {}) {
if (caseId && path === `/api/cases/${caseId}/map-layers` && request.method() === 'GET') {
return json(route, []);
}
+ // Detect's top-bar activity reads the case's runs whenever a case opens,
+ // whichever tool is showing, so this is part of opening a case rather than
+ // something a spec asked for. A spec about Detect routes it itself.
+ if (caseId && path === `/api/cases/${caseId}/analysis/runs` && request.method() === 'GET') {
+ return json(route, []);
+ }
if (caseId && path === `/api/cases/${caseId}/analysis-views`) {
if (request.method() === 'GET') {
return json(route, {
diff --git a/frontend/e2e/compare.spec.js b/frontend/e2e/compare.spec.js
index edbe57c..3526e8e 100644
--- a/frontend/e2e/compare.spec.js
+++ b/frontend/e2e/compare.spec.js
@@ -19,6 +19,12 @@ async function openCompare(page, providerB = 'Esri World Imagery') {
});
await page.route('**/compare/sessions/*/preview', (route) => route.fulfill({ json: { path: 'media/Comparison.png' } }));
await page.goto('/#compare');
+ // Compare opens on its default pair; these tests build their own.
+ await expect(page.locator('.surface-shell').first()).toBeVisible();
+ for (const letter of ['A', 'B']) {
+ const remove = page.getByRole('button', { name: `Remove imagery ${letter}`, exact: true });
+ if (await remove.count()) await remove.click();
+ }
await expect(page.locator('.empty-slot')).toHaveCount(2);
for (const letter of ['A', 'B']) {
await page.locator('.empty-slot').filter({ has: page.locator('.slot-letter', { hasText: letter }) }).click();
@@ -28,6 +34,23 @@ async function openCompare(page, providerB = 'Esri World Imagery') {
return { fixture, errors, saved };
}
+test('opens on a Wayback release a year back against today’s World Imagery', async ({ page }) => {
+ await installAppFixture(page);
+ await page.route('**/api/satellite/providers', (route) => route.fulfill({ json: [
+ { id: 'esri-world-imagery', label: 'Esri World Imagery', url: 'https://tiles.invalid/{z}/{x}/{y}.png', imagery: true, max_zoom: 19, tile_size: 256, oversample: 1, attribution: 'Browser fixture' },
+ { id: 'esri-wayback', label: 'Esri Wayback', url: 'https://tiles.invalid/{z}/{x}/{y}.png', imagery: true, max_zoom: 19, tile_size: 256, oversample: 1, attribution: 'Browser fixture' },
+ ] }));
+ // a newest release no clock reaches, and one far older than a year
+ await page.route('**/api/satellite/wayback/releases', (route) => route.fulfill({ json: { releases: [{ release: 2, date: '2099-01-01' }, { release: 1, date: '2020-01-01' }] } }));
+ const history = [];
+ page.on('request', (request) => request.url().includes('/wayback/changes') && history.push(request.url()));
+ await page.goto('/#compare');
+ await awaitMapReady(page, 2);
+ await expect(page.locator('.empty-slot')).toHaveCount(0);
+ await expect(page.locator('.wb-wrap .chip')).toContainText('2020-01-01');
+ expect(history).toEqual([]);
+});
+
test('linked maps keep annotations on the ground through pan, modes and save', async ({ page }) => {
const { errors, saved } = await openCompare(page);
const canvas = page.getByLabel('Annotations on imagery A', { exact: true });
@@ -190,26 +213,31 @@ test('spectral frames are requested only by Run, including after reopening and m
await page.getByRole('button', { name: 'Open', exact: true }).click();
await page.locator('.session-open').click();
await awaitMapReady(page, 2);
- // Reopening in Difference mode brings its column with it; nothing to click.
+ // Reopening a Difference session brings its strip with it; nothing to click.
await expect(page.getByLabel('Difference', { exact: true })).toBeVisible();
await expect(page.locator('button[aria-label="Reset to north"] + button')).toHaveText('35°');
+ await page.getByRole('button', { name: 'Difference settings', exact: true }).click();
await expect(page.getByLabel('Method', { exact: true })).toHaveValue('index');
expect(requests).toHaveLength(0);
- await page.getByRole('button', { name: 'Read this view', exact: true }).click();
+ // Read sits on the strip, so pressing it leaves the settings open.
+ await page.getByRole('button', { name: 'Read', exact: true }).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']);
const box = await page.locator('.compare-stage').boundingBox();
await page.mouse.move(box.x + 100, box.y + 100);
await page.mouse.down();
await page.mouse.move(box.x + 180, box.y + 130, { steps: 8 });
await page.mouse.up();
+ // 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.getByLabel('Difference', { exact: true })).toContainText('Run again to match this view');
- await expect(page.getByRole('button', { name: 'Read this view', exact: true })).toBeEnabled();
+ await expect(page.getByRole('button', { name: 'Read', exact: true })).toBeEnabled();
expect(requests).toHaveLength(2);
// 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);
@@ -226,15 +254,17 @@ test('changes run in the worker and export a composed PNG', async ({ page }) =>
});
await page.getByRole('button', { name: 'Difference', exact: true }).click();
await expect(page.locator('.secondary .change-map')).toBeVisible({ timeout: 20000 });
- await expect(page.getByLabel('Difference', { exact: true })).toContainText('highlighted');
+ await expect(page.locator('.change-legend')).toContainText('highlighted');
// Highlights that come and go are easier to catch over busy imagery.
await page.getByRole('button', { name: 'Blink the highlights', exact: true }).click();
await expect(page.locator('.secondary .change-map')).toBeHidden();
await expect(page.locator('.secondary .change-map')).toBeVisible();
await page.getByRole('button', { name: 'Stop blinking the highlights', exact: true }).click();
await expect(page.locator('.secondary .change-map')).toBeVisible();
+ await page.getByRole('button', { name: 'Difference settings', exact: true }).click();
await page.getByLabel('Method', { exact: true }).selectOption('structure');
- await expect(page.getByLabel('Difference', { exact: true })).toContainText('coverage');
+ await expect(page.locator('aside.settings .readout')).toContainText('coverage');
+ await page.keyboard.press('Escape');
await page.getByRole('button', { name: 'Export', exact: true }).click();
await page.getByRole('button', { name: 'Export copy', exact: true }).click();
await expect.poll(() => exports.length).toBe(1);
@@ -242,99 +272,131 @@ test('changes run in the worker and export a composed PNG', async ({ page }) =>
expect(errors).toEqual([]);
});
-test('analyzer areas run explicitly, and candidates are reviewed one at a time', async ({ page }) => {
- const { errors } = await openCompare(page, 'Esri Wayback');
- const requests = [];
- const sizes = {
- small: { min_area: 300, max_area: 0, cleanup: 0, smoothing: 0, merge_metres: 0 },
- medium: { min_area: 2000, max_area: 0, cleanup: 1, smoothing: 0, merge_metres: 30 },
- large: { min_area: 20000, max_area: 0, cleanup: 1, smoothing: 1, merge_metres: 100 },
- };
- const recipe = { id: 'large-change', name: 'Any surface change', description: 'Reflectance that moved',
- phenomenon: 'Surface change', method: 'surface', zones: [], colour: '#f6a81a', style: 'both',
- parameters: { sensitivity: 67, ...sizes.medium, index: 'ndvi', direction: 'both',
- ignore_clouds: true, ignore_shadows: true, cloud_margin: 5 } };
- await page.route('**/api/compare/analyzers', (route) => route.fulfill({ json: {
- builtins: [recipe], custom: [], max_tiles: 4096, max_results: 2000, grid: [13, 512],
- methods: [{ id: 'surface', label: 'Any reflectance change', single: false, clouds: true, sizes,
- measure: 'Reflectance moved by {value}%' }],
- } }));
- await page.route('**/api/satellite/sentinel/acquisitions', (route) => route.fulfill({ json: {
- dates: [{ date: '2026-05-11', cloud: 2, granules: 1, coverage: 1 },
- { date: '2026-05-04', cloud: 4, granules: 1, coverage: 1 }], truncated: false } }));
- let saved;
- await page.route('**/api/cases/*/analysis/**', async (route) => {
- const path = new URL(route.request().url()).pathname;
- if (route.request().method() === 'POST' && path.endsWith('/runs')) {
- const input = route.request().postDataJSON(); requests.push(input);
- const [[w, n], [e, s]] = input.zones[0].points;
- const row = { id: '0-1', coordinates: [(w + e) / 2, (n + s) / 2],
- bbox: [Math.min(w, e), Math.min(n, s), Math.max(w, e), Math.max(n, s)],
- area: 90, width: 15, height: 6, margin: 3.4, strength: 'strong', measure: { value: 18.2 },
- phenomenon: 'Surface change', review: 'new', parts: [{ frames: ['a', 'b'], box: [0, 0, 1, 1] }] };
- saved = { id: '123456789abc', title: input.title, input, status: 'ready', progress: 1, total: 1,
- count: 1, results: [row], engine_version: 2, created_at: '2026-09-16T00:00:00Z' };
- await route.fulfill({ json: { ...saved, status: 'queued', results: [], count: 0 } });
- } else if (route.request().method() === 'PATCH' && path.includes('/results/')) {
- saved.results[0].review = route.request().postDataJSON().review;
- await route.fulfill({ json: saved.results[0] });
- } else if (path.endsWith('/runs/123456789abc')) await route.fulfill({ json: saved });
- else if (path.endsWith('/preview')) await route.fulfill({ contentType: 'image/png', body: Buffer.from(
- 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=', 'base64') });
- else await route.fulfill({ json: path.endsWith('/runs') && saved ? [saved] : [] });
- });
- await page.getByRole('button', { name: 'Detect', exact: true }).click();
- // One column, one place: Difference's settings were in the same slot.
- await expect(page.getByLabel('Detect', { exact: true })).toBeVisible();
- await expect(page.getByLabel('Analyzer', { exact: true })).toHaveValue('large-change');
- await expect(page.getByRole('button', { name: /^Run on/ })).toBeDisabled();
- expect(requests).toHaveLength(0);
- await page.getByRole('button', { name: 'Rectangle', exact: true }).click();
+/** Turn the shared camera to an exact bearing from the compass. */
+async function turnTo(page, degrees) {
+ await page.getByTitle('Click to type an exact angle', { exact: true }).first().click();
+ const input = page.getByLabel('Set bearing in degrees', { exact: true });
+ await input.fill(String(degrees));
+ await input.press('Enter');
+ await expect(page.getByTitle('Click to type an exact angle', { exact: true }).first())
+ .toContainText(`${degrees}`);
+}
+
+/** The corners of an outline path, as [x, y] pairs. */
+const cornersOf = (d) => [...d.matchAll(/(-?[\d.]+),(-?[\d.]+)/g)].map((m) => [Number(m[1]), Number(m[2])]);
+const length = (a, b) => Math.hypot(b[0] - a[0], b[1] - a[1]);
+
+test('on a turned map a box runs along the screen, and turns from its grip', async ({ page }) => {
+ const { errors, saved } = await openCompare(page);
+ await turnTo(page, 30);
const canvas = page.getByLabel('Annotations on imagery A', { exact: true });
const box = await canvas.boundingBox();
- await page.mouse.move(box.x + 80, box.y + 100);
- await page.mouse.down(); await page.mouse.move(box.x + 190, box.y + 190, { steps: 6 }); await page.mouse.up();
- await expect(page.getByLabel('Area name', { exact: true })).toHaveCount(1);
- await expect(page.getByLabel('Detect', { exact: true })).toContainText('1 tile');
- // Wayback on the maps is nothing Detect can read, so it asks for Sentinel-2 dates.
- await expect(page.getByLabel('Detect', { exact: true })).toContainText('Detect reads Sentinel-2');
- await page.getByRole('button', { name: 'Change dates or the rule…' }).click();
- await page.getByRole('button', { name: 'Find passes', exact: true }).click();
- await page.getByLabel('Use 2026-05-04').getByRole('button', { name: 'A', exact: true }).click();
- await page.getByLabel('Use 2026-05-11').getByRole('button', { name: 'B', exact: true }).click();
- await page.getByLabel('Analysis name', { exact: true }).fill('Harbour sweep');
- await page.getByRole('group', { name: 'Target size' }).scrollIntoViewIfNeeded();
- await page.screenshot({ path: test.info().outputPath('analyzers-setup.png') });
- expect(requests).toHaveLength(0);
- await page.getByRole('button', { name: 'Run on 1 area', exact: true }).click();
- await expect(page.getByText('Strong · Reflectance moved by 18.2%', { exact: true })).toBeVisible();
- expect(requests).toHaveLength(1);
- expect(requests[0].zones).toHaveLength(1);
- const pins = page.locator('.analysis-overlay [role="button"]');
- await expect(pins).toHaveCount(2); // the same candidate on both maps
- await page.getByRole('button', { name: 'Toggle Harbour sweep', exact: true }).click();
- await expect(pins).toHaveCount(0);
- await page.getByRole('button', { name: 'Toggle Harbour sweep', exact: true }).click();
- await expect(pins).toHaveCount(2);
- await page.mouse.move(box.x + 80, box.y + 250); await page.mouse.wheel(0, -300);
- await expect(pins).toHaveCount(2);
- expect(requests).toHaveLength(1);
- // Dismissing is a verdict on one candidate, and it takes it off the map.
- await expect(page.getByText('1 still to review · 0 kept, 0 dismissed')).toBeVisible();
- await page.getByRole('button', { name: 'Dismiss', exact: true }).click();
- await expect(page.getByText('All 1 reviewed · 0 kept, 1 dismissed')).toBeVisible();
- await expect(pins).toHaveCount(0);
- // Detect's own drawing belongs to Detect; the reading modes stay clean.
- await page.getByRole('button', { name: 'Side by side', exact: true }).click();
- await expect(page.getByLabel('Detect', { exact: true })).toHaveCount(0);
- await expect(page.locator('.analysis-overlay')).toHaveCount(0);
- await page.getByRole('button', { name: 'Detect', exact: true }).click();
- await page.getByRole('button', { name: 'Saved', exact: true }).click();
- await page.locator('.cmp-dock .link').filter({ hasText: 'Harbour sweep' }).first().click();
- await expect(page.getByText('Strong · Reflectance moved by 18.2%', { exact: true })).toBeVisible();
- expect(requests).toHaveLength(1);
- expect(requests[0].a).toMatchObject({ provider: 'sentinel2', date: '2026-05-04' });
- expect(requests[0].b).toMatchObject({ provider: 'sentinel2', date: '2026-05-11' });
- await page.screenshot({ path: test.info().outputPath('analyzers.png') });
+ const cx = box.x + box.width / 2;
+ const cy = box.y + box.height / 2;
+ await page.getByTitle('Box (R)', { exact: true }).click();
+ await page.mouse.move(cx - 80, cy - 40);
+ await page.mouse.down();
+ await page.mouse.move(cx + 80, cy + 40, { steps: 6 });
+ await page.mouse.up();
+
+ const outline = canvas.locator('.mark > path:not(.edge)');
+ const drawn = cornersOf(await outline.getAttribute('d'));
+ // Along the screen it was drawn on: level sides, the size the drag covered.
+ expect(drawn).toHaveLength(4);
+ expect(Math.abs(drawn[1][1] - drawn[0][1])).toBeLessThan(1);
+ expect(length(drawn[0], drawn[1])).toBeCloseTo(160, -1);
+ expect(length(drawn[1], drawn[2])).toBeCloseTo(80, -1);
+
+ // A quarter turn from the grip stands it on end about its centre.
+ const grip = canvas.locator('.turn circle').last();
+ const at = await grip.boundingBox();
+ await page.mouse.move(at.x + at.width / 2, at.y + at.height / 2);
+ await page.mouse.down();
+ await page.mouse.move(cx + 90, cy, { steps: 8 });
+ await page.mouse.up();
+ const turned = cornersOf(await outline.getAttribute('d'));
+ const xs = turned.map((point) => point[0] - box.x);
+ const ys = turned.map((point) => point[1] - box.y);
+ 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('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.
+ expect(saved[0].spec.annotations[0].angle).toBeCloseTo(60, 0);
+ expect(errors).toEqual([]);
+});
+
+test('the export frame keeps its shape when the camera turns, and still exports', async ({ page }) => {
+ // Tall enough for the frame's four corners to stay in view once it is turned.
+ await page.setViewportSize({ width: 1600, height: 1100 });
+ const { errors } = await openCompare(page);
+ const exports = [];
+ await page.route('**/api/cases/*/plates', async (route) => {
+ exports.push(route.request().postDataJSON());
+ await route.fulfill({ json: { file: 'comparison.png', path: '' } });
+ });
+ await page.getByRole('button', { name: 'Fade', exact: true }).click();
+ await page.getByRole('button', { name: 'Export', exact: true }).click();
+ const dialog = page.getByRole('dialog', { name: 'Export a copy' });
+ await dialog.getByRole('button', { name: 'Draw…', exact: true }).click();
+ const stage = await page.locator('.compare-stage').boundingBox();
+ const cx = stage.x + stage.width / 2;
+ const cy = stage.y + stage.height / 2;
+ await page.mouse.move(cx - 170, cy - 110);
+ await page.mouse.down();
+ await page.mouse.move(cx + 170, cy + 110, { steps: 5 });
+ await page.mouse.up();
+ await dialog.getByRole('button', { name: 'Close', exact: true }).click();
+
+ const edge = page.locator('.compare-stage > .export-frame .edge');
+ const [a, b, c, d] = cornersOf(await edge.getAttribute('d'));
+ await turnTo(page, 40);
+ await expect.poll(async () => cornersOf(await edge.getAttribute('d'))[0][1]).not.toBeCloseTo(a[1], 0);
+ const [e, f, g, h] = cornersOf(await edge.getAttribute('d'));
+ // Same sides and diagonals: turned with the ground, not stretched to the screen.
+ expect(length(e, f)).toBeCloseTo(length(a, b), 0);
+ expect(length(f, g)).toBeCloseTo(length(b, c), 0);
+ expect(length(e, g)).toBeCloseTo(length(f, h), 0);
+ expect(length(e, g)).toBeCloseTo(length(a, c), 0);
+ expect(d).toBeTruthy();
+
+ await page.getByRole('button', { name: 'Export', exact: true }).click();
+ await page.getByRole('button', { name: 'Export copy', exact: true }).click();
+ await expect.poll(() => exports.length).toBe(1);
+ const png = Buffer.from(exports[0].png, 'base64');
+ // Upright as drawn: the picture is the frame's own width, not the turned box around it.
+ expect(png.readUInt32BE(16)).toBe(Math.round(length(a, b)));
+ expect(errors).toEqual([]);
+});
+
+test("Difference's settings stay put through a read, lie over the highlights, and close outside", async ({ page }) => {
+ const { errors } = await openCompare(page, 'Esri Wayback');
+ await page.getByRole('button', { name: 'Difference', exact: true }).click();
+ await expect(page.locator('.secondary .change-map')).toBeVisible({ timeout: 20000 });
+ await page.getByRole('button', { name: 'Difference settings', exact: true }).click();
+ const panel = page.locator('aside.settings');
+ await expect(panel).toBeVisible();
+ const before = await panel.boundingBox();
+
+ // A read in flight used to widen the strip, and the panel hanging off it moved.
+ await page.getByLabel('Method', { exact: true }).selectOption('structure');
+ await expect(panel.locator('.readout')).toContainText('coverage', { timeout: 20000 });
+ const after = await panel.boundingBox();
+ expect(after.x).toBeCloseTo(before.x, 0);
+ expect(after.y).toBeCloseTo(before.y, 0);
+ expect(after.height).toBeCloseTo(before.height, 0);
+
+ // Over the highlights, not under them.
+ const inside = await page.evaluate(({ x, y }) =>
+ !!document.elementFromPoint(x, y)?.closest('aside.settings'),
+ { x: after.x + 20, y: after.y + 20 });
+ expect(inside).toBe(true);
+
+ // A press on the map beside it closes it.
+ const stage = await page.locator('.compare-stage').boundingBox();
+ await page.mouse.click(stage.x + 80, stage.y + 80);
+ await expect(panel).toBeHidden();
expect(errors).toEqual([]);
});
diff --git a/frontend/e2e/detect.spec.js b/frontend/e2e/detect.spec.js
new file mode 100644
index 0000000..c967634
--- /dev/null
+++ b/frontend/e2e/detect.spec.js
@@ -0,0 +1,144 @@
+import { test, expect } from '@playwright/test';
+import { awaitMapReady, installAppFixture } 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,
+ cleanup: 0, smoothing: 0, merge_metres: 0, index: 'ndvi', direction: 'both' } };
+const area = { id: 'aaaaaaaaaaaa', name: 'North site', colour: '#38bdf8',
+ geometry: { type: 'Polygon', coordinates: [[[2.29, 48.855], [2.3, 48.855], [2.3, 48.862], [2.29, 48.862], [2.29, 48.855]]] } };
+const zone = { id: area.id, name: area.name, kind: 'polygon', points: area.geometry.coordinates[0].slice(0, -1) };
+const source = (date) => ({ provider: 'sentinel2', date, layer: 'TRUE_COLOR', maxcc: 30 });
+
+async function openDetect(page, withRun = false) {
+ await installAppFixture(page);
+ const errors = [], calls = [], prefs = [];
+ page.on('pageerror', (error) => errors.push(error.message));
+ const a = source('2026-09-01'), b = source('2026-09-10');
+ const candidate = { id: 'candidate-1', origin: 'detector', area_id: area.id, area_name: area.name,
+ phenomenon: 'Surface change', coordinates: [2.2945, 48.8584], geometry: area.geometry,
+ bbox: [2.29, 48.855, 2.3, 48.862], review: 'new', strength: 'clear', measure: {},
+ sources: { a, b }, area: 300, width: 20, height: 15 };
+ const run = { id: 'bbbbbbbbbbbb', title: 'North site pass', status: 'ready', progress: 1, total: 1,
+ count: 3, created_at: '2026-09-10T12:00:00Z', results: [candidate,
+ { ...candidate, id: 'candidate-2', phenomenon: 'A longer candidate name wrapping across several lines in the review panel', width: 12345 },
+ { ...candidate, id: 'candidate-3', phenomenon: 'Third candidate' }],
+ input: { title: 'North site pass', recipe, zones: [zone], a, b },
+ area_runs: [{ area_id: area.id, name: area.name, a, b, status: 'ready' }] };
+ await page.route('**/api/compare/analyzers', (route) => route.fulfill({ json: {
+ builtins: [recipe, { ...recipe, id: 'boats', name: 'Vessels', method: 'vessels' }], custom: [],
+ methods: [{ id: 'surface', single: false, sizes: {} }, { id: 'vessels', single: true, sizes: {} }],
+ grid: [13, 512], max_tiles: 4096, max_results: 2000,
+ } }));
+ await page.route('**/api/settings/prefs', (route) => {
+ prefs.push(route.request().postDataJSON()); return route.fulfill({ json: {} });
+ });
+ await page.route('**/api/satellite/providers', (route) => route.fulfill({ json: [
+ { 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: 'Copernicus Sentinel-2', url: 'https://tiles.invalid/{z}/{x}/{y}.png',
+ imagery: true, max_zoom: 19, tile_size: 256, attribution: 'Copernicus Sentinel data' },
+ ] }));
+ await page.route('**/api/satellite/sentinel/**', (route) => {
+ calls.push(route.request().url()); return route.fulfill({ json: { dates: [] } });
+ });
+ await page.route('**/api/cases/*/analysis/**', async (route) => {
+ const suffix = route.request().url().split('/analysis/')[1];
+ const method = route.request().method();
+ if (suffix.endsWith('/preview')) return route.fulfill({ contentType: 'image/svg+xml',
+ body: `<svg xmlns="http://www.w3.org/2000/svg" width="${suffix.includes('candidate-2') ? 80 : 600}" height="160"><rect width="100%" height="100%" fill="#30352b"/></svg>` });
+ if (method === 'PATCH') {
+ const found = run.results.find((row) => suffix.endsWith('/' + row.id));
+ Object.assign(found, route.request().postDataJSON());
+ if (found.review === 'dismissed') run.results = run.results.filter((row) => row.id !== found.id);
+ return route.fulfill({ json: found });
+ }
+ if (suffix === `runs/${run.id}/results` && method === 'POST') {
+ const body = route.request().postDataJSON();
+ const manual = { ...candidate, id: 'manual-1', origin: 'manual', geometry: body.geometry };
+ run.results.push(manual); run.count++;
+ return route.fulfill({ json: manual });
+ }
+ if (method === 'GET') {
+ const data = suffix === 'areas' ? [area] : suffix === 'runs' ? (withRun ? [run] : [])
+ : suffix === `runs/${run.id}` ? run : [];
+ return route.fulfill({ json: data });
+ }
+ return route.fulfill({ json: {} });
+ });
+ await page.goto('/#detect');
+ await awaitMapReady(page);
+ return { errors, calls, prefs };
+}
+
+test('landing, dock rail and the When step fit the existing map workspace', async ({ page }) => {
+ 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);
+ const map = page.locator('.detect-tool .map');
+ const before = await map.boundingBox();
+ await page.getByRole('button', { name: 'Collapse Detect panel', exact: true }).click();
+ await expect(page.locator('.dock-tabs.rail')).toBeVisible();
+ await expect.poll(async () => (await map.boundingBox()).width).toBeGreaterThan(before.width + 200);
+ await expect.poll(() => prefs.some((p) => p.detect_view?.collapsed)).toBe(true);
+ await page.getByRole('button', { name: 'Areas', exact: true }).click();
+ await expect(page.getByRole('button', { name: /^North site/ })).toBeVisible();
+ await page.getByRole('button', { name: 'Edit North site', exact: true }).click();
+ await expect(page.getByLabel('Rename North site')).toBeVisible();
+ await page.keyboard.press(']');
+ await expect(page.locator('.dock-tabs.rail')).toBeVisible();
+ await page.keyboard.press(']');
+ await page.getByRole('button', { name: 'New detection', exact: true }).click();
+ await page.getByRole('button', { name: 'New one pass', exact: true }).click();
+ await page.getByRole('button', { name: 'North site', exact: true }).click();
+ await page.getByRole('button', { name: 'Next: What' }).click();
+ await page.getByRole('button', { name: 'Next: When' }).click();
+ // A and B are asked in the step itself, B the newest pass until a day is chosen
+ await expect(page.getByRole('heading', { name: 'Which two images' })).toBeVisible();
+ await expect(page.getByLabel('Day of A')).toBeVisible();
+ await expect(page.getByRole('radio', { name: 'Newest pass' })).toHaveAttribute('aria-checked', 'true');
+ await page.getByRole('radio', { name: 'A day I choose' }).click();
+ await expect(page.getByLabel('Day of B')).toBeVisible();
+ await expect(page.getByRole('button', { name: 'Find passes', exact: true })).toBeVisible();
+ expect((await map.boundingBox()).height).toBe(before.height);
+ expect(calls).toEqual([]);
+ await page.screenshot({ path: test.info().outputPath('detect-dates.png') });
+ expect(errors).toEqual([]);
+});
+
+test('review adds a manual point and uses the standard pin dialog', async ({ page }) => {
+ const { errors } = await openDetect(page, true);
+ await page.getByRole('button', { name: 'Saved', exact: true }).click();
+ await page.getByRole('button', { name: /^North site pass/ }).click();
+ const keep = page.getByRole('button', { name: 'Keep', exact: true });
+ const dismiss = page.getByRole('button', { name: 'Dismiss', exact: true });
+ const actionBox = await keep.boundingBox();
+ const previewBox = await page.locator('.candidate .preview').boundingBox();
+ await keep.click();
+ await expect(page.locator('.candidate > strong')).toContainText('A longer candidate name');
+ expect(await keep.boundingBox()).toEqual(actionBox);
+ // Firefox reports this box a ten-thousandth of a pixel off its own earlier reading.
+ expect((await page.locator('.candidate .preview').boundingBox()).height).toBeCloseTo(previewBox.height, 2);
+ await dismiss.click();
+ await expect(page.locator('.candidate > strong')).toContainText('Third candidate');
+ expect(await keep.boundingBox()).toEqual(actionBox);
+ await page.locator('.review-body').evaluate((node) => { node.scrollTop = node.scrollHeight; });
+ expect(await keep.boundingBox()).toEqual(actionBox);
+ await page.screenshot({ path: test.info().outputPath('detect-review.png') });
+ await page.getByRole('button', { name: 'Pin', exact: true }).click();
+ const pin = page.getByRole('dialog', { name: 'Pin candidate' });
+ await expect(pin.getByLabel('After image only')).not.toBeChecked();
+ await expect(pin.getByLabel('Area', { exact: true })).toBeChecked();
+ await pin.getByRole('button', { name: 'Close', exact: true }).click();
+ await page.getByRole('button', { name: 'Add candidate', exact: true }).click();
+ await page.getByRole('button', { name: 'Add point', exact: true }).click();
+ await page.locator('.detect-tool .map').click({ position: { x: 300, y: 300 } });
+ await expect(page.locator('.candidate > strong')).toContainText('Manual');
+ await page.getByRole('button', { name: 'Pin', exact: true }).click();
+ await expect(pin.getByLabel('Point', { exact: true })).toBeChecked();
+ await expect(pin.getByLabel('Area', { exact: true })).toBeDisabled();
+ await page.screenshot({ path: test.info().outputPath('detect-pin.png') });
+ await pin.getByRole('button', { name: 'Close', exact: true }).click();
+ await page.getByRole('button', { name: 'Routines', exact: true }).click();
+ await expect(page.getByRole('button', { name: 'Imagery provider', exact: true })).toContainText('Esri World Imagery');
+ expect(errors).toEqual([]);
+});
diff --git a/frontend/src/App.svelte b/frontend/src/App.svelte
index 5cc95b5..d5e02f6 100644
--- a/frontend/src/App.svelte
+++ b/frontend/src/App.svelte
@@ -34,6 +34,7 @@
import CaseSidebar from './components/CaseSidebar.svelte';
import Toasts from './components/Toasts.svelte';
import UpdateModal from './components/UpdateModal.svelte';
+ import DetectActivity from './components/DetectActivity.svelte';
import WorkspaceStopped from './components/WorkspaceStopped.svelte';
import { readStatus, stoppedBecause } from './lib/workspace.js';
import { analysisSearch, leaveAnalysisView } from './lib/analysisSearch.svelte.js';
@@ -56,6 +57,7 @@
{ id: 'inspect', label: TOOL_LABELS.inspect, load: () => import('./tools/Inspector.svelte') },
{ id: 'satellite', label: TOOL_LABELS.satellite, load: () => import('./tools/Satellite.svelte') },
{ id: 'compare', label: TOOL_LABELS.compare, load: () => import('./tools/Compare.svelte') },
+ { id: 'detect', label: TOOL_LABELS.detect, load: () => import('./tools/Detect.svelte') },
{ id: 'coordinates', label: TOOL_LABELS.coordinates, load: () => import('./tools/Coordinates.svelte') },
{ id: 'proof', label: TOOL_LABELS.proof, load: () => import('./tools/ProofComposer.svelte') },
{ id: 'post', label: TOOL_LABELS.post, load: () => import('./tools/PostComposer.svelte') },
@@ -254,6 +256,7 @@
</button>
</div>
<div class="spacer"></div>
+ <DetectActivity />
<!-- The one mark that answers "what is this tab I am standing in". It sits beside
the gear rather than in each toolbar so there is one of it, and it opens the
Guide on the section written about the current tool. Silent on the Guide
diff --git a/frontend/src/components/CopernicusNeeded.render.test.js b/frontend/src/components/CopernicusNeeded.render.test.js
new file mode 100644
index 0000000..435cc0b
--- /dev/null
+++ b/frontend/src/components/CopernicusNeeded.render.test.js
@@ -0,0 +1,28 @@
+import { describe, expect, it, vi } from 'vitest';
+import { render } from 'svelte/server';
+
+vi.mock('../lib/navigate.js', () => ({ openCopernicusSettings: vi.fn() }));
+const { default: CopernicusNeeded } = await import('./CopernicusNeeded.svelte');
+
+describe('what a tool needs from Copernicus', () => {
+ it('says the account is free, and how to add both layers', () => {
+ const { body } = render(CopernicusNeeded, { props: { need: 'account', tool: 'Detect' } });
+ expect(body).toContain('Detect needs a Copernicus key');
+ expect(body).toContain('free');
+ expect(body).toContain('Simple Sentinel-2 L2A template');
+ // the template brings Sentinel-2; Sentinel-1 is a layer added by hand
+ expect(body).toContain('The template brings the Sentinel-2 layers with it');
+ expect(body).toContain('Sentinel-1 GRD');
+ expect(body).toContain('Open Settings → Imagery');
+ });
+
+ it('walks the radar layer form field by field once the key is set', () => {
+ const { body } = render(CopernicusNeeded, { props: { need: 'radar', tool: 'Two radar passes' } });
+ expect(body).toContain('Two radar passes needs the Sentinel-1 layer');
+ for (const field of ['Data processing', 'Polarization', 'VV + VH', 'Orthorectification', 'Speckle Filter']) {
+ expect(body).toContain(field);
+ }
+ expect(body).toContain('Open the Configuration Utility');
+ expect(body).not.toContain('Simple Sentinel-2 L2A template');
+ });
+});
diff --git a/frontend/src/components/CopernicusNeeded.svelte b/frontend/src/components/CopernicusNeeded.svelte
new file mode 100644
index 0000000..a815b78
--- /dev/null
+++ b/frontend/src/components/CopernicusNeeded.svelte
@@ -0,0 +1,156 @@
+<script>
+ /**
+ * What a tool needs from Copernicus before it can work, in the middle of it.
+ *
+ * Detect reads nothing else, and Compare's satellite and radar passes neither,
+ * so a missing account is not a detail for a corner: it is said where the
+ * work would be, with the recipe and the way to Settings. Two layers come out
+ * of the recipe. The Sentinel-2 one arrives with the template the key is made
+ * from; the Sentinel-1 one is added by hand to the same configuration, only
+ * for the radar analyzers and the radar basemap.
+ */
+ import Icon from './Icon.svelte';
+ import RadarForm from './RadarForm.svelte';
+ import {
+ ACCOUNT_STEPS,
+ COPERNICUS_CONFIGURATIONS,
+ COPERNICUS_SIGNUP,
+ RADAR_STEPS,
+ } from '../lib/copernicusSetup.js';
+ import { openCopernicusSettings } from '../lib/navigate.js';
+
+ let {
+ /** 'account': no Copernicus key yet · 'radar': the key, but no Sentinel-1 layer. */
+ need = 'account',
+ /** Who is asking, e.g. "Detect" or "Two satellite passes". */
+ tool = 'This tool',
+ /** Shown when the notice can be put away, as Compare's can. */
+ onclose = null,
+ } = $props();
+</script>
+
+<section class="copernicus card" aria-label="Copernicus setup">
+ <header>
+ <Icon name="satellite" size={18} />
+ <h3>{need === 'account'
+ ? `${tool} needs a Copernicus key`
+ : `${tool} needs the Sentinel-1 layer`}</h3>
+ {#if onclose}
+ <button class="cmp-icon" onclick={onclose} aria-label="Close" title="Close"><Icon name="x" size={13} /></button>
+ {/if}
+ </header>
+ <p class="lead">
+ {need === 'account'
+ ? 'Copernicus is the EU’s satellite archive. The account is free and takes a few minutes to set up.'
+ : 'The key is set. Radar needs one more layer in the same Copernicus configuration.'}
+ </p>
+
+ {#if need === 'account'}
+ <h4><span class="n">1</span> Sentinel-2, the key</h4>
+ <ol>
+ {#each ACCOUNT_STEPS as step (step)}<li>{step}</li>{/each}
+ </ol>
+ <p class="note">The template brings the Sentinel-2 layers with it: there is nothing more to add for them.</p>
+ <details>
+ <summary><span class="n">2</span> Sentinel-1 radar, only for the radar analyzers</summary>
+ <ol>
+ {#each RADAR_STEPS as step (step)}<li>{step}</li>{/each}
+ </ol>
+ <RadarForm />
+ </details>
+ {:else}
+ <ol>
+ {#each RADAR_STEPS as step (step)}<li>{step}</li>{/each}
+ </ol>
+ <RadarForm />
+ {/if}
+
+ <div class="actions">
+ <button class="btn btn-primary btn-sm" onclick={openCopernicusSettings}>Open Settings → Imagery</button>
+ <a class="btn btn-sm" href={need === 'account' ? COPERNICUS_SIGNUP : COPERNICUS_CONFIGURATIONS}
+ target="_blank" rel="noreferrer">
+ {need === 'account' ? 'Register on Copernicus' : 'Open the Configuration Utility'} <Icon name="external" size={11} />
+ </a>
+ </div>
+</section>
+
+<style>
+ .copernicus {
+ display: grid;
+ gap: 8px;
+ width: min(560px, calc(100% - 32px));
+ max-height: calc(100% - 32px);
+ overflow-y: auto;
+ padding: 16px 18px;
+ background: var(--bg-1);
+ box-shadow: var(--shadow-2);
+ font-size: var(--fs-xs);
+ color: var(--text-2);
+ }
+ header {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ color: var(--text-1);
+ }
+ h3 {
+ flex: 1;
+ margin: 0;
+ font-size: var(--fs-md, 14px);
+ }
+ h4,
+ summary {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ margin: 4px 0 0;
+ color: var(--text-1);
+ font-size: var(--fs-sm);
+ font-weight: 600;
+ }
+ summary {
+ cursor: pointer;
+ }
+ .n {
+ display: inline-grid;
+ place-items: center;
+ width: 18px;
+ height: 18px;
+ border-radius: 50%;
+ background: var(--accent-soft);
+ color: var(--accent);
+ font-size: 10.5px;
+ }
+ .lead,
+ .note {
+ margin: 0;
+ line-height: 1.5;
+ }
+ .note {
+ color: var(--text-3);
+ }
+ ol {
+ margin: 0;
+ padding-left: 20px;
+ line-height: 1.55;
+ }
+ details {
+ display: grid;
+ gap: 6px;
+ }
+ details[open] > :global(*:not(summary)) {
+ margin-top: 6px;
+ }
+ .actions {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 8px;
+ margin-top: 4px;
+ }
+ .actions a {
+ display: inline-flex;
+ align-items: center;
+ gap: 5px;
+ text-decoration: none;
+ }
+</style>
diff --git a/frontend/src/components/DetectActivity.svelte b/frontend/src/components/DetectActivity.svelte
new file mode 100644
index 0000000..9b63394
--- /dev/null
+++ b/frontend/src/components/DetectActivity.svelte
@@ -0,0 +1,56 @@
+<script>
+ /**
+ * The top bar's word on Detect while a run is queued or running in the open
+ * case. It is there so a sweep can be left to work: the analyst goes back to
+ * any other tool and still sees it moving, and one press returns to it.
+ */
+ import { caseState } from '../lib/state.svelte.js';
+ import { detectRuns, openDetect, refreshRuns } from '../lib/detectRuns.svelte.js';
+ import { isActive, plural } from '../lib/map/detections.js';
+
+ const active = $derived(
+ detectRuns.caseId && detectRuns.caseId === caseState.current?.id ? detectRuns.rows.filter(isActive) : []
+ );
+ const running = $derived(active.find((row) => row.status === 'running'));
+ const share = $derived(running?.total ? Math.round((100 * (running.progress ?? 0)) / running.total) : 0);
+ const label = $derived(running ? `Detect ${share}%` : 'Detect queued');
+ const title = $derived(active.map((row) => row.title).join(', '));
+
+ // A case opened with runs still queued, say after a reload, is found here.
+ $effect(() => {
+ void refreshRuns(caseState.current?.id ?? null).catch(() => {});
+ });
+</script>
+
+{#if active.length}
+ <button
+ class="btn btn-ghost btn-sm detect-activity"
+ title={`${plural(active.length, 'detection')} working: ${title}`}
+ onclick={() => openDetect(`runs-${(running ?? active[0]).id}`)}
+ >
+ <span class="pulse" aria-hidden="true"></span>
+ {label}{active.length > 1 ? ` · ${active.length}` : ''}
+ </button>
+{/if}
+
+<style>
+ .detect-activity {
+ gap: 7px;
+ color: var(--accent);
+ font-variant-numeric: tabular-nums;
+ }
+ .pulse {
+ width: 7px;
+ height: 7px;
+ border-radius: 50%;
+ background: var(--accent);
+ animation: pulse 1.4s var(--ease) infinite;
+ }
+ @keyframes pulse {
+ 0%, 100% { opacity: 1; }
+ 50% { opacity: 0.3; }
+ }
+ @media (prefers-reduced-motion: reduce) {
+ .pulse { animation: none; }
+ }
+</style>
diff --git a/frontend/src/components/Icon.svelte b/frontend/src/components/Icon.svelte
index 3a4a4bc..095d750 100644
--- a/frontend/src/components/Icon.svelte
+++ b/frontend/src/components/Icon.svelte
@@ -138,6 +138,7 @@
minimize: 'M8 3v3a2 2 0 0 1-2 2H3m18 0h-3a2 2 0 0 1-2-2V3M3 16h3a2 2 0 0 1 2 2v3m8 0v-3a2 2 0 0 1 2-2h3',
ruler: 'M4 15.5 15.5 4l4.5 4.5L8.5 20 4 15.5Zm3.5-.5 1.5 1.5m1-4.5 1.5 1.5m1-4.5L14 11',
polygon: 'M12 3.5 20 9.5l-3 9.5H7L4 9.5l8-6Z',
+ mapArea: 'M3 5l7-2 4 4 7-2v14l-7 2-4-4-7 2V5Zm7-2v14m4-10v14',
// Compare's reading modes: two panes, a divider, a blend, alternation, a change
columns: 'M4 5h6.5v14H4a1 1 0 0 1-1-1V6a1 1 0 0 1 1-1Zm9.5 0H20a1 1 0 0 1 1 1v12a1 1 0 0 1-1 1h-6.5V5Z',
swipe: 'M4 5h16a1 1 0 0 1 1 1v12a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V6a1 1 0 0 1 1-1Zm8-2v18m-3-9-1.5 0M16.5 12H15',
diff --git a/frontend/src/components/RadarForm.svelte b/frontend/src/components/RadarForm.svelte
new file mode 100644
index 0000000..292bcfa
--- /dev/null
+++ b/frontend/src/components/RadarForm.svelte
@@ -0,0 +1,85 @@
+<script>
+ /**
+ * The dashboard's "Add a new layer" form for Sentinel-1, field by field.
+ *
+ * Nobody guesses these answers, and one of them (Data processing) blocks the
+ * Save button until it is filled, so the table says what to put in each
+ * field and, where it matters, why. The script under it is for the form that
+ * offers no predefined product: it only has to be valid.
+ */
+ import { RADAR_FORM, RADAR_SCRIPT } from '../lib/copernicusSetup.js';
+
+ let copied = $state(false);
+
+ async function copy() {
+ try {
+ await navigator.clipboard.writeText(RADAR_SCRIPT);
+ copied = true;
+ setTimeout(() => (copied = false), 1500);
+ } catch {
+ copied = false;
+ }
+ }
+</script>
+
+<table class="radar-form" aria-label="Sentinel-1 layer form">
+ <tbody>
+ {#each RADAR_FORM as [field, value, why] (field)}
+ <tr>
+ <th scope="row">{field}</th>
+ <td><strong>{value}</strong>{#if why}<small>{why}</small>{/if}</td>
+ </tr>
+ {/each}
+ </tbody>
+</table>
+<details class="script">
+ <summary>No predefined product in the list?</summary>
+ <p>Paste this in the processing script instead.</p>
+ <pre>{RADAR_SCRIPT}</pre>
+ <button class="btn btn-sm" onclick={copy}>{copied ? 'Copied' : 'Copy the script'}</button>
+</details>
+
+<style>
+ .radar-form {
+ width: 100%;
+ border-collapse: collapse;
+ font-size: var(--fs-xs);
+ }
+ .radar-form th,
+ .radar-form td {
+ padding: 4px 6px;
+ border-bottom: 1px solid var(--border);
+ text-align: left;
+ vertical-align: top;
+ }
+ .radar-form th {
+ width: 38%;
+ color: var(--text-2);
+ font-weight: 500;
+ }
+ .radar-form strong {
+ color: var(--text-1);
+ font-weight: 600;
+ }
+ .radar-form small {
+ display: block;
+ color: var(--text-3);
+ font-size: 10.5px;
+ }
+ .script {
+ font-size: var(--fs-xs);
+ color: var(--text-2);
+ }
+ .script p {
+ margin: 6px 0 4px;
+ }
+ .script pre {
+ margin: 0 0 6px;
+ padding: 6px 8px;
+ overflow-x: auto;
+ border-radius: var(--r-sm);
+ background: var(--bg-0);
+ color: var(--text-1);
+ font-size: 10.5px;
+ }
+</style>
diff --git a/frontend/src/lib/copernicusSetup.js b/frontend/src/lib/copernicusSetup.js
new file mode 100644
index 0000000..2a83555
--- /dev/null
+++ b/frontend/src/lib/copernicusSetup.js
@@ -0,0 +1,63 @@
+/**
+ * How to get Copernicus working, said the same way wherever it is needed.
+ *
+ * Detect cannot run without it, Compare's satellite passes cannot either, and
+ * Settings is where the answer is typed in. The account and the Sentinel-2
+ * configuration are one recipe; the Sentinel-1 layer is a second one, added to
+ * that same configuration, and its form asks questions nobody could guess the
+ * answers to. Both live here so the three places cannot drift apart.
+ */
+
+/** Where a free account is opened, and where its configurations are built. */
+export const COPERNICUS_SIGNUP = 'https://dataspace.copernicus.eu/';
+export const COPERNICUS_CONFIGURATIONS = 'https://shapps.dataspace.copernicus.eu/dashboard/#/configurations';
+
+/** The account and its Sentinel-2 configuration, whose ID is the key. */
+export const ACCOUNT_STEPS = Object.freeze([
+ 'Register on dataspace.copernicus.eu. It is free and asks for no card.',
+ 'Open the Sentinel Hub Dashboard, then Configuration Utility → New configuration, based on "Simple Sentinel-2 L2A template".',
+ 'Open it and turn off Show logo and Show warnings. Both are burned into every tile.',
+ 'Copy the ID under "Service endpoints" and paste it in Settings → Imagery → Sentinel Hub.',
+]);
+
+/** The Sentinel-1 layer, added to that same configuration. */
+export const RADAR_STEPS = Object.freeze([
+ 'In the Configuration Utility, open the configuration whose ID Azimut has, and press Add new layer.',
+ 'Fill the form as below, then Save.',
+ 'Back here, press Find the radar layer. Each layer it asks about is one request.',
+]);
+
+/**
+ * The "Add a new layer" form, field by field, as it reads on the dashboard.
+ * Azimut draws with its own script, so Data processing only has to be valid.
+ */
+export const RADAR_FORM = Object.freeze([
+ ['Layer name', 'Anything, for example RADAR', 'Azimut finds it by asking.'],
+ ['Source', 'Sentinel-1 GRD', ''],
+ ['Data processing', 'Any predefined product, from the pencil', 'Required by the form; Azimut replaces it.'],
+ ['Time range', 'Leave both boxes unticked', ''],
+ ['Mosaic order', 'Most recent', ''],
+ ['Acquisition mode', 'IW', ''],
+ ['Polarization', 'VV + VH', 'Every radar analyzer reads both.'],
+ ['Resolution', 'High', '10 m, the grid Detect sweeps.'],
+ ['Orbit Direction', 'Any', 'Azimut tells the passes apart.'],
+ ['Orthorectification', 'Copernicus 30 m DEM', 'Keeps hills where they stand; twice the processing units. Disabled is fine at sea.'],
+ ['Backscatter coefficient', 'gamma0', 'Terrain gamma0 costs 2.5 times more.'],
+ ['Speckle Filter', 'None', 'Azimut averages speckle itself; a filter doubles the cost.'],
+]);
+
+/**
+ * The script to paste when the form offers no predefined product. It only has
+ * to be valid: Azimut sends its own with every request.
+ */
+export const RADAR_SCRIPT = `//VERSION=3
+function setup() { return { input: ["VV", "VH", "dataMask"], output: { bands: 4 } }; }
+function evaluatePixel(p) { return [p.VV * 2.5, p.VH * 8, 0, p.dataMask]; }`;
+
+/** What is missing for a Copernicus road, from the providers the app offers. */
+export function copernicusNeed(providers, { radar = false } = {}) {
+ const has = (id) => (providers ?? []).some((provider) => provider.id === id && !provider.needs_key);
+ if (!has('sentinel2')) return 'account';
+ if (radar && !has('sentinel1')) return 'radar';
+ return '';
+}
diff --git a/frontend/src/lib/detectRuns.svelte.js b/frontend/src/lib/detectRuns.svelte.js
new file mode 100644
index 0000000..cdc9689
--- /dev/null
+++ b/frontend/src/lib/detectRuns.svelte.js
@@ -0,0 +1,90 @@
+/**
+ * What Detect is doing, said outside Detect.
+ *
+ * A run is queued in the case and keeps going whichever tool is open, so its
+ * progress can't live in Detect's column alone: the top bar marks it while
+ * anything is queued or running, and a toast says when one settles, with a way
+ * back to its results. Detect's own list reads the same rows.
+ *
+ * This reads the case's run list, a local file listing, and asks again only
+ * while something is still working. It never starts a run or fetches imagery.
+ */
+import { api } from './api.js';
+import { reloadCase, toast, uiState } from './state.svelte.js';
+import { isActive, settledMessage } from './map/detections.js';
+
+export const POLL_MS = 1500;
+
+export const detectRuns = $state({ caseId: null, rows: [] });
+
+let timer = null;
+let era = 0;
+let asked = 0;
+let applied = 0;
+/** Whether this case's runs were read before, so a new row is news rather than history. */
+let known = false;
+
+/** Detect, opened on one of its saved items (`runs-<id>`, `followups-<id>`…). */
+export function openDetect(stem) {
+ uiState.tool = 'detect';
+ uiState.openAnalyzer = stem;
+}
+
+/**
+ * Toast every run that settled since the last read: one that was working, and
+ * one that was not there at all, since a run can fail or finish from the cache
+ * before the first read after it started. True when any settled.
+ */
+function announce(before, after) {
+ const working = new Set(before.filter(isActive).map((row) => row.id));
+ const seen = new Set(before.map((row) => row.id));
+ let settled = false;
+ for (const row of after) {
+ if (isActive(row) || !(working.has(row.id) || (known && !seen.has(row.id)))) continue;
+ settled = true;
+ const said = settledMessage(row);
+ if (!said) continue;
+ const action = row.status === 'ready' && row.count
+ ? { label: 'Review', onClick: () => openDetect(`runs-${row.id}`) } : null;
+ toast(said.text, said.kind, 8000, action);
+ }
+ return settled;
+}
+
+function schedule() {
+ clearTimeout(timer);
+ timer = null;
+ if (detectRuns.rows.some(isActive)) {
+ const caseId = detectRuns.caseId;
+ timer = setTimeout(() => void refreshRuns(caseId).catch(() => {}), POLL_MS);
+ }
+}
+
+/**
+ * Read the case's runs now, and keep reading while any is working. Another
+ * case is other work: switching drops the old rows and never announces them.
+ * Answers are applied in the order they were asked, so a slow one can't put
+ * back a run list the next one already moved past.
+ */
+export async function refreshRuns(caseId) {
+ if ((caseId ?? null) !== detectRuns.caseId) {
+ era++;
+ clearTimeout(timer);
+ timer = null;
+ detectRuns.caseId = caseId ?? null;
+ detectRuns.rows = [];
+ known = false;
+ }
+ if (!caseId) return [];
+ const mine = era;
+ const order = ++asked;
+ const rows = await api.get(`/api/cases/${caseId}/analysis/runs`);
+ if (mine !== era || order < applied) return rows;
+ applied = order;
+ const settled = announce(detectRuns.rows, rows);
+ known = true;
+ detectRuns.rows = rows;
+ schedule();
+ if (settled) await reloadCase().catch(() => {});
+ return rows;
+}
diff --git a/frontend/src/lib/detectRuns.test.js b/frontend/src/lib/detectRuns.test.js
new file mode 100644
index 0000000..b3bf39a
--- /dev/null
+++ b/frontend/src/lib/detectRuns.test.js
@@ -0,0 +1,70 @@
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+
+const get = vi.fn();
+const toast = vi.fn();
+const reloadCase = vi.fn(async () => {});
+const uiState = { tool: 'media', openAnalyzer: null };
+vi.mock('./api.js', () => ({ api: { get } }));
+vi.mock('./state.svelte.js', () => ({ toast, reloadCase, uiState }));
+const { POLL_MS, detectRuns, openDetect, refreshRuns } = await import('./detectRuns.svelte.js');
+
+const row = (status, extra = {}) => ({ id: 'aaaaaaaaaaaa', title: 'Harbour', status, count: 0, ...extra });
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ vi.clearAllMocks();
+});
+afterEach(async () => {
+ get.mockResolvedValue([]);
+ await refreshRuns(null);
+ vi.useRealTimers();
+});
+
+it('reads once and stops when nothing is working', async () => {
+ get.mockResolvedValue([row('ready', { count: 2 })]);
+ await refreshRuns('case-a');
+ expect(get).toHaveBeenCalledWith('/api/cases/case-a/analysis/runs');
+ await vi.advanceTimersByTimeAsync(POLL_MS * 3);
+ expect(get).toHaveBeenCalledTimes(1);
+ // a run that was already finished when the case opened is not news
+ expect(toast).not.toHaveBeenCalled();
+});
+
+it('keeps reading while a run works, then says it finished and how to get to it', async () => {
+ get.mockResolvedValueOnce([row('running', { progress: 1, total: 4 })])
+ .mockResolvedValueOnce([row('running', { progress: 3, total: 4 })])
+ .mockResolvedValue([row('ready', { count: 3 })]);
+ await refreshRuns('case-a');
+ await vi.advanceTimersByTimeAsync(POLL_MS);
+ expect(detectRuns.rows[0].progress).toBe(3);
+ await vi.advanceTimersByTimeAsync(POLL_MS);
+ expect(toast).toHaveBeenCalledWith('Harbour: 3 candidates to review', 'ok', 8000,
+ expect.objectContaining({ label: 'Review' }));
+ expect(reloadCase).toHaveBeenCalledTimes(1);
+ toast.mock.calls[0][3].onClick();
+ expect(uiState).toMatchObject({ tool: 'detect', openAnalyzer: 'runs-aaaaaaaaaaaa' });
+ await vi.advanceTimersByTimeAsync(POLL_MS * 3);
+ expect(get).toHaveBeenCalledTimes(3);
+});
+
+it('announces a run that settled before any read saw it working', async () => {
+ get.mockResolvedValueOnce([]).mockResolvedValue([row('failed', { message: 'no recent pass' })]);
+ await refreshRuns('case-a');
+ await refreshRuns('case-a');
+ expect(toast).toHaveBeenCalledWith('Harbour failed: no recent pass', 'warn', 8000, null);
+});
+
+it('never announces another case\'s runs after a switch', async () => {
+ get.mockResolvedValueOnce([row('running')]).mockResolvedValue([row('ready', { count: 1 })]);
+ await refreshRuns('case-a');
+ get.mockResolvedValue([]);
+ await refreshRuns('case-b');
+ await vi.advanceTimersByTimeAsync(POLL_MS * 2);
+ expect(detectRuns.caseId).toBe('case-b');
+ expect(toast).not.toHaveBeenCalled();
+});
+
+it('opens Detect on the item named', () => {
+ openDetect('followups-bbbbbbbbbbbb');
+ expect(uiState).toMatchObject({ tool: 'detect', openAnalyzer: 'followups-bbbbbbbbbbbb' });
+});
diff --git a/frontend/src/lib/guide.js b/frontend/src/lib/guide.js
index 8c646a5..303cb0c 100644
--- a/frontend/src/lib/guide.js
+++ b/frontend/src/lib/guide.js
@@ -192,11 +192,11 @@ export const GUIDE = [
id: 'map',
title: 'Map',
lead: 'Where a finding gets a coordinate, and where a coordinate gets a picture.',
- tools: ['satellite', 'compare', 'coordinates'],
+ tools: ['satellite', 'compare', 'detect', 'coordinates'],
points: [
{
label: 'Four providers need no key',
- text: 'Esri, its Wayback archive of past releases, OSM and OpenTopoMap are built in. Sentinel-2 and the other keyed providers use your own key, and a custom XYZ template is accepted.',
+ text: 'Esri, its Wayback archive of past releases, OSM and OpenTopoMap are built in. Sentinel-2, Sentinel-1 radar and the other keyed providers use your own key, and a custom XYZ template is accepted.',
},
{
label: 'Right-click the ground',
@@ -224,7 +224,19 @@ export const GUIDE = [
},
{
label: 'Compare keeps the ground fixed',
- text: 'Read two locked views side by side, by swipe, opacity or blink. Matched products also get Difference and Detect; notes, shapes and stamped markers stay editable in the saved comparison and appear in its outputs.',
+ text: 'Read two locked views side by side, by swipe, opacity or blink. On a matched pair, Difference highlights what changed over any of them; notes, shapes and stamped markers stay editable in the saved comparison and appear in its outputs.',
+ },
+ {
+ label: 'All dates, and when it appeared',
+ text: 'With the same dated archive on both sides, All dates lists every picture of the point under the crosshair. Put one without the thing on A and one with it on B, and Date it halves the gap until they are neighbours.',
+ },
+ {
+ label: 'Detect sweeps ground, once or again and again',
+ text: 'Name the ground the case watches once, say what to look for there, and read the pass. A one-off pass is reviewed and done; a routine keeps its areas, runs again on each new pass and gathers what you kept. Runs queue in the case and carry on while you work elsewhere.',
+ },
+ {
+ label: 'Radar sees through cloud',
+ text: 'The radar analyzers read Sentinel-1 through a layer you add to your Copernicus configuration, found from Settings → Imagery. A and B have to share a track, which the pass list marks.',
},
{
label: 'Coords & Sky keeps calculations separate',
diff --git a/frontend/src/lib/map/acquisitions.js b/frontend/src/lib/map/acquisitions.js
index b0090df..d43cffd 100644
--- a/frontend/src/lib/map/acquisitions.js
+++ b/frontend/src/lib/map/acquisitions.js
@@ -30,14 +30,20 @@ export const LOOKBACK_WINDOWS = Object.freeze([
export const FULL_COVER = 0.98;
/** The request body for a lookup over the areas currently drawn. */
-export function acquisitionQuery(zones, days, now = new Date()) {
+export function acquisitionQuery(zones, days, now = new Date(), collection = 'sentinel2') {
return {
zones: zones.map(({ id, name, kind, points }) => ({ id, name, kind, points })),
start: daysBefore(days, now),
end: isoDay(now),
+ collection,
};
}
+/** One pass as a key: a radar day can hold two passes, morning and evening. */
+export function passKey(entry) {
+ return entry?.time ? `${entry.date}T${entry.time}` : entry?.date ?? '';
+}
+
/**
* What a coverage share was measured over, as a comparable key.
*
diff --git a/frontend/src/lib/map/analyzers.js b/frontend/src/lib/map/analyzers.js
index 2aa9827..6ad5276 100644
--- a/frontend/src/lib/map/analyzers.js
+++ b/frontend/src/lib/map/analyzers.js
@@ -36,6 +36,9 @@ export function displayGroups(rows, project, radius = 24) {
/** A source as a date; runs saved before Detect went Copernicus-only name their release. */
export function sourceLabel(source) {
if (source.provider === 'esri-wayback') return `Wayback release ${source.release}`;
+ if (source.provider === 'sentinel1' && source.date && source.time) {
+ return `${source.date} ${source.time.slice(0, 5)} UTC`;
+ }
return source.date || 'no date yet';
}
@@ -161,7 +164,8 @@ export function coverage(zones, grid) {
*/
export const SECONDS_PER_FRAME = 0.35;
-/** Frames fetched per tile: for each date, the picture reviewed and the bands measured. */
+/** Frames fetched per tile: for each date, the picture reviewed and the bands measured.
+ * The catalogue states its own figure per method (`frames`), which wins. */
export function framesPerTile({ single = false } = {}) {
return single ? 2 : 4;
}
@@ -187,3 +191,35 @@ export function viewZone(bounds, name = 'Current view') {
points: [[west, north], [east, south]],
};
}
+
+/**
+ * The built-ins as the catalogue groups them, by what an analyst looks for,
+ * and the analyst's own after them. A built-in no group names still shows,
+ * under Other, so a catalogue ahead of this list never hides one.
+ */
+export function analyzerGroups(catalogue) {
+ const builtins = catalogue?.builtins ?? [];
+ const groups = catalogue?.groups?.length
+ ? catalogue.groups.map((group) => ({
+ label: group.label,
+ list: group.recipes.map((id) => builtins.find((entry) => entry.id === id)).filter(Boolean),
+ }))
+ : [{ label: 'Built in', list: builtins }];
+ const grouped = new Set(groups.flatMap((group) => group.list.map((entry) => entry.id)));
+ const rest = builtins.filter((entry) => !grouped.has(entry.id));
+ if (rest.length) groups.push({ label: 'Other', list: rest });
+ if (catalogue?.custom?.length) groups.push({ label: 'Mine', list: catalogue.custom });
+ return groups.filter((group) => group.list.length);
+}
+
+/**
+ * Why an analyzer cannot run yet, or '' when it can: every one without a
+ * Copernicus key, the radar ones until Settings has found their layer.
+ */
+export function analyzerLock(entry, catalogue) {
+ if (!entry || !catalogue) return '';
+ if (catalogue.copernicus_key === false) return 'Needs a free Copernicus key';
+ const method = catalogue.methods?.find((candidate) => candidate.id === entry.method);
+ if (method?.sensor === 'sentinel1' && !catalogue.radar_layer) return 'Needs the Sentinel-1 layer';
+ return '';
+}
diff --git a/frontend/src/lib/map/analyzers.test.js b/frontend/src/lib/map/analyzers.test.js
index c2c73e9..39f9493 100644
--- a/frontend/src/lib/map/analyzers.test.js
+++ b/frontend/src/lib/map/analyzers.test.js
@@ -1,19 +1,5 @@
import { describe, expect, it } from 'vitest';
-import {
- coverage,
- describeMeasure,
- displayGroups,
- framesPerTile,
- mapSource,
- readableDuration,
- marksToZones,
- sizeBand,
- sizeOf,
- sourceLabel,
- viewZone,
- zoneMarks,
- zoneRing,
-} from './analyzers.js';
+import { analyzerGroups, analyzerLock, coverage, describeMeasure, displayGroups, framesPerTile, mapSource, marksToZones, readableDuration, sizeBand, sizeOf, sourceLabel, viewZone, zoneMarks, zoneRing } from './analyzers.js';
describe('saved analysis geometry', () => {
it('keeps geographic points and names when drawings are edited', () => {
@@ -122,3 +108,27 @@ describe('what a candidate says about itself', () => {
expect(sizeBand({ min_area: 0, max_area: 0 })).toContain('Any size');
});
});
+
+describe('the analyzer list', () => {
+ const catalogue = {
+ builtins: [{ id: 'boats', method: 'vessels' }, { id: 'radar-vessels', method: 'sar-vessels' }, { id: 'new', method: 'surface' }],
+ custom: [{ id: 'custom-1', method: 'vessels' }],
+ methods: [{ id: 'vessels', sensor: 'sentinel2' }, { id: 'sar-vessels', sensor: 'sentinel1' }, { id: 'surface', sensor: 'sentinel2' }],
+ groups: [{ id: 'vessels', label: 'Vessels', recipes: ['radar-vessels', 'boats'] }],
+ copernicus_key: true,
+ radar_layer: '',
+ };
+
+ it('groups the built-ins by what they look for, and shows one no group names', () => {
+ expect(analyzerGroups(catalogue).map((group) => [group.label, group.list.map((entry) => entry.id)])).toEqual([
+ ['Vessels', ['radar-vessels', 'boats']], ['Other', ['new']], ['Mine', ['custom-1']]]);
+ expect(analyzerGroups({ builtins: [{ id: 'a' }] })).toEqual([{ label: 'Built in', list: [{ id: 'a' }] }]);
+ });
+
+ it('locks every analyzer without a key, and radar ones without their layer', () => {
+ expect(analyzerLock(catalogue.builtins[0], catalogue)).toBe('');
+ expect(analyzerLock(catalogue.builtins[1], catalogue)).toBe('Needs the Sentinel-1 layer');
+ expect(analyzerLock(catalogue.builtins[1], { ...catalogue, radar_layer: 'RADAR' })).toBe('');
+ expect(analyzerLock(catalogue.builtins[0], { ...catalogue, copernicus_key: false })).toBe('Needs a free Copernicus key');
+ });
+});
diff --git a/frontend/src/lib/map/changeAssist.js b/frontend/src/lib/map/changeAssist.js
index b59d32b..7a25733 100644
--- a/frontend/src/lib/map/changeAssist.js
+++ b/frontend/src/lib/map/changeAssist.js
@@ -13,6 +13,8 @@
* The detection itself lives in `changeDetect.js` and runs in a worker.
*/
+import { RADAR_ID, sameTrack } from '../radar.js';
+
const same = (left, right) => JSON.stringify(left) === JSON.stringify(right);
export const CHANGE_METHODS = Object.freeze([
@@ -71,15 +73,13 @@ export const CHANGE_PALETTES = Object.freeze({
export const CHANGE_CLASSES = Object.freeze(['gain', 'loss', 'changed']);
/**
- * What the highlighted pixels are laid over. One image answers "where did it
- * change"; the pair answers "change from what into what", which is the question
- * a single base cannot show at all — so it is offered beside the other two
- * rather than buried as a background setting.
+ * Which images carry the highlights, whatever view mode the pair is read in.
+ * Both is the default: "change from what into what" needs the two pictures.
*/
export const CHANGE_BASES = Object.freeze([
{ id: 'a', label: 'A' },
{ id: 'b', label: 'B' },
- { id: 'side', label: 'Both' },
+ { id: 'both', label: 'Both' },
]);
export const CHANGE_DEFAULTS = Object.freeze({
@@ -104,8 +104,7 @@ export const CHANGE_DEFAULTS = Object.freeze({
palette: 'directional',
zones: true,
opacity: 70,
- base: 'b',
- visible: true,
+ base: 'both',
blink: false,
});
@@ -141,7 +140,6 @@ export function changeSettings(raw = {}) {
zones: value.zones ?? CHANGE_DEFAULTS.zones,
opacity: whole(value.opacity, 0, 100, CHANGE_DEFAULTS.opacity),
base: pick(value.base, CHANGE_BASES.map((entry) => entry.id), CHANGE_DEFAULTS.base),
- visible: value.visible !== false,
blink: value.blink === true,
};
}
@@ -203,6 +201,34 @@ export function changeCompatibility(a, b) {
};
}
+ if (a.provider === RADAR_ID && b.provider === RADAR_ID) {
+ const passA = a.radar ?? {};
+ const passB = b.radar ?? {};
+ if (!passA.date || !passB.date) return refuse('Choose a dated Sentinel-1 pass on both sides.');
+ if (passA.date === passB.date && passA.time === passB.time) {
+ return refuse('Choose two different Sentinel-1 passes.');
+ }
+ // Another track sees the ground from another angle, and that difference is
+ // not change. The picker marks the passes on the other side's track.
+ if (!sameTrack(passA.time, passB.time)) {
+ return refuse('Radar compares two passes of one track. Pick passes at the same time of day.');
+ }
+ if (!same(layerReading(a), layerReading(b))) {
+ return refuse('Match the reference layers on A and B before comparing pixels.');
+ }
+ return {
+ ok: true,
+ family: 'sentinel1',
+ clouds: false,
+ grade: 'indicative',
+ label: 'Sentinel-1 radar',
+ from: passA.date,
+ to: passB.date,
+ notes: ['Reads the rendered radar picture. Detect measures the backscatter itself.'],
+ methods: PIXEL_METHODS,
+ };
+ }
+
if (ESRI.has(a.provider) && ESRI.has(b.provider)) {
const releaseA = a.provider === 'esri-wayback' ? a.waybackRelease : 'current';
const releaseB = b.provider === 'esri-wayback' ? b.waybackRelease : 'current';
diff --git a/frontend/src/lib/map/changeAssist.test.js b/frontend/src/lib/map/changeAssist.test.js
index d057ddd..5344f79 100644
--- a/frontend/src/lib/map/changeAssist.test.js
+++ b/frontend/src/lib/map/changeAssist.test.js
@@ -126,7 +126,32 @@ describe('Difference settings', () => {
min_area: 0,
classes: ['loss'],
opacity: 35,
- base: 'b',
+ base: 'both',
});
});
+
+ it('lays the highlights over both images unless told otherwise', () => {
+ expect(changeSettings().base).toBe('both');
+ // "side" was the name Both had when it was a layout of its own
+ expect(changeSettings({ base: 'side' }).base).toBe('both');
+ expect(changeSettings({ base: 'a' }).base).toBe('a');
+ });
+});
+
+describe('a radar pair', () => {
+ const radar = (date, time) => side({ provider: 'sentinel1', radar: { date, time } });
+
+ it('reads two passes of one track, as a picture and without tone matching', () => {
+ const status = changeCompatibility(radar('2026-05-02', '05:42:10'), radar('2026-05-14', '05:42:40'));
+ expect(status).toMatchObject({ ok: true, family: 'sentinel1', grade: 'indicative', clouds: false });
+ expect(status.methods).toEqual(['colour', 'structure', 'brightness']);
+ });
+
+ it('refuses another track, the same pass, or an undated side', () => {
+ expect(changeCompatibility(radar('2026-05-02', '05:42:10'), radar('2026-05-14', '17:33:02')).reason)
+ .toMatch(/one track/);
+ expect(changeCompatibility(radar('2026-05-14', '05:42:10'), radar('2026-05-14', '05:42:10')).reason)
+ .toMatch(/two different/);
+ expect(changeCompatibility(radar('', ''), radar('2026-05-14', '05:42:10')).ok).toBe(false);
+ });
});
diff --git a/frontend/src/lib/map/changeDetect.js b/frontend/src/lib/map/changeDetect.js
index 26bef7f..116e4f2 100644
--- a/frontend/src/lib/map/changeDetect.js
+++ b/frontend/src/lib/map/changeDetect.js
@@ -803,10 +803,11 @@ export function detectChange({
// Two Sentinel-2 passes are already corrected to surface reflectance and
// rendered by one formula, so there is no exposure left to match — only real
// change, which a match would eat: a burn over most of a view moves the
- // histogram, and matching it puts the view back the way it was.
+ // histogram, and matching it puts the view back the way it was. Two radar
+ // passes of one track are calibrated backscatter drawn by one formula too.
const tone = settings.normalize !== 'auto'
? settings.normalize
- : (family === 'sentinel2' ? 'none' : 'histogram');
+ : (family === 'sentinel2' || family === 'sentinel1' ? 'none' : 'histogram');
const keep = blocked ? blocked.map((flag) => (flag ? 0 : 1)) : null;
const toned = usesPixels ? matchTone(a, registered, tone, keep) : registered;
const measured = measure(a, toned, width, height, settings, decoded, blocked);
diff --git a/frontend/src/lib/map/compare.js b/frontend/src/lib/map/compare.js
index e3ff160..d7601c4 100644
--- a/frontend/src/lib/map/compare.js
+++ b/frontend/src/lib/map/compare.js
@@ -1,27 +1,22 @@
/** Pure parts of the two-surface imagery comparison tool. */
/**
- * Every mode is one row of buttons, but they answer two different questions,
- * and running them together is what made the tool unreadable. `read` modes
- * only change how the pair is shown at the camera you are on. `find` modes
- * compute something: Difference reads the pixels on screen right now, Detect
- * sweeps a drawn area at full resolution and keeps what it found. The dock
- * draws a rule between the groups, and each `find` mode owns its whole panel
- * rather than sharing one with a cross-link.
+ * How the pair is shown at the camera you are on. Difference is not one of
+ * them: it is a layer of highlights laid over whichever of these is on.
*/
export const COMPARE_MODES = Object.freeze([
- { id: 'side', label: 'Side by side', short: 'Side', icon: 'columns', key: '1', group: 'read' },
- { id: 'swipe', label: 'Swipe', short: 'Swipe', icon: 'swipe', key: '2', group: 'read' },
- { id: 'opacity', label: 'Fade', short: 'Fade', icon: 'fade', key: '3', group: 'read' },
- { id: 'blink', label: 'Blink', short: 'Blink', icon: 'blink', key: '4', group: 'read' },
- { id: 'change', label: 'Difference', short: 'Diff', icon: 'changes', key: '5', group: 'find' },
- { id: 'analysis', label: 'Detect', short: 'Detect', icon: 'grid', key: '6', group: 'find' },
+ { id: 'side', label: 'Side by side', short: 'Side', icon: 'columns', key: '1' },
+ { id: 'swipe', label: 'Swipe', short: 'Swipe', icon: 'swipe', key: '2' },
+ { id: 'opacity', label: 'Fade', short: 'Fade', icon: 'fade', key: '3' },
+ { id: 'blink', label: 'Blink', short: 'Blink', icon: 'blink', key: '4' },
]);
-/** Modes that lay a computed result over the pair rather than restyling it. */
-export const FIND_MODES = Object.freeze(
- COMPARE_MODES.filter((entry) => entry.group === 'find').map((entry) => entry.id)
-);
+export const DIFFERENCE_KEY = '5';
+
+/** A saved view mode, with the one that used to be Difference read as side by side. */
+export function compareMode(value) {
+ return COMPARE_MODES.some((entry) => entry.id === value) ? value : 'side';
+}
export const DEFAULT_DIVIDER = 50;
export const DEFAULT_OPACITY = 50;
@@ -69,7 +64,7 @@ export function percentage(value, fallback = 50) {
/** How a provider is offered in the picker: imagery, a dated archive, or a map. */
export function providerKind(provider) {
- if (provider?.id === 'esri-wayback' || provider?.id === 'sentinel2') return 'archive';
+ if (['esri-wayback', 'sentinel2', 'sentinel1'].includes(provider?.id)) return 'archive';
return provider?.imagery === false ? 'map' : 'imagery';
}
@@ -98,6 +93,13 @@ export const COMPARE_PRESETS = Object.freeze([
a: 'sentinel2',
b: 'sentinel2',
},
+ {
+ id: 'radar',
+ label: 'Two radar passes',
+ hint: 'Sentinel-1 on both sides, through cloud and at night',
+ a: 'sentinel1',
+ b: 'sentinel1',
+ },
{
id: 'map',
label: 'Imagery and map',
@@ -107,6 +109,9 @@ export const COMPARE_PRESETS = Object.freeze([
},
]);
+/** What Compare opens on: an archive against today, both key-less. */
+export const DEFAULT_PRESET = 'archive';
+
/** The presets this catalogue can actually start. */
export function availablePresets(providers) {
const usable = new Set(
diff --git a/frontend/src/lib/map/compare.test.js b/frontend/src/lib/map/compare.test.js
index d118962..d1adebe 100644
--- a/frontend/src/lib/map/compare.test.js
+++ b/frontend/src/lib/map/compare.test.js
@@ -2,22 +2,26 @@ import { describe, expect, it } from 'vitest';
import {
COMPARE_LAYERS,
COMPARE_MODES,
- FIND_MODES,
+ DIFFERENCE_KEY,
availablePresets,
+ compareMode,
comparisonLayers,
percentage,
providerKind,
} from './compare.js';
describe('compare helpers', () => {
- it('offers six modes with a key each, split into reading and computing', () => {
- expect(COMPARE_MODES.map((mode) => mode.id)).toEqual(['side', 'swipe', 'opacity', 'blink', 'change', 'analysis']);
- expect(COMPARE_MODES.map((mode) => mode.key)).toEqual(['1', '2', '3', '4', '5', '6']);
- // The dock rules the two groups apart, so they have to stay contiguous.
- expect(COMPARE_MODES.map((mode) => mode.group)).toEqual(
- ['read', 'read', 'read', 'read', 'find', 'find']
- );
- expect(FIND_MODES).toEqual(['change', 'analysis']);
+ it('offers four view modes with a key each, and Difference on the next key', () => {
+ expect(COMPARE_MODES.map((mode) => mode.id)).toEqual(['side', 'swipe', 'opacity', 'blink']);
+ expect(COMPARE_MODES.map((mode) => mode.key)).toEqual(['1', '2', '3', '4']);
+ expect(DIFFERENCE_KEY).toBe('5');
+ });
+
+ it('reads a saved mode back, the old Difference mode as side by side', () => {
+ expect(compareMode('swipe')).toBe('swipe');
+ expect(compareMode('change')).toBe('side');
+ expect(compareMode('analysis')).toBe('side');
+ expect(compareMode(undefined)).toBe('side');
});
it('keeps layers ordered, unique and supported', () => {
@@ -52,5 +56,8 @@ describe('compare helpers', () => {
expect(ids(free)).toEqual(['archive', 'map']);
expect(ids([...free, { id: 'sentinel2', needs_key: true }])).toEqual(['archive', 'map']);
expect(ids([...free, { id: 'sentinel2' }])).toEqual(['archive', 'sentinel', 'map']);
+ // radar arrives once Settings has found its layer
+ expect(ids([...free, { id: 'sentinel2' }, { id: 'sentinel1' }])).toEqual(['archive', 'sentinel', 'radar', 'map']);
+ expect(providerKind({ id: 'sentinel1' })).toBe('archive');
});
});
diff --git a/frontend/src/lib/map/compareAnnotations.js b/frontend/src/lib/map/compareAnnotations.js
index c7828a4..57bcb7c 100644
--- a/frontend/src/lib/map/compareAnnotations.js
+++ b/frontend/src/lib/map/compareAnnotations.js
@@ -7,12 +7,19 @@
* an arrow at a spot on both. Screen positions are derived on demand through a
* projection the caller supplies (the live map, or an export frame).
*
- * Rectangles and ellipses are shapes on the ground: two opposite corners, drawn
- * turned when the map is turned. Measures and polygons read their length and
- * area off the ground, not the screen.
+ * Rectangles and ellipses are shapes on the ground: two opposite corners, and
+ * as `angle` the compass direction that was up on the screen they were drawn
+ * on (`groundFrame`'s bearing, not the app's clockwise turn), so a box drawn on a
+ * turned map runs along that screen and turns with the ground after. Turning a
+ * mark turns its points about its centre, and a box's angle with them.
+ * Measures and polygons read their length and area off the ground, not the
+ * screen.
*/
import { formatArea, formatDistance, haversine, polygonArea } from '../measure.js';
+import {
+ boxCorners, boxPoint, compassAngle, fromMercator, toMercator, turnAbout, turnedBox,
+} from './groundFrame.js';
import {
ICON_BOX, PROOF_ICONS, glyphInk, iconByName, iconOrigin, isSolidIcon,
} from '../proofIcons.js';
@@ -50,6 +57,12 @@ const LIMITS = {
export const canFill = (kind) => kind === 'rect' || kind === 'ellipse' || kind === 'polygon';
+/** The kinds whose sides follow an angle rather than the points alone. */
+export const ANGLED = new Set(['rect', 'ellipse']);
+
+/** The kinds a turn means anything to: one point turns about itself. */
+export const TURNABLE = new Set(['arrow', 'line', 'measure', 'rect', 'ellipse', 'polygon', 'freehand']);
+
const bounded = (value, fallback, min, max) => {
const number = Number(value);
return Math.min(max, Math.max(min, Number.isFinite(number) ? number : fallback));
@@ -91,6 +104,7 @@ export function comparisonAnnotations(value) {
// so a comparison made on a newer version still shows a mark there.
number: Math.round(bounded(raw.number, 1, 1, 999)),
glyph: iconByName(raw.glyph) ? String(raw.glyph) : PROOF_ICONS[0].name,
+ angle: ANGLED.has(raw.kind) ? compassAngle(raw.angle) : 0,
}];
});
}
@@ -148,7 +162,14 @@ export function nextMarkNumber(marks, colour) {
const asLatLon = ([lon, lat]) => ({ lat, lon });
/** An ellipse inscribed in the ground box of two corners, as a ring of ground points. */
-export function ellipseRing([first, second], steps = 48) {
+export function ellipseRing([first, second], steps = 48, angle = 0) {
+ if (angle) {
+ const box = turnedBox([first, second], angle);
+ return Array.from({ length: steps }, (_, step) => {
+ const turn = (step / steps) * Math.PI * 2;
+ return boxPoint(box, Math.cos(turn) / 2, Math.sin(turn) / 2);
+ });
+ }
const centreLon = (first[0] + second[0]) / 2;
const centreLat = (first[1] + second[1]) / 2;
const radiusLon = Math.abs(second[0] - first[0]) / 2;
@@ -159,15 +180,15 @@ export function ellipseRing([first, second], steps = 48) {
});
}
-/** A ground box of two corners as its four ground corners. */
-export const boxRing = ([first, second]) => [
- first, [second[0], first[1]], second, [first[0], second[1]],
-];
+/** A ground box of two corners as its four ground corners, its sides along `angle`. */
+export const boxRing = ([first, second], angle = 0) => (angle
+ ? boxCorners(turnedBox([first, second], angle))
+ : [first, [second[0], first[1]], second, [first[0], second[1]]]);
/** The ground ring a filled mark encloses, or null for a mark with no inside. */
export function markRing(mark) {
- if (mark.kind === 'rect') return boxRing(mark.points);
- if (mark.kind === 'ellipse') return ellipseRing(mark.points);
+ if (mark.kind === 'rect') return boxRing(mark.points, mark.angle ?? 0);
+ if (mark.kind === 'ellipse') return ellipseRing(mark.points, 48, mark.angle ?? 0);
if (mark.kind === 'polygon') return mark.points;
return null;
}
@@ -200,6 +221,42 @@ export function movedMark(mark, dLon, dLat) {
};
}
+/**
+ * The ground point a mark turns about: a box's own centre, or the middle of
+ * whatever the points span.
+ */
+export function markCentre(mark) {
+ if (ANGLED.has(mark.kind)) return fromMercator(...turnedBox(mark.points, mark.angle ?? 0).centre);
+ const metres = mark.points.map((point) => toMercator(...point));
+ const xs = metres.map((point) => point[0]);
+ const ys = metres.map((point) => point[1]);
+ return fromMercator((Math.min(...xs) + Math.max(...xs)) / 2, (Math.min(...ys) + Math.max(...ys)) / 2);
+}
+
+/**
+ * Where a box's top edge crosses its own up axis, which is where the grip that
+ * turns it sits: it turns with the box rather than hanging off the screen.
+ * Null for a mark with no sides of its own.
+ */
+export function markTop(mark) {
+ if (!ANGLED.has(mark.kind)) return null;
+ const box = turnedBox(mark.points, mark.angle ?? 0);
+ return boxPoint(box, 0, -Math.sign(box.height || 1) / 2);
+}
+
+/** A mark turned clockwise by `degrees` about `pivot`, its points clamped to the map. */
+export function turnedMark(mark, pivot, degrees) {
+ if (!TURNABLE.has(mark.kind) || !degrees) return mark;
+ return {
+ ...mark,
+ points: mark.points.map((point) => {
+ const [lon, lat] = turnAbout(point, pivot, degrees);
+ return [Math.min(180, Math.max(-180, lon)), Math.min(85, Math.max(-85, lat))];
+ }),
+ ...(ANGLED.has(mark.kind) ? { angle: compassAngle((mark.angle ?? 0) + degrees) } : {}),
+ };
+}
+
/**
* Screen geometry for one mark under a projection `([lon, lat]) => [x, y]`.
* `path` is the outline to stroke (closed when `closed`), `anchor` where its
diff --git a/frontend/src/lib/map/compareAnnotations.test.js b/frontend/src/lib/map/compareAnnotations.test.js
index 27d35ef..2a86c8c 100644
--- a/frontend/src/lib/map/compareAnnotations.test.js
+++ b/frontend/src/lib/map/compareAnnotations.test.js
@@ -5,14 +5,19 @@ import {
ellipseRing,
glyphBox,
markGlyph,
+ markCentre,
markLabel,
markMetric,
+ markRing,
+ markTop,
markSize,
movedMark,
nextMarkNumber,
onSide,
projectMark,
+ turnedMark,
} from './compareAnnotations.js';
+import { toMercator } from './groundFrame.js';
const mark = (patch) => ({ id: 'm', colour: '#f6a81a', side: 'both', ...patch });
@@ -29,10 +34,19 @@ describe('ground annotations', () => {
])).toEqual([{
id: 'm', kind: 'rect', side: 'both', colour: '#ff0000',
points: [[2, 48], [2.1, 48.1]], stroke_width: 3, fill_opacity: 1, font_size: 16, text: '',
- number: 1, glyph: 'point',
+ number: 1, glyph: 'point', angle: 0,
}]);
});
+ it('keeps the angle a box was drawn at, and only on the kinds that have sides', () => {
+ const [box, line] = comparisonAnnotations([
+ mark({ kind: 'rect', points: [[2, 48], [2.1, 48.1]], angle: -30 }),
+ mark({ kind: 'line', points: [[2, 48], [2.1, 48.1]], angle: 40 }),
+ ]);
+ expect(box.angle).toBeCloseTo(330);
+ expect(line.angle).toBe(0);
+ });
+
it('belongs to one side or both', () => {
expect(onSide(mark({ side: 'a' }), 'a')).toBe(true);
expect(onSide(mark({ side: 'a' }), 'b')).toBe(false);
@@ -60,6 +74,52 @@ describe('ground annotations', () => {
expect(ring[1][1]).toBeCloseTo(1);
});
+ it('draws a box along the screen it was drawn on, not along north', () => {
+ // Drawn on an east-up screen, top-left to bottom-right: its first side runs
+ // south from the first corner, and its second runs west.
+ const points = [[0, 0.001], [-0.002, -0.001]];
+ const ring = markRing(mark({ kind: 'rect', points, angle: 90 }));
+ expect(ring).toHaveLength(4);
+ expect(ring[1][0]).toBeCloseTo(0, 9);
+ expect(ring[1][1]).toBeCloseTo(-0.001, 9);
+ expect(ring[3][0]).toBeCloseTo(-0.002, 9);
+ expect(ring[3][1]).toBeCloseTo(0.001, 9);
+ expect(markRing(mark({ kind: 'ellipse', points, angle: 90 }))).toHaveLength(48);
+ const centre = markCentre(mark({ kind: 'ellipse', points, angle: 90 }));
+ expect(centre[0]).toBeCloseTo(-0.001, 9);
+ expect(centre[1]).toBeCloseTo(0, 9);
+ });
+
+ it("turns a mark about its centre, and a box's sides with it", () => {
+ const box = mark({ kind: 'rect', points: [[0, 0], [0.002, -0.001]], angle: 0 });
+ const turned = turnedMark(box, markCentre(box), 90);
+ expect(turned.angle).toBe(90);
+ // The same box, stood on end: its ring holds the same four corners turned.
+ const metres = (ring) => ring.map((point) => toMercator(...point));
+ const [a, b] = metres(markRing(turned));
+ const [c, d] = metres(markRing(box));
+ expect(Math.hypot(b[0] - a[0], b[1] - a[1])).toBeCloseTo(Math.hypot(d[0] - c[0], d[1] - c[1]), 3);
+ expect(Math.abs(b[1] - a[1])).toBeGreaterThan(Math.abs(b[0] - a[0]));
+ const polygon = mark({ kind: 'polygon', points: [[0, 0], [0.002, 0], [0.001, 0.001]] });
+ const spun = turnedMark(polygon, markCentre(polygon), 180);
+ expect(spun.points[0][0]).toBeCloseTo(0.002, 9);
+ expect(spun.angle).toBeUndefined();
+ // One point turns about itself, which is no turn at all.
+ const stamp = mark({ kind: 'number', points: [[1, 1]] });
+ expect(turnedMark(stamp, [0, 0], 90)).toBe(stamp);
+ });
+
+ it("stands the turn grip on a box's own top edge", () => {
+ const box = mark({ kind: 'rect', points: [[0, 0.002], [0.002, 0]], angle: 0 });
+ const top = markTop(box);
+ expect(top[0]).toBeCloseTo(0.001, 9);
+ expect(top[1]).toBeCloseTo(0.002, 9);
+ // Drawn from the bottom corner up, the top is still the top.
+ const upward = markTop(mark({ kind: 'rect', points: [[0, 0], [0.002, 0.002]], angle: 0 }));
+ expect(upward[1]).toBeCloseTo(0.002, 9);
+ expect(markTop(mark({ kind: 'polygon', points: [[0, 0], [1, 0], [1, 1]] }))).toBeNull();
+ });
+
it('projects a box as a closed ring and an arrow with a head', () => {
const project = ([lon, lat]) => [lon * 100, -lat * 100];
const box = projectMark(mark({ kind: 'rect', points: [[0, 0], [1, 1]] }), project);
diff --git a/frontend/src/lib/map/compareExport.js b/frontend/src/lib/map/compareExport.js
index eb35ddb..99050e6 100644
--- a/frontend/src/lib/map/compareExport.js
+++ b/frontend/src/lib/map/compareExport.js
@@ -145,7 +145,7 @@ function drawChangeMask(ctx, mask, target, x, y, pixelScale, opacity) {
ctx.beginPath();
ctx.rect(x, y, target.width * pixelScale, target.height * pixelScale);
ctx.clip();
- ctx.globalAlpha = clamp(opacity, 0, 100) / 100;
+ ctx.globalAlpha *= clamp(opacity, 0, 100) / 100;
ctx.imageSmoothingEnabled = false;
ctx.setTransform?.(1, 0, 0, 1, 0, 0);
ctx.transform(toTarget.a, toTarget.b, toTarget.c, toTarget.d, toTarget.e + x, toTarget.f + y);
@@ -157,7 +157,8 @@ function drawChangeMask(ctx, mask, target, x, y, pixelScale, opacity) {
* @param {object} input
* @param {{canvas: HTMLCanvasElement, frame: object}} input.a A as captured, with its camera frame
* @param {{canvas: HTMLCanvasElement, frame: object}} input.b
- * @param {'side'|'swipe'|'opacity'|'blink'|'change'} input.mode
+ * @param {'side'|'swipe'|'opacity'|'blink'} input.mode
+ * @param {object|null} input.change a finished difference to lay over the view, or null
*/
export function composeComparison({
a,
@@ -182,16 +183,16 @@ export function composeComparison({
throw new Error('both maps must be ready before they can be exported');
}
+ if (change && !(change.canvas?.width && change.frame)) {
+ throw new Error('the difference must finish before it can be exported');
+ }
const pixelScale = a.canvas.width / a.frame.width;
const s = pixelScale;
- // A difference laid over both images is two panes, like side by side, with
- // the same mask drawn on each through that pane's own frame.
- const pairedChange = mode === 'change' && change?.base === 'side';
- const side = mode === 'side' || pairedChange;
+ const side = mode === 'side';
const mapWidth = side ? a.canvas.width + b.canvas.width : Math.max(a.canvas.width, b.canvas.width);
const mapHeight = Math.max(a.canvas.height, b.canvas.height);
const header = Math.round((title ? 64 : 48) * s);
- const legend = mode === 'change' && change ? Math.round(30 * s) : 0;
+ const legend = change ? Math.round(30 * s) : 0;
const footer = Math.round(26 * s) + legend;
const output = canvasOf(mapWidth, header + mapHeight + footer, makeCanvas);
const ctx = output.getContext('2d');
@@ -213,6 +214,12 @@ export function composeComparison({
draw();
ctx.restore();
};
+ // The highlights ride on the image they were asked over, in whatever view.
+ const maskOn = (capture, letter, offsetX) => {
+ if (!change || change.opacity <= 0) return;
+ if (change.base !== 'both' && change.base !== letter) return;
+ drawChangeMask(ctx, change, capture.frame, offsetX, top, s, change.opacity);
+ };
const markAnnotations = (capture, letter, offsetX) => {
const marks = annotations.filter((mark) => onSide(mark, letter));
clipped(offsetX, capture.canvas.width, capture.canvas.height, () =>
@@ -221,15 +228,10 @@ export function composeComparison({
};
if (side) {
- if (pairedChange && !(change?.canvas?.width && change?.frame)) {
- throw new Error('change assist must finish before it can be exported');
- }
ctx.drawImage(a.canvas, 0, top);
ctx.drawImage(b.canvas, paneB, top);
- if (pairedChange && change.visible !== false && change.opacity > 0) {
- drawChangeMask(ctx, change, a.frame, 0, top, s, change.opacity);
- drawChangeMask(ctx, change, b.frame, paneB, top, s, change.opacity);
- }
+ maskOn(a, 'a', 0);
+ maskOn(b, 'b', paneB);
markAnnotations(a, 'a', 0);
markAnnotations(b, 'b', paneB);
ctx.fillStyle = 'rgba(255,255,255,.92)';
@@ -243,6 +245,7 @@ export function composeComparison({
ctx.rect(0, top, split, mapHeight);
ctx.clip();
ctx.drawImage(a.canvas, 0, top);
+ maskOn(a, 'a', 0);
markAnnotations(a, 'a', 0);
ctx.restore();
ctx.save();
@@ -250,6 +253,7 @@ export function composeComparison({
ctx.rect(split, top, mapWidth - split, mapHeight);
ctx.clip();
ctx.drawImage(b.canvas, 0, top);
+ maskOn(b, 'b', 0);
markAnnotations(b, 'b', 0);
ctx.restore();
ctx.fillStyle = 'rgba(255,255,255,.95)';
@@ -260,9 +264,12 @@ export function composeComparison({
}
} else if (mode === 'opacity') {
ctx.drawImage(a.canvas, 0, top);
+ maskOn(a, 'a', 0);
+ // B's highlights fade with B, as they do on screen.
ctx.save();
ctx.globalAlpha = clamp(Number(opacity), 0, 100) / 100;
ctx.drawImage(b.canvas, 0, top);
+ maskOn(b, 'b', 0);
ctx.restore();
markAnnotations(a, 'a', 0);
const onlyB = annotations.filter((mark) => mark.side === 'b');
@@ -270,22 +277,11 @@ export function composeComparison({
drawAnnotations(ctx, onlyB, captureProjection(b, 0, top), { scale: s, units })
);
drawTag(ctx, `B ${Math.round(opacity)}%`, mapWidth - 12 * s, top + 12 * s, { scale: s, accent: true, align: 'right' });
- } else if (mode === 'change') {
- if (!change?.canvas?.width || !change?.frame) {
- throw new Error('change assist must finish before it can be exported');
- }
- const base = change.base === 'a' ? a : b;
- const letter = change.base === 'a' ? 'a' : 'b';
- ctx.drawImage(base.canvas, 0, top);
- if (change.visible !== false && change.opacity > 0) {
- drawChangeMask(ctx, change, base.frame, 0, top, s, change.opacity);
- }
- markAnnotations(base, letter, 0);
- drawTag(ctx, `Base ${letter.toUpperCase()}`, mapWidth - 12 * s, top + 12 * s, { scale: s, accent: true, align: 'right' });
} else {
const shown = mode === 'blink' && blinkB ? b : a;
const letter = shown === b ? 'b' : 'a';
ctx.drawImage(shown.canvas, 0, top);
+ maskOn(shown, letter, 0);
markAnnotations(shown, letter, 0);
drawTag(ctx, letter.toUpperCase(), 12 * s, top + 12 * s, { scale: s, accent: true });
}
diff --git a/frontend/src/lib/map/compareExport.test.js b/frontend/src/lib/map/compareExport.test.js
index eeeeb2b..5d3ad54 100644
--- a/frontend/src/lib/map/compareExport.test.js
+++ b/frontend/src/lib/map/compareExport.test.js
@@ -99,30 +99,70 @@ describe('comparison export', () => {
expect(draws(out)[1][1]).toBe(BASE.b.canvas);
});
- it('draws the chosen base once and lays the change mask on its ground', () => {
- const mask = { canvas: { width: 250, height: 150 }, frame: FRAME, base: 'a', opacity: 55, visible: true };
- const out = composeComparison({ ...BASE, mode: 'change', change: mask });
- expect(draws(out).map((call) => call[1])).toEqual([BASE.a.canvas, mask.canvas]);
+ const mask = (base) => ({ canvas: { width: 250, height: 150 }, frame: FRAME, base, opacity: 55 });
+
+ it('lays the difference on its ground, scaled back up, with a legend', () => {
+ const change = mask('a');
+ const out = composeComparison({ ...BASE, mode: 'side', change });
+ expect(draws(out).map((call) => call[1])).toEqual([BASE.a.canvas, BASE.b.canvas, change.canvas]);
// the working mask is half the frame's size, so it is scaled back up
const [, a, , , d] = out.context.calls.find(([name]) => name === 'transform');
expect(a).toBeCloseTo(2);
expect(d).toBeCloseTo(2);
+ expect(out.width).toBe(1000);
expect(out.height).toBe(48 + 300 + 26 + 30);
});
- it('lays one reading over both images when the difference is shown on the pair', () => {
- const mask = { canvas: { width: 250, height: 150 }, frame: FRAME, base: 'side', opacity: 55, visible: true };
- const out = composeComparison({ ...BASE, mode: 'change', change: mask });
- expect(out.width).toBe(1000);
+ it('lays one reading over both panes side by side', () => {
+ const change = mask('both');
+ const out = composeComparison({ ...BASE, mode: 'side', change });
expect(draws(out).map((call) => call[1]))
- .toEqual([BASE.a.canvas, BASE.b.canvas, mask.canvas, mask.canvas]);
+ .toEqual([BASE.a.canvas, BASE.b.canvas, change.canvas, change.canvas]);
// The second copy is offset onto B's pane, not redrawn over A.
const offsets = out.context.calls.filter(([name]) => name === 'transform').map((call) => call[5]);
expect(offsets[1] - offsets[0]).toBe(500);
});
- it('refuses a change export without a finished mask', () => {
- expect(() => composeComparison({ ...BASE, mode: 'change' })).toThrow('must finish');
+ it('keeps the view mode under the difference', () => {
+ const change = mask('b');
+ const swipe = composeComparison({ ...BASE, mode: 'swipe', divider: 40, change });
+ expect(swipe.width).toBe(500);
+ expect(draws(swipe).map((call) => call[1])).toEqual([BASE.a.canvas, BASE.b.canvas, change.canvas]);
+ // blink shows the highlights only on the side that carries them
+ const onA = composeComparison({ ...BASE, mode: 'blink', blinkB: false, change });
+ expect(draws(onA).map((call) => call[1])).toEqual([BASE.a.canvas]);
+ const onB = composeComparison({ ...BASE, mode: 'blink', blinkB: true, change });
+ expect(draws(onB).map((call) => call[1])).toEqual([BASE.b.canvas, change.canvas]);
+ });
+
+ it('fades B’s highlights with B', () => {
+ const alphas = [];
+ const makeCanvas = () => {
+ const canvas = fakeCanvas();
+ const { context } = canvas;
+ const saved = [];
+ context.save = () => saved.push(context.globalAlpha);
+ context.restore = () => { context.globalAlpha = saved.pop(); };
+ context.drawImage = (image) => alphas.push([image, context.globalAlpha]);
+ return canvas;
+ };
+ const change = mask('b');
+ composeComparison({ ...BASE, makeCanvas, mode: 'opacity', opacity: 40, change });
+ // B's highlights are drawn inside B's faded pass: B's alpha times their own.
+ expect(alphas[0]).toEqual([BASE.a.canvas, 1]);
+ expect(alphas[1]).toEqual([BASE.b.canvas, 0.4]);
+ expect(alphas[2][0]).toBe(change.canvas);
+ expect(alphas[2][1]).toBeCloseTo(0.4 * 0.55);
+ });
+
+ it('draws nothing extra and no legend without a difference', () => {
+ const out = composeComparison({ ...BASE, mode: 'swipe', divider: 50 });
+ expect(draws(out).map((call) => call[1])).toEqual([BASE.a.canvas, BASE.b.canvas]);
+ expect(out.height).toBe(48 + 300 + 26);
+ });
+
+ it('refuses a difference export without a finished mask', () => {
+ expect(() => composeComparison({ ...BASE, mode: 'side', change: { base: 'both' } })).toThrow('must finish');
});
it('shows only the frame blink is on', () => {
@@ -153,8 +193,7 @@ describe('comparison export', () => {
});
it('drops a change legend entry that would run off a framed export', () => {
- const mask = { canvas: { width: 250, height: 150 }, frame: FRAME, base: 'a', opacity: 55, visible: true };
- const out = composeComparison({ ...BASE, a: FRAMED, b: FRAMED, mode: 'change', change: mask });
+ const out = composeComparison({ ...BASE, a: FRAMED, b: FRAMED, mode: 'blink', change: mask('a') });
const written = out.context.calls.filter(([name]) => name === 'fillText').map(([, text]) => text);
expect(written).toContain('Appeared or brighter in B');
expect(written).not.toContain('Other change');
diff --git a/frontend/src/lib/map/comparePair.js b/frontend/src/lib/map/comparePair.js
index 10e0714..836a730 100644
--- a/frontend/src/lib/map/comparePair.js
+++ b/frontend/src/lib/map/comparePair.js
@@ -18,9 +18,13 @@
* Nothing is fetched until a row is pressed: both lookups are requests.
*/
import { WAYBACK_ID } from '../wayback.js';
+import { RADAR_ID, onTrack } from '../radar.js';
export const SENTINEL_ID = 'sentinel2';
+/** How far back a radar lookup asks: a track repeats every six to twelve days. */
+export const RADAR_WINDOW_DAYS = 60;
+
/** How far back a Copernicus lookup asks. A pass every few days, so half a
* year is generous even where cloud hides most of them. */
export const SENTINEL_WINDOW_DAYS = 180;
@@ -39,6 +43,13 @@ export const COMPARE_SOURCES = [
/** Only offered when Sentinel-2 is configured. */
provider: SENTINEL_ID,
},
+ {
+ id: 'radar',
+ label: 'Copernicus radar',
+ detail: 'the last two passes of one track, through cloud',
+ /** Only offered once a Sentinel-1 layer is set up. */
+ provider: RADAR_ID,
+ },
];
const day = (date) => date.toISOString().slice(0, 10);
@@ -108,9 +119,44 @@ export async function sentinelPair(api, { lat, lon }, today = new Date()) {
};
}
+/**
+ * The two most recent Sentinel-1 passes of one track over a point.
+ *
+ * The newest pass sets the track, and the one before it on that track is its
+ * pair: another track sees the ground from another angle, and that difference
+ * would read as change.
+ */
+export async function radarPair(api, { lat, lon }, today = new Date()) {
+ const start = new Date(today);
+ start.setUTCDate(start.getUTCDate() - RADAR_WINDOW_DAYS);
+ const answer = await api.get(
+ `/api/satellite/sentinel/dates?collection=sentinel1&lat=${lat}&lon=${lon}&start=${day(start)}&end=${day(today)}`
+ );
+ const passes = (answer?.dates ?? []).filter((entry) => entry.time);
+ const [newer] = passes;
+ const older = newer ? onTrack(passes.slice(1), newer.time)[0] : null;
+ if (!newer || !older) {
+ throw new Error(
+ `Copernicus radar has ${newer ? 'one pass of this track' : 'no pass'} over this point in the last two months.`
+ );
+ }
+ const side = (entry) => ({
+ provider: RADAR_ID,
+ radar: { date: entry.date, time: entry.time },
+ present: true,
+ });
+ return {
+ title: 'Radar · this point',
+ a: side(older),
+ b: side(newer),
+ dates: [older.date, newer.date],
+ };
+}
+
/** The pair for one source id, at one point. */
export function comparePair(api, source, at, today = new Date()) {
if (source === 'wayback') return waybackPair(api, at);
if (source === 'sentinel') return sentinelPair(api, at, today);
+ if (source === 'radar') return radarPair(api, at, today);
return Promise.reject(new Error(`unknown comparison source: ${source}`));
}
diff --git a/frontend/src/lib/map/comparePair.test.js b/frontend/src/lib/map/comparePair.test.js
index 3236639..8eaefd5 100644
--- a/frontend/src/lib/map/comparePair.test.js
+++ b/frontend/src/lib/map/comparePair.test.js
@@ -1,5 +1,5 @@
import { describe, expect, it, vi } from 'vitest';
-import { comparePair, sentinelPair, sentinelWindow, waybackPair } from './comparePair.js';
+import { comparePair, radarPair, sentinelPair, sentinelWindow, waybackPair } from './comparePair.js';
const api = (answers) => ({
get: vi.fn(async (url) => {
@@ -77,3 +77,27 @@ describe('the Copernicus window', () => {
});
});
});
+
+describe('two radar passes of one point', () => {
+ it('pairs the newest pass with the one before it on the same track', async () => {
+ const client = api({
+ '/sentinel/dates': { dates: [
+ { date: '2026-09-20', time: '17:33:02', orbit: 'ascending' },
+ { date: '2026-09-18', time: '05:42:40', orbit: 'descending' },
+ { date: '2026-09-08', time: '17:32:50', orbit: 'ascending' },
+ ] },
+ });
+ const pair = await radarPair(client, { lat: 51.9, lon: 4.0 }, new Date('2026-09-23T00:00:00Z'));
+ expect(client.get.mock.calls[0][0]).toContain('collection=sentinel1');
+ expect(pair.a.radar).toEqual({ date: '2026-09-08', time: '17:32:50' });
+ expect(pair.b.radar).toEqual({ date: '2026-09-20', time: '17:33:02' });
+ expect(await comparePair(client, 'radar', { lat: 51.9, lon: 4.0 }, new Date('2026-09-23T00:00:00Z')))
+ .toMatchObject({ title: 'Radar · this point' });
+ });
+
+ it('says so when the track has one pass only', async () => {
+ const client = api({ '/sentinel/dates': { dates: [
+ { date: '2026-09-20', time: '17:33:02' }, { date: '2026-09-18', time: '05:42:40' }] } });
+ await expect(radarPair(client, { lat: 1, lon: 2 })).rejects.toThrow(/one pass of this track/);
+ });
+});
diff --git a/frontend/src/lib/map/detectReview.js b/frontend/src/lib/map/detectReview.js
new file mode 100644
index 0000000..bbc134c
--- /dev/null
+++ b/frontend/src/lib/map/detectReview.js
@@ -0,0 +1,48 @@
+export function pinDefaults(candidate, single) {
+ return {
+ title: `${candidate.phenomenon} · ${candidate.coordinates[1].toFixed(4)}, ${candidate.coordinates[0].toFixed(4)}`.slice(0, 120),
+ description: '', after_only: single, shape: candidate.geometry?.type === 'Point' || single ? 'point' : 'area',
+ };
+}
+
+export function candidatePaths(geometry, project) {
+ if (!geometry || geometry.type === 'Point') return '';
+ const polygons = geometry.type === 'Polygon' ? [geometry.coordinates] : geometry.coordinates;
+ return polygons.flatMap((polygon) => polygon.map((ring) => ring.map((point, i) => {
+ const p = project(point); return `${i ? 'L' : 'M'}${p.x},${p.y}`;
+ }).join(' ') + 'Z')).join(' ');
+}
+
+/** The high-resolution picture a lone detection is held up against. */
+export const HIGH_RESOLUTION = 'esri-world-imagery';
+
+/**
+ * The pair Compare opens a candidate on, framed close on it.
+ *
+ * At 10 m a candidate is a cue rather than a verdict, so the question Compare
+ * answers depends on what was found. A change is read on the two passes that
+ * found it, so the analyst can swipe, blink or run Difference over them. A thing
+ * present on one pass, a hull or a fire, is held against today's high-resolution
+ * picture: a platform, a rock or a flare stack is still there, a ship is not.
+ * Nothing is fetched to decide it: the candidate already names its passes.
+ */
+export function comparePairFor(candidate, { single = false, method = '' } = {}) {
+ const [lon, lat] = candidate.coordinates;
+ const { a, b } = candidate.sources ?? {};
+ if (!b?.date) return null;
+ const side = (source, layer) => (source.provider === 'sentinel1'
+ ? { provider: 'sentinel1', radar: { date: source.date, time: source.time ?? '' }, present: true }
+ : { provider: 'sentinel2', sentinel: { date: source.date, layer, maxcc: 100 }, present: true });
+ // A fire reads in short-wave infrared, which is where the detector saw it.
+ const layer = method === 'hotspots' ? 'SWIR' : 'TRUE_COLOR';
+ const lone = single || !a?.date || (a.date === b.date && a.time === b.time);
+ return {
+ lat,
+ lon,
+ zoom: 16,
+ title: `${candidate.phenomenon} · ${b.date}`.slice(0, 120),
+ a: lone ? { provider: HIGH_RESOLUTION, present: true } : side(a, layer),
+ b: side(b, layer),
+ dates: lone ? ['', b.date] : [a.date, b.date],
+ };
+}
diff --git a/frontend/src/lib/map/detectReview.test.js b/frontend/src/lib/map/detectReview.test.js
new file mode 100644
index 0000000..088d21c
--- /dev/null
+++ b/frontend/src/lib/map/detectReview.test.js
@@ -0,0 +1,49 @@
+import { describe, expect, it } from 'vitest';
+import { HIGH_RESOLUTION, candidatePaths, comparePairFor, pinDefaults } from './detectReview.js';
+
+const candidate = { phenomenon: 'Change', coordinates: [2, 48], geometry: { type: 'Polygon', coordinates: [] } };
+describe('Detect review', () => {
+ it('defaults single-image methods to an after image and a point', () => {
+ expect(pinDefaults(candidate, true)).toEqual({ title: 'Change · 48.0000, 2.0000', description: '', after_only: true, shape: 'point' });
+ });
+ it('defaults change methods to paired images and an area', () => {
+ expect(pinDefaults(candidate, false)).toMatchObject({ after_only: false, shape: 'area' });
+ expect(pinDefaults({ ...candidate, geometry: { type: 'Point' } }, false).shape).toBe('point');
+ });
+ it('draws all rings and merged parts instead of a bbox', () => {
+ const shape = { type: 'MultiPolygon', coordinates: [[[[0, 0], [2, 0], [1, 1], [0, 0]]], [[[3, 3], [4, 3], [4, 4], [3, 3]]]] };
+ const path = candidatePaths(shape, ([x, y]) => ({ x, y }));
+ expect(path).toBe('M0,0 L2,0 L1,1 L0,0Z M3,3 L4,3 L4,4 L3,3Z');
+ });
+});
+
+describe('a candidate opened in Compare', () => {
+ const found = (sources, extra = {}) => ({ phenomenon: 'Burn scar', coordinates: [44.1, 15.3], sources, ...extra });
+ const optical = (date) => ({ provider: 'sentinel2', date, layer: 'TRUE_COLOR', maxcc: 30 });
+ const radar = (date, time) => ({ provider: 'sentinel1', date, time, layer: 'SAR_IW', maxcc: 100 });
+
+ it('reads a change on the two passes that found it, framed close', () => {
+ const pair = comparePairFor(found({ a: optical('2026-05-04'), b: optical('2026-05-11') }));
+ expect(pair).toMatchObject({ lat: 15.3, lon: 44.1, zoom: 16, dates: ['2026-05-04', '2026-05-11'] });
+ expect(pair.a).toEqual({ provider: 'sentinel2', sentinel: { date: '2026-05-04', layer: 'TRUE_COLOR', maxcc: 100 }, present: true });
+ });
+
+ it('holds a thing present on one pass against today’s high-resolution picture', () => {
+ const pass = optical('2026-05-11');
+ const pair = comparePairFor(found({ a: pass, b: pass }), { single: true, method: 'hotspots' });
+ expect(pair.a).toEqual({ provider: HIGH_RESOLUTION, present: true });
+ // a fire is read where the detector saw it, in short-wave infrared
+ expect(pair.b.sentinel.layer).toBe('SWIR');
+ });
+
+ it('opens radar passes on the radar basemap', () => {
+ const pair = comparePairFor(found({ a: radar('2026-05-02', '05:42:10'), b: radar('2026-05-14', '05:42:40') }));
+ expect(pair.b).toEqual({ provider: 'sentinel1', radar: { date: '2026-05-14', time: '05:42:40' }, present: true });
+ const ship = radar('2026-05-14', '05:42:40');
+ expect(comparePairFor(found({ a: ship, b: ship }), { single: true }).a.provider).toBe(HIGH_RESOLUTION);
+ });
+
+ it('has nothing to open without a dated pass', () => {
+ expect(comparePairFor(found({ a: optical(''), b: optical('') }))).toBe(null);
+ });
+});
diff --git a/frontend/src/lib/map/detectWhen.js b/frontend/src/lib/map/detectWhen.js
new file mode 100644
index 0000000..6db7b2a
--- /dev/null
+++ b/frontend/src/lib/map/detectWhen.js
@@ -0,0 +1,92 @@
+/**
+ * The When step of a detection, the part that is not a view.
+ *
+ * Every area keeps its own pair of sources, because areas far apart can sit
+ * under different swaths. Most detections still want one pair for all of
+ * them, so the step reads and writes every area at once, and only says "per
+ * 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.
+ */
+
+/** A side as a line: its day, and a radar pass's time. */
+export function sideLine(source, radar = false) {
+ if (!source?.date) return '';
+ return radar && source.time ? `${source.date} ${source.time.slice(0, 5)} UTC` : source.date;
+}
+
+/** The pass every area holds on one side, or null when they differ. */
+export function sharedSide(pairs, letter) {
+ if (!pairs?.length) return null;
+ const [first, ...rest] = pairs.map((pair) => pair[letter] ?? {});
+ const same = rest.every((side) => (side.date ?? '') === (first.date ?? '') && (side.time ?? '') === (first.time ?? ''));
+ return same ? { date: first.date ?? '', time: first.time ?? '' } : null;
+}
+
+/** Whether one choice stands for every area. */
+export function uniform(pairs) {
+ return !!sharedSide(pairs, 'a') && !!sharedSide(pairs, 'b');
+}
+
+/**
+ * Every area's side set to one pass. A typed day has no time yet: the engine
+ * settles which radar pass of it at launch.
+ */
+export function setSide(pairs, letter, date, time = '', radar = false) {
+ return pairs.map((pair) => ({
+ ...pair,
+ [letter]: { ...pair[letter], date, time: radar ? time : '' },
+ date_rule: letter === 'b' && pair.date_rule !== 'latest_previous'
+ ? (date ? 'manual' : 'latest_reference') : pair.date_rule,
+ }));
+}
+
+/** The rule each area follows once a routine says what it compares against. */
+export function withRule(pairs, against) {
+ const rule = against === 'previous' ? 'latest_previous' : 'latest_reference';
+ return pairs.map((pair) => ({ ...pair, date_rule: rule }));
+}
+
+/**
+ * What still stops the step, in one sentence, or ''.
+ *
+ * A routine that compares with its previous pass needs A only until a run has
+ * finished, which a saved routine may already have.
+ */
+export function whenNeed({ single, routine, against, followupId, pairs, chooseB }) {
+ const waived = routine && followupId && against === 'previous';
+ const noA = pairs.filter((pair) => !pair.a?.date);
+ if (!single && !waived && noA.length) {
+ if (noA.length < pairs.length) return 'Choose A for every area.';
+ if (!routine) return 'Choose A, the picture before.';
+ return `Choose A, the picture ${against === 'previous' ? 'the first run' : 'every run'} compares with.`;
+ }
+ if (!routine && chooseB && pairs.some((pair) => !pair.b?.date)) {
+ return single ? 'Choose the day, or take the newest pass.' : 'Choose the day of B, or take the newest pass.';
+ }
+ return '';
+}
+
+/** One area's days, for the list shown when the areas differ. */
+export function areaLine(pair, { single, routine, radar = false }) {
+ const a = sideLine(pair?.a, radar) || 'not chosen';
+ const b = sideLine(pair?.b, radar) || 'newest pass';
+ if (single) return routine ? 'newest pass' : 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 }) {
+ if (pairs.length > 1 && !uniform(pairs)) return 'Its own days for each area';
+ const a = sideLine(sharedSide(pairs, 'a'), radar);
+ const b = sideLine(sharedSide(pairs, 'b'), radar) || 'newest pass';
+ if (routine) {
+ if (single) return 'Each run: the newest pass';
+ return against === 'previous'
+ ? `Each run: the newest pass against the one before${a ? `, first against ${a}` : ''}`
+ : `Each run: the newest pass 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
new file mode 100644
index 0000000..171a112
--- /dev/null
+++ b/frontend/src/lib/map/detectWhen.test.js
@@ -0,0 +1,100 @@
+import { describe, expect, it } from 'vitest';
+import {
+ areaLine, setSide, sharedSide, sideLine, uniform, whenNeed, whenSummary, withRule,
+} from './detectWhen.js';
+
+const pair = (id, a = '', b = '', extra = {}) => ({
+ area_id: id,
+ a: { provider: 'sentinel2', date: a, layer: 'TRUE_COLOR', maxcc: 30 },
+ b: { provider: 'sentinel2', date: b, layer: 'TRUE_COLOR', maxcc: 30 },
+ date_rule: 'latest_reference',
+ ...extra,
+});
+
+describe('the When step of a detection', () => {
+ it('reads a side as its day, and a radar pass with its time', () => {
+ expect(sideLine({ date: '2026-08-01' })).toBe('2026-08-01');
+ expect(sideLine({ date: '2026-08-01', time: '16:32:10' }, true)).toBe('2026-08-01 16:32 UTC');
+ expect(sideLine({ date: '' })).toBe('');
+ });
+
+ it('speaks for every area only while they agree', () => {
+ const pairs = [pair('x', '2026-08-01'), pair('y', '2026-08-01')];
+ expect(sharedSide(pairs, 'a')).toEqual({ date: '2026-08-01', time: '' });
+ expect(uniform(pairs)).toBe(true);
+ pairs[1].a.date = '2026-07-20';
+ expect(sharedSide(pairs, 'a')).toBe(null);
+ expect(uniform(pairs)).toBe(false);
+ expect(sharedSide([], 'a')).toBe(null);
+ });
+
+ it('sets one side of every area, and a pass on B makes the run manual', () => {
+ const set = setSide([pair('x'), pair('y')], 'b', '2026-09-06');
+ expect(set.map((row) => row.b.date)).toEqual(['2026-09-06', '2026-09-06']);
+ expect(set.map((row) => row.date_rule)).toEqual(['manual', 'manual']);
+ expect(setSide(set, 'b', '').map((row) => row.date_rule)).toEqual(['latest_reference', 'latest_reference']);
+ // a routine that compares with the pass before keeps that rule
+ const routine = setSide([pair('x', '', '', { date_rule: 'latest_previous' })], 'b', '2026-09-06');
+ expect(routine[0].date_rule).toBe('latest_previous');
+ });
+
+ it('keeps a radar time and drops a leftover one on optical sides', () => {
+ expect(setSide([pair('x')], 'a', '2026-08-01', '16:32:10', true)[0].a.time).toBe('16:32:10');
+ expect(setSide([pair('x')], 'a', '2026-08-01', '16:32:10', false)[0].a.time).toBe('');
+ });
+
+ it('follows the routine rule once it is chosen', () => {
+ expect(withRule([pair('x')], 'previous')[0].date_rule).toBe('latest_previous');
+ expect(withRule([pair('x')], 'reference')[0].date_rule).toBe('latest_reference');
+ });
+
+ it('says what is missing, in the words of the step', () => {
+ const base = { single: false, routine: false, against: 'previous', followupId: null, chooseB: false };
+ expect(whenNeed({ ...base, pairs: [pair('x')] })).toBe('Choose A, the picture before.');
+ expect(whenNeed({ ...base, pairs: [pair('x', '2026-08-01'), pair('y')] })).toBe('Choose A for every area.');
+ expect(whenNeed({ ...base, pairs: [pair('x', '2026-08-01')] })).toBe('');
+ expect(whenNeed({ ...base, chooseB: true, pairs: [pair('x', '2026-08-01')] }))
+ .toBe('Choose the day of B, or take the newest pass.');
+ expect(whenNeed({ ...base, single: true, chooseB: true, pairs: [pair('x')] }))
+ .toBe('Choose the day, or take the newest pass.');
+ expect(whenNeed({ ...base, single: true, pairs: [pair('x')] })).toBe('');
+ });
+
+ it('asks a routine for A until a run has finished', () => {
+ const base = { single: false, routine: true, chooseB: true, pairs: [pair('x')] };
+ expect(whenNeed({ ...base, against: 'previous', followupId: null }))
+ .toBe('Choose A, the picture the first run compares with.');
+ expect(whenNeed({ ...base, against: 'previous', followupId: 'abcdef123456' })).toBe('');
+ expect(whenNeed({ ...base, against: 'reference', followupId: 'abcdef123456' }))
+ .toBe('Choose A, the picture every run compares with.');
+ // a routine names no B, whatever the switch last said
+ expect(whenNeed({ ...base, single: true, against: 'previous', followupId: null })).toBe('');
+ });
+
+ 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');
+ 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');
+ });
+
+ 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, 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')] }))
+ .toBe('Its own days for each area');
+ const routine = { single: false, routine: true };
+ expect(whenSummary({ ...routine, against: 'previous', pairs: [pair('x', '2026-08-01')] }))
+ .toBe('Each run: the newest pass against the one before, first against 2026-08-01');
+ expect(whenSummary({ ...routine, against: 'reference', pairs: [pair('x', '2026-08-01')] }))
+ .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');
+ 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');
+ });
+});
diff --git a/frontend/src/lib/map/detections.js b/frontend/src/lib/map/detections.js
new file mode 100644
index 0000000..9431501
--- /dev/null
+++ b/frontend/src/lib/map/detections.js
@@ -0,0 +1,102 @@
+/**
+ * Detect's home list, worked out from the two listings the panel reads: the
+ * saved detections and the runs of the case. A run names the detection it
+ * belongs to (`followup_id`), so each detection carries its own history and
+ * the runs started without saving one stand on their own.
+ */
+
+export const ACTIVE = Object.freeze(['queued', 'running']);
+export const isActive = (row) => ACTIVE.includes(row?.status);
+
+export const plural = (count, word) => `${count} ${word}${count === 1 ? '' : 's'}`;
+
+/**
+ * Each saved detection with its runs, newest first, and the one working now.
+ * Timestamps are only seconds deep, so two runs of one routine can share one;
+ * the pass they swept settles the order between them.
+ */
+export const byRecency = (one, two) =>
+ `${two.created_at ?? ''}${two.dates?.[1] ?? ''}`.localeCompare(`${one.created_at ?? ''}${one.dates?.[1] ?? ''}`);
+
+export function detectionsWithRuns(watches, runs) {
+ return watches.map((watch) => {
+ const history = runs.filter((run) => run.followup_id === watch.id).sort(byRecency);
+ return { ...watch, history, latest: history[0] ?? null, active: history.find(isActive) ?? null };
+ });
+}
+
+/** Runs no saved detection claims: started once, or left by one since deleted. */
+export function singleRuns(watches, runs) {
+ const saved = new Set(watches.map((watch) => watch.id));
+ return runs.filter((run) => !run.followup_id || !saved.has(run.followup_id));
+}
+
+/**
+ * The Saved tab in groups: each routine with its runs, newest first, then the
+ * passes swept once, which include the runs of a routine since deleted. A
+ * routine that has not run yet has nothing to show here.
+ */
+export function savedGroups(watches, runs) {
+ const routines = watches
+ .map((watch) => ({ id: watch.id, kind: 'routine', title: watch.title, colour: watch.colour ?? '',
+ runs: runs.filter((run) => run.followup_id === watch.id).sort(byRecency) }))
+ .filter((group) => group.runs.length);
+ const once = singleRuns(watches, runs).sort(byRecency);
+ return once.length ? [...routines, { id: 'once', kind: 'once', title: 'One passes', colour: '', runs: once }] : routines;
+}
+
+/** The two days a run compared, as a row line, or '' before it has them. */
+export function runDays(run) {
+ const [a, b] = run?.dates ?? [];
+ if (!b) return '';
+ return a && a !== b ? `${a} → ${b}` : b;
+}
+
+function found(run) {
+ if (!run.count) return 'nothing found';
+ if (run.to_review) return `${run.to_review} to review`;
+ return `${plural(run.count, 'candidate')}, all reviewed`;
+}
+
+/**
+ * Where a run stands, in the words the list shows, and a tone for its colour.
+ * A finished run leads with the day of the pass it swept, because across a
+ * detection's history that is what tells one run from the next.
+ */
+export function runState(run) {
+ if (!run) return { tone: 'idle', text: 'Not run yet' };
+ switch (run.status) {
+ case 'queued': return { tone: 'busy', text: 'Queued' };
+ case 'running': return { tone: 'busy', text: `Running · ${run.progress ?? 0}/${run.total ?? 0} tiles` };
+ case 'failed': return { tone: 'warn', text: run.message ? `Failed · ${run.message}` : 'Failed' };
+ case 'cancelled': return { tone: 'idle', text: 'Cancelled' };
+ case 'no_new_imagery': return { tone: 'idle', text: 'No new pass since the last run' };
+ case 'ready': {
+ const day = run.dates?.[1];
+ const text = found(run);
+ return { tone: run.to_review ? 'new' : 'done', text: day ? `${day} · ${text}` : text[0].toUpperCase() + text.slice(1) };
+ }
+ default: return { tone: 'idle', text: run.status ?? '' };
+ }
+}
+
+/** How a detection picks its imagery, short enough for a list row. */
+export function ruleLabel(rule, single) {
+ if (rule === 'manual') return 'fixed dates';
+ if (single) return 'newest pass';
+ return rule === 'latest_reference' ? 'newest pass against a reference' : 'newest pass against the last run';
+}
+
+/** What to say when a run settles, or null when there is nothing to say. */
+export function settledMessage(run) {
+ const title = run.title || 'Detection';
+ switch (run.status) {
+ case 'ready':
+ return run.count
+ ? { text: `${title}: ${plural(run.count, 'candidate')} to review`, kind: 'ok' }
+ : { text: `${title}: nothing passed the thresholds`, kind: 'info' };
+ case 'no_new_imagery': return { text: `${title}: no new pass since the last run`, kind: 'info' };
+ case 'failed': return { text: `${title} failed: ${run.message || 'see Detect'}`, kind: 'warn' };
+ default: return null;
+ }
+}
diff --git a/frontend/src/lib/map/detections.test.js b/frontend/src/lib/map/detections.test.js
new file mode 100644
index 0000000..7ec5e82
--- /dev/null
+++ b/frontend/src/lib/map/detections.test.js
@@ -0,0 +1,83 @@
+import { describe, expect, it } from 'vitest';
+import {
+ detectionsWithRuns,
+ isActive,
+ ruleLabel,
+ runDays,
+ runState,
+ savedGroups,
+ settledMessage,
+ singleRuns,
+} from './detections.js';
+
+const watch = (id, title = id) => ({ id, title });
+const run = (id, followup_id, extra = {}) => ({ id, followup_id, title: 'Harbour', status: 'ready',
+ count: 0, to_review: 0, dates: ['2026-09-01', '2026-09-06'], ...extra });
+
+describe('detections and their runs', () => {
+ it('gives each detection its own history, newest first, and the run working now', () => {
+ const runs = [run('r3', 'w1', { status: 'running' }), run('r2', 'w2'), run('r1', 'w1')];
+ const [one, two] = detectionsWithRuns([watch('w1'), watch('w2')], runs);
+ expect(one.history.map((r) => r.id)).toEqual(['r3', 'r1']);
+ expect(one.latest.id).toBe('r3');
+ expect(one.active.id).toBe('r3');
+ expect(two.active).toBe(null);
+ });
+
+ it('keeps runs of a deleted detection among the single runs rather than losing them', () => {
+ const runs = [run('r1', null), run('r2', 'gone'), run('r3', 'w1')];
+ expect(singleRuns([watch('w1')], runs).map((r) => r.id)).toEqual(['r1', 'r2']);
+ });
+
+ it('groups the saved runs under their routine, then the passes swept once', () => {
+ const runs = [run('r1', null, { created_at: '2026-09-01' }), run('r2', 'w2', { created_at: '2026-09-02' }),
+ run('r3', 'gone', { created_at: '2026-09-03' }), run('r4', 'w2', { created_at: '2026-09-04' })];
+ const groups = savedGroups([watch('w1', 'Idle'), watch('w2', 'Harbour weekly')], runs);
+ expect(groups.map((group) => [group.kind, group.title])).toEqual([['routine', 'Harbour weekly'], ['once', 'One passes']]);
+ expect(groups[0].runs.map((r) => r.id)).toEqual(['r4', 'r2']);
+ // a deleted routine's runs are kept, with the passes swept once
+ expect(groups[1].runs.map((r) => r.id)).toEqual(['r3', 'r1']);
+ expect(savedGroups([watch('w2')], [run('r2', 'w2')]).map((group) => group.kind)).toEqual(['routine']);
+ });
+
+ it('names the two days a run compared', () => {
+ expect(runDays(run('r', 'w'))).toBe('2026-09-01 → 2026-09-06');
+ expect(runDays(run('r', 'w', { dates: ['2026-09-06', '2026-09-06'] }))).toBe('2026-09-06');
+ expect(runDays(run('r', 'w', { dates: [] }))).toBe('');
+ });
+
+ it('knows queued and running from everything else', () => {
+ expect(['queued', 'running', 'ready', 'failed'].map((status) => isActive({ status })))
+ .toEqual([true, true, false, false]);
+ });
+});
+
+describe('what a row says', () => {
+ it('leads a finished run with the day of the pass it swept', () => {
+ expect(runState(run('r', 'w', { count: 5, to_review: 3 }))).toEqual({ tone: 'new', text: '2026-09-06 · 3 to review' });
+ expect(runState(run('r', 'w', { count: 2 })).text).toBe('2026-09-06 · 2 candidates, all reviewed');
+ expect(runState(run('r', 'w')).text).toBe('2026-09-06 · nothing found');
+ expect(runState(run('r', 'w', { dates: [] })).text).toBe('Nothing found');
+ });
+
+ it('says where an unfinished run stands', () => {
+ expect(runState(null).text).toBe('Not run yet');
+ expect(runState({ status: 'running', progress: 3, total: 40 }).text).toBe('Running · 3/40 tiles');
+ expect(runState({ status: 'failed', message: 'no recent pass' })).toEqual({ tone: 'warn', text: 'Failed · no recent pass' });
+ expect(runState({ status: 'no_new_imagery' }).text).toBe('No new pass since the last run');
+ });
+
+ it('names the date rule, with no reference for a one-image method', () => {
+ expect(ruleLabel('manual', false)).toBe('fixed dates');
+ expect(ruleLabel('latest_previous', true)).toBe('newest pass');
+ expect(ruleLabel('latest_previous', false)).toBe('newest pass against the last run');
+ expect(ruleLabel('latest_reference', false)).toBe('newest pass against a reference');
+ });
+
+ it('announces a settled run, and says nothing of a cancelled one', () => {
+ expect(settledMessage(run('r', 'w', { count: 1 }))).toEqual({ text: 'Harbour: 1 candidate to review', kind: 'ok' });
+ expect(settledMessage(run('r', 'w')).text).toBe('Harbour: nothing passed the thresholds');
+ expect(settledMessage({ title: 'Harbour', status: 'failed', message: 'offline' }).kind).toBe('warn');
+ expect(settledMessage({ title: 'Harbour', status: 'cancelled' })).toBe(null);
+ });
+});
diff --git a/frontend/src/lib/map/exportFrame.js b/frontend/src/lib/map/exportFrame.js
index 6909ff2..c19b34d 100644
--- a/frontend/src/lib/map/exportFrame.js
+++ b/frontend/src/lib/map/exportFrame.js
@@ -3,8 +3,9 @@
*
* A comparison is read on a whole browser window, but the thing worth showing
* is usually a building or a crater in the middle of it. The frame is drawn
- * once on imagery A and kept as two ground corners, like an annotation: the
- * camera can move, the window can be resized, the same ground comes out.
+ * once on imagery A and kept as two ground corners and the bearing that was up
+ * while it was drawn, like a box annotation: the camera can move or turn, the
+ * window can be resized, and the same ground comes out, upright as drawn.
*
* Cropping happens before composition, on the captured canvases: each side is
* cut to the same ground box and handed a frame of its own, so the change
@@ -12,7 +13,10 @@
* whole view.
*/
-import { apply, fromMercator, invert, screenToMercator, toMercator } from './groundFrame.js';
+import {
+ apply, compassAngle, fromMercator, frameToFrame, invert, mercatorPerPixel, screenToMercator,
+ toMercator, turnedBox,
+} from './groundFrame.js';
/**
* The narrowest frame worth exporting, in CSS pixels.
@@ -24,29 +28,6 @@ export const MIN_FRAME = 320;
const clamp = (value, min, max) => Math.min(max, Math.max(min, value));
-/** Ground pair → the pixel box of `frame` that covers it. */
-export function screenRect(points, frame) {
- const toScreen = invert(screenToMercator(frame));
- const corners = points.map(([lon, lat]) => apply(toScreen, ...toMercator(lon, lat)));
- const xs = corners.map((point) => point[0]);
- const ys = corners.map((point) => point[1]);
- return {
- x: Math.min(...xs),
- y: Math.min(...ys),
- w: Math.max(...xs) - Math.min(...xs),
- h: Math.max(...ys) - Math.min(...ys),
- };
-}
-
-/** Pixel box of `frame` → the two ground corners it spans. */
-export function groundRect(rect, frame) {
- const toGround = screenToMercator(frame);
- return [
- fromMercator(...apply(toGround, rect.x, rect.y)),
- fromMercator(...apply(toGround, rect.x + rect.w, rect.y + rect.h)),
- ];
-}
-
/**
* A drawn box made exportable: grown to the minimum around its own centre,
* then held inside the view. A frame drawn smaller than the view can always
@@ -63,7 +44,7 @@ export function boundedRect(rect, frame) {
};
}
-/** How much ground the frame spans along the current screen axes, in metres. */
+/** How much ground the frame spans along the axes of the screen it was drawn on, in metres. */
export function frameSpan(points, bearing = 0) {
const [first, second] = points.map(([lon, lat]) => toMercator(lon, lat));
const shrink = Math.cos((((points[0][1] + points[1][1]) / 2) * Math.PI) / 180);
@@ -109,6 +90,60 @@ export function cropCapture(capture, rect, makeCanvas) {
return { canvas, frame: { ...capture.frame, lng, lat, width: rect.w, height: rect.h } };
}
+/**
+ * Cut one captured surface to a frame turned against it: the pixels are
+ * resampled through the turn, so the cut comes out upright at its own bearing.
+ */
+export function turnedCapture(capture, frame, makeCanvas) {
+ const pixelScale = capture.canvas.width / capture.frame.width;
+ const canvas = canvasOf(frame.width * pixelScale, frame.height * pixelScale, makeCanvas);
+ const ctx = canvas.getContext('2d');
+ if (!ctx) throw new Error('this browser cannot frame the comparison');
+ ctx.imageSmoothingQuality = 'high';
+ const m = frameToFrame(capture.frame, frame);
+ ctx.setTransform(m.a, m.b, m.c, m.d, m.e * pixelScale, m.f * pixelScale);
+ ctx.drawImage(capture.canvas, 0, 0);
+ return { canvas, frame };
+}
+
+/** Whether two bearings put the same way up, to far under a pixel across any view. */
+function sameUp(first, second) {
+ const gap = Math.abs(compassAngle(first) - compassAngle(second));
+ return Math.min(gap, 360 - gap) < 1e-6;
+}
+
+/**
+ * One capture cut to the frame's ground: centred on `centre` (Web Mercator),
+ * `size` pixels across or the box's own span at the capture's zoom.
+ *
+ * A frame drawn at the bearing the capture was taken at is cut on whole
+ * pixels, so the export holds the screen's own pixels; one drawn at another
+ * bearing is turned upright.
+ */
+function cutOne(capture, box, angle, centre, size, makeCanvas) {
+ const view = capture.frame;
+ const perPixel = mercatorPerPixel(view.zoom);
+ const w = size?.w ?? Math.max(1, Math.round(Math.abs(box.width) / perPixel));
+ const h = size?.h ?? Math.max(1, Math.round(Math.abs(box.height) / perPixel));
+ const refuse = () => {
+ throw new Error('the export frame must be fully visible; move or zoom out, then try again');
+ };
+ if (sameUp(angle, view.bearing)) {
+ const [cx, cy] = apply(invert(screenToMercator(view)), ...centre);
+ const rect = { x: Math.round(cx - w / 2), y: Math.round(cy - h / 2), w, h };
+ if (rect.x < 0 || rect.y < 0 || rect.x + w > view.width || rect.y + h > view.height) refuse();
+ return cropCapture(capture, rect, makeCanvas);
+ }
+ const [lng, lat] = fromMercator(...centre);
+ const frame = { ...view, lng, lat, width: w, height: h, bearing: angle };
+ const toView = frameToFrame(frame, view);
+ for (const [x, y] of [[0, 0], [w, 0], [w, h], [0, h]]) {
+ const [vx, vy] = apply(toView, x, y);
+ if (vx < -0.5 || vy < -0.5 || vx > view.width + 0.5 || vy > view.height + 0.5) refuse();
+ }
+ return turnedCapture(capture, frame, makeCanvas);
+}
+
/**
* Both captures cut to the same ground box.
*
@@ -118,29 +153,15 @@ export function cropCapture(capture, rect, makeCanvas) {
*/
export function cropSources(sources, frame, makeCanvas) {
if (!frame?.points) return sources;
- const fitted = (rect, captureFrame, size = null) => {
- const cut = {
- x: Math.round(rect.x),
- y: Math.round(rect.y),
- w: size?.w ?? Math.max(1, Math.round(rect.w)),
- h: size?.h ?? Math.max(1, Math.round(rect.h)),
- };
- if (cut.x < 0 || cut.y < 0 || cut.x + cut.w > captureFrame.width || cut.y + cut.h > captureFrame.height) {
- throw new Error('the export frame must be fully visible; move or zoom out, then try again');
- }
- return cut;
- };
- const rectA = fitted(screenRect(frame.points, sources.a.frame), sources.a.frame);
- const ground = groundRect(rectA, sources.a.frame);
- const onB = screenRect(ground, sources.b.frame);
- const rectB = fitted(onB, sources.b.frame, rectA);
- return {
- a: cropCapture(sources.a, rectA, makeCanvas),
- b: cropCapture(sources.b, rectB, makeCanvas),
- };
+ const angle = compassAngle(frame.angle);
+ const box = turnedBox(frame.points, angle);
+ const a = cutOne(sources.a, box, angle, box.centre, null, makeCanvas);
+ const landed = toMercator(a.frame.lng, a.frame.lat);
+ const b = cutOne(sources.b, box, angle, landed, { w: a.frame.width, h: a.frame.height }, makeCanvas);
+ return { a, b };
}
-/** What a saved session carries: nothing, or two ground corners. */
+/** What a saved session carries: nothing, or two ground corners and the bearing they were drawn at. */
export function exportFrameSpec(value) {
const points = value?.points;
if (!Array.isArray(points) || points.length !== 2) return null;
@@ -148,5 +169,5 @@ export function exportFrameSpec(value) {
if (cleaned.some(([lon, lat]) => !Number.isFinite(lon) || !Number.isFinite(lat))) return null;
if (cleaned.some(([lon, lat]) => Math.abs(lon) > 180 || Math.abs(lat) > 90)) return null;
if (cleaned[0][0] === cleaned[1][0] && cleaned[0][1] === cleaned[1][1]) return null;
- return { points: cleaned };
+ return { points: cleaned, angle: compassAngle(value.angle) };
}
diff --git a/frontend/src/lib/map/exportFrame.test.js b/frontend/src/lib/map/exportFrame.test.js
index 665c79d..da6084d 100644
--- a/frontend/src/lib/map/exportFrame.test.js
+++ b/frontend/src/lib/map/exportFrame.test.js
@@ -6,22 +6,33 @@ import {
cropSources,
exportFrameSpec,
frameSpan,
- groundRect,
- screenRect,
} from './exportFrame.js';
-import { mercatorPerPixel } from './groundFrame.js';
+import { apply, frameToFrame, fromMercator, mercatorPerPixel, screenToMercator } from './groundFrame.js';
+
+/** The two ground corners a pixel box covers, which is what a drawn frame keeps.
+ * The projection itself is `groundFrame`'s, and tested there. */
+const groundRect = (rect, frame) => {
+ const toGround = screenToMercator(frame);
+ return [
+ fromMercator(...apply(toGround, rect.x, rect.y)),
+ fromMercator(...apply(toGround, rect.x + rect.w, rect.y + rect.h)),
+ ];
+};
const FRAME = { lng: 2.3, lat: 48.8, zoom: 17, bearing: 0, width: 1200, height: 800 };
function fakeCanvas() {
const drawn = [];
+ const turns = [];
return {
width: 0,
height: 0,
drawn,
+ turns,
getContext: () => ({
imageSmoothingQuality: '',
drawImage: (...args) => drawn.push(args),
+ setTransform: (...args) => turns.push(args),
}),
};
}
@@ -31,33 +42,6 @@ const capture = (frame = FRAME, pixelScale = 1) => ({
frame,
});
-describe('screenRect / groundRect', () => {
- it('round-trips a drawn box through the ground', () => {
- const rect = { x: 320, y: 180, w: 400, h: 260 };
- const back = screenRect(groundRect(rect, FRAME), FRAME);
- expect(back.x).toBeCloseTo(rect.x, 6);
- expect(back.y).toBeCloseTo(rect.y, 6);
- expect(back.w).toBeCloseTo(rect.w, 6);
- expect(back.h).toBeCloseTo(rect.h, 6);
- });
-
- it('follows the ground when the camera moves', () => {
- const points = groundRect({ x: 400, y: 300, w: 300, h: 200 }, FRAME);
- const panned = { ...FRAME, lng: FRAME.lng + 0.001 };
- const moved = screenRect(points, panned);
- expect(moved.x).toBeLessThan(400);
- expect(moved.w).toBeCloseTo(300, 6);
- });
-
- it('keeps the same ground box under two frames of the same camera', () => {
- const points = groundRect({ x: 100, y: 120, w: 500, h: 300 }, FRAME);
- const wider = { ...FRAME, width: 1600 };
- const rect = screenRect(points, wider);
- expect(rect.w).toBeCloseTo(500, 6);
- expect(rect.x).toBeCloseTo(100 + 200, 6);
- });
-});
-
describe('boundedRect', () => {
it('holds a frame inside the view', () => {
const rect = boundedRect({ x: -80, y: 700, w: 500, h: 400 }, FRAME);
@@ -157,12 +141,51 @@ describe('cropSources', () => {
const frame = { points: groundRect({ x: -40, y: 200, w: 480, h: 320 }, FRAME) };
expect(() => cropSources(sources(), frame, fakeCanvas)).toThrow('must be fully visible');
});
+
+ it('cuts a frame drawn at the camera bearing on whole pixels, turned or not', () => {
+ const turned = { ...FRAME, bearing: 40 };
+ const frame = { points: groundRect({ x: 300, y: 200, w: 480, h: 320 }, turned), angle: 40 };
+ const cut = cropSources({ a: capture(turned), b: capture(turned) }, frame, fakeCanvas);
+ expect(cut.a.canvas.turns).toHaveLength(0);
+ expect(cut.a.canvas.drawn[0].slice(1, 5)).toEqual([300, 200, 480, 320]);
+ expect(cut.a.frame.bearing).toBe(40);
+ });
+
+ it('keeps its shape when the camera turns after, and comes out upright as drawn', () => {
+ // Drawn with the camera at 30°, exported with it back at north.
+ const drawnOn = { ...FRAME, bearing: 30 };
+ const frame = { points: groundRect({ x: 400, y: 250, w: 400, h: 300 }, drawnOn), angle: 30 };
+ const cut = cropSources(sources(), frame, fakeCanvas);
+ expect(cut.a.frame.width).toBe(400);
+ expect(cut.a.frame.height).toBe(300);
+ expect(cut.a.frame.bearing).toBe(30);
+ expect(cut.b.frame.bearing).toBe(30);
+ expect(cut.a.canvas.turns).toHaveLength(1);
+ // The cut's top-left is the corner first drawn, so the ground is the frame's.
+ const topLeft = fromMercator(...apply(screenToMercator(cut.a.frame), 0, 0));
+ expect(topLeft[0]).toBeCloseTo(frame.points[0][0], 7);
+ expect(topLeft[1]).toBeCloseTo(frame.points[0][1], 7);
+ // And the pixels are laid through the same turn the frame takes.
+ const m = frameToFrame(FRAME, cut.a.frame);
+ expect(cut.a.canvas.turns[0].slice(0, 4)).toEqual([m.a, m.b, m.c, m.d]);
+ });
+
+ it('refuses a turned frame one of whose corners has left the view', () => {
+ // It fits the screen it was drawn on, not one turned 30° from it.
+ const drawnOn = { ...FRAME, bearing: 30 };
+ const frame = { points: groundRect({ x: 60, y: 60, w: 1080, h: 680 }, drawnOn), angle: 30 };
+ expect(() => cropSources({ a: capture(drawnOn), b: capture(drawnOn) }, frame, fakeCanvas)).not.toThrow();
+ expect(() => cropSources(sources(), frame, fakeCanvas)).toThrow('must be fully visible');
+ });
});
describe('exportFrameSpec', () => {
it('keeps two ground corners', () => {
expect(exportFrameSpec({ points: [[2.3, 48.8], [2.31, 48.79]] }))
- .toEqual({ points: [[2.3, 48.8], [2.31, 48.79]] });
+ .toEqual({ points: [[2.3, 48.8], [2.31, 48.79]], angle: 0 });
+ // The bearing the box was drawn at travels with it, so it comes back upright.
+ expect(exportFrameSpec({ points: [[2.3, 48.8], [2.31, 48.79]], angle: 431 }))
+ .toEqual({ points: [[2.3, 48.8], [2.31, 48.79]], angle: 71 });
});
it('drops anything that is not a pair of ground points', () => {
diff --git a/frontend/src/lib/map/groundFrame.js b/frontend/src/lib/map/groundFrame.js
index 792275d..1d1228e 100644
--- a/frontend/src/lib/map/groundFrame.js
+++ b/frontend/src/lib/map/groundFrame.js
@@ -117,6 +117,63 @@ export function frameToFrame(from, to) {
return compose(invert(screenToMercator(to)), screenToMercator(from));
}
+/**
+ * A box on the ground drawn on a turned screen: two opposite corners, and the
+ * bearing that was up while it was drawn. Its sides run along that screen, so
+ * the box keeps its shape when the camera turns on, and turns with the ground.
+ *
+ * Returned in Web Mercator metres: the centre, the unit vectors the screen's
+ * right and down pointed along, and the signed extent along each.
+ */
+export function turnedBox([first, second], bearing = 0) {
+ const p = toMercator(...first);
+ const q = toMercator(...second);
+ const turn = (bearing * Math.PI) / 180;
+ const right = [Math.cos(turn), -Math.sin(turn)];
+ const down = [-Math.sin(turn), -Math.cos(turn)];
+ const dx = q[0] - p[0];
+ const dy = q[1] - p[1];
+ return {
+ centre: [(p[0] + q[0]) / 2, (p[1] + q[1]) / 2],
+ right,
+ down,
+ width: dx * right[0] + dy * right[1],
+ height: dx * down[0] + dy * down[1],
+ };
+}
+
+/** The `[lon, lat]` of a box at fractions `s` across and `t` down, from -0.5 to 0.5. */
+export function boxPoint(box, s, t) {
+ return fromMercator(
+ box.centre[0] + s * box.width * box.right[0] + t * box.height * box.down[0],
+ box.centre[1] + s * box.width * box.right[1] + t * box.height * box.down[1]
+ );
+}
+
+/** The four `[lon, lat]` corners, from the first one drawn, round to the far one and back. */
+export const boxCorners = (box) =>
+ [[-0.5, -0.5], [0.5, -0.5], [0.5, 0.5], [-0.5, 0.5]].map(([s, t]) => boxPoint(box, s, t));
+
+/** A ground point turned clockwise about another by `degrees`, as the screen shows a turn. */
+export function turnAbout(point, pivot, degrees) {
+ const [x, y] = toMercator(...point);
+ const [px, py] = toMercator(...pivot);
+ const turn = (degrees * Math.PI) / 180;
+ const cos = Math.cos(turn);
+ const sin = Math.sin(turn);
+ const dx = x - px;
+ const dy = y - py;
+ return fromMercator(px + dx * cos + dy * sin, py - dx * sin + dy * cos);
+}
+
+/** An angle folded into [0, 360), or 0 for anything that is not a number. */
+export function compassAngle(value) {
+ const number = Number(value);
+ if (!Number.isFinite(number)) return 0;
+ const folded = ((number % 360) + 360) % 360;
+ return folded >= 360 - 1e-9 ? 0 : folded;
+}
+
/**
* The ground corners of a view, as `[lon, lat]`, clockwise from top-left.
* What a computed overlay remembers about where it lies.
diff --git a/frontend/src/lib/map/groundFrame.test.js b/frontend/src/lib/map/groundFrame.test.js
index 76fcfe9..6e8b25c 100644
--- a/frontend/src/lib/map/groundFrame.test.js
+++ b/frontend/src/lib/map/groundFrame.test.js
@@ -1,6 +1,8 @@
import { describe, expect, it } from 'vitest';
import {
apply,
+ boxCorners,
+ compassAngle,
compose,
frameBox,
frameToFrame,
@@ -10,6 +12,8 @@ import {
invert,
screenToMercator,
toMercator,
+ turnAbout,
+ turnedBox,
} from './groundFrame.js';
const frame = (patch = {}) => ({ lng: 2.2945, lat: 48.8584, zoom: 15, bearing: 0, width: 800, height: 600, ...patch });
@@ -77,3 +81,51 @@ describe('affine maps between frames', () => {
close(apply(toView, 0, 0), apply(invert(screenToMercator(view)), ...ground), 4);
});
});
+
+describe('a box drawn on a turned screen', () => {
+ const metres = (a, b) => Math.hypot(...toMercator(...a).map((v, i) => v - toMercator(...b)[i]));
+
+ it('is the plain ground box of its two corners on a north-up screen', () => {
+ const corners = boxCorners(turnedBox([[2, 48], [2.01, 47.99]], 0));
+ close(corners[0], [2, 48], 9);
+ close(corners[1], [2.01, 48], 9);
+ close(corners[2], [2.01, 47.99], 9);
+ close(corners[3], [2, 47.99], 9);
+ });
+
+ it('runs its sides along the screen it was drawn on', () => {
+ // Drawn with east up: the screen's right points south, its down points west.
+ const view = frame({ bearing: 90 });
+ const toGround = screenToMercator(view);
+ const drawn = [[100, 100], [300, 200]].map(([x, y]) => fromMercator(...apply(toGround, x, y)));
+ const box = turnedBox(drawn, 90);
+ close(box.right, [0, -1], 9);
+ close(box.down, [-1, 0], 9);
+ const onScreen = boxCorners(box).map((point) => apply(invert(toGround), ...toMercator(...point)));
+ close(onScreen[0], [100, 100], 4);
+ close(onScreen[1], [300, 100], 4);
+ close(onScreen[2], [300, 200], 4);
+ close(onScreen[3], [100, 200], 4);
+ });
+
+ it('keeps its sides and its right angles whatever the camera does after', () => {
+ const corners = boxCorners(turnedBox([[2, 48], [2.004, 47.998]], 33));
+ const [a, b, c, d] = corners;
+ expect(metres(a, b)).toBeCloseTo(metres(d, c), 3);
+ expect(metres(a, d)).toBeCloseTo(metres(b, c), 3);
+ expect(metres(a, c)).toBeCloseTo(metres(b, d), 3);
+ });
+
+ it('turns a point clockwise, as the screen shows a turn', () => {
+ const turned = turnAbout([0.01, 0], [0, 0], 90);
+ close(turned, [0, -0.01], 9);
+ });
+
+ it('folds an angle into one turn', () => {
+ expect(compassAngle(-30)).toBeCloseTo(330);
+ expect(compassAngle(725)).toBeCloseTo(5);
+ expect(compassAngle(360)).toBe(0);
+ expect(compassAngle('x')).toBe(0);
+ expect(compassAngle(undefined)).toBe(0);
+ });
+});
diff --git a/frontend/src/lib/map/passStrip.js b/frontend/src/lib/map/passStrip.js
new file mode 100644
index 0000000..c8d0126
--- /dev/null
+++ b/frontend/src/lib/map/passStrip.js
@@ -0,0 +1,261 @@
+/**
+ * Every dated picture of one point, in a row, and the bracket that dates a change.
+ *
+ * Compare reads two pictures. Dating an event asks a different question: not
+ * "what changed between A and B" but "between which two pictures did it
+ * appear". The strip lists every picture the archive A and B share holds for
+ * the point in the middle of the view, oldest to newest, and the bracket halves
+ * the gap between a picture where the thing is absent and one where it is
+ * present until they are neighbours, a question at a time: log2 of the gap
+ * rather than the whole of it.
+ *
+ * Three archives answer it: Sentinel-2 days, Sentinel-1 passes of one track,
+ * and the Esri Wayback releases that changed the point. The lookups are the
+ * routes the pickers already use; everything here is pure.
+ */
+
+import { RADAR_ID, sameTrack, validPass } from '../radar.js';
+import { WAYBACK_ID } from '../wayback.js';
+import { daysBefore, isoDay, overCloudCeiling } from '../sentinel.js';
+
+export const SENTINEL_ID = 'sentinel2';
+export const STRIP_ARCHIVES = Object.freeze([SENTINEL_ID, RADAR_ID, WAYBACK_ID]);
+
+/** How much of the calendar a lookup covers around the pair, in days. */
+export const LEAD_DAYS = 90;
+export const TRAIL_DAYS = 30;
+export const EMPTY_WINDOW_DAYS = 180;
+export const MAX_WINDOW_DAYS = 400;
+
+/** The archive both sides show, when they show the same one. */
+export function stripArchive(a, b) {
+ if (!a?.present || !b?.present || a.provider !== b.provider) return null;
+ return STRIP_ARCHIVES.includes(a.provider) ? a.provider : null;
+}
+
+/** The day a side names, '' when it shows the most recent. */
+export function sideDay(side) {
+ if (side?.provider === RADAR_ID) return side.radar?.date ?? '';
+ if (side?.provider === SENTINEL_ID) return side.sentinel?.date ?? '';
+ return '';
+}
+
+/**
+ * The window to look in: some months before the older side and a month after
+ * the newer, capped at a year and a bit so one lookup keeps it whole (the
+ * catalogue answers up to 100 granules).
+ */
+export function lookupWindow(a, b, today = new Date()) {
+ const now = isoDay(today);
+ const days = [sideDay(a), sideDay(b)].filter(Boolean).sort();
+ if (!days.length) return { start: daysBefore(EMPTY_WINDOW_DAYS, today), end: now };
+ const shift = (day, delta) => {
+ const moment = new Date(`${day}T00:00:00Z`);
+ moment.setUTCDate(moment.getUTCDate() + delta);
+ return isoDay(moment);
+ };
+ let start = shift(days[0], -LEAD_DAYS);
+ const end = [shift(days.at(-1), TRAIL_DAYS), now].sort()[0];
+ if (shift(start, MAX_WINDOW_DAYS) < end) start = shift(end, -MAX_WINDOW_DAYS);
+ return { start, end };
+}
+
+/**
+ * The lookup route for an archive over a point.
+ *
+ * A Wayback history is read at the view's zoom: which releases changed is a
+ * question about the tile the analyst is looking at.
+ */
+export function lookupPath(archive, { lat, lon, zoom }, window) {
+ if (archive === WAYBACK_ID) {
+ return `/api/satellite/wayback/changes?lat=${lat}&lon=${lon}&zoom=${Math.max(1, Math.min(22, Math.round(zoom)))}`;
+ }
+ const collection = archive === RADAR_ID ? '&collection=sentinel1' : '';
+ return `/api/satellite/sentinel/dates?lat=${lat}&lon=${lon}&start=${window.start}&end=${window.end}${collection}`;
+}
+
+/**
+ * The strip's rows, oldest first, whatever archive answered.
+ *
+ * `usable` is false for a Sentinel-2 day over the cloud ceiling, and for a
+ * radar pass off the track the pair is read on: both are shown, neither is
+ * offered to the bracket.
+ */
+export function stripEntries(archive, answer, { maxcc = 100, track = '' } = {}) {
+ if (archive === WAYBACK_ID) {
+ return (answer?.changes ?? [])
+ .map((entry) => ({
+ key: `r${entry.release}`,
+ date: entry.acquired || entry.date || '',
+ note: entry.acquired ? 'taken' : '',
+ release: entry.release,
+ usable: true,
+ }))
+ .reverse();
+ }
+ const rows = (answer?.dates ?? []).map((entry) => {
+ if (archive === RADAR_ID) {
+ return {
+ key: `${entry.date}T${entry.time}`,
+ date: entry.date,
+ time: entry.time,
+ orbit: entry.orbit ?? '',
+ note: `${String(entry.time ?? '').slice(0, 5)} UTC`,
+ usable: !track || sameTrack(entry.time, track),
+ };
+ }
+ return {
+ key: entry.date,
+ date: entry.date,
+ cloud: entry.cloud,
+ note: entry.cloud == null ? '' : `${Math.round(entry.cloud)}% cloud`,
+ usable: !overCloudCeiling(entry.cloud, maxcc),
+ };
+ });
+ return rows.filter((row) => row.date).sort((x, y) => (x.key < y.key ? -1 : x.key > y.key ? 1 : 0));
+}
+
+/** The row a side shows, if the strip holds it. */
+export function entryOf(entries, archive, side) {
+ if (!side) return null;
+ if (archive === WAYBACK_ID) {
+ if (side.wayback_release == null) return entries.at(-1) ?? null;
+ return entries.find((entry) => entry.release === side.wayback_release) ?? null;
+ }
+ if (archive === RADAR_ID) {
+ const pass = side.radar;
+ return validPass(pass) ? entries.find((entry) => entry.key === `${pass.date}T${pass.time}`) ?? null : null;
+ }
+ const day = side.sentinel?.date;
+ return day ? entries.find((entry) => entry.key === day) ?? null : null;
+}
+
+/** What a side becomes when the strip shows a row on it. */
+export function sidePatch(archive, entry) {
+ if (archive === WAYBACK_ID) return { wayback_release: entry.release };
+ if (archive === RADAR_ID) return { radar: { date: entry.date, time: entry.time } };
+ return { sentinel: { date: entry.date } };
+}
+
+// -- the bracket ------------------------------------------------------------------
+
+/**
+ * A bracket from what A and B show: A before the thing, B after it.
+ * Null when they do not make one — a side the strip does not hold, or A not
+ * older than B.
+ */
+export function startBracket(entries, before, after) {
+ if (!before || !after) return null;
+ const from = entries.indexOf(before);
+ const to = entries.indexOf(after);
+ if (from < 0 || to < 0 || from >= to) return null;
+ return { before: before.key, after: after.key, probe: null, skipped: [], history: [] };
+}
+
+/** The usable rows strictly between the bracket's ends. */
+export function between(entries, bracket) {
+ const from = entries.findIndex((entry) => entry.key === bracket.before);
+ const to = entries.findIndex((entry) => entry.key === bracket.after);
+ if (from < 0 || to < 0) return [];
+ return entries.slice(from + 1, to)
+ .filter((entry) => entry.usable && !bracket.skipped.includes(entry.key));
+}
+
+/** The next row to look at: the middle of what is left, or null when done. */
+export function nextProbe(entries, bracket) {
+ const left = between(entries, bracket);
+ return left.length ? left[Math.floor((left.length - 1) / 2)] : null;
+}
+
+/**
+ * The bracket after one answer about the probe.
+ *
+ * `there` moves the "after" end to the probe, `absent` the "before" end, and
+ * `unclear` (cloud, a smear, a look that settles nothing) drops the probe
+ * without moving either. Every answer can be taken back.
+ */
+export function answerProbe(bracket, verdict) {
+ const probe = bracket.probe;
+ if (!probe) return bracket;
+ const history = [...bracket.history, { before: bracket.before, after: bracket.after, skipped: bracket.skipped }];
+ if (verdict === 'there') return { ...bracket, after: probe, probe: null, history };
+ if (verdict === 'absent') return { ...bracket, before: probe, probe: null, history };
+ return { ...bracket, skipped: [...bracket.skipped, probe], probe: null, history };
+}
+
+/** Take the last answer back. */
+export function undoAnswer(bracket) {
+ const last = bracket.history.at(-1);
+ if (!last) return bracket;
+ return { ...bracket, ...last, probe: null, history: bracket.history.slice(0, -1) };
+}
+
+/** Whether nothing usable is left between the ends. */
+export function settled(entries, bracket) {
+ return !nextProbe(entries, bracket);
+}
+
+/**
+ * The finding, in a sentence the analyst can paste into a note. It says how
+ * many pictures between the ends could not settle it, because "between the
+ * 3rd and the 18th" hides a cloudy week that "no clear pass between" does not.
+ */
+export function bracketSentence(entries, bracket, label) {
+ const before = entries.find((entry) => entry.key === bracket.before);
+ const after = entries.find((entry) => entry.key === bracket.after);
+ if (!before || !after) return '';
+ const name = (entry) => (entry.time ? `${entry.date} ${entry.time.slice(0, 5)} UTC` : entry.date);
+ const from = entries.indexOf(before);
+ const to = entries.indexOf(after);
+ const unread = entries.slice(from + 1, to).length;
+ const tail = unread
+ ? `; ${unread === 1 ? 'one picture' : `${unread} pictures`} between them could not tell`
+ : '';
+ return `Absent on ${name(before)}, present on ${name(after)} (${label})${tail}.`;
+}
+
+// -- pictures ------------------------------------------------------------------------
+
+/** How big a picture of the view is drawn in the strip, in CSS px. */
+export const THUMB = Object.freeze({ width: 132, height: 84 });
+
+/**
+ * The tiles that draw the view, shrunk into one picture of the strip.
+ *
+ * The level is the deepest at which the whole view still fits a thumbnail at
+ * one tile pixel per screen pixel or more, capped at the provider's native
+ * level so nothing is bought that is only upsampled. That keeps a picture to
+ * one tile, two or four where the view straddles a tile edge: each is one
+ * request through the tile proxy, which caches it on disk.
+ */
+export function thumbTiles({ lat, lon, zoom, viewWidth }, provider, box = THUMB) {
+ const size = provider?.tile_size ?? 256;
+ const shift = Math.log2(size / 256);
+ const native = (provider?.max_native_zoom ?? provider?.max_zoom ?? 18) - shift;
+ const viewGrid = zoom - shift;
+ const wanted = Math.floor(viewGrid - Math.log2(Math.max(1, viewWidth) / box.width));
+ const grid = Math.max(0, Math.min(Math.floor(native), wanted));
+ const scale = box.width / (Math.max(1, viewWidth) * 2 ** (grid - viewGrid));
+ const count = 2 ** grid;
+ const world = count * size;
+ const x = ((lon + 180) / 360) * world;
+ const sin = Math.min(0.9999, Math.max(-0.9999, Math.sin((lat * Math.PI) / 180)));
+ const y = (0.5 - Math.log((1 + sin) / (1 - sin)) / (4 * Math.PI)) * world;
+ const left = x - box.width / 2 / scale;
+ const top = y - box.height / 2 / scale;
+ const tiles = [];
+ for (let ty = Math.floor(top / size); ty <= Math.floor((top + box.height / scale) / size); ty++) {
+ if (ty < 0 || ty >= count) continue;
+ for (let tx = Math.floor(left / size); tx <= Math.floor((left + box.width / scale) / size); tx++) {
+ tiles.push({
+ z: grid,
+ x: ((tx % count) + count) % count,
+ y: ty,
+ left: (tx * size - left) * scale,
+ top: (ty * size - top) * scale,
+ size: size * scale,
+ });
+ }
+ }
+ return tiles;
+}
diff --git a/frontend/src/lib/map/passStrip.test.js b/frontend/src/lib/map/passStrip.test.js
new file mode 100644
index 0000000..612abd2
--- /dev/null
+++ b/frontend/src/lib/map/passStrip.test.js
@@ -0,0 +1,122 @@
+import { describe, expect, it } from 'vitest';
+import {
+ answerProbe,
+ between,
+ bracketSentence,
+ entryOf,
+ lookupPath,
+ lookupWindow,
+ nextProbe,
+ sidePatch,
+ startBracket,
+ stripArchive,
+ stripEntries,
+ thumbTiles,
+ undoAnswer,
+} from './passStrip.js';
+
+const s2 = (date) => ({ present: true, provider: 'sentinel2', sentinel: { date, layer: 'TRUE_COLOR', maxcc: 100 } });
+const DAYS = ['2026-05-03', '2026-05-08', '2026-05-13', '2026-05-18', '2026-05-23', '2026-05-28', '2026-06-02'];
+const optical = { dates: DAYS.map((date, i) => ({ date, cloud: i === 2 ? 80 : 5, granules: 1 })).reverse() };
+
+describe('the archive both sides show', () => {
+ it('is a dated archive shared by A and B, or nothing', () => {
+ expect(stripArchive(s2(''), s2(''))).toBe('sentinel2');
+ expect(stripArchive({ present: true, provider: 'sentinel1' }, { present: true, provider: 'sentinel1' })).toBe('sentinel1');
+ expect(stripArchive(s2(''), { present: true, provider: 'esri-wayback' })).toBe(null);
+ expect(stripArchive({ present: true, provider: 'osm' }, { present: true, provider: 'osm' })).toBe(null);
+ expect(stripArchive(s2(''), { ...s2(''), present: false })).toBe(null);
+ });
+
+ it('is looked up around the pair, never past today, a year at most', () => {
+ const today = new Date('2026-09-23T12:00:00Z');
+ expect(lookupWindow(s2('2026-05-03'), s2('2026-06-02'), today)).toEqual({ start: '2026-02-02', end: '2026-07-02' });
+ expect(lookupWindow(s2(''), s2(''), today)).toEqual({ start: '2026-03-27', end: '2026-09-23' });
+ expect(lookupWindow(s2('2024-01-01'), s2('2026-09-01'), today).start).toBe('2025-08-19');
+ expect(lookupPath('sentinel1', { lat: 1, lon: 2, zoom: 14 }, { start: 'x', end: 'y' })).toContain('collection=sentinel1');
+ expect(lookupPath('esri-wayback', { lat: 1, lon: 2, zoom: 14.6 }, null)).toContain('/wayback/changes?lat=1&lon=2&zoom=15');
+ });
+});
+
+describe('the strip', () => {
+ it('runs oldest to newest, and greys a day over the cloud ceiling', () => {
+ const rows = stripEntries('sentinel2', optical, { maxcc: 30 });
+ expect(rows.map((row) => row.date)).toEqual(DAYS);
+ expect(rows[2]).toMatchObject({ usable: false, note: '80% cloud' });
+ });
+
+ it('holds radar to one track and Wayback to the releases that changed', () => {
+ const radar = stripEntries('sentinel1', { dates: [
+ { date: '2026-05-14', time: '17:33:02', orbit: 'ascending' },
+ { date: '2026-05-14', time: '05:42:10', orbit: 'descending' },
+ { date: '2026-05-02', time: '05:42:40', orbit: 'descending' },
+ ] }, { track: '05:42:00' });
+ expect(radar.map((row) => [row.key, row.usable])).toEqual([
+ ['2026-05-02T05:42:40', true], ['2026-05-14T05:42:10', true], ['2026-05-14T17:33:02', false]]);
+ const wayback = stripEntries('esri-wayback', { changes: [
+ { release: 55, acquired: '2025-02-20' }, { release: 41, acquired: '2023-06-11' }] });
+ expect(wayback.map((row) => row.release)).toEqual([41, 55]);
+ expect(entryOf(wayback, 'esri-wayback', { wayback_release: null })).toBe(wayback[1]);
+ expect(sidePatch('esri-wayback', wayback[0])).toEqual({ wayback_release: 41 });
+ expect(sidePatch('sentinel1', radar[0])).toEqual({ radar: { date: '2026-05-02', time: '05:42:40' } });
+ });
+});
+
+describe('dating a change', () => {
+ const rows = stripEntries('sentinel2', optical, { maxcc: 30 });
+ const start = () => startBracket(rows, rows[0], rows[6]);
+
+ it('needs A older than B, both on the strip', () => {
+ expect(startBracket(rows, rows[6], rows[0])).toBe(null);
+ expect(startBracket(rows, null, rows[0])).toBe(null);
+ expect(between(rows, start()).map((row) => row.date)).toEqual(
+ ['2026-05-08', '2026-05-18', '2026-05-23', '2026-05-28']); // the cloudy 13th left out
+ });
+
+ it('halves the gap an answer at a time until the ends are neighbours', () => {
+ let bracket = start();
+ const ask = () => ({ ...bracket, probe: nextProbe(rows, bracket).key });
+ bracket = ask();
+ expect(bracket.probe).toBe('2026-05-18');
+ bracket = answerProbe(bracket, 'there'); // it is on the 18th
+ bracket = ask();
+ expect(bracket.probe).toBe('2026-05-08');
+ bracket = answerProbe(bracket, 'absent'); // not yet on the 8th
+ expect(nextProbe(rows, bracket)).toBe(null);
+ expect(bracketSentence(rows, bracket, 'Sentinel-2')).toBe(
+ 'Absent on 2026-05-08, present on 2026-05-18 (Sentinel-2); one picture between them could not tell.');
+ });
+
+ it('drops a picture that settles nothing, and takes an answer back', () => {
+ let bracket = { ...start(), probe: '2026-05-18' };
+ bracket = answerProbe(bracket, 'unclear');
+ expect(between(rows, bracket).map((row) => row.date)).not.toContain('2026-05-18');
+ const undone = undoAnswer(bracket);
+ expect(between(rows, undone).map((row) => row.date)).toContain('2026-05-18');
+ expect(undoAnswer(undone)).toBe(undone);
+ });
+});
+
+describe('pictures of the view', () => {
+ const sentinel = { tile_size: 512, max_native_zoom: 14, max_zoom: 18 };
+
+ it('draws the view from a tile or a few, never past the native level', () => {
+ const tiles = thumbTiles({ lat: 51.95, lon: 4.05, zoom: 15, viewWidth: 1000 }, sentinel);
+ expect(tiles.length).toBeGreaterThanOrEqual(1);
+ expect(tiles.length).toBeLessThanOrEqual(4);
+ expect(tiles.every((tile) => tile.z === 11)).toBe(true);
+ const deep = thumbTiles({ lat: 51.95, lon: 4.05, zoom: 22, viewWidth: 400 }, sentinel);
+ expect(deep.every((tile) => tile.z === 13)).toBe(true);
+ });
+
+ it('puts the middle of the view in the middle of the picture', () => {
+ const [tile] = thumbTiles({ lat: 0, lon: 0, zoom: 10, viewWidth: 132 }, { tile_size: 256, max_zoom: 19 });
+ // the equator and the meridian meet at a tile corner, drawn at the centre
+ const corners = thumbTiles({ lat: 0, lon: 0, zoom: 10, viewWidth: 132 }, { tile_size: 256, max_zoom: 19 });
+ expect(corners).toHaveLength(4);
+ const right = corners.find((entry) => entry.left >= 0 && entry.top >= 0);
+ expect(right.left).toBeCloseTo(66, 0);
+ expect(right.top).toBeCloseTo(42, 0);
+ expect(tile.z).toBe(10);
+ });
+});
diff --git a/frontend/src/lib/map/wheelRelay.js b/frontend/src/lib/map/wheelRelay.js
new file mode 100644
index 0000000..5213c33
--- /dev/null
+++ b/frontend/src/lib/map/wheelRelay.js
@@ -0,0 +1,28 @@
+/**
+ * The wheel belongs to the map, wherever the pointer happens to be.
+ *
+ * Everything we draw over a map — marks, watched areas, candidates — is a
+ * sibling of the map element rather than a child of it, so a wheel over one of
+ * those shapes stops there and the view does not zoom until the pointer is
+ * moved off whatever was drawn. A press can be the shape's; the wheel is always
+ * handed down to the picture under it.
+ */
+
+/** Relay `event` to the map element under the pointer. `root` is the overlay. */
+export function relayWheel(event, { engine, root }) {
+ const container = engine?.container;
+ if (!container) return;
+ const below = document
+ .elementsFromPoint(event.clientX, event.clientY)
+ .find((element) => !root?.contains(element) && container.contains(element));
+ if (!below) return;
+ event.preventDefault();
+ below.dispatchEvent(new WheelEvent('wheel', {
+ deltaX: event.deltaX, deltaY: event.deltaY, deltaZ: event.deltaZ,
+ deltaMode: event.deltaMode,
+ clientX: event.clientX, clientY: event.clientY,
+ ctrlKey: event.ctrlKey, shiftKey: event.shiftKey,
+ altKey: event.altKey, metaKey: event.metaKey,
+ bubbles: true, cancelable: true,
+ }));
+}
diff --git a/frontend/src/lib/navigate.js b/frontend/src/lib/navigate.js
index d64510c..eab343a 100644
--- a/frontend/src/lib/navigate.js
+++ b/frontend/src/lib/navigate.js
@@ -43,9 +43,10 @@ export const ENTITY_TOOL = {
post: 'post',
'inspect-session': 'inspect',
'compare-session': 'compare',
- 'analysis-zones': 'compare',
- 'analysis-follow-up': 'compare',
- 'analysis-run': 'compare',
+ 'analysis-zones': 'detect',
+ 'analysis-area': 'detect',
+ 'analysis-follow-up': 'detect',
+ 'analysis-run': 'detect',
};
/**
@@ -107,9 +108,9 @@ export function openEntity(entity) {
uiState.tool = 'compare';
return;
}
- if (['analysis-zones', 'analysis-follow-up', 'analysis-run'].includes(entity.type)) {
+ if (['analysis-area', 'analysis-zones', 'analysis-follow-up', 'analysis-run'].includes(entity.type)) {
uiState.openAnalyzer = specName(entity.attrs?.spec);
- uiState.tool = 'compare';
+ uiState.tool = 'detect';
return;
}
if (entity.type === 'place') {
@@ -234,3 +235,14 @@ export function gotoCapture(entity) {
};
uiState.tool = 'satellite';
}
+
+/**
+ * Open Settings on the Copernicus card, open.
+ *
+ * Detect and Compare send the analyst here when Copernicus is missing, and a
+ * tab of eight cards with the right one shut would make them look for it.
+ */
+export function openCopernicusSettings() {
+ uiState.settingsTab = 'imagery:sentinelhub';
+ uiState.tool = 'settings';
+}
diff --git a/frontend/src/lib/radar.js b/frontend/src/lib/radar.js
new file mode 100644
index 0000000..ef1218e
--- /dev/null
+++ b/frontend/src/lib/radar.js
@@ -0,0 +1,70 @@
+/**
+ * Sentinel-1 radar as a basemap: which pass a map shows.
+ *
+ * A pass rides on the provider id as a variant, `sentinel1~2026-05-14~054210`,
+ * the way a Sentinel-2 day does (`lib/sentinel.js`); `engine/sentinel.py` reads
+ * the same shape. A pass is a day *and* a time: the radar can see a place twice
+ * on one day, at dawn flying south and at dusk flying north, and those are two
+ * pictures of the ground from opposite sides.
+ */
+
+export const RADAR_ID = 'sentinel1';
+const SEP = '~';
+const TIME = /^([01]\d|2[0-3]):([0-5]\d):([0-5]\d)$/;
+const DAY = /^\d{4}-\d{2}-\d{2}$/;
+
+/**
+ * Two looks at one place are the same track when they pass at the same time of
+ * day. A track repeats to the second every twelve days, whichever satellite
+ * flies it, and the neighbouring track that also sees the place passes about
+ * eight minutes off. Mirrors `same_track` in `engine/sentinel.py`.
+ */
+export const SAME_TRACK_MINUTES = 4;
+
+/** A pass as `{ date, time }`, or null when it is not one. */
+export function validPass(pass) {
+ return Boolean(pass && DAY.test(pass.date ?? '') && TIME.test(pass.time ?? ''));
+}
+
+/** The provider id for one pass, or the plain id for the most recent. */
+export function radarId(baseId, pass) {
+ if (baseId !== RADAR_ID || !validPass(pass)) return baseId;
+ return [baseId, pass.date, pass.time.replace(/:/g, '')].join(SEP);
+}
+
+/** …and back: the pass an id names, or null for the plain basemap. */
+export function passOf(providerId) {
+ const [base, day, time] = String(providerId ?? '').split(SEP);
+ if (base !== RADAR_ID || !DAY.test(day ?? '') || !/^\d{6}$/.test(time ?? '')) return null;
+ const pass = { date: day, time: `${time.slice(0, 2)}:${time.slice(2, 4)}:${time.slice(4)}` };
+ return validPass(pass) ? pass : null;
+}
+
+function minutes(time) {
+ const [, hours, mins, secs] = TIME.exec(time);
+ return Number(hours) * 60 + Number(mins) + (Number(secs) >= 30 ? 1 : 0);
+}
+
+/** Whether two pass times are one track: the same look, so comparable. */
+export function sameTrack(one, other) {
+ if (!TIME.test(one ?? '') || !TIME.test(other ?? '')) return false;
+ const gap = Math.abs(minutes(one) - minutes(other)) % 1440;
+ return Math.min(gap, 1440 - gap) <= SAME_TRACK_MINUTES;
+}
+
+/** How a pass reads: "2026-05-14 · 05:42 UTC". */
+export function passLabel(pass) {
+ if (!validPass(pass)) return 'Most recent';
+ return `${pass.date} · ${pass.time.slice(0, 5)} UTC`;
+}
+
+/** The direction as an arrow a list row can carry. */
+export function orbitMark(orbit) {
+ return orbit === 'descending' ? '↓' : orbit === 'ascending' ? '↑' : '';
+}
+
+/** The passes of a list that share `track`'s time of day, newest first. */
+export function onTrack(list, track) {
+ if (!TIME.test(track ?? '')) return list ?? [];
+ return (list ?? []).filter((entry) => sameTrack(entry.time, track));
+}
diff --git a/frontend/src/lib/radar.test.js b/frontend/src/lib/radar.test.js
new file mode 100644
index 0000000..c8e87c6
--- /dev/null
+++ b/frontend/src/lib/radar.test.js
@@ -0,0 +1,41 @@
+import { describe, expect, it } from 'vitest';
+import { RADAR_ID, onTrack, orbitMark, passLabel, passOf, radarId, sameTrack, validPass } from './radar.js';
+
+describe('a Sentinel-1 pass on the provider id', () => {
+ it('rides as a day and a time without colons, and comes back', () => {
+ const pass = { date: '2026-05-14', time: '05:42:10' };
+ expect(radarId(RADAR_ID, pass)).toBe('sentinel1~2026-05-14~054210');
+ expect(passOf('sentinel1~2026-05-14~054210')).toEqual(pass);
+ });
+
+ it('stays the plain id for the most recent pass, and on any other basemap', () => {
+ expect(radarId(RADAR_ID, null)).toBe(RADAR_ID);
+ expect(radarId(RADAR_ID, { date: '2026-05-14', time: '5:42' })).toBe(RADAR_ID);
+ expect(radarId('sentinel2', { date: '2026-05-14', time: '05:42:10' })).toBe('sentinel2');
+ expect(passOf('sentinel1')).toBe(null);
+ expect(passOf('sentinel1~2026-05-14~99')).toBe(null);
+ expect(validPass({ date: '2026-05-14', time: '24:00:00' })).toBe(false);
+ });
+
+ it('reads as a day, a UTC time and a direction', () => {
+ expect(passLabel({ date: '2026-05-14', time: '05:42:10' })).toBe('2026-05-14 · 05:42 UTC');
+ expect(passLabel(null)).toBe('Most recent');
+ expect(orbitMark('descending')).toBe('↓');
+ expect(orbitMark('ascending')).toBe('↑');
+ });
+});
+
+describe('one track', () => {
+ it('repeats to the minute; the neighbouring track passes eight minutes off', () => {
+ expect(sameTrack('17:49:10', '17:48:40')).toBe(true);
+ expect(sameTrack('17:49:10', '17:41:05')).toBe(false);
+ expect(sameTrack('23:59:30', '00:01:10')).toBe(true);
+ expect(sameTrack('', '17:49:10')).toBe(false);
+ });
+
+ it('keeps the passes of a track, or all of them when there is none yet', () => {
+ const list = [{ time: '05:42:10' }, { time: '17:33:02' }, { time: '05:41:50' }];
+ expect(onTrack(list, '05:42:00')).toEqual([list[0], list[2]]);
+ expect(onTrack(list, '')).toBe(list);
+ });
+});
diff --git a/frontend/src/lib/state.svelte.js b/frontend/src/lib/state.svelte.js
index be29bbb..1a624cb 100644
--- a/frontend/src/lib/state.svelte.js
+++ b/frontend/src/lib/state.svelte.js
@@ -23,6 +23,7 @@ export const prefs = $state({
coordFormat: 'dd', // 'dd' | 'dms' | 'mgrs'
units: 'metric', // 'metric' | 'imperial'
homeView: { lat: 43, lon: 25, zoom: 3 }, // where Satellite opens
+ detectView: { collapsed: false, basemap: 'esri-world-imagery', overlays: ['boundaries'], 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
@@ -92,6 +93,7 @@ export function applyPrefs(s) {
if (s.coord_format) prefs.coordFormat = s.coord_format;
if (s.units) prefs.units = s.units;
if (s.home_view) prefs.homeView = s.home_view;
+ if (s.detect_view) prefs.detectView = s.detect_view;
if (s.capture_scale_north !== undefined) prefs.captureScaleNorth = s.capture_scale_north;
if (s.post_mention !== undefined) prefs.postMention = s.post_mention; // '' = none
if (s.post_target !== undefined) prefs.postTarget = s.post_target;
@@ -245,7 +247,7 @@ export const uiState = $state({
focusMedia: null, // media path to highlight & scroll to in the Media Library
openInspect: null, // inspect-session name to reopen in the Inspect tool
openCompare: null, // compare-session name to reopen in the Compare tool
- openAnalyzer: null, // saved analysis item stem to reopen without loading imagery
+ openAnalyzer: null, // saved Detect item stem to reopen without loading imagery
// Entity id the Board should open Details on. The graph-only types — a person,
// an account, a claim — have no tool of their own to be reopened in, so the
// board is where following a relation to one of them lands.
diff --git a/frontend/src/lib/trash.js b/frontend/src/lib/trash.js
index 6295d97..7cbbee8 100644
--- a/frontend/src/lib/trash.js
+++ b/frontend/src/lib/trash.js
@@ -27,6 +27,7 @@ export const FILE_BACKED = new Set([
'inspect-session',
'compare-session',
'analysis-zones',
+ 'analysis-area',
'analysis-follow-up',
'analysis-run',
'note',
diff --git a/frontend/src/lib/wayback.js b/frontend/src/lib/wayback.js
index 73d589f..0c32c94 100644
--- a/frontend/src/lib/wayback.js
+++ b/frontend/src/lib/wayback.js
@@ -93,3 +93,17 @@ export function changesKey(lat, lon, zoom) {
const y = Math.floor((0.5 - Math.log((1 + sin) / (1 - sin)) / (4 * Math.PI)) * scale);
return `${z}/${x}/${y}`;
}
+
+/**
+ * The release a "then" side opens on: the newest published a year or more
+ * before `today`, else the oldest. Null when that would be the newest release,
+ * which is today's World Imagery again.
+ */
+export function releaseYearBefore(releases, today = new Date()) {
+ if (!releases?.length) return null;
+ const cutoff = new Date(today);
+ cutoff.setUTCFullYear(cutoff.getUTCFullYear() - 1);
+ const day = cutoff.toISOString().slice(0, 10);
+ const found = releases.find((entry) => entry.date <= day) ?? releases.at(-1);
+ return found === releases[0] ? null : found.release;
+}
diff --git a/frontend/src/lib/wayback.test.js b/frontend/src/lib/wayback.test.js
index 6d010cc..993cd29 100644
--- a/frontend/src/lib/wayback.test.js
+++ b/frontend/src/lib/wayback.test.js
@@ -5,6 +5,7 @@ import {
positionOf,
releaseDate,
releaseOf,
+ releaseYearBefore,
stepRelease,
validRelease,
visibleReleases,
@@ -109,3 +110,22 @@ describe('the question a point history answers', () => {
expect(changesKey(50.45, 30.51, 22).startsWith('19/')).toBe(true);
});
});
+
+describe('the release a "then" side opens on', () => {
+ const today = new Date('2026-09-23T12:00:00Z');
+
+ it('is the newest published a year or more before today', () => {
+ expect(releaseYearBefore(RELEASES, today)).toBe(64776);
+ expect(releaseYearBefore(RELEASES, new Date('2024-06-13T00:00:00Z'))).toBe(25982);
+ });
+
+ it('falls back to the oldest when every release is younger', () => {
+ expect(releaseYearBefore(RELEASES.slice(0, 2), new Date('2024-01-01T00:00:00Z'))).toBe(64776);
+ });
+
+ it('refuses to name the newest, which is today’s imagery again', () => {
+ expect(releaseYearBefore(RELEASES.slice(0, 1), today)).toBeNull();
+ expect(releaseYearBefore([], today)).toBeNull();
+ expect(releaseYearBefore(undefined, today)).toBeNull();
+ });
+});
diff --git a/frontend/src/lib/workspaces.js b/frontend/src/lib/workspaces.js
index a4f748c..5a138ca 100644
--- a/frontend/src/lib/workspaces.js
+++ b/frontend/src/lib/workspaces.js
@@ -44,7 +44,7 @@ export const HOME_WORKSPACE = {
export const WORKSPACES = [
{ id: 'collect', label: 'Sources', icon: 'download', tools: ['media', 'files', 'reverse'] },
{ id: 'examine', label: 'Examine', icon: 'inspect', tools: ['inspect'] },
- { id: 'map', label: 'Map', icon: 'satellite', tools: ['satellite', 'compare', 'coordinates'] },
+ { id: 'map', label: 'Map', icon: 'satellite', tools: ['satellite', 'compare', 'detect', 'coordinates'] },
{ id: 'compose', label: 'Compose', icon: 'proof', tools: ['proof', 'post', 'notebook'] },
];
@@ -64,6 +64,7 @@ export const TOOL_LABELS = {
inspect: 'Inspect',
satellite: 'Satellite',
compare: 'Compare',
+ detect: 'Detect',
coordinates: 'Coords & Sky',
proof: 'Geo Proof',
post: 'Geo Report',
diff --git a/frontend/src/lib/workspaces.test.js b/frontend/src/lib/workspaces.test.js
index a52572c..73d7318 100644
--- a/frontend/src/lib/workspaces.test.js
+++ b/frontend/src/lib/workspaces.test.js
@@ -12,13 +12,13 @@ import {
const ALL_TOOLS = [
'overview', 'guide',
- 'board', 'graph', 'timeline', 'sheet', 'media', 'files', 'reverse', 'inspect', 'satellite', 'compare', 'coordinates', 'proof', 'post', 'notebook',
+ 'board', 'graph', 'timeline', 'sheet', 'media', 'files', 'reverse', 'inspect', 'satellite', 'compare', 'detect', 'coordinates', 'proof', 'post', 'notebook',
'settings',
];
describe('workspaceOf', () => {
it('maps every tool to exactly one workspace', () => {
- for (const tool of ['overview', 'guide', 'board', 'graph', 'timeline', 'sheet', 'media', 'files', 'reverse', 'inspect', 'satellite', 'compare', 'coordinates', 'proof', 'post', 'notebook']) {
+ for (const tool of ['overview', 'guide', 'board', 'graph', 'timeline', 'sheet', 'media', 'files', 'reverse', 'inspect', 'satellite', 'compare', 'detect', 'coordinates', 'proof', 'post', 'notebook']) {
const owners = ALL_WORKSPACES.filter((w) => w.tools.includes(tool));
expect(owners).toHaveLength(1);
expect(workspaceOf(tool)).toBe(owners[0]);
diff --git a/frontend/src/tools/Compare.pair.test.js b/frontend/src/tools/Compare.pair.test.js
index fbc6047..c5920c8 100644
--- a/frontend/src/tools/Compare.pair.test.js
+++ b/frontend/src/tools/Compare.pair.test.js
@@ -24,8 +24,8 @@ describe('Compare here', () => {
it('travels as a pair of sides, the shape a saved comparison stores', () => {
expect(state).toContain('compareAt: null,');
expect(map).toContain('uiState.compareAt = { ...point, zoom: center.zoom, ...pair };');
- expect(compare).toContain('applySide(a, s2a, wba, pair.a);');
- expect(compare).toContain('applySide(b, s2b, wbb, pair.b);');
+ expect(compare).toContain('applySide(a, s2a, wba, pair.a, s1a);');
+ expect(compare).toContain('applySide(b, s2b, wbb, pair.b, s1b);');
});
it('opens unsaved and unnamed, because nothing was filed', () => {
diff --git a/frontend/src/tools/Compare.render.test.js b/frontend/src/tools/Compare.render.test.js
index b0066ac..61b9c88 100644
--- a/frontend/src/tools/Compare.render.test.js
+++ b/frontend/src/tools/Compare.render.test.js
@@ -47,7 +47,7 @@ const SIZES = {
};
const RECIPE = {
id: 'pair', name: 'Any surface change', description: 'Reflectance that moved',
- phenomenon: 'Change', method: 'surface', zones: [], colour: '#f6a81a', style: 'both',
+ phenomenon: 'Change', method: 'surface', colour: '#f6a81a', style: 'both',
parameters: { sensitivity: 67, ...SIZES.medium, index: 'ndvi', direction: 'both',
ignore_clouds: true, ignore_shadows: true, cloud_margin: 5 },
};
@@ -63,6 +63,8 @@ const ANALYZERS = {
max_tiles: 4096, max_results: 2000, grid: [13, 512],
};
+// Newest first. Empty by default, so the opening pair has no "then" to show.
+let releases = [];
const get = vi.fn(async (path) => {
if (path === '/api/compare/analyzers') return structuredClone(ANALYZERS);
if (path.startsWith('/api/cases/case-a/analysis/')) return [];
@@ -79,11 +81,22 @@ const get = vi.fn(async (path) => {
if (path === '/api/settings') return { usage: {}, month: '2026-09' };
if (path.includes('/satellite/index')) return [];
if (path.includes('/imagery-date')) return { supported: true, date: '2024-01-02' };
- if (path === '/api/satellite/wayback/releases') return { releases: [] };
+ if (path === '/api/satellite/wayback/releases') return { releases: structuredClone(releases) };
if (path === '/api/cases/case-a/compare/sessions') {
- return [{ name: 'Harbour change', title: 'Harbour change', provider_a: 'esri-world-imagery', provider_b: 'esri-wayback', mode: 'swipe' }];
+ return [
+ { name: 'Harbour change', title: 'Harbour change', provider_a: 'esri-world-imagery', provider_b: 'esri-wayback', mode: 'swipe' },
+ { name: 'Old difference', title: 'Old difference', provider_a: 'esri-world-imagery', provider_b: 'esri-wayback', mode: 'change' },
+ ];
}
if (path === '/api/cases/case-a/compare/sessions/Harbour%20change') return SESSION;
+ // Saved while Difference was a mode of its own, over one image.
+ if (path === '/api/cases/case-a/compare/sessions/Old%20difference') {
+ return {
+ ...SESSION,
+ title: 'Old difference',
+ spec: { ...SESSION.spec, mode: 'change', frame: null, change_assist: { base: 'side' } },
+ };
+ }
return {};
});
const post = vi.fn(async (path) => {
@@ -100,6 +113,7 @@ const toast = vi.fn();
const ensureCase = vi.fn(async () => ({ id: 'case-a' }));
const reloadCase = vi.fn(async () => {});
const caseState = { current: { id: 'case-a' } };
+const uiState = { tool: 'compare', openCompare: null };
vi.mock('../lib/state.svelte.js', () => ({
caseState,
ensureCase,
@@ -108,7 +122,7 @@ vi.mock('../lib/state.svelte.js', () => ({
prefsReady: Promise.resolve(),
reloadCase,
toast,
- uiState: { tool: 'compare', openCompare: null },
+ uiState,
}));
const engines = [];
@@ -123,6 +137,8 @@ function fakeEngine(opening, container) {
following: () => false,
camera: vi.fn(() => ({ ...camera })),
getZoom: vi.fn(() => camera.zoom),
+ viewBounds: vi.fn(() => ({ west: camera.lon - 0.001, south: camera.lat - 0.001,
+ east: camera.lon + 0.001, north: camera.lat + 0.001 })),
container,
setBearing: vi.fn((bearing) => (camera.bearing = bearing)),
setView: vi.fn((view, zoom) => (camera = { ...camera, ...view, zoom })),
@@ -173,7 +189,8 @@ async function settle() {
flushSync();
}
-async function open() {
+/** Mount Compare on its opening pair. */
+async function openFresh() {
target = document.createElement('div');
document.body.append(target);
live = mount(Compare, { target });
@@ -181,10 +198,30 @@ async function open() {
await settle();
}
+/** …then clear both sides, for a test that builds its own pair. */
+async function open() {
+ await openFresh();
+ for (const letter of ['A', 'B']) {
+ target.querySelector(`button[aria-label="Remove imagery ${letter}"]`)?.click();
+ flushSync();
+ }
+ await settle();
+ engines.length = 0;
+}
+
function button(label, root = document) {
return [...root.querySelectorAll('button')].find((entry) => entry.textContent.trim().includes(label));
}
+/** Start over from the New menu, on one of its presets. */
+async function startNew(label = 'Then and now') {
+ button('New', target).click();
+ flushSync();
+ button(label, target.querySelector('.new-menu')).click();
+ flushSync();
+ await settle();
+}
+
async function add(slot, provider = 'Esri World Imagery') {
const empty = [...target.querySelectorAll('.empty-slot')].find(
(entry) => entry.querySelector('.slot-letter').textContent === slot
@@ -201,6 +238,7 @@ async function add(slot, provider = 'Esri World Imagery') {
beforeEach(() => {
vi.clearAllMocks();
engines.length = 0;
+ releases = [];
});
afterEach(() => {
@@ -212,13 +250,53 @@ afterEach(() => {
});
describe('Compare', () => {
- it('opens empty and asks before any imagery is loaded', async () => {
- await open();
+ it('opens on a Wayback release a year back against today’s World Imagery', async () => {
+ releases = [
+ { release: 30, date: '2026-09-01' },
+ { release: 20, date: '2025-06-01' },
+ { release: 10, date: '2014-02-20' },
+ ];
+ vi.useFakeTimers({ toFake: ['Date'] });
+ vi.setSystemTime(new Date('2026-09-23T12:00:00Z'));
+ try {
+ await openFresh();
+ } finally {
+ vi.useRealTimers();
+ }
expect(target.querySelector('h2').textContent).toBe('Compare');
- expect(target.querySelectorAll('.empty-slot')).toHaveLength(2);
- expect(target.querySelectorAll('.surface-shell')).toHaveLength(0);
- expect(engines).toHaveLength(0);
- expect(get).toHaveBeenCalledWith('/api/satellite/providers');
+ 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();
+ flushSync();
+ button('Save comparison', document.querySelector('[role="dialog"]')).click();
+ await settle();
+ expect(saved().spec.a).toMatchObject({ present: true, provider: 'esri-wayback', wayback_release: 20 });
+ expect(saved().spec.b).toMatchObject({ present: true, provider: 'esri-world-imagery' });
+ // local-first: the pair costs the release list, never a point's history
+ expect(get.mock.calls.some(([path]) => path.includes('/wayback/changes'))).toBe(false);
+ });
+
+ it('leaves the then side empty rather than showing today twice', async () => {
+ // 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.querySelectorAll('.empty-slot')).toHaveLength(1);
+ });
+
+ it('asks nothing when an untouched pair is left, however it was panned', async () => {
+ releases = [{ release: 30, date: '2026-09-01' }, { release: 10, date: '2014-02-20' }];
+ await openFresh();
+ 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);
+ await startNew();
+ expect(document.querySelector('[role="alertdialog"]')).toBeNull();
});
it('adds two independent surfaces and then offers every comparison mode', async () => {
@@ -236,7 +314,6 @@ describe('Compare', () => {
'Fade',
'Blink',
'Difference',
- 'Detect',
]);
// The second surface opens on the first camera without needing a corrective move.
expect(engines[1].camera()).toEqual(engines[0].camera());
@@ -256,7 +333,7 @@ describe('Compare', () => {
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
- // walks this point's history until the analyst opens the picker
+ // walks this point's history until the analyst asks for the changes
expect(get).toHaveBeenCalledWith('/api/satellite/wayback/releases');
expect(get.mock.calls.some(([path]) => path.includes('/wayback/changes'))).toBe(false);
});
@@ -298,77 +375,64 @@ describe('Compare', () => {
expect(target.querySelector('.compare-stage').style.getPropertyValue('--opacity')).toBe('0.25');
});
- it('toggles only the difference overlay from its eye button', async () => {
+ it('offers Difference only on a pair it can read', async () => {
await open();
await add('A');
- await add('B', 'Esri Wayback');
- button('Difference', target).click();
- flushSync();
- await settle();
-
- const eye = () => target.querySelector('button[aria-label*="difference overlay"]');
- expect(eye().getAttribute('aria-label')).toBe('Hide the difference overlay');
- eye().click();
- flushSync();
- expect(eye().getAttribute('aria-label')).toBe('Show the difference overlay');
- expect(eye().getAttribute('aria-pressed')).toBe('false');
- eye().click();
- flushSync();
- expect(eye().getAttribute('aria-label')).toBe('Hide the difference overlay');
- expect(eye().getAttribute('aria-pressed')).toBe('true');
+ await add('B');
+ // The same picture twice: nothing a pixel reading could say about it.
+ expect(button('Difference', target)).toBeUndefined();
+ expect(target.querySelector('.difference-bar')).toBeNull();
});
- it('lays the difference over one image or over both, from the same switch', async () => {
+ it('lays the difference over the view that is on, without a panel of its own', async () => {
await open();
await add('A');
await add('B', 'Esri Wayback');
+ button('Swipe', target).click();
+ flushSync();
button('Difference', target).click();
flushSync();
await settle();
const stage = () => target.querySelector('.compare-stage');
+ // The view stays what it was, and the maps keep the whole width.
+ expect(stage().classList.contains('swipe')).toBe(true);
+ expect(button('Swipe', target).getAttribute('aria-pressed')).toBe('true');
+ expect(button('Difference', target).getAttribute('aria-pressed')).toBe('true');
+ expect(target.querySelector('.cmp-dock')).toBeNull();
+ // Its controls sit in the footer beside the view's own.
+ 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();
+ // Over both images unless asked otherwise.
const base = (label) => [...target.querySelectorAll('[aria-label="Image under the highlights"] button')]
.find((entry) => entry.textContent.trim() === label);
- // B alone: the two maps are stacked, and only one of them is read.
- expect(base('B').getAttribute('aria-pressed')).toBe('true');
- expect(stage().classList.contains('base-b')).toBe(true);
+ expect(base('Both').getAttribute('aria-pressed')).toBe('true');
- base('Both').click();
+ // Another view keeps the difference on over it.
+ button('Blink', target).click();
flushSync();
- await settle();
- // Both: the pair is side by side again, with the same reading on each.
- expect(stage().classList.contains('overlay')).toBe(false);
- expect(stage().classList.contains('base-b')).toBe(false);
- expect(target.textContent).toContain('Both images, the same highlights on each.');
+ expect(stage().classList.contains('overlay')).toBe(true);
+ expect(target.querySelector('.difference-bar')).not.toBeNull();
- base('A').click();
+ button('Difference', target).click();
flushSync();
- expect(stage().classList.contains('base-a')).toBe(true);
+ expect(target.querySelector('.difference-bar')).toBeNull();
+ expect(target.querySelector('.change-legend')).toBeNull();
+ expect(button('Blink', target).getAttribute('aria-pressed')).toBe('true');
});
- it('gives each computing mode the same column, and only one at a time', async () => {
+ it('shows the difference side by side with no footer of the view to share', async () => {
await open();
await add('A');
await add('B', 'Esri Wayback');
- expect(target.querySelector('.cmp-dock')).toBeNull();
-
+ expect(target.querySelector('.mode-footer')).toBeNull();
button('Difference', target).click();
flushSync();
await settle();
- expect([...target.querySelectorAll('.cmp-dock')].map((dock) => dock.getAttribute('aria-label')))
- .toEqual(['Difference']);
-
- button('Detect', target).click();
- flushSync();
- await settle();
- expect([...target.querySelectorAll('.cmp-dock')].map((dock) => dock.getAttribute('aria-label')))
- .toEqual(['Detect']);
- // Detect works over an undivided pair, whatever reading mode preceded it.
expect(target.querySelector('.compare-stage').classList.contains('overlay')).toBe(false);
-
- button('Side by side', target).click();
- flushSync();
- expect(target.querySelector('.cmp-dock')).toBeNull();
+ expect(target.querySelector('.mode-footer .difference-bar')).not.toBeNull();
});
it('pauses blink on the side that is currently shown', async () => {
@@ -410,8 +474,7 @@ describe('Compare', () => {
it('warns before discarding an unsaved comparison', async () => {
await open();
await add('A');
- button('New', target).click();
- flushSync();
+ await startNew();
const warning = document.querySelector('[role="alertdialog"]');
expect(warning.textContent).toContain('Discard unsaved changes?');
@@ -419,11 +482,12 @@ describe('Compare', () => {
flushSync();
expect(target.querySelectorAll('.surface-shell')).toHaveLength(1);
- button('New', target).click();
- flushSync();
+ await startNew();
button('Discard changes', document.querySelector('[role="alertdialog"]')).click();
- flushSync();
- expect(target.querySelectorAll('.empty-slot')).toHaveLength(2);
+ 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');
});
it('gives each source its own layers and keeps export choices in one modal', async () => {
@@ -508,11 +572,10 @@ describe('Compare', () => {
expect(post).toHaveBeenCalledWith(
'/api/cases/case-a/compare/sessions',
expect.objectContaining({
- spec: expect.objectContaining({ frame: { points: [[10, 5], [410, 365]] } }),
+ spec: expect.objectContaining({ frame: { points: [[10, 5], [410, 365]], angle: 0 } }),
})
);
- button('New', target).click();
- flushSync();
+ await startNew();
expect(target.querySelector('.export-frame')).toBeNull();
});
@@ -645,9 +708,8 @@ describe('Compare', () => {
})
);
- button('New', target).click();
- flushSync();
- expect(target.querySelectorAll('.empty-slot')).toHaveLength(2);
+ await startNew();
+ expect(target.querySelector('input[aria-label="Comparison name"]').value).toBe('Comparison');
button('Open', target).click();
await settle();
button('Harbour change', document.querySelector('[role="dialog"]')).click();
@@ -660,36 +722,32 @@ describe('Compare', () => {
expect(engines.at(-1).camera()).toEqual(expect.objectContaining({ lat: 43.3, lon: 5.4, zoom: 18 }));
});
- it('puts the imagery a run would sweep on the maps, and shows one for one date', async () => {
+ it('saves Difference as a switch beside the view', async () => {
await open();
await add('A');
await add('B', 'Esri Wayback');
- // Outside Detect the source cards lead.
- expect(target.querySelector('.source-bar')).not.toBeNull();
-
- button('Detect', target).click();
+ button('Fade', target).click();
+ button('Difference', target).click();
+ flushSync();
await settle();
- const dock = () => target.querySelector('.cmp-dock');
- const stage = () => target.querySelector('.compare-stage');
- expect(stage().classList.contains('solo')).toBe(false);
- // Inside it, one place to choose imagery, and the maps follow it: Detect
- // reads Sentinel-2 bands, so world imagery and Wayback hand over the wheel.
- expect(target.querySelector('.source-bar')).toBeNull();
- expect(dock().textContent).toContain('Detect reads Sentinel-2, so the maps now show it.');
- expect(target.querySelectorAll('.surface-shell .map')).toHaveLength(2);
-
- const picker = target.querySelector('select[aria-label="Analyzer"]');
- picker.value = 'solo';
- picker.dispatchEvent(new Event('change', { bubbles: true }));
+ button('Save comparison', target).click();
+ flushSync();
+ button('Save comparison', document.querySelector('[role="dialog"]')).click();
await settle();
- // One date to read, so one map, and no reference image asked for.
- expect(stage().classList.contains('solo')).toBe(true);
- expect(dock().textContent).not.toContain('Reference A');
+ const saved = post.mock.calls.find(([path]) => path === '/api/cases/case-a/compare/sessions')[1].spec;
+ expect(saved).toMatchObject({ mode: 'opacity', difference: true, change_assist: { base: 'both' } });
- button('Side by side', target).click();
- flushSync();
- expect(stage().classList.contains('solo')).toBe(false);
- expect(target.querySelector('.source-bar')).not.toBeNull();
+ });
+
+ it('reads a comparison saved with the old Difference mode as side by side with Difference on', async () => {
+ await open();
+ button('Open', target).click();
+ await settle();
+ button('Old difference', document.querySelector('[role="dialog"]')).click();
+ await settle();
+ expect(target.querySelector('.compare-stage').classList.contains('overlay')).toBe(false);
+ expect(button('Side by side', target).getAttribute('aria-pressed')).toBe('true');
+ expect(button('Difference', target).getAttribute('aria-pressed')).toBe('true');
});
it('discards edits back to the saved version, where New would start over', async () => {
diff --git a/frontend/src/tools/Compare.svelte b/frontend/src/tools/Compare.svelte
index 55509b4..514a11b 100644
--- a/frontend/src/tools/Compare.svelte
+++ b/frontend/src/tools/Compare.svelte
@@ -2,9 +2,9 @@
/**
* Two maps, one piece of ground.
*
- * Satellite explores one imagery view. Compare starts empty and lets the
- * analyst choose two views deliberately, then changes only how that pair is
- * read. The provider, Wayback release and Sentinel-2 day belong to each
+ * Satellite explores one imagery view. Compare opens on a key-less pair, a
+ * Wayback release a year back against today's World Imagery, and lets the
+ * analyst swap either side, then changes only how that pair is read. The provider, Wayback release and Sentinel-2 day belong to each
* MapSurface; the camera is the one shared fact.
*/
import { onMount, tick, untrack } from 'svelte';
@@ -24,12 +24,15 @@
import {
COMPARE_LAYERS,
COMPARE_MODES,
- FIND_MODES,
+ DIFFERENCE_KEY,
DEFAULT_DIVIDER,
DEFAULT_OPACITY,
comparisonLayers,
+ compareMode,
percentage,
+ DEFAULT_PRESET,
availablePresets,
+ COMPARE_PRESETS,
PROVIDER_KINDS,
providerKind,
} from '../lib/map/compare.js';
@@ -74,8 +77,9 @@
import { isRegistered, sourceRect } from '../lib/screenCrop.js';
import { deletedToast } from '../lib/trash.js';
import { assignFolder } from '../lib/filing.js';
- import { SENTINEL_ID } from '../lib/sentinel.js';
- import { WAYBACK_ID } from '../lib/wayback.js';
+ import { SENTINEL_ID, variantId } from '../lib/sentinel.js';
+ import { WAYBACK_ID, releaseYearBefore, waybackId } from '../lib/wayback.js';
+ import { RADAR_ID, radarId } from '../lib/radar.js';
import Icon from '../components/Icon.svelte';
import Compass from '../components/Compass.svelte';
import ConfirmDialog from '../components/ConfirmDialog.svelte';
@@ -84,14 +88,15 @@
import ModeDock from './compare/ModeDock.svelte';
import ModeControl from './compare/ModeControl.svelte';
import SourceCard from './compare/SourceCard.svelte';
- import ChangePanel from './compare/ChangePanel.svelte';
- import AnalyzerPanel from './compare/AnalyzerPanel.svelte';
- import AnalysisOverlay from './compare/AnalysisOverlay.svelte';
- import { zoneMarks, marksToZones, viewZone } from '../lib/map/analyzers.js';
- import './compare/compare.css';
+ import DifferenceBar from './compare/DifferenceBar.svelte';
+ import PassStrip from './compare/PassStrip.svelte';
+ import CopernicusNeeded from '../components/CopernicusNeeded.svelte';
+ import { copernicusNeed } from '../lib/copernicusSetup.js';
+ import { stripArchive } from '../lib/map/passStrip.js';
+ import './mapdock.css';
import { linkCameras } from '../lib/map/cameraLink.js';
import { detectCaptures } from '../lib/map/changeCapture.js';
- import { apply, cssMatrix, frameToFrame, fromMercator, screenToMercator } from '../lib/map/groundFrame.js';
+ import { apply, compassAngle, cssMatrix, frameToFrame, fromMercator, screenToMercator } from '../lib/map/groundFrame.js';
import MapSurface from './satellite/MapSurface.svelte';
import MapContextMenu from './satellite/MapContextMenu.svelte';
import PlaceDialog from './satellite/PlaceDialog.svelte';
@@ -105,6 +110,7 @@
import { createImageryState, FALLBACK_PROVIDER } from './satellite/state/imagery.svelte.js';
import { createSentinelState } from './satellite/state/sentinel.svelte.js';
import { createWaybackState } from './satellite/state/wayback.svelte.js';
+ import { createRadarState } from './satellite/state/radar.svelte.js';
const imagery = createImageryState({ api });
let home = $state(null);
@@ -142,7 +148,17 @@
let sessionDialog = $state(false);
let sessionBusy = $state(false);
let sessionList = $state([]);
- let discardTarget = $state(null); // { kind: 'new' | 'open' | 'revert' | 'pair', name?, pair? } | null
+ let discardTarget = $state(null); // { kind: 'new' | 'open' | 'revert' | 'pair', name?, pair?, preset? } | null
+ let newMenu = $state(false);
+ let newMenuEl = $state(null);
+ $effect(() => {
+ if (!newMenu) return;
+ const outside = (event) => {
+ if (newMenuEl && !newMenuEl.contains(event.target)) newMenu = false;
+ };
+ document.addEventListener('mousedown', outside, true);
+ return () => document.removeEventListener('mousedown', outside, true);
+ });
let annotations = $state([]);
let annotationTool = $state('select');
let selectedAnnotationId = $state(null);
@@ -159,100 +175,15 @@
let annotationRedo = $state([]);
let annotationPreviewBase = null;
let changeOptions = $state(changeSettings());
- let analyzerPanel = $state(null);
- let analyzerZones = $state([]);
- let analyzerDrawing = $state('select');
- let analyzerSelectedZone = $state(null);
- let analyzerLayers = $state([]);
- let analyzerAreasVisible = $state(true);
- let analyzerSingle = $state(false);
- let analyzerResult = $state(null);
- let analyzerOpening = $state(null);
- const analyzerMarks = $derived(zoneMarks(analyzerZones));
- const detecting = $derived(mode === 'analysis');
- /**
- * Detect draws over an undivided pair, whatever reading mode preceded it.
- * Difference over both images is the side-by-side layout with the same mask
- * laid on each: one question, two answers, rather than a hidden background.
- */
- const stageMode = $derived(
- mode === 'analysis' || (mode === 'change' && changeOptions.base === 'side') ? 'side' : mode
- );
- /** What an export composes. A difference is a difference however it is laid
- * out, so only Detect's borrowed layout is translated here. */
- const captureMode = $derived(mode === 'analysis' ? 'side' : mode);
- /**
- * A vessel or a hotspot is present on one date, so that analyzer reads one
- * image and the stage shows one map. Two identical maps would say the run
- * compares them, which is the kind of quiet untruth this tool cannot afford.
- */
- const soloStage = $derived(detecting && analyzerSingle);
- /** The surface actually on screen, which is what "the current view" means. */
- const primeEngine = $derived(soloStage ? (b.engine ?? a.engine) : (a.engine ?? b.engine));
-
- /**
- * Show, on the maps, the imagery a run would sweep.
- *
- * Outside Detect the source cards lead and the maps follow them. Inside it
- * that direction is wrong: a detection fetches its own tiles at a fixed grid,
- * so the pair on screen can quietly be imagery the run never reads, which is
- * what made the panel feel unmoored from the map under it. So Detect leads.
- * The source cards step aside while it is on, and this is how what is drawn
- * on stays what is measured.
- */
- /** Said once per absence: every date picked pushes sources again. */
- let sentinelMissingSaid = false;
- function applyAnalysisSources(next) {
- let missing = false;
- for (const [letter, target, sentinel] of [['a', a, s2a], ['b', b, s2b]]) {
- const source = next?.[letter];
- if (!source) continue;
- if (!imagery.find(source.provider)) {
- missing = true;
- continue;
- }
- target.providerId = source.provider;
- target.present = true;
- sentinel.layer = source.layer || sentinel.layer;
- sentinel.date = source.date || '';
- sentinel.setMaxcc(source.maxcc ?? 100);
- }
- if (missing && !sentinelMissingSaid) {
- toast('Copernicus Sentinel-2 is not configured, so the maps still show the previous imagery', 'warn', 6000);
- }
- sentinelMissingSaid = missing;
- invalidateChangeAssist();
- }
+ // Every dated picture of the point, when A and B show the same archive.
+ let stripOpen = $state(false);
+ // What Copernicus still lacks for a road the analyst asked for: `{ need, tool }`.
+ let copernicus = $state(null);
+ // Highlights laid over whichever view mode is on, never a layout of their own.
+ let difference = $state(false);
+ /** The surface the shared controls act on. */
+ const primeEngine = $derived(a.engine ?? b.engine);
- /** The camera as a rectangle to sweep: the one place the map decides what a
- * run covers, after which the area is fixed and the camera is free again. */
- function useCurrentView() {
- const bounds = primeEngine?.viewBounds?.();
- if (!bounds) return;
- analyzerZones = [...analyzerZones, viewZone(bounds, `Area ${analyzerZones.length + 1}`)];
- analyzerAreasVisible = true;
- analyzerDrawing = 'select';
- }
- function focusAnalysis([lon, lat], source) {
- const engine = primeEngine;
- if (engine) engine.setView({ lon, lat }, engine.getZoom());
- else if (source && imagery.find(source.provider)) {
- view = { lat, lon, zoom: 16 };
- applySide(a, s2a, wba, { present: true, provider: source.provider,
- sentinel: { date: source.date, layer: source.layer, maxcc: source.maxcc },
- wayback_release: source.release });
- } else toast('Choose an imagery source to show this area on the map', 'info');
- }
- function setAnalyzerMarks(marks) {
- analyzerZones = marksToZones(marks, analyzerZones);
- }
- $effect(() => {
- const requested = uiState.openAnalyzer;
- if (!requested) return;
- analyzerOpening = requested;
- uiState.openAnalyzer = null;
- mode = 'analysis';
- });
let changeBusy = $state(false);
let changeError = $state('');
let changeResult = $state(null);
@@ -260,8 +191,8 @@
/** One transform per surface: the mask is ground, and each map frames it. */
let changeTransform = $state({ a: '', b: '' });
let changeBlinkOn = $state(true);
- const changeVisible = $derived(changeOptions.visible && (!changeOptions.blink || changeBlinkOn));
- const changeBase = $derived(changeOptions.base);
+ 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);
const changeCounts = $derived(changeResult?.counts);
@@ -341,6 +272,20 @@
api,
place: () => ({ lat: view.lat, lon: view.lon, zoom: view.zoom }),
});
+ // Each radar side knows the other's pass, so its picker can mark the passes
+ // on the same track: only those compare like with like.
+ const s1a = createRadarState({
+ api,
+ place: () => ({ lat: view.lat, lon: view.lon }),
+ onBilled: () => imagery.refreshUsage(),
+ peer: () => (b.present && b.providerId === RADAR_ID ? s1b.pass : null),
+ });
+ const s1b = createRadarState({
+ api,
+ place: () => ({ lat: view.lat, lon: view.lon }),
+ onBilled: () => imagery.refreshUsage(),
+ peer: () => (a.present && a.providerId === RADAR_ID ? s1a.pass : null),
+ });
$effect(() => {
const caseId = caseState.current?.id;
@@ -351,10 +296,10 @@
const both = $derived(a.present && b.present);
const activeView = $derived(view);
const shownA = $derived(
- imagery.displayed(a.providerId, view.zoom, { ...s2a.variant, release: wba.release })
+ imagery.displayed(a.providerId, view.zoom, { ...s2a.variant, release: wba.release, pass: s1a.pass })
);
const shownB = $derived(
- imagery.displayed(b.providerId, view.zoom, { ...s2b.variant, release: wbb.release })
+ imagery.displayed(b.providerId, view.zoom, { ...s2b.variant, release: wbb.release, pass: s1b.pass })
);
const labelA = $derived(imagery.find(a.providerId)?.label ?? 'Imagery A');
const labelB = $derived(imagery.find(b.providerId)?.label ?? 'Imagery B');
@@ -362,9 +307,13 @@
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.
+ let pristineSignature = $state(null);
+ const discardable = $derived(sessionDirty && pairSignature() !== pristineSignature);
let firmsSensors = $state([]);
- function changeSide(target, sentinel, wayback, shown) {
+ function changeSide(target, sentinel, wayback, shown, radar) {
return {
present: target.present,
provider: shown.provider?.id ?? target.providerId,
@@ -379,22 +328,39 @@
maxcc: sentinel.maxcc,
},
waybackRelease: wayback.release,
+ radar: radarSpec(radar),
};
}
- const changeStatus = $derived(
- changeCompatibility(changeSide(a, s2a, wba, shownA), changeSide(b, s2b, wbb, shownB))
- );
+ /** A side's radar pass as a session keeps it. */
+ function radarSpec(radar) {
+ return { date: radar.pass?.date ?? '', time: radar.pass?.time ?? '' };
+ }
- /**
- * What Detect needs before a run can fetch anything: Sentinel-2, which only
- * lists once Copernicus credentials are in Settings. Not a lock — the panel
- * still opens on the areas and runs already saved — only said up front.
- */
- const detectStatus = $derived(
- imagery.providers.length && !imagery.find('sentinel2')
- ? { ok: false, reason: 'Detect reads Copernicus Sentinel-2: add your credentials in Settings → Imagery.' }
- : { ok: true, reason: '' }
+ const archive = $derived(stripArchive(sideSpec(a, s2a, wba, s1a), sideSpec(b, s2b, wbb, s1b)));
+ $effect(() => {
+ if (!archive) stripOpen = false;
+ });
+
+ /** Show one of the strip's pictures on a side. */
+ function assignFromStrip(letter, entry) {
+ const [target, sentinel, wayback, radar] = letter === 'a' ? [a, s2a, wba, s1a] : [b, s2b, wbb, s1b];
+ if (!target.present) return;
+ if (archive === RADAR_ID) radar.pick(entry);
+ else if (archive === WAYBACK_ID) wayback.pick(entry.release);
+ else sentinel.date = entry.date;
+ invalidateChangeAssist();
+ }
+
+ /** The provider id a strip picture is drawn from: B's layer, on that row's date. */
+ function stripVariant(entry) {
+ if (archive === RADAR_ID) return radarId(RADAR_ID, entry);
+ if (archive === WAYBACK_ID) return waybackId(WAYBACK_ID, entry.release);
+ return variantId(SENTINEL_ID, { layer: s2b.layer, from: entry.date, to: entry.date });
+ }
+
+ const changeStatus = $derived(
+ changeCompatibility(changeSide(a, s2a, wba, shownA, s1a), changeSide(b, s2b, wbb, shownB, s1b))
);
function openImagerySettings() {
@@ -428,6 +394,9 @@
home = { ...prefs.homeView };
view = { ...home };
await loadProviders();
+ if (gone) return;
+ // A handoff from the map brings its own pair.
+ if (!a.present && !b.present && !uiState.compareAt) void newComparison();
await loadFireCatalogue();
})();
return () => {
@@ -484,7 +453,7 @@
// the overlay can blink in place rather than the analyst toggling the eye.
const CHANGE_BLINK_MS = 620;
$effect(() => {
- if (!(mode === 'change' && changeOptions.blink && changeOptions.visible && changeUrl)) {
+ if (!(difference && changeOptions.blink && changeUrl)) {
changeBlinkOn = true;
return;
}
@@ -528,19 +497,38 @@
}
function swapSides() {
- const left = sideSpec(a, s2a, wba);
- const right = sideSpec(b, s2b, wbb);
- applySide(a, s2a, wba, right);
- applySide(b, s2b, wbb, left);
+ const left = sideSpec(a, s2a, wba, s1a);
+ const right = sideSpec(b, s2b, wbb, s1b);
+ applySide(a, s2a, wba, right, s1a);
+ applySide(b, s2b, wbb, left, s1b);
annotations = annotations.map((mark) => ({ ...mark, side: mark.side === 'a' ? 'b' : mark.side === 'b' ? 'a' : 'both' }));
invalidateChangeAssist();
}
- function startPreset(preset) {
- a.providerId = preset.a;
- b.providerId = preset.b;
- a.present = true;
- b.present = true;
+ let presetRequest = 0;
+
+ /**
+ * Put a preset's two views on the sides.
+ *
+ * A Wayback side opens a year back, so "then" is not today's mosaic twice.
+ * Without a release list it stays empty rather than showing B again.
+ */
+ async function applyPreset(preset) {
+ const request = ++presetRequest;
+ const sides = [[a, wba, preset.a], [b, wbb, preset.b]];
+ for (const [target, , id] of sides) {
+ target.providerId = id;
+ if (id !== WAYBACK_ID) target.present = true;
+ }
+ for (const [target, wayback, id] of sides) {
+ if (id !== WAYBACK_ID) continue;
+ const past = releaseYearBefore(await wayback.loadReleases());
+ if (request !== presetRequest) return;
+ if (past == null) continue;
+ wayback.pick(past);
+ target.present = true;
+ }
+ pristineSignature = pairSignature();
}
function visitZone(zone) {
@@ -551,6 +539,28 @@
activeEngine()?.setView({ lat, lon }, view.zoom);
}
+ /**
+ * The Copernicus roads a missing key or layer closes, offered anyway.
+ *
+ * Compare works without Copernicus, so nothing is said until one of them is
+ * asked for; then what it needs is said in the middle of the stage rather
+ * than the road quietly missing from the list.
+ */
+ const lockedPresets = $derived(imagery.providers.length
+ ? COMPARE_PRESETS.filter((preset) => ['sentinel2', 'sentinel1'].includes(preset.a)
+ && !availablePresets(imagery.providers).includes(preset))
+ : []);
+ const lockedArchives = $derived(imagery.providers.length
+ ? [['sentinel2', 'Sentinel-2 (Copernicus)'], ['sentinel1', 'Sentinel-1 radar (Copernicus)']]
+ .filter(([id]) => !imagery.find(id))
+ : []);
+
+ function askCopernicus(id, tool) {
+ picking = null;
+ newMenu = false;
+ copernicus = { need: copernicusNeed(imagery.providers, { radar: id === 'sentinel1' }), tool };
+ }
+
function chooseProvider(provider) {
if (!picking || provider.needs_key) return;
const target = side(picking);
@@ -572,6 +582,7 @@
target.firms = freshFirms();
target.night = freshNight();
mode = 'side';
+ difference = false;
}
// Compare owns the same Google-Earth style gesture as Satellite. Either map
@@ -600,8 +611,6 @@
// the browser has laid the new rectangles out, or tiles keep the old size.
$effect(() => {
mode;
- soloStage;
- stageMode;
a.present;
b.present;
void tick().then(() => {
@@ -654,8 +663,6 @@
let s2bPassTimer;
let s2aLatestTimer;
let s2bLatestTimer;
- let wbaChangesTimer;
- let wbbChangesTimer;
$effect(() => {
if (!a.present || !s2a.menuOpen || shownA.provider?.id !== SENTINEL_ID) return;
@@ -697,22 +704,6 @@
$effect(() => {
if (b.ready && shownB.provider?.id === WAYBACK_ID) wbb.loadReleases();
});
- // Once a side's picker has been opened, its history follows the map, picker
- // open or not: both surfaces share one view, so both walk the same tile.
- $effect(() => {
- if (!wba.watching || shownA.provider?.id !== WAYBACK_ID) return;
- wba.here;
- clearTimeout(wbaChangesTimer);
- wbaChangesTimer = setTimeout(() => wba.follow(), 900);
- return () => clearTimeout(wbaChangesTimer);
- });
- $effect(() => {
- if (!wbb.watching || shownB.provider?.id !== WAYBACK_ID) return;
- wbb.here;
- clearTimeout(wbbChangesTimer);
- wbbChangesTimer = setTimeout(() => wbb.follow(), 900);
- return () => clearTimeout(wbbChangesTimer);
- });
function activeEngine() {
return a.engine ?? b.engine;
@@ -766,19 +757,19 @@
}
function setMode(next) {
- if (next === 'change' && !changeStatus.ok) {
- toast(changeStatus.reason, 'warn', 6000);
- return;
- }
mode = next;
blinkPaused = false;
- // Leaving Detect must not leave the map armed to draw an area.
- if (next !== 'analysis') analyzerDrawing = 'select';
- if (next === 'change') {
- changeOptions.visible = true;
- if (!changeStatus.methods.includes(changeOptions.method)) changeOptions.method = changeStatus.methods[0];
- void refreshChangeAssist({ fetch: false });
+ }
+
+ function setDifference(on) {
+ if (on && !changeStatus.ok) {
+ toast(changeStatus.reason, 'warn', 6000);
+ return;
}
+ difference = on;
+ if (!on) return;
+ if (!changeStatus.methods.includes(changeOptions.method)) changeOptions.method = changeStatus.methods[0];
+ void refreshChangeAssist({ fetch: false });
}
function setDividerAt(clientX) {
@@ -811,7 +802,7 @@
event.preventDefault();
}
- function sideSpec(target, sentinel, wayback) {
+ function sideSpec(target, sentinel, wayback, radar) {
return {
present: target.present,
provider: target.providerId,
@@ -822,10 +813,11 @@
layer: sentinel.layer,
// A difference is only honest over named acquisitions. Freeze a live
// "latest" pass to the date it meant when this workspace is saved.
- date: mode === 'change' ? sentinel.date || sentinel.latest : sentinel.date,
+ date: difference ? sentinel.date || sentinel.latest : sentinel.date,
maxcc: sentinel.maxcc,
},
wayback_release: wayback.release,
+ radar: radarSpec(radar),
};
}
@@ -833,17 +825,16 @@
return {
version: 2,
camera: { lat: view.lat, lon: view.lon, zoom: view.zoom, bearing },
- // Detect is a place to work, not a way to read the pair: a comparison
- // reopened from My work shows the imagery, and its runs live in the case.
- mode: mode === 'analysis' ? 'side' : mode,
+ mode,
+ difference,
divider,
opacity,
blink: { interval: blinkInterval },
change_assist: changeSettings(changeOptions),
annotations: comparisonAnnotations(annotations),
frame: exportFrame,
- a: sideSpec(a, s2a, wba),
- b: sideSpec(b, s2b, wbb),
+ a: sideSpec(a, s2a, wba, s1a),
+ b: sideSpec(b, s2b, wbb, s1b),
};
}
@@ -851,6 +842,11 @@
return JSON.stringify([sessionName.trim(), sessionSpec()]);
}
+ function pairSignature() {
+ const { camera, ...pair } = sessionSpec();
+ return JSON.stringify([sessionName.trim(), pair]);
+ }
+
function requestSaveSession() {
if (!both) return;
if (openedSession) void performSessionSave();
@@ -872,6 +868,7 @@
if (caseState.current?.id !== owner.id) return;
sessionName = result.title;
openedSession = { name: result.name, title: result.title };
+ pristineSignature = null;
savedSignature = JSON.stringify([result.title, savedSpec]);
saveDialog = false;
let previewError = null;
@@ -909,7 +906,7 @@
}
}
- function applySide(target, sentinel, wayback, saved) {
+ function applySide(target, sentinel, wayback, saved, radar) {
const provider = imagery.find(saved?.provider) ? saved.provider : FALLBACK_PROVIDER;
if (saved?.provider && provider !== saved.provider) {
toast(`${saved.provider} is unavailable. Using ${imagery.find(provider)?.label ?? provider}`, 'warn');
@@ -928,6 +925,7 @@
sentinel.date = saved?.sentinel?.date || '';
sentinel.setMaxcc(saved?.sentinel?.maxcc ?? 100);
wayback.pick(saved?.wayback_release ?? null);
+ radar.pick(saved?.radar?.date ? saved.radar : null);
target.present = Boolean(saved?.present);
target.refused = false;
}
@@ -937,6 +935,8 @@
const caseId = caseState.current.id;
sessionBusy = true;
sessionDialog = false;
+ presetRequest++;
+ pristineSignature = null;
try {
const saved = await api.get(
`/api/cases/${caseId}/compare/sessions/${encodeURIComponent(name)}`
@@ -949,7 +949,9 @@
zoom: spec.camera.zoom,
};
bearing = spec.camera?.bearing ?? 0;
- mode = COMPARE_MODES.some((entry) => entry.id === spec.mode) ? spec.mode : 'side';
+ 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';
divider = percentage(spec.divider, DEFAULT_DIVIDER);
opacity = percentage(spec.opacity, DEFAULT_OPACITY);
changeOptions = changeSettings(spec.change_assist);
@@ -957,8 +959,8 @@
annotations = comparisonAnnotations(spec.annotations);
exportFrame = exportFrameSpec(spec.frame);
resetAnnotationHistory();
- applySide(a, s2a, wba, spec.a);
- applySide(b, s2b, wbb, spec.b);
+ applySide(a, s2a, wba, spec.a, s1a);
+ applySide(b, s2b, wbb, spec.b, s1b);
sessionName = saved.title || name;
openedSession = { name, title: sessionName };
await tick();
@@ -972,7 +974,7 @@
a.engine?.resize();
b.engine?.resize();
savedSignature = sessionSignature();
- if (mode === 'change') void refreshChangeAssist({ fetch: false });
+ if (difference) void refreshChangeAssist({ fetch: false });
toast(`Opened ${sessionName}`, 'ok');
} catch (error) {
toast(`Could not open the comparison: ${error.message}`, 'danger');
@@ -989,13 +991,16 @@
* unsaved and unnamed: nothing was filed, the analyst is being shown a pair.
*/
async function openPair(pair) {
+ presetRequest++;
+ pristineSignature = null;
view = { lat: pair.lat, lon: pair.lon, zoom: pair.zoom ?? view.zoom };
bearing = 0;
mode = 'side';
+ difference = false;
annotations = comparisonAnnotations(null);
resetAnnotationHistory();
- applySide(a, s2a, wba, pair.a);
- applySide(b, s2b, wbb, pair.b);
+ applySide(a, s2a, wba, pair.a, s1a);
+ applySide(b, s2b, wbb, pair.b, s1b);
sessionName = pair.title ?? 'Comparison';
openedSession = null;
savedSignature = null;
@@ -1012,7 +1017,7 @@
if (uiState.tool !== 'compare' || !uiState.compareAt || !imagery.providers.length) return;
const pair = uiState.compareAt;
uiState.compareAt = null;
- if (sessionDirty) {
+ if (discardable) {
discardTarget = { kind: 'pair', pair };
return;
}
@@ -1020,7 +1025,7 @@
});
function requestOpenSession(name) {
- if (sessionDirty) {
+ if (discardable) {
discardTarget = { kind: 'open', name };
return;
}
@@ -1048,7 +1053,10 @@
}
}
- function newComparison() {
+ /** Start over on a preset, the default one unless another is named. */
+ function newComparison(preset = availablePresets(imagery.providers).find((entry) => entry.id === DEFAULT_PRESET)) {
+ presetRequest++;
+ pristineSignature = null;
a.present = false;
b.present = false;
a.overlays = [];
@@ -1058,6 +1066,7 @@
a.night = freshNight();
b.night = freshNight();
mode = 'side';
+ difference = false;
divider = DEFAULT_DIVIDER;
opacity = DEFAULT_OPACITY;
changeOptions = changeSettings();
@@ -1065,12 +1074,6 @@
changeResult = null;
changeUrl = '';
changeRequest++;
- // Detect's areas and result layers belong to the comparison that drew them.
- analyzerZones = [];
- analyzerLayers = [];
- analyzerSelectedZone = null;
- analyzerDrawing = 'select';
- analyzerOpening = null;
annotations = [];
annotationTool = 'select';
resetAnnotationHistory();
@@ -1081,23 +1084,26 @@
openedSession = null;
savedSignature = null;
rightPanel = null;
+ if (preset) return applyPreset(preset);
}
- function requestNewComparison() {
- if (sessionDirty) {
- discardTarget = { kind: 'new' };
+ function requestNewComparison(preset) {
+ newMenu = false;
+ if (discardable) {
+ discardTarget = { kind: 'new', preset };
return;
}
- newComparison();
+ newComparison(preset);
}
/**
* 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 empty. New
- * always wipes, which is why it is not an answer to "undo what I just did".
+ * 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".
*/
function requestDiscardChanges() {
- if (!sessionDirty || sessionBusy) return;
+ if (!discardable || sessionBusy) return;
discardTarget = openedSession
? { kind: 'revert', name: openedSession.name }
: { kind: 'new' };
@@ -1106,7 +1112,7 @@
function confirmDiscard() {
const target = discardTarget;
discardTarget = null;
- if (target?.kind === 'new') newComparison();
+ if (target?.kind === 'new') newComparison(target.preset);
else if (target?.kind === 'pair') void openPair(target.pair);
else if (target) void openSession(target.name);
}
@@ -1154,10 +1160,10 @@
const changeFrames = $derived(changeNeedsFrames(changeSettings(changeOptions), changeStatus));
function changeKey() {
- const { opacity, base, visible, blink, zones, ...analysis } = changeSettings(changeOptions);
+ const { opacity, base, blink, zones, ...analysis } = changeSettings(changeOptions);
return JSON.stringify([
- changeSide(a, s2a, wba, shownA),
- changeSide(b, s2b, wbb, shownB),
+ changeSide(a, s2a, wba, shownA, s1a),
+ changeSide(b, s2b, wbb, shownB, s1b),
view,
bearing,
analysis,
@@ -1166,7 +1172,7 @@
function invalidateChangeAssist() {
changeRenderedKey = '';
- if (mode !== 'change') return;
+ 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.
clearTimeout(changeTimer);
@@ -1174,12 +1180,12 @@
}
async function refreshChangeAssist({ fetch = true } = {}) {
- if (mode !== 'change' || !changeStatus.ok) return;
+ 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;
const settings = changeSettings(changeOptions);
- const sides = [changeSide(a, s2a, wba, shownA), changeSide(b, s2b, wbb, shownB)];
+ const sides = [changeSide(a, s2a, wba, shownA, s1a), changeSide(b, s2b, wbb, shownB, s1b)];
const request = ++changeRequest;
changeBusy = true;
changeError = '';
@@ -1190,7 +1196,7 @@
const sources = await sourceCanvases();
if (request !== changeRequest || key !== changeKey()) return;
const result = await detectCaptures(sources, settings, sides, changeStatus, fetch);
- if (request !== changeRequest || mode !== 'change' || key !== changeKey()) return;
+ 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;
@@ -1209,7 +1215,7 @@
}
$effect(() => {
- if (mode !== 'change' || uiState.tool !== 'compare') { changeRequest++; return; }
+ if (!difference || uiState.tool !== 'compare') { changeRequest++; return; }
if (!changeStatus.ok) {
changeRequest += 1;
changeResult = null;
@@ -1346,6 +1352,7 @@
if (!event.ctrlKey && !event.metaKey && !event.altKey) {
const reading = COMPARE_MODES.find((entry) => entry.key === key);
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 ((event.ctrlKey || event.metaKey) && key === 'z') {
@@ -1385,7 +1392,7 @@
let canvasA = $state(null);
let canvasB = $state(null);
const pointActions = $derived(
- actionsFor(both && !detecting ? ['lookup', 'place', 'measure'] : ['lookup', 'place'])
+ actionsFor(both ? ['lookup', 'place', 'measure'] : ['lookup', 'place'])
);
function onMapContextMenu(side, at) {
@@ -1591,7 +1598,7 @@
/** The frame stated as the ground it covers, which no camera can change. */
function frameLabel(value) {
- const span = frameSpan(value.points, bearing);
+ const span = frameSpan(value.points, value.angle ?? 0);
return `${formatDistance(span.width, prefs.units)} × ${formatDistance(span.height, prefs.units)}`;
}
@@ -1620,7 +1627,7 @@
function compose(
sources,
- { renderMode = captureMode, renderBlinkB = blinkB, renderChangeMap = changeResult } = {}
+ { renderMode = mode, renderBlinkB = blinkB, renderChangeMap = null } = {}
) {
const provenanceA = a.surface?.provenance?.() ?? {};
const provenanceB = b.surface?.provenance?.() ?? {};
@@ -1641,30 +1648,40 @@
attributionA: shownA.provider?.attribution,
attributionB: shownB.provider?.attribution,
view,
- bearing,
+ // A framed export comes out upright at the bearing its frame was drawn at.
+ // A frame counts the compass direction that is up; the app counts the
+ // map's clockwise turn, the same angle the other way.
+ bearing: compassAngle(-sources.a.frame.bearing),
});
}
- async function comparisonBlob() {
- if (mode === 'change' && !changeStatus.ok) throw new Error(changeStatus.reason);
- if (mode === 'change' && (changeRenderedKey !== changeKey() || !changeResult)) {
+ /** The difference an export carries: none when it is off, this view's when on. */
+ async function exportedChange() {
+ if (!difference) return null;
+ if (!changeStatus.ok) throw new Error(changeStatus.reason);
+ if (changeRenderedKey !== changeKey() || !changeResult) {
clearTimeout(changeTimer);
await refreshChangeAssist({ fetch: changeFrames !== '' });
}
- const sources = await exportSources();
- if (mode === 'change' && (changeRenderedKey !== changeKey() || !changeResult)) {
- throw new Error('Run Difference for this view before exporting');
+ if (changeRenderedKey !== changeKey() || !changeResult) {
+ throw new Error('Read the difference for this view before exporting');
}
- const renderChangeMap = mode === 'change' ? changeResult : null;
+ return changeResult;
+ }
+
+ async function comparisonBlob() {
+ const renderChangeMap = await exportedChange();
+ const sources = await exportSources();
return canvasBlob(compose(sources, { renderChangeMap }));
}
async function saveWorkingPreview(caseId, name) {
const form = new FormData();
if (mode === 'blink') {
+ const renderChangeMap = await exportedChange();
const sources = await exportSources();
- const frameA = await canvasBlob(compose(sources, { renderMode: 'blink', renderBlinkB: false }));
- const frameB = await canvasBlob(compose(sources, { renderMode: 'blink', renderBlinkB: true }));
+ const frameA = await canvasBlob(compose(sources, { renderMode: 'blink', renderBlinkB: false, renderChangeMap }));
+ const frameB = await canvasBlob(compose(sources, { renderMode: 'blink', renderBlinkB: true, renderChangeMap }));
form.append('image_a', frameA, 'comparison-a.png');
form.append('image_b', frameB, 'comparison-b.png');
form.append('format', 'blink');
@@ -1719,9 +1736,10 @@
outputBusy = 'gif';
try {
const owner = await ensureCase();
+ const renderChangeMap = await exportedChange();
const sources = await exportSources();
- const frameA = await canvasBlob(compose(sources, { renderMode: 'blink', renderBlinkB: false }));
- const frameB = await canvasBlob(compose(sources, { renderMode: 'blink', renderBlinkB: true }));
+ const frameA = await canvasBlob(compose(sources, { renderMode: 'blink', renderBlinkB: false, renderChangeMap }));
+ const frameB = await canvasBlob(compose(sources, { renderMode: 'blink', renderBlinkB: true, renderChangeMap }));
const form = new FormData();
form.append('image_a', frameA, 'comparison-a.png');
form.append('image_b', frameB, 'comparison-b.png');
@@ -1784,7 +1802,7 @@
aria-label="Comparison name"
onkeydown={(event) => event.key === 'Enter' && requestSaveSession()}
/>
- {#if sessionDirty}<span class="badge">unsaved</span>{/if}
+ {#if discardable}<span class="badge">unsaved</span>{/if}
{:else}
<span class="sub">Two imagery views, one shared camera</span>
{/if}
@@ -1808,14 +1826,31 @@
<button
class="btn btn-sm"
onclick={requestDiscardChanges}
- disabled={!sessionDirty || sessionBusy}
+ disabled={!discardable || sessionBusy}
title={openedSession ? 'Go back to the saved version' : 'Throw this comparison away'}
>
<Icon name="undo" size={13} /> Discard
</button>
- <button class="btn btn-sm" onclick={requestNewComparison} title="Start a new comparison">
- <Icon name="plus" size={13} /> New
- </button>
+ <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">
+ <Icon name="plus" size={13} /> New <Icon name="chevronDown" size={11} />
+ </button>
+ {#if newMenu}
+ <div class="new-menu card" role="menu">
+ {#each availablePresets(imagery.providers) as preset}
+ <button class="new-row" role="menuitem" onclick={() => requestNewComparison(preset)}>
+ <strong>{preset.label}</strong><span>{preset.hint}</span>
+ </button>
+ {/each}
+ {#each lockedPresets as preset (preset.id)}
+ <button class="new-row locked" role="menuitem" onclick={() => askCopernicus(preset.a, preset.label)}>
+ <strong>{preset.label} <small>set up</small></strong><span>Needs a free Copernicus setup</span>
+ </button>
+ {/each}
+ </div>
+ {/if}
+ </div>
{/if}
<button
class="btn btn-primary btn-sm"
@@ -1829,7 +1864,14 @@
{#if both}
<div class="compare-bar">
- <ModeDock {mode} change={changeStatus} detect={detectStatus} onmode={setMode} onswap={swapSides} />
+ <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, and when a change appeared'
+ : '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. -->
@@ -1842,12 +1884,16 @@
{#if !a.present && !b.present}
<div class="presets">
{#each availablePresets(imagery.providers) as preset}
- <button class="btn btn-sm" title={preset.hint} onclick={() => startPreset(preset)}>{preset.label}</button>
+ <button class="btn btn-sm" title={preset.hint} onclick={() => applyPreset(preset)}>{preset.label}</button>
+ {/each}
+ {#each lockedPresets as preset (preset.id)}
+ <button class="btn btn-sm locked" title={`${preset.hint}. Needs a free Copernicus setup`}
+ onclick={() => askCopernicus(preset.a, preset.label)}>{preset.label} <small>set up</small></button>
{/each}
</div>
{/if}
<div class="compare-workspace">
- {#if both && !detecting}
+ {#if both}
<AnnotationToolbar
bind:tool={annotationTool}
selected={editableAnnotation}
@@ -1878,21 +1924,18 @@
{/if}
<!-- The cards ride over the stage, not over the tool: the annotation rail on
- the left and a computing panel on the right both narrow the stage, and a
- full-width bar put the seam between the cards tens of pixels away from
- the seam between the maps.
- Detect owns the imagery while it is on, so the cards would be a second
- place to choose the same thing. One choice, one place. -->
+ 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) && !detecting}
+ {#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}
+ <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}
+ <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}
@@ -1900,13 +1943,9 @@
{/if}
<div
class="compare-stage"
- class:overlay={both && stageMode !== 'side'}
- class:swipe={both && stageMode === 'swipe'}
- class:blended={both && stageMode === 'opacity'}
- class:change={both && stageMode === 'change'}
- class:base-a={both && stageMode === 'change' && changeBase === 'a'}
- class:base-b={both && stageMode === 'change' && changeBase === 'b'}
- class:solo={soloStage}
+ class:overlay={both && mode !== 'side'}
+ class:swipe={both && mode === 'swipe'}
+ class:blended={both && mode === 'opacity'}
class:capturing={grabbing}
class:capture-a={captureSide === 'a'}
class:capture-b={captureSide === 'b'}
@@ -1931,6 +1970,7 @@
{imagery}
s2={s2a}
wayback={wba}
+ s1={s1a}
{home}
resetToHome={false}
imperial={prefs.units === 'imperial'}
@@ -1973,35 +2013,23 @@
</MapSurface>
<!-- 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 && mode === 'change' && changeUrl && changeVisible}
+ {#if both && difference && changeOver('a') && changeUrl && changeVisible}
<img class="change-map" 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}
<!-- Side by side has two coordinate spaces, so A owns the editable
frame and B shows the matching ground read-only. -->
- {#if both && !grabbing && !detecting && stageMode === 'side' && (framing || exportFrame)}
+ {#if both && !grabbing && mode === 'side' && (framing || exportFrame)}
<ExportFrame engine={a.engine} frame={exportFrame} drawing={framing} units={prefs.units} {bearing}
onframe={setExportFrame} oncancel={finishFraming} />
{/if}
- {#if both && !grabbing && !detecting}
+ {#if both && !grabbing}
<AnnotationCanvas bind:this={canvasA} {annotations} engine={a.engine} letter="a" units={prefs.units}
active={uiState.tool === 'compare'} bind:tool={annotationTool} bind:selectedId={selectedAnnotationId}
colour={annotationColour} strokeWidth={annotationStroke} fillOpacity={annotationFill}
glyph={annotationGlyph} stampSize={annotationStampSize}
- editVertices={true} {annotationSide} onchange={setAnnotations} />
- {/if}
- <!-- Detect's own drawing stays in Detect: areas and candidates belong
- to the column that explains them, and the reading modes stay clean
- pictures. A kept candidate is a pin, and pins are shown by Saved. -->
- {#if detecting && !grabbing && analyzerLayers.some((layer) => layer.visible)}
- <AnalysisOverlay engine={a.engine} layers={analyzerLayers} selected={analyzerResult}
- onpick={(run, result) => analyzerPanel?.pick(run, result)} />
- {/if}
- {#if detecting && !grabbing && analyzerAreasVisible}
- <AnnotationCanvas annotations={analyzerMarks} engine={a.engine} letter="a" editVertices={true} edgeOnly={true}
- bind:tool={analyzerDrawing} bind:selectedId={analyzerSelectedZone} colour="#38bdf8"
- fillOpacity={0.08} onchange={setAnalyzerMarks} />
+ editVertices={true} {annotationSide} {bearing} turnable={true} onchange={setAnnotations} />
{/if}
{#if rotating?.which === 'a'}
<div class="rotate-pivot" style:left={`${rotating.x}px`} style:top={`${rotating.y}px`} aria-hidden="true"></div>
@@ -2035,6 +2063,7 @@
{imagery}
s2={s2b}
wayback={wbb}
+ s1={s1b}
{home}
resetToHome={false}
imperial={prefs.units === 'imperial'}
@@ -2075,29 +2104,20 @@
/>
{/if}
</MapSurface>
- {#if both && mode === 'change' && changeUrl && changeVisible}
+ {#if both && difference && changeOver('b') && changeUrl && changeVisible}
<img class="change-map" 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}
- {#if both && !grabbing && !detecting && stageMode === 'side' && exportFrame}
+ {#if both && !grabbing && mode === 'side' && exportFrame}
<ExportFrame engine={b.engine} frame={exportFrame} readonly={true} units={prefs.units} {bearing} />
{/if}
- {#if both && !grabbing && !detecting}
+ {#if both && !grabbing}
<AnnotationCanvas bind:this={canvasB} {annotations} engine={b.engine} letter="b" units={prefs.units}
active={uiState.tool === 'compare'} bind:tool={annotationTool} bind:selectedId={selectedAnnotationId}
colour={annotationColour} strokeWidth={annotationStroke} fillOpacity={annotationFill}
glyph={annotationGlyph} stampSize={annotationStampSize}
- editVertices={true} {annotationSide} onchange={setAnnotations} />
- {/if}
- {#if detecting && !grabbing && analyzerLayers.some((layer) => layer.visible)}
- <AnalysisOverlay engine={b.engine} layers={analyzerLayers} selected={analyzerResult}
- onpick={(run, result) => analyzerPanel?.pick(run, result)} />
- {/if}
- {#if detecting && !grabbing && analyzerAreasVisible}
- <AnnotationCanvas annotations={analyzerMarks} engine={b.engine} letter="b" editVertices={true} edgeOnly={true}
- bind:tool={analyzerDrawing} bind:selectedId={analyzerSelectedZone} colour="#38bdf8"
- fillOpacity={0.08} onchange={setAnalyzerMarks} />
+ editVertices={true} {annotationSide} {bearing} turnable={true} onchange={setAnnotations} />
{/if}
{#if rotating?.which === 'b'}
<div class="rotate-pivot" style:left={`${rotating.x}px`} style:top={`${rotating.y}px`} aria-hidden="true"></div>
@@ -2136,50 +2156,49 @@
</button>
{/if}
- <!-- Fade, Swipe, Blink and the single-image Difference layouts stack both
- maps in one coordinate space. Their frame therefore sits above the
+ <!-- Fade, Swipe and Blink stack both maps in one coordinate space. Their frame therefore sits above the
complete stage, where neither B nor the swipe clip can block it. -->
- {#if both && !grabbing && !detecting && stageMode !== 'side' && (framing || exportFrame)}
+ {#if both && !grabbing && mode !== 'side' && (framing || exportFrame)}
<ExportFrame engine={a.engine} frame={exportFrame} drawing={framing} units={prefs.units} {bearing}
onframe={setExportFrame} oncancel={finishFraming} />
{/if}
- {#if both && mode === 'change'}
- <div class="change-legend" class:colourblind={changePalette === 'colourblind'} class:hidden={!changeOptions.visible}>
+ {#if copernicus}
+ <div class="need-over">
+ <CopernicusNeeded need={copernicus.need || 'account'} tool={copernicus.tool}
+ onclose={() => (copernicus = null)} />
+ </div>
+ {/if}
+
+ {#if both && difference}
+ <div class="change-legend" class:colourblind={changePalette === 'colourblind'}>
<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>Analysing…</em>{:else if changeError}<em>{changeError}</em>{:else if changeCounts}<em>{changeShare(changeCounts)}% highlighted</em>{/if}
+ {#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}
</div>
{/if}
</div>
+ {#if both && stripOpen && archive}
+ <PassStrip {archive} a={sideSpec(a, s2a, wba, s1a)} b={sideSpec(b, s2b, wbb, s1b)} {view}
+ viewWidth={a.element?.clientWidth ?? 1000} provider={imagery.find(archive)} maxcc={s2b.maxcc}
+ variantFor={stripVariant} onassign={assignFromStrip} onbilled={() => imagery.refreshUsage()}
+ onclose={() => (stripOpen = false)} />
+ {/if}
</div>
- <!-- The two computing modes share this column, so where their settings live
- never depends on which one is on: the stage narrows, the maps stay whole
- and clickable, and the mode dock above is the only switch between them. -->
- {#if both && mode === 'change'}
- <ChangePanel bind:settings={changeOptions} status={changeStatus} result={changeResult}
- busy={changeBusy} error={changeError}
- stale={!!changeResult && changeRenderedKey !== detectionKey}
- onrun={() => refreshChangeAssist()} onzone={visitZone} onclose={() => setMode('side')} />
- {/if}
- {#if both && detecting}
- <AnalyzerPanel bind:this={analyzerPanel} caseId={caseState.current?.id}
- sources={{ a: sideSpec(a, s2a, wba), b: sideSpec(b, s2b, wbb) }}
- bind:zones={analyzerZones} bind:drawing={analyzerDrawing} bind:selectedZone={analyzerSelectedZone}
- bind:layers={analyzerLayers} bind:showZones={analyzerAreasVisible}
- bind:singleImage={analyzerSingle} bind:selectedResult={analyzerResult}
- opening={analyzerOpening} onfocus={focusAnalysis} onusecurrentview={useCurrentView}
- needs={detectStatus.reason} onsettings={openImagerySettings}
- onsources={applyAnalysisSources} onclose={() => setMode('side')} />
- {/if}
</div>
- {#if both && !FIND_MODES.includes(mode) && mode !== 'side'}
+ {#if both && (mode !== 'side' || difference)}
<div class="mode-footer">
<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}
+ onrun={() => refreshChangeAssist()} onzone={visitZone} />
+ {/if}
</div>
{/if}
{#if rightPanel === 'export'}
@@ -2312,6 +2331,18 @@
</span>
</button>
{/each}
+ {#if kind.id === 'archive'}
+ {#each lockedArchives as [id, label] (id)}
+ <button class="provider-card locked" onclick={() => askCopernicus(id, label)}
+ title="Free, from a Copernicus account">
+ <Icon name="satellite" size={18} />
+ <span class="provider-copy">
+ <strong>{label}</strong>
+ <small>{id === 'sentinel1' && imagery.find('sentinel2') ? 'Needs its layer' : 'Needs a free key'}</small>
+ </span>
+ </button>
+ {/each}
+ {/if}
</div>
{/if}
{/each}
@@ -2427,8 +2458,46 @@
.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); }
.camera-readout { color: var(--text-3); font-size: var(--fs-xs); }
- .mode-footer { display: flex; justify-content: center; padding: 6px; background: var(--bg-1); }
+ /* 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); }
.presets { display: flex; justify-content: center; gap: 8px; padding: 8px; }
+ .locked small { color: var(--accent); }
+ .provider-card.locked { opacity: 0.8; }
+ .need-over {
+ position: absolute;
+ inset: 0;
+ z-index: 700;
+ display: grid;
+ place-items: center;
+ padding: 16px;
+ background: rgb(0 0 0 / 0.4);
+ }
+ .new-wrap { position: relative; display: flex; }
+ .new-menu {
+ position: absolute;
+ top: calc(100% + 6px);
+ right: 0;
+ z-index: 800;
+ display: flex;
+ flex-direction: column;
+ width: 260px;
+ padding: 4px;
+ background: var(--bg-1);
+ box-shadow: var(--shadow-2);
+ }
+ .new-row {
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+ padding: 6px 8px;
+ border-radius: var(--r-sm);
+ text-align: left;
+ cursor: pointer;
+ }
+ .new-row:hover { background: var(--bg-3); }
+ .new-row strong { font-size: var(--fs-sm); color: var(--text-1); font-weight: 600; }
+ .new-row span { font-size: var(--fs-xs); color: var(--text-3); }
.compare-workspace { display: flex; min-height: 0; flex: 1; }
/* The cards and the maps they describe share one width, so the split between
A and B is one line down the whole tool. */
@@ -2442,6 +2511,9 @@
padding: 1px;
background: var(--border-strong);
overflow: hidden;
+ /* The map panes, highlights and legend climb to z-index 800 among
+ themselves; isolating them keeps that ladder from reaching the footer. */
+ isolation: isolate;
}
.surface-shell, .empty-slot {
position: relative;
@@ -2497,17 +2569,11 @@
.compare-stage.overlay .primary { z-index: 1; }
.compare-stage.overlay .secondary { z-index: 2; }
.compare-stage.overlay .surface-label { display: none; }
- /* Detect with a one-date analyzer: one map, and no letter to disambiguate. */
- .compare-stage.solo .primary { display: none; }
- .compare-stage.solo .secondary { flex: 1 1 100%; }
- .compare-stage.solo .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),
.compare-stage.blended .secondary :global(.map-glass) { opacity: var(--opacity); }
.compare-stage.overlay .secondary.blink-hidden { opacity: 0; pointer-events: none; }
- .compare-stage.change.base-a .secondary { opacity: 0; pointer-events: none; }
- .compare-stage.change.base-b .secondary { opacity: 1; }
.change-map {
position: absolute;
z-index: 545;
@@ -2536,7 +2602,6 @@
font-size: 10px;
backdrop-filter: blur(6px);
}
- .change-legend.hidden { opacity: .58; }
.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); }
@@ -2545,6 +2610,7 @@
.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 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,
.compare-stage.capturing .swipe-line { visibility: hidden; }
diff --git a/frontend/src/tools/Detect.render.test.js b/frontend/src/tools/Detect.render.test.js
new file mode 100644
index 0000000..5aac74b
--- /dev/null
+++ b/frontend/src/tools/Detect.render.test.js
@@ -0,0 +1,245 @@
+// @vitest-environment happy-dom
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { flushSync, mount, unmount } from 'svelte';
+
+const ANALYZERS = {
+ builtins: [{
+ id: 'boats', name: 'Vessels', description: 'Brighter than the water around it',
+ phenomenon: 'Vessel candidate', method: 'vessels', colour: '#38bdf8', style: 'both',
+ parameters: { sensitivity: 70, min_area: 250, max_area: 150000, cleanup: 0, smoothing: 0,
+ merge_metres: 50, index: 'ndvi', direction: 'both', ignore_clouds: true, ignore_shadows: true,
+ cloud_margin: 5 },
+ }],
+ custom: [],
+ methods: [{ id: 'vessels', label: 'Vessels: infrared contrast over water', single: true, clouds: true,
+ sizes: { medium: { min_area: 250, max_area: 150000, cleanup: 0, smoothing: 0, merge_metres: 50 } },
+ measure: '{value}× brighter than the water around it' }],
+ max_tiles: 4096, max_results: 2000, grid: [13, 512],
+};
+const PROVIDERS = [{ id: 'esri-world-imagery', label: 'Esri World Imagery', kind: 'tiles' },
+ { id: 'osm', label: 'OpenStreetMap', kind: 'tiles' }, { id: 'sentinel2', label: 'Copernicus Sentinel-2', kind: 'tiles' }];
+const WATCH = 'abcdef123456';
+const area = [{ id: 'z1', name: 'Anchorage', kind: 'rect', points: [[42.9, 14.84], [42.97, 14.78]] }];
+
+const get = vi.fn(async (path) => {
+ if (path === '/api/compare/analyzers') return structuredClone(ANALYZERS);
+ if (path === '/api/satellite/providers') return PROVIDERS;
+ if (path === '/api/cases/case-a/analysis/areas') return [{ id: '111111111111', name: 'Anchorage', colour: '#123456',
+ geometry: { type: 'Polygon', coordinates: [[[42.9, 14.84], [42.97, 14.84], [42.97, 14.78], [42.9, 14.78], [42.9, 14.84]]] } }];
+ if (path === '/api/cases/case-a/analysis/followups') {
+ return [{ id: WATCH, title: 'Hodeidah anchorage', created_at: '2026-09-01T00:00:00Z', analyzer: 'Vessels',
+ method: 'vessels', colour: '#38bdf8', areas: 1, zones: area, date_rule: 'latest_previous', note: '' }];
+ }
+ if (path === `/api/cases/case-a/analysis/followups/${WATCH}`) {
+ return { id: WATCH, title: 'Hodeidah anchorage', note: '', zones: area,
+ recipe: structuredClone(ANALYZERS.builtins[0]), a: { provider: 'sentinel2', date: '2026-09-01' },
+ b: { provider: 'sentinel2', date: '' }, offline: false, date_rule: 'latest_previous', followup_id: null };
+ }
+ if (path.startsWith('/api/cases/case-a/analysis/')) return [];
+ if (path.startsWith('/api/settings')) return { usage: {}, month: '2026-09' };
+ return {};
+});
+const post = vi.fn(async () => ({}));
+const put = vi.fn(async () => ({}));
+vi.mock('../lib/api.js', () => ({ api: { get, post, put, patch: vi.fn(), del: vi.fn() } }));
+
+const toast = vi.fn();
+const caseState = { current: { id: 'case-a' }, rev: 0 };
+const prefs = { homeView: { lat: 14.8, lon: 42.95, zoom: 12 }, units: 'metric', coordFormat: 'dd', detectView: undefined };
+const { uiState } = await import('./detect/uistate.fixture.svelte.js');
+vi.mock('../lib/state.svelte.js', () => ({
+ api: {},
+ caseState,
+ uiState,
+ toast,
+ ensureCase: vi.fn(async () => ({ id: 'case-a' })),
+ reloadCase: vi.fn(async () => {}),
+ fmtCoords: (lat, lon) => `${lat.toFixed(5)}, ${lon.toFixed(5)}`,
+ prefs,
+ prefsReady: Promise.resolve(),
+}));
+
+const engines = [];
+function fakeEngine(view) {
+ let camera = { ...view, bearing: 0 };
+ const engine = {
+ on: vi.fn(() => () => {}),
+ camera: vi.fn(() => ({ ...camera })),
+ getZoom: vi.fn(() => camera.zoom),
+ setView: vi.fn((next, zoom) => { camera = { ...camera, ...next, zoom }; }),
+ setBearing: vi.fn(),
+ fitBounds: vi.fn(),
+ viewBounds: vi.fn(() => ({ west: 42.9, south: 14.78, east: 42.97, north: 14.84 })),
+ latLngToContainerPoint: vi.fn(({ lat, lon }) => ({ x: lon * 10, y: lat * 10 })),
+ containerPointToLatLng: vi.fn(({ x, y }) => ({ lat: y, lon: x })),
+ resize: vi.fn(),
+ panBy: vi.fn(),
+ destroy: vi.fn(),
+ };
+ // The turn gesture reads the map's own box (lib/map/gestures.js).
+ const container = document.createElement('div');
+ container.getBoundingClientRect = () => ({ left: 0, top: 0, width: 800, height: 600 });
+ engine.container = container;
+ engines.push(engine);
+ return engine;
+}
+vi.mock('../lib/map/engine.js', () => ({
+ createMapEngine: vi.fn(async (element, { view }) => fakeEngine(view)),
+}));
+const showBasemap = vi.fn();
+const setOverlay = vi.fn();
+vi.mock('../lib/map/basemap.js', () => ({
+ OVERLAY_IDS: ['boundaries', 'roads', 'labels'],
+ createBasemaps: vi.fn(() => ({ show: showBasemap, setOverlay, setZoomCeiling: vi.fn(), dispose: vi.fn() })),
+}));
+
+const { default: Detect } = await import('./Detect.svelte');
+
+let live, target;
+const settle = async () => { for (let i = 0; i < 80; i++) await Promise.resolve(); flushSync(); };
+const button = (text) => [...target.querySelectorAll('button')].find((b) => b.textContent.trim() === text);
+const starts = (text) => [...target.querySelectorAll('button')].find((b) => b.textContent.trim().startsWith(text));
+const labelled = (label) => target.querySelector(`button[aria-label="${label}"]`);
+
+async function open() {
+ target = document.createElement('div');
+ document.body.append(target);
+ live = mount(Detect, { target });
+ flushSync();
+ await settle();
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ engines.length = 0;
+ uiState.tool = 'detect';
+ uiState.openAnalyzer = null;
+ prefs.detectView = undefined;
+});
+afterEach(() => {
+ if (live) unmount(live);
+ live = null;
+ target?.remove();
+ document.body.innerHTML = '';
+});
+
+describe('Detect', () => {
+ it('opens one map and the case list beside it, fetching no imagery of its own', async () => {
+ await open();
+ expect(target.querySelectorAll('.map')).toHaveLength(1);
+ expect(target.querySelector('.cmp-dock').getAttribute('aria-label')).toBe('Detect');
+ expect(target.textContent).toContain('Hodeidah anchorage');
+ // the list is local state; nothing was posted and no run was started
+ expect(post).not.toHaveBeenCalled();
+ });
+
+ it('draws the shared areas in their colour and opens Areas when pressed', async () => {
+ await open();
+ const outlines = target.querySelectorAll('.detect-areas polygon:not(.hit)');
+ expect(outlines).toHaveLength(1);
+ target.querySelector('.detect-areas g.area').dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ await settle();
+ expect(outlines[0].getAttribute('stroke')).toBe('#123456');
+ labelled('Edit Anchorage').click(); await settle();
+ expect(target.querySelector('[aria-label="Rename Anchorage"]')).not.toBe(null);
+ starts('Anchorage').click(); await settle();
+ expect(engines[0].fitBounds).toHaveBeenCalledWith(
+ expect.objectContaining({ west: 42.9, east: 42.97 }), expect.anything()
+ );
+ });
+
+ it('shows which way is up, and lands framed on the ground this case watches', async () => {
+ await open();
+ // The surface's own chrome is off here, so Detect carries the compass itself.
+ expect(target.querySelector('[aria-label="Reset to north"]')).not.toBe(null);
+ // One framing, on the areas of the case, rather than the unrelated home view.
+ expect(engines[0].fitBounds).toHaveBeenCalledTimes(1);
+ expect(engines[0].fitBounds).toHaveBeenCalledWith(
+ { west: 42.9, east: 42.97, south: 14.78, north: 14.84 }, expect.anything()
+ );
+ });
+
+ it('turns the map from a shift- or middle-drag, like every other map in the app', async () => {
+ await open();
+ const surface = target.querySelector('.map');
+ const grab = (extra) => surface.dispatchEvent(
+ new MouseEvent('mousedown', { bubbles: true, clientX: 400, clientY: 300, ...extra })
+ );
+ grab({ button: 0 });
+ flushSync();
+ expect(target.querySelector('.rotate-pivot')).toBe(null); // a plain drag pans
+ grab({ button: 1 });
+ flushSync();
+ expect(target.querySelector('.rotate-pivot')).not.toBe(null);
+ window.dispatchEvent(new MouseEvent('mousemove', { bubbles: true, clientX: 500, clientY: 200 }));
+ window.dispatchEvent(new MouseEvent('mouseup', { bubbles: true }));
+ flushSync();
+ expect(engines[0].setBearing).toHaveBeenCalled();
+ expect(target.querySelector('.rotate-pivot')).toBe(null);
+ });
+
+ it('keeps the drawn areas in the map\'s own layer list', async () => {
+ await open();
+ starts('Layers').click(); await settle();
+ const row = target.querySelector('[aria-label="Watched areas"]');
+ expect(row.getAttribute('aria-pressed')).toBe('true');
+ row.click(); await settle();
+ expect(target.querySelectorAll('.detect-areas polygon:not(.hit)')).toHaveLength(0);
+ });
+
+ it('opens on Esri with Borders and saved work, with the search over the map and no header strip', async () => {
+ await open();
+ expect(target.querySelector('.bar')).toBe(null);
+ expect(target.querySelector('.surface-shell .search.cmp-glass')).not.toBe(null);
+ expect(showBasemap).toHaveBeenCalledWith(expect.objectContaining({ id: 'esri-world-imagery' }), 'esri-world-imagery', expect.anything());
+ expect(setOverlay).toHaveBeenCalledWith('boundaries', true, null);
+ starts('Layers').click(); await settle();
+ expect(target.querySelector('[aria-label="Saved work"]').getAttribute('aria-pressed')).toBe('true');
+ expect(get.mock.calls.some(([path]) => path.includes('/sentinel/'))).toBe(false);
+ expect(post).not.toHaveBeenCalled();
+ });
+
+ it('collapses to a remembered rail, resizes the map and reopens from a tab or shortcut', async () => {
+ await open();
+ engines[0].resize.mockClear();
+ target.querySelector('[aria-label="Collapse Detect panel"]').click(); await settle();
+ expect(target.querySelector('.dock-tabs.rail')).not.toBe(null);
+ expect(engines[0].resize).toHaveBeenCalled();
+ expect(put).toHaveBeenLastCalledWith('/api/settings/prefs', { detect_view: expect.objectContaining({ collapsed: true }) });
+ target.querySelector('[aria-label="Saved"]').click(); await settle();
+ expect(target.querySelector('.dock-tabs.rail')).toBe(null);
+ window.dispatchEvent(new KeyboardEvent('keydown', { key: ']' })); await settle();
+ expect(target.querySelector('.dock-tabs.rail')).not.toBe(null);
+ await unmount(live); live = null; target.remove();
+ await open();
+ expect(target.querySelector('.dock-tabs.rail')).not.toBe(null);
+ });
+
+ it('restores the Detect basemap and overlays without requesting a pass', async () => {
+ prefs.detectView = { collapsed: false, basemap: 'osm', overlays: ['roads'], saved: false };
+ await open();
+ expect(showBasemap).toHaveBeenLastCalledWith(expect.objectContaining({ id: 'osm' }), 'osm', expect.anything());
+ expect(setOverlay).toHaveBeenCalledWith('roads', true, null);
+ expect(setOverlay).toHaveBeenCalledWith('boundaries', false, undefined);
+ expect(post).not.toHaveBeenCalled();
+ });
+
+ it('takes the current view as an area to sweep', async () => {
+ await open();
+ button('New detection').click(); await settle();
+ starts('One pass').click(); await settle();
+ expect(target.textContent).toContain('Draw an area to look in.');
+ button('Use current view').click(); await settle();
+ expect(target.querySelector('[aria-label="Area name"]').value).toBe('Area 1');
+ expect(target.textContent).toContain('tile');
+ });
+
+ it('opens a saved item the rest of the app asked for', async () => {
+ await open();
+ uiState.openAnalyzer = `followups-${WATCH}`;
+ flushSync();
+ await settle();
+ expect(uiState.openAnalyzer).toBe(null);
+ expect(get).toHaveBeenCalledWith(`/api/cases/case-a/analysis/followups/${WATCH}`);
+ });
+});
diff --git a/frontend/src/tools/Detect.svelte b/frontend/src/tools/Detect.svelte
new file mode 100644
index 0000000..0de8b8b
--- /dev/null
+++ b/frontend/src/tools/Detect.svelte
@@ -0,0 +1,457 @@
+<script>
+ /**
+ * Detect: watch an area of Copernicus Sentinel-2 or Sentinel-1 over time.
+ *
+ * It stands on its own rather than inside Compare, because it is a different
+ * job: Compare reads two pictures side by side, while this one sweeps ground
+ * and comes back to it. One map is enough for that — the evidence for a
+ * candidate is the before/after picture the panel shows, not a second
+ * surface — so the map here is the ground you draw on and the pass you are
+ * about to read, and the column beside it holds the work.
+ *
+ * Nothing here fetches imagery on its own beyond the basemap the map shows.
+ * Starting a run, and looking a pass up, are the acts that reach Copernicus.
+ */
+ import { onMount, tick, untrack } from 'svelte';
+ import { api } from '../lib/api.js';
+ import { caseState, prefs, prefsReady, toast, uiState } from '../lib/state.svelte.js';
+ import { marksToZones, viewZone, zoneMarks, zoneRing } from '../lib/map/analyzers.js';
+ import { createImageryState } from './satellite/state/imagery.svelte.js';
+ import { createSentinelState } from './satellite/state/sentinel.svelte.js';
+ import { createRadarState } from './satellite/state/radar.svelte.js';
+ import { RADAR_ID, passLabel } from '../lib/radar.js';
+ import { copernicusNeed } from '../lib/copernicusSetup.js';
+ import CopernicusNeeded from '../components/CopernicusNeeded.svelte';
+ import MapSurface from './satellite/MapSurface.svelte';
+ import PlaceSearch from './satellite/PlaceSearch.svelte';
+ import ImageryChip from './satellite/ImageryChip.svelte';
+ import MapLayers from './satellite/MapLayers.svelte';
+ import Compass from '../components/Compass.svelte';
+ import Icon from '../components/Icon.svelte';
+ import { createWaybackState } from './satellite/state/wayback.svelte.js';
+ import { startRotateDrag } from '../lib/map/gestures.js';
+ import AnnotationCanvas from './compare/AnnotationCanvas.svelte';
+ import AnalysisOverlay from './detect/AnalysisOverlay.svelte';
+ import DetectAreas from './detect/DetectAreas.svelte';
+ import DetectPanel from './detect/DetectPanel.svelte';
+ import './mapdock.css';
+
+ const SENTINEL = 'sentinel2';
+ const imagery = createImageryState({ api });
+
+ let home = $state(null);
+ let view = $state({ lat: 0, lon: 0, zoom: 2 });
+ let bearing = $state(0);
+ let engine = $state(null);
+ let element = $state(null);
+ let ready = $state(false);
+ let refused = $state(false);
+ let dated = $state(null);
+ let providerId = $state('esri-world-imagery');
+ let chosenBasemap = $state('esri-world-imagery');
+ let collapsed = $state(false);
+ let overlays = $state(['boundaries']);
+ let savedVisible = $state(true);
+ let readingPass = $state(false);
+ let layersOpen = $state(false);
+ let prefsLoaded = $state(false);
+ const wayback = createWaybackState({ api, place: () => view });
+ const s1 = createRadarState({ api, place: () => view, onBilled: () => imagery.refreshUsage() });
+ const shown = $derived(imagery.displayed(providerId, view.zoom, { ...s2.variant, release: wayback.release, pass: s1.pass }));
+ /** The metered archives are on the map only while a pass is being read. */
+ const PASSES = [SENTINEL, RADAR_ID];
+ const selectableImagery = $derived({ ...imagery, providers: imagery.providers.filter((p) => readingPass || !PASSES.includes(p.id)) });
+ const layerRows = $derived([
+ ...[['boundaries', 'Borders'], ['labels', 'Labels'], ['roads', 'Roads'], ['railway', 'Railways'],
+ ['power', 'Power lines'], ['seamarks', 'Seamarks'], ['gpstraces', 'GPS traces']].map(([id, label]) => ({
+ id, label, on: overlays.includes(id), toggle: () => {
+ overlays = overlays.includes(id) ? overlays.filter((value) => value !== id) : [...overlays, id];
+ },
+ })),
+ { id: 'saved', label: 'Saved work', on: savedVisible, toggle: () => (savedVisible = !savedVisible) },
+ { id: 'areas', label: 'Watched areas', on: showZones, toggle: () => (showZones = !showZones) },
+ ]);
+ let searchText = $state('');
+ let searching = $state(false);
+ let panel = $state(null);
+ let opening = $state(null);
+
+ const s2 = createSentinelState({
+ place: () => ({ lat: view.lat, lon: view.lon }),
+ onBilled: () => imagery.refreshUsage(),
+ notify: toast,
+ api,
+ });
+
+ // What the column owns and the map draws.
+ let zones = $state([]);
+ let drawing = $state('select');
+ let selectedZone = $state(null);
+ let layers = $state([]);
+ let showZones = $state(true);
+ let selectedResult = $state(null);
+ let areaGroups = $state([]);
+ let highlight = $state([]);
+ let manual = $state(null);
+ let manualTool = $state('select');
+ $effect(() => { manualTool = manual?.kind === 'polygon' ? 'polygon' : 'select'; });
+
+ const marks = $derived(zoneMarks(zones));
+ const mapDate = $derived(s2.date || '');
+ const passChip = $derived(providerId === RADAR_ID ? passLabel(s1.pass) : mapDate);
+ /**
+ * 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,
+ * where the work would be. Not a lock: the panel still opens on the
+ * detections already saved.
+ */
+ const needs = $derived(imagery.providers.length ? copernicusNeed(imagery.providers) : '');
+
+ onMount(() => {
+ let gone = false;
+ void (async () => {
+ imagery.refreshUsage();
+ await prefsReady;
+ if (gone) return;
+ const saved = prefs.detectView;
+ collapsed = saved?.collapsed ?? false;
+ chosenBasemap = saved?.basemap && !PASSES.includes(saved.basemap) ? saved.basemap : 'esri-world-imagery';
+ providerId = chosenBasemap;
+ overlays = [...(saved?.overlays ?? ['boundaries'])];
+ savedVisible = saved?.saved ?? true;
+ prefsLoaded = true;
+ home = { ...prefs.homeView };
+ view = { ...home };
+ try {
+ await imagery.loadProviders();
+ } catch {
+ /* the panel still opens on local state; the map says what it cannot show */
+ }
+ if (gone) return;
+ if (!imagery.find(providerId)) providerId = 'esri-world-imagery';
+ })();
+ return () => { gone = true; };
+ });
+
+ $effect(() => {
+ if (!PASSES.includes(providerId)) chosenBasemap = providerId;
+ });
+ let lastPrefs = '';
+ $effect(() => {
+ if (!prefsLoaded) return;
+ const value = { collapsed, basemap: chosenBasemap, overlays: [...overlays], saved: savedVisible };
+ const key = JSON.stringify(value);
+ if (!lastPrefs) { lastPrefs = key; return; }
+ if (key === lastPrefs) return;
+ lastPrefs = key;
+ prefs.detectView = value;
+ void api.put('/api/settings/prefs', { detect_view: value }).catch(() => toast('Could not save the Detect preferences', 'danger'));
+ });
+ $effect(() => {
+ collapsed;
+ void tick().then(() => engine?.resize());
+ });
+
+ // 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. Detect had
+ // the compass without the gesture, so north could be reset and never left.
+ let rotating = $state(null);
+ $effect(() => {
+ if (!element || !engine) return;
+ const surface = element;
+ const down = (event) => {
+ const shiftDrag = event.button === 0 && event.shiftKey;
+ if (event.button !== 1 && !shiftDrag) return;
+ startRotateDrag(engine, event, {
+ onPivot: (point) => (rotating = point),
+ onEnd: () => (rotating = null),
+ });
+ };
+ surface.addEventListener('mousedown', down, true);
+ return () => surface.removeEventListener('mousedown', down, true);
+ });
+ function toggleDock(event) {
+ if (uiState.tool !== 'detect' || event.repeat || event.key !== ']' || event.ctrlKey || event.metaKey || event.altKey
+ || event.target?.closest?.('input, textarea, select, [contenteditable="true"]')) return;
+ event.preventDefault();
+ collapsed = !collapsed;
+ }
+ function leavePass() {
+ readingPass = false;
+ providerId = chosenBasemap;
+ }
+
+ // A saved item asked for from elsewhere: the case sidebar, or the top bar
+ // while a run was working (lib/detectRuns.svelte.js).
+ $effect(() => {
+ const requested = uiState.openAnalyzer;
+ if (!requested) return;
+ untrack(() => {
+ opening = requested;
+ uiState.openAnalyzer = null;
+ });
+ });
+
+ /** The camera as a rectangle to sweep: the one place the map decides what a
+ * run covers, after which the area is fixed and the camera is free again. */
+ function useCurrentView() {
+ const bounds = engine?.viewBounds?.();
+ if (!bounds) return;
+ zones = [...zones, viewZone(bounds, `Area ${zones.length + 1}`)];
+ showZones = true;
+ drawing = 'select';
+ }
+
+ /** Go to a point of the work. A candidate under review asks to be close
+ * enough to read; a saved place only asks to be on screen. */
+ function focus([lon, lat], closest = 13) {
+ engine?.setView({ lon, lat }, Math.max(engine.getZoom(), closest));
+ }
+
+ /** A framing asked for before the map engine existed, run once it does: the
+ * case's areas usually arrive first. */
+ let waitingFrame = $state(null);
+ $effect(() => {
+ if (!engine || !waitingFrame) return;
+ const shapes = waitingFrame;
+ untrack(() => { waitingFrame = null; frame(shapes); });
+ });
+
+ /** Frame a whole set of areas: opening a routine should show all of it. */
+ function frame(shapes) {
+ if (!engine?.fitBounds) { waitingFrame = shapes; return; }
+ const points = shapes.flatMap((zone) => zoneRing(zone));
+ if (!points.length) return;
+ const xs = points.map(([lon]) => lon);
+ const ys = points.map(([, lat]) => lat);
+ engine.fitBounds(
+ { west: Math.min(...xs), east: Math.max(...xs), south: Math.min(...ys), north: Math.max(...ys) },
+ { padding: 60, maxZoom: 15 }
+ );
+ }
+
+ /** Put a pass on the map, so the picture is the one the work is about. */
+ function showDate({ provider, date, time, layer, maxcc }) {
+ if (!date) { leavePass(); return; }
+ if (provider === RADAR_ID) {
+ // A radar pass is shown by the radar basemap, once Settings has its layer.
+ if (!imagery.find(RADAR_ID)) return;
+ readingPass = true;
+ providerId = RADAR_ID;
+ s1.pick({ date, time });
+ return;
+ }
+ if (!imagery.find(SENTINEL)) return;
+ readingPass = true;
+ providerId = SENTINEL;
+ if (layer) s2.layer = layer;
+ if (maxcc !== undefined && maxcc !== null) s2.setMaxcc(maxcc);
+ s2.date = date ?? '';
+ }
+
+ async function goTo() {
+ const text = searchText.trim();
+ if (!text || searching || !engine) return;
+ searching = true;
+ try {
+ try {
+ const parsed = await api.post('/api/geo/parse', { text });
+ engine.setView(parsed, Math.max(engine.getZoom(), 16));
+ return;
+ } catch {
+ /* not coordinates: ask the geocoder below */
+ }
+ const place = await api.get(`/api/geo/geocode?q=${encodeURIComponent(text)}`);
+ engine.setView(place, Math.max(engine.getZoom(), 13));
+ if (place.display_name) toast(place.display_name, 'info', 5000);
+ } catch {
+ toast('No match. Try coordinates, DMS, MGRS, a plus code or a place name', 'danger');
+ } finally {
+ searching = false;
+ }
+ }
+</script>
+
+<svelte:window onkeydown={toggleDock} />
+<div class="detect-tool">
+ <div class="stage">
+ <div class="surface-shell">
+ <div class="search cmp-glass">
+ <PlaceSearch
+ bind:value={searchText}
+ centre={{ lat: view.lat, lon: view.lon }}
+ units={prefs.units}
+ {searching}
+ listId="detect-suggestions"
+ onsubmit={goTo}
+ onpick={(place) => { searchText = place.label ?? searchText; goTo(); }}
+ />
+ </div>
+ <div class="map-choices">
+ <ImageryChip imagery={selectableImagery} bind:providerId {s2} {wayback} {s1} {shown} />
+ <div class="layer-picker cmp-glass">
+ <MapLayers rows={layerRows} bind:open={layersOpen} />
+ </div>
+ {#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>
+ {/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>
+ {#if home}
+ <MapSurface
+ bind:engine
+ bind:element
+ bind:view
+ bind:bearing
+ bind:ready
+ bind:refused
+ bind:dated
+ bind:providerId
+ {imagery}
+ {s2}
+ {wayback}
+ {s1}
+ {overlays}
+ chrome={false}
+ {home}
+ resetToHome={false}
+ imperial={prefs.units === 'imperial'}
+ armed={drawing !== 'select' ? 'selecting' : null}
+ onclick={({ lon, lat }) => {
+ if (manual?.kind === 'point') void panel?.addManual({ type: 'Point', coordinates: [lon, lat] });
+ }}
+ controlsTop={98}
+ onusage={() => imagery.refreshUsage()}
+ />
+ {#if savedVisible && layers.some((layer) => layer.visible)}
+ <AnalysisOverlay {engine} {layers} selected={selectedResult} active={!manual}
+ onpick={(run, result) => panel?.pick(run, result)} />
+ {/if}
+ {#if areaGroups.length && !manual}
+ <DetectAreas {engine} groups={areaGroups} {highlight} onpick={(id) => panel?.openArea(id)} />
+ {/if}
+ {#if manual?.kind === 'polygon'}
+ <AnnotationCanvas annotations={[]} {engine} letter="a" bind:tool={manualTool} colour="#ffffff"
+ onchange={(next) => {
+ const polygon = marksToZones(next, [])[0];
+ if (polygon) {
+ const ring = zoneRing(polygon);
+ void panel?.addManual({ type: 'Polygon', coordinates: [[...ring, ring[0]]] });
+ }
+ }} />
+ {:else if showZones && !manual}
+ <AnnotationCanvas annotations={marks} {engine} letter="a" editVertices={true} edgeOnly={true}
+ bind:tool={drawing} bind:selectedId={selectedZone} colour="#38bdf8" fillOpacity={0.08}
+ onchange={(next) => (zones = marksToZones(next, zones))} />
+ {/if}
+ {:else}
+ <div class="loading">Reading your preferences…</div>
+ {/if}
+ {#if rotating}
+ <div class="rotate-pivot" style:left={`${rotating.x}px`} style:top={`${rotating.y}px`} aria-hidden="true"></div>
+ {/if}
+ {#if needs}
+ <div class="need-over">
+ <CopernicusNeeded need={needs} tool="Detect" />
+ </div>
+ {/if}
+ {#if manual}
+ <div class="manual-chip cmp-glass">{manual.kind === 'point' ? 'Click the candidate on the map' : 'Click corners; Enter finishes'}
+ <button class="cmp-icon" aria-label="Cancel adding candidate" title="Cancel adding candidate" onclick={() => (manual = null)}><Icon name="x" size={13} /></button>
+ </div>
+ {/if}
+ </div>
+
+ <DetectPanel
+ bind:this={panel}
+ bind:collapsed
+ bind:manual
+ caseId={caseState.current?.id}
+ bind:zones
+ bind:drawing
+ bind:selectedZone
+ bind:layers
+ bind:showZones
+ bind:selectedResult
+ bind:areaGroups
+ bind:highlight
+ {opening}
+ onopened={() => (opening = null)}
+ onfocus={focus}
+ onframe={frame}
+ onusecurrentview={useCurrentView}
+ onshow={showDate}
+ onleavepass={leavePass}
+ />
+ </div>
+</div>
+
+<style>
+ .detect-tool {
+ display: flex;
+ flex-direction: column;
+ height: 100%;
+ min-height: 0;
+ background: var(--bg-0);
+ }
+ .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 :global(.count) { margin-left: auto; color: var(--text-3); }
+ .layer-picker :global(.layers) { min-width: 190px; margin-top: 8px; }
+ .pass-chip { display: flex; align-items: center; gap: 8px; padding: 4px 8px; font-size: var(--fs-xs); }
+ /* Over the map and under its own controls, which stay usable around it. */
+ .need-over {
+ position: absolute;
+ inset: 0;
+ z-index: 640;
+ display: grid;
+ place-items: center;
+ padding: 16px;
+ background: rgb(0 0 0 / 0.35);
+ }
+ .manual-chip { position: absolute; bottom: 36px; left: 12px; z-index: 650; display: flex; align-items: center; padding: 4px 8px; font-size: var(--fs-xs); }
+ /* The point a turn is happening about, drawn as Satellite and Compare draw it. */
+ .rotate-pivot {
+ position: absolute;
+ z-index: 570;
+ width: 34px;
+ height: 34px;
+ transform: translate(-50%, -50%);
+ border: 1px solid rgb(255 255 255 / 0.92);
+ border-radius: 50%;
+ pointer-events: none;
+ box-shadow: 0 0 0 1px rgb(0 0 0 / 0.7), inset 0 0 0 8px rgb(0 0 0 / 0.25);
+ }
+ .rotate-pivot::before,
+ .rotate-pivot::after {
+ content: '';
+ position: absolute;
+ background: rgb(255 255 255 / 0.92);
+ }
+ .rotate-pivot::before { left: 50%; top: 5px; bottom: 5px; width: 1px; }
+ .rotate-pivot::after { top: 50%; left: 5px; right: 5px; height: 1px; }
+ .stage { display: flex; flex: 1; min-height: 0; }
+ /* The surface itself is a flex child (`.map-wrap`), so this has to be a flex
+ container or the map lands with no height at all. */
+ .surface-shell {
+ position: relative;
+ display: flex;
+ flex: 1;
+ min-width: 0;
+ min-height: 0;
+ overflow: hidden;
+ background: var(--bg-0);
+ }
+ .loading {
+ display: grid;
+ place-items: center;
+ height: 100%;
+ color: var(--text-3);
+ font-size: var(--fs-sm);
+ }
+</style>
diff --git a/frontend/src/tools/Files.svelte b/frontend/src/tools/Files.svelte
index 959b858..1d52be1 100644
--- a/frontend/src/tools/Files.svelte
+++ b/frontend/src/tools/Files.svelte
@@ -620,7 +620,7 @@
openNotebook(entity.id);
return;
}
- if (['compare-session', 'analysis-zones', 'analysis-follow-up', 'analysis-run'].includes(entity.type)) {
+ if (['compare-session', 'analysis-area', 'analysis-zones', 'analysis-follow-up', 'analysis-run'].includes(entity.type)) {
openEntity(entity);
return;
}
diff --git a/frontend/src/tools/Satellite.svelte b/frontend/src/tools/Satellite.svelte
index 788b9a8..63b56f7 100644
--- a/frontend/src/tools/Satellite.svelte
+++ b/frontend/src/tools/Satellite.svelte
@@ -7,6 +7,7 @@
import { createSurface } from '../lib/map/surface.js';
import MapSurface from './satellite/MapSurface.svelte';
import { createSentinelState } from './satellite/state/sentinel.svelte.js';
+ import { createRadarState } from './satellite/state/radar.svelte.js';
import { createWaybackState } from './satellite/state/wayback.svelte.js';
import { createAddedLayersState } from './satellite/state/addedLayers.svelte.js';
import { createSavedState } from './satellite/state/saved.svelte.js';
@@ -387,19 +388,28 @@
// --- Esri Wayback: which release of World Imagery ---
// The release rides on the provider id like a Sentinel-2 window, and both
- // questions it asks (the release list, a point's history) reach Esri, so
- // neither is asked until the basemap is on screen or its picker is open.
+ // questions it asks reach Esri: the release list once the basemap is on
+ // screen, a point's history only when the analyst asks for it.
const wb = createWaybackState({
api,
place: () => ({ lat: center.lat, lon: center.lon, zoom: center.zoom }),
});
+ // --- Sentinel-1: which radar pass ---
+ // Passes are read by the month while its picker is open; the pass rides on
+ // the provider id like the others.
+ const s1 = createRadarState({
+ api,
+ place: () => ({ lat: center.lat, lon: center.lon }),
+ onBilled: () => imagery.refreshUsage(),
+ });
+
// --- what the map is actually showing (state/imagery.svelte.js) ---
// A billed basemap steps aside for free imagery when paused (90% soft block)
// or zoomed out (eco). The capture follows the display, so provenance always
// matches the pixels.
const shown = $derived(
- imagery.displayed(providerId, center.zoom, { ...s2.variant, release: wb.release })
+ imagery.displayed(providerId, center.zoom, { ...s2.variant, release: wb.release, pass: s1.pass })
);
// Fullscreen: the tool covers the whole viewport; SAVED stays collapsible (item 4).
@@ -643,18 +653,6 @@
if (mapReady && shown.provider?.id === WAYBACK_ID) wb.loadReleases();
});
- // Once the picker has been opened, the history follows the map: a view that
- // settles over another tile reads that tile's history, picker open or not.
- // Debounced, and answered from memory for a tile already read.
- $effect(() => {
- if (!wb.watching || shown.provider?.id !== WAYBACK_ID) return;
- wb.here; // the tile under the map: a new one is a new history
- clearTimeout(wbChangesTimer);
- wbChangesTimer = setTimeout(() => wb.follow(), 900);
- return () => clearTimeout(wbChangesTimer);
- });
- let wbChangesTimer;
-
// --- middle-drag rotate (item 3), Google-Earth style ---
// Grab a point → the map turns around *that* point (not the centre) as the
// cursor sweeps, with a sober target marking the pivot. A map only rotates
@@ -894,10 +892,11 @@
if (!sky.on) arm(modes, 'sky');
sky.handOff({ ...point, date: sky.day || undefined });
} else if (id === 'history') {
+ const zoom = Math.max(center.zoom, 15);
providerId = WAYBACK_ID;
- engine.setView(point, Math.max(center.zoom, 15));
+ engine.setView(point, zoom);
await tick();
- if (!wb.menuOpen) wb.toggleMenu();
+ wb.historyAt({ lat: point.lat, lon: point.lon, zoom });
} else if (id === 'compare') {
await comparePoint(point, value);
}
@@ -2124,6 +2123,7 @@
{imagery}
{s2}
wayback={wb}
+ {s1}
home={openingHome}
{overlays}
imperial={prefs.units === 'imperial'}
diff --git a/frontend/src/tools/Satellite.test.js b/frontend/src/tools/Satellite.test.js
index beda3da..64802df 100644
--- a/frontend/src/tools/Satellite.test.js
+++ b/frontend/src/tools/Satellite.test.js
@@ -751,15 +751,17 @@ describe('Esri Wayback', () => {
expect(source).toContain('if (mapReady && shown.provider?.id === WAYBACK_ID) wb.loadReleases();');
});
- it('reads no history until the picker has been opened, and follows the map after', () => {
- const effect = source.slice(source.indexOf('if (!wb.watching || shown.provider?.id !== WAYBACK_ID) return;'));
- expect(effect.slice(0, 300)).toContain('wb.here;');
- expect(effect.slice(0, 300)).toContain('wb.follow()');
+ it('reads a history only when asked, at the point the menu names', () => {
+ // a moving map never starts the walk: it is dozens of requests to Esri
+ expect(source).not.toMatch(/wb\.(follow|watching|here)\b/);
+ expect(source).toContain('wb.historyAt({ lat: point.lat, lon: point.lon, zoom });');
});
it('puts the release on the id every tile and capture keys on', () => {
- expect(source).toContain('imagery.displayed(providerId, center.zoom, { ...s2.variant, release: wb.release })');
+ expect(source).toContain('imagery.displayed(providerId, center.zoom, { ...s2.variant, release: wb.release, pass: s1.pass })');
expect(source).toContain('wayback={wb}');
+ // …and the radar pass beside it
+ expect(source).toContain('{s1}');
});
});
diff --git a/frontend/src/tools/Settings.svelte b/frontend/src/tools/Settings.svelte
index 675ce09..1f26dad 100644
--- a/frontend/src/tools/Settings.svelte
+++ b/frontend/src/tools/Settings.svelte
@@ -24,6 +24,7 @@
import ExtensionTab from './settings/ExtensionTab.svelte';
import GeneralTab from './settings/GeneralTab.svelte';
import ImageryTab from './settings/ImageryTab.svelte';
+ import { ACCOUNT_STEPS } from '../lib/copernicusSetup.js';
import PublishingTab from './settings/PublishingTab.svelte';
import StorageTab from './settings/StorageTab.svelte';
import SystemTab from './settings/SystemTab.svelte';
@@ -108,20 +109,16 @@
{
id: 'sentinelhub',
label: 'Sentinel Hub',
- gives: 'Sentinel-2 · free · 10 m/px',
+ gives: 'Sentinel-2 and Sentinel-1 · free · 10 m/px',
cost: 'Never billed',
field: 'Copernicus configuration instance ID',
placeholder: 'a1b2c3d4-0000-0000-0000-000000000000',
help: 'https://shapps.dataspace.copernicus.eu/dashboard/#/configurations',
usage: USAGE_LINKS.sentinelhub,
// Not a token you're issued but a configuration you build, so the field
- // needs the recipe, not just a "get one here" link.
- steps: [
- 'Register (free) on dataspace.copernicus.eu, then open the Sentinel Hub Dashboard.',
- 'Configuration Utility → New configuration, based on "Simple Sentinel-2 L2A template".',
- 'Open it and turn off Show logo and Show warnings. Both are burned into every tile.',
- 'Copy the ID under "Service endpoints" and paste it here.',
- ],
+ // needs the recipe, not just a "get one here" link (lib/copernicusSetup.js,
+ // which Detect and Compare show too).
+ steps: ACCOUNT_STEPS,
overage:
'A free account gets 30,000 requests a month and simply stops serving until the 1st. It never bills.',
// the correction the free-allowance box exists for, told where it's useful
@@ -339,6 +336,9 @@
let updateOnStart = $state(true); // pop a notice on load when a release is out
// whether saving a proof files its point as a place, or asks first
let proofPlaceAuto = $state(true);
+ let radarLayer = $state('');
+ // a card of the Imagery tab asked for from elsewhere, opened and scrolled to
+ let focusCard = $state('');
// The app-wide logo lives beside settings.json and reaches cases only in proof PNGs.
// `sigBust` refreshes the preview after replacement.
let signature = $state(false);
@@ -552,6 +552,7 @@
reversePrefill = s.reverse_prefill ?? true;
updateOnStart = s.update_check_on_start ?? true;
proofPlaceAuto = s.proof_place_auto ?? true;
+ radarLayer = s.sentinel1_layer ?? '';
applyPrefs(s); // the rest of the app reads these live
await loadScrapers().catch(() => {}); // local disk read; never blocks Settings
// shells out to `ffmpeg -version`; non-blocking, System only reads it
@@ -698,9 +699,12 @@
$effect(() => {
if (uiState.tool !== 'settings') return;
const aliases = { preferences: 'general', about: 'system' };
- const target = aliases[uiState.settingsTab] ?? uiState.settingsTab;
+ // `imagery:sentinelhub` is a tab and the card to open on it
+ const [asked, card] = String(uiState.settingsTab ?? '').split(':');
+ const target = aliases[asked] ?? asked;
if (!target) return;
if (TABS.some((t) => t.id === target)) tab = target;
+ focusCard = card ?? '';
uiState.settingsTab = null;
});
@@ -886,6 +890,8 @@
{saveFreeTier}
bind:eco
bind:ecoMaxZoom
+ bind:radarLayer
+ bind:focusCard
/>
{/if}
diff --git a/frontend/src/tools/compare/AnalyzerPanel.svelte b/frontend/src/tools/compare/AnalyzerPanel.svelte
deleted file mode 100644
index f145a03..0000000
--- a/frontend/src/tools/compare/AnalyzerPanel.svelte
+++ /dev/null
@@ -1,1017 +0,0 @@
-<script>
- /**
- * Detect mode's own column: sweep a drawn area of Copernicus Sentinel-2 at
- * native resolution and keep what was found.
- *
- * The setup reads as three numbered steps because that is the order the work
- * actually happens in — an area first, then the images, then what to look for
- * — and because the flat wall of tabs it replaces gave no clue where to
- * start. Step 2 and the stage share one imagery between them, so what is on
- * screen is always what a run would sweep; see the effect that owns that.
- * Nothing here fetches anything. Only Run does.
- */
- import { onMount, untrack } from 'svelte';
- import { api } from '../../lib/api.js';
- import { ensureCase, reloadCase, toast } from '../../lib/state.svelte.js';
- import {
- SECONDS_PER_FRAME,
- STRENGTHS,
- clone,
- coverage,
- describeMeasure,
- framesPerTile,
- mapSource,
- readableDuration,
- sizeBand,
- sizeOf,
- sourceLabel,
- } from '../../lib/map/analyzers.js';
- import { acquisitionQuery, areaKey, coverageWarning, sweptNote } from '../../lib/map/acquisitions.js';
- import AcquisitionPicker from './AcquisitionPicker.svelte';
- import CloudFilter from './CloudFilter.svelte';
- import Icon from '../../components/Icon.svelte';
-
- let {
- caseId,
- sources = {},
- zones = $bindable([]),
- drawing = $bindable('select'),
- selectedZone = $bindable(null),
- layers = $bindable([]),
- showZones = $bindable(true),
- /** The candidate the review is on, so the map can ring the same one. */
- selectedResult = $bindable(null),
- /** Reported up so the stage can stop showing a pair the run never reads. */
- singleImage = $bindable(false),
- opening = null,
- onfocus = () => {},
- onusecurrentview = () => {},
- onsources = () => {},
- onclose = () => {},
- /** What a run still lacks, said above everything else; empty when nothing. */
- needs = '',
- onsettings = () => {},
- } = $props();
-
- const EMPTY_SOURCE = { provider: 'sentinel2', date: '', layer: 'TRUE_COLOR', maxcc: 30 };
- const SIZES = [['small', 'Small'], ['medium', 'Medium'], ['large', 'Large'], ['all', 'All']];
- const INDICES = [
- ['ndvi', 'NDVI · vegetation'], ['nbr', 'NBR · burn scars'], ['mndwi', 'MNDWI · open water'],
- ['ndwi', 'NDWI · open water'], ['bsi', 'BSI · bare soil'], ['ndbi', 'NDBI · built-up'],
- ];
-
- let catalogue = $state(null);
- let recipe = $state(null);
- let chosen = $state('');
- let title = $state('');
- let a = $state({ ...EMPTY_SOURCE });
- let b = $state({ ...EMPTY_SOURCE });
- let dateRule = $state('manual');
- /** The Sentinel-2 passes the drawn areas have, and the lookup that found them. */
- let passes = $state([]);
- let passDays = $state(30);
- let passBusy = $state(false);
- let passError = $state('');
- let passTruncated = $state(false);
- let passSearched = $state(false);
- let offline = $state(false);
- /** True once the imagery was set by hand; the maps stop driving it. */
- let pinned = $state(false);
- let attachZones = $state(false);
- let zonesId = $state(null);
- let zonesTitle = $state('Analysis areas');
- let followupId = $state(null);
- let lists = $state({ zones: [], followups: [], runs: [] });
- let current = $state(null);
- let candidateId = $state(null);
- let busy = $state(false);
- let error = $state('');
- let view = $state('setup');
- let showImagery = $state(false);
- let showDetection = $state(false);
- let showRecipe = $state(false);
- let showNew = $state(false);
- /** Undefined until the first case is seen, so mounting is not a case switch. */
- let loadedCase;
- let lastMapKey = '';
- let lastAreaKey = '';
- let lastPushed = '';
- let generation = 0;
- /** True once this step took the wheel because the maps could not drive it. */
- let tookOver = $state(false);
-
- const pending = $derived(current && ['queued', 'running'].includes(current.status));
- const candidate = $derived(current?.results?.find((r) => r.id === candidateId));
- const candidates = $derived(current?.results ?? []);
- const counts = $derived.by(() => {
- const tally = { kept: 0, dismissed: 0, new: 0 };
- for (const row of candidates) tally[row.review] = (tally[row.review] ?? 0) + 1;
- return tally;
- });
- const tally = $derived(
- counts.new === 0 ? `All ${candidates.length} reviewed · ${counts.kept} kept, ${counts.dismissed} dismissed`
- : `${counts.new} still to review · ${counts.kept} kept, ${counts.dismissed} dismissed`
- );
- /** What the method can do, straight from the catalogue rather than by name:
- * the panel should never keep its own list of which method is which. */
- const methodOf = (method) => catalogue?.methods?.find((m) => m.id === method) ?? {};
- const capability = $derived(methodOf(recipe?.method));
- /** Mine to change: a built-in is read-only, and an unsaved draft is not in the library yet. */
- const mine = $derived(!!(catalogue?.custom ?? []).some((r) => r.id === chosen));
- const draft = $derived(recipe?.id === 'custom');
- /** A vessel or a fire is present on a date, not a difference between two. */
- const single = $derived(!!capability.single);
- $effect(() => { singleImage = single; });
- $effect(() => { selectedResult = view === 'results' ? candidateId : null; });
- const size = $derived(recipe ? sizeOf(recipe.parameters, capability.sizes) : '');
- const cost = $derived(coverage(zones, catalogue?.grid ?? null));
- const tooMany = $derived(catalogue && cost.tiles > catalogue.max_tiles);
- /** The same pair on both maps, or null when they cannot drive a run. */
- const mapPair = $derived.by(() => {
- const left = mapSource(sources.a);
- const right = mapSource(sources.b);
- return left && right ? { left, right } : null;
- });
- const frames = $derived(cost.tiles * framesPerTile({ single }));
- const duration = $derived(readableDuration(frames * SECONDS_PER_FRAME));
- const blocked = $derived(
- !zones.length ? 'Draw an area to analyze.'
- : tooMany ? (Number.isFinite(cost.tiles)
- ? `These areas need ${cost.tiles} tiles; the limit is ${catalogue.max_tiles}. Draw smaller areas.`
- : `These areas are far past the ${catalogue.max_tiles}-tile limit. Draw smaller areas.`)
- // Said here rather than discovered when the run comes back failed.
- : dateRule === 'manual' && !b.date ? `Choose the ${single ? 'image' : 'image to compare'}.`
- : !single && !a.date && !(dateRule === 'latest_previous' && followupId)
- ? 'Choose the reference image.'
- : pending ? 'A run is already working in this case.'
- : ''
- );
-
- const base = (id = caseId) => `/api/cases/${id}/analysis`;
- const statusLabel = (status) => ({ queued: 'Queued', running: 'Running', ready: 'Completed',
- failed: 'Failed', cancelled: 'Cancelled', no_new_imagery: 'No new imagery' }[status] ?? status);
- const focus = (coordinates) => onfocus(coordinates, current?.input?.b ?? b);
- const round = (value, digits = 1) => Number(value.toFixed(digits));
- const plural = (count, word) => `${count} ${word}${count === 1 ? '' : 's'}`;
- const dates = (input) => methodOf(input.recipe.method).single || !(input.a?.date || input.a?.release)
- ? sourceLabel(input.b) : `${sourceLabel(input.a)} → ${sourceLabel(input.b)}`;
- /** A candidate's reading, in the words its method's catalogue entry gives. */
- const reading = (row, input) => [
- STRENGTHS[row.strength],
- describeMeasure(methodOf(input.recipe.method).measure, row.measure, input.recipe.parameters.index),
- ].filter(Boolean).join(' · ');
-
- function setWeather(on) {
- if (!recipe) return;
- recipe.parameters = { ...recipe.parameters, ignore_clouds: on, ignore_shadows: on };
- }
-
- function setSize(name) {
- if (!recipe || !capability.sizes?.[name]) return;
- recipe.parameters = { ...recipe.parameters, ...capability.sizes[name] };
- }
-
- /** The pass behind a chosen date, so its coverage can be said out loud. */
- const passOf = (day) => passes.find((entry) => entry.date === day) ?? null;
- const coverWarnings = $derived(
- [coverageWarning(passOf(b.date)), single ? '' : coverageWarning(passOf(a.date))].filter(Boolean)
- );
-
- /**
- * What passes the drawn areas really have. Never on mount and never on a
- * redraw: it reaches Copernicus and is billed, so it waits to be asked for.
- */
- async function lookUpPasses() {
- if (passBusy || !zones.length) return;
- passBusy = true; passError = '';
- try {
- const found = await api.post('/api/satellite/sentinel/acquisitions',
- acquisitionQuery(zones, passDays));
- passes = found.dates ?? [];
- passTruncated = !!found.truncated;
- passSearched = true;
- } catch (e) {
- passes = []; passTruncated = false; passSearched = false;
- passError = e.message;
- } finally {
- passBusy = false;
- }
- }
-
- /** Taking a date off the list is a deliberate choice, so the maps follow it. */
- function usePass(letter, entry) {
- pinned = true;
- if (letter === 'a') a = { ...a, date: entry.date };
- else {
- b = { ...b, date: entry.date };
- if (single) a = { ...a, date: entry.date };
- }
- }
-
- async function act(fn) {
- if (busy) return;
- busy = true; error = '';
- try { await fn(); } catch (e) { error = e.message; }
- finally { busy = false; }
- }
-
- async function refresh(id = caseId) {
- if (!id) return;
- const epoch = generation;
- const answer = await Promise.all(['zones', 'followups', 'runs'].map((kind) => api.get(`${base(id)}/${kind}`)));
- if (epoch !== generation) return;
- lists = { zones: answer[0], followups: answer[1], runs: answer[2] };
- }
-
- onMount(() => {
- let alive = true;
- api.get('/api/compare/analyzers').then((answer) => {
- if (!alive) return;
- catalogue = answer;
- if (!recipe) choose(answer.builtins[0]?.id);
- }).catch((e) => { if (alive) error = e.message; });
- return () => { alive = false; generation++; };
- });
-
- // Another case is other work: its areas, drafts and result layers are not
- // this one's. Mounting is not a switch, so re-entering Detect keeps what the
- // parent is still holding.
- $effect(() => {
- const id = caseId;
- if (id === loadedCase) return;
- const switching = loadedCase !== undefined;
- loadedCase = id; generation++;
- current = null; followupId = null; zonesId = null; candidateId = null;
- if (switching) {
- layers = []; zones = []; selectedZone = null; drawing = 'select';
- view = 'setup'; pinned = false; lastMapKey = ''; title = '';
- }
- lists = { zones: [], followups: [], runs: [] };
- if (id) void refresh(id).catch((e) => (error = e.message));
- });
-
- /**
- * Which way the imagery flows, in one place.
- *
- * On arrival the maps lead: whatever is above the stage is almost always what
- * you came to analyze, and inheriting it silently is the whole reason this
- * step usually needs no attention. From the first deliberate change here —
- * or straight away when the maps show something other than Sentinel-2 — the
- * direction reverses and the stage follows this step, so what is on screen
- * is what a run would sweep. Keyed on values, so a parent re-render that
- * rebuilds the same objects changes nothing.
- */
- $effect(() => {
- if (!catalogue || !recipe) return;
- const key = mapPair ? JSON.stringify(mapPair) : '';
- if (!pinned && key) {
- if (key === lastMapKey) return;
- lastMapKey = key;
- untrack(() => { a = clone(mapPair.left); b = clone(mapPair.right); });
- return;
- }
- if (!pinned) {
- untrack(() => { pinned = true; tookOver = true; });
- return;
- }
- const shown = JSON.stringify({ a, b });
- if (shown === lastPushed) return;
- lastPushed = shown;
- untrack(() => onsources(JSON.parse(shown)));
- });
-
- /** Areas redrawn, so the coverage shares no longer describe them (`areaKey`). */
- $effect(() => {
- const key = areaKey(zones);
- if (key === lastAreaKey) return;
- lastAreaKey = key;
- untrack(() => {
- passes = [];
- passSearched = false;
- passTruncated = false;
- passError = '';
- });
- });
-
- $effect(() => {
- if (!pending || !caseId) return;
- const id = current.id;
- const owner = caseId;
- const epoch = generation;
- let stopped = false;
- let timer;
- async function poll() {
- try {
- const run = await api.get(`${base(owner)}/runs/${id}`);
- if (stopped || epoch !== generation) return;
- acceptRun(run);
- if (['queued', 'running'].includes(run.status)) timer = setTimeout(poll, 900);
- else { await refresh(owner); await reloadCase(); }
- } catch (e) { if (!stopped) error = e.message; }
- }
- timer = setTimeout(poll, 900);
- return () => { stopped = true; clearTimeout(timer); };
- });
-
- $effect(() => {
- if (!opening || !caseId) return;
- const match = /^(zones|followups|runs)-([a-f0-9]{12})$/.exec(opening);
- if (match) untrack(() => void act(() => openItem(match[1], match[2])));
- });
-
- function choose(id) {
- const found = [...(catalogue?.builtins ?? []), ...(catalogue?.custom ?? [])].find((r) => r.id === id);
- if (!found) return;
- recipe = clone(found); chosen = id;
- if (recipe.zones.length) zones = clone(recipe.zones);
- attachZones = recipe.zones.length > 0;
- }
-
- function followMaps() {
- if (!mapPair) return;
- pinned = false; tookOver = false; lastMapKey = ''; lastPushed = '';
- a = clone(mapPair.left); b = clone(mapPair.right);
- }
-
- function runTitle() {
- const name = title.trim();
- if (name) return name;
- return `${recipe?.name ?? 'Detection'} · ${new Date().toISOString().slice(0, 10)}`;
- }
-
- function input() {
- return { title: runTitle(), zones: clone(zones),
- recipe: { ...clone(recipe), zones: attachZones ? clone(zones) : [] },
- a: clone(a), b: clone(b), date_rule: dateRule, offline, followup_id: followupId };
- }
-
- /** Runs and watches saved before Detect went Copernicus-only name a Wayback
- * release; they reopen undated, which is what they are for Sentinel-2. */
- const sentinelSource = (source) => source?.provider === 'sentinel2'
- ? { ...EMPTY_SOURCE, ...clone(source) } : { ...EMPTY_SOURCE };
-
- function hydrate(body) {
- title = body.title; zones = clone(body.zones); recipe = clone(body.recipe); chosen = recipe.id;
- a = sentinelSource(body.a); b = sentinelSource(body.b); offline = body.offline;
- dateRule = body.date_rule; attachZones = recipe.zones.length > 0;
- followupId = body.followup_id;
- pinned = true;
- }
-
- function acceptRun(run) {
- current = run;
- if (run.status === 'ready') {
- const old = layers.find((r) => r.id === run.id);
- layers = [...layers.filter((r) => r.id !== run.id), { ...clone(run), visible: old?.visible ?? true }];
- if (!run.results.some((r) => r.id === candidateId)) candidateId = run.results[0]?.id ?? null;
- }
- }
-
- async function openItem(kind, id) {
- if (!id) return;
- const epoch = generation;
- const body = await api.get(`${base()}/${kind}/${id}`);
- if (epoch !== generation) return;
- if (kind === 'zones') { zones = clone(body.zones); zonesTitle = body.title; zonesId = id; view = 'setup'; }
- if (kind === 'followups') { hydrate(body); followupId = id; view = 'setup'; }
- if (kind === 'runs') { hydrate(body.input); acceptRun(body); view = 'results'; }
- }
-
- /**
- * Start an analyzer of your own, from this one or from a plain one.
- *
- * Built-ins cannot be written over, so "copy" is how an analyst keeps a tuned
- * version: the library is shared by every case, which is why it is explicit.
- */
- function startNew(from) {
- const base = from === 'copy'
- ? recipe
- : (catalogue?.builtins ?? []).find((r) => r.id === 'large-change') ?? catalogue?.builtins?.[0];
- if (!base) return;
- recipe = { ...clone(base), id: 'custom',
- name: from === 'copy' ? `${base.name} copy` : 'My analyzer' };
- chosen = 'custom';
- showNew = false;
- showRecipe = true;
- }
-
- async function deleteRecipe() {
- if (!mine) return;
- const gone = chosen;
- await api.del(`/api/compare/analyzers/${gone}`);
- catalogue = await api.get('/api/compare/analyzers');
- showRecipe = false;
- choose(catalogue?.builtins?.[0]?.id ?? '');
- toast('Analyzer removed from the library', 'ok');
- }
-
- async function saveRecipe(asNew = false) {
- const next = { ...clone(recipe), zones: attachZones ? clone(zones) : [] };
- if (asNew) next.id = 'custom';
- recipe = await api.post('/api/compare/analyzers', next);
- chosen = recipe.id;
- catalogue = await api.get('/api/compare/analyzers');
- toast('Analyzer saved for all cases', 'ok');
- }
-
- async function saveAreas(asNew = false) {
- const owner = await ensureCase();
- const data = { title: zonesTitle, zones: clone(zones) };
- const saved = zonesId && !asNew ? await api.put(`${base(owner.id)}/zones/${zonesId}`, data)
- : await api.post(`${base(owner.id)}/zones`, data);
- zonesId = saved.id; await refresh(owner.id); await reloadCase();
- toast('Areas saved in this case', 'ok');
- }
-
- async function saveWatch(asNew = false) {
- const owner = await ensureCase();
- const saved = followupId && !asNew ? await api.put(`${base(owner.id)}/followups/${followupId}`, input())
- : await api.post(`${base(owner.id)}/followups`, input());
- followupId = saved.id; await refresh(owner.id); await reloadCase();
- toast('Watch saved. Run it again from Saved whenever you want.', 'ok');
- }
-
- async function run() {
- const owner = await ensureCase();
- const result = await api.post(`${base(owner.id)}/runs`, input());
- candidateId = null; view = 'results';
- acceptRun(result);
- await refresh(owner.id); await reloadCase();
- }
-
- /** A watch is a recipe, its areas and a date rule. Running it again is the
- * whole of the recurring check: load what was saved, then launch it. */
- async function runWatch(id) {
- await openItem('followups', id);
- await run();
- }
-
- function applyResult(row) {
- acceptRun({ ...current, results: current.results.map((r) => r.id === row.id ? row : r) });
- }
-
- /** Reviewing is a queue: a verdict moves on to the next one still waiting. */
- function advance() {
- const index = candidates.findIndex((r) => r.id === candidateId);
- for (let i = 1; i <= candidates.length; i++) {
- const row = candidates[(index + i) % candidates.length];
- if (row?.review === 'new') { candidateId = row.id; focus(row.coordinates); return; }
- }
- }
-
- async function review(value) {
- applyResult(await api.patch(`${base()}/runs/${current.id}/results/${candidateId}`, { review: value }));
- if (value !== 'new') advance();
- }
-
- /** The pin's name has to mean something in the case, long after this run. */
- const pinTitle = (row) =>
- `${row.phenomenon} · ${row.coordinates[1].toFixed(4)}, ${row.coordinates[0].toFixed(4)}`.slice(0, 120);
-
- async function keep() {
- const answer = await api.post(`${base()}/runs/${current.id}/results/${candidateId}/promote`,
- { title: pinTitle(candidate) });
- applyResult(answer.result);
- await reloadCase();
- toast('Pin and evidence saved in this case', 'ok');
- advance();
- }
-
- async function undoKeep() {
- const answer = await api.del(`${base()}/runs/${current.id}/results/${candidateId}/promote`);
- applyResult(answer.result);
- await reloadCase();
- toast('The pin went to Trash', 'ok');
- }
-
- function step(direction) {
- const index = candidates.findIndex((r) => r.id === candidateId);
- const row = candidates[(index + direction + candidates.length) % candidates.length];
- if (row) { candidateId = row.id; focus(row.coordinates); }
- }
-
- export function pick(runId, resultId) {
- const found = layers.find((r) => r.id === runId);
- if (found) { current = found; candidateId = resultId; view = 'results'; }
- }
-
- function removeZone(id) {
- zones = zones.filter((z) => z.id !== id);
- if (selectedZone === id) selectedZone = null;
- }
-
- async function removeItem(kind, id) {
- await api.del(`${base()}/${kind}/${id}`);
- if (kind === 'runs') { layers = layers.filter((r) => r.id !== id); if (current?.id === id) current = null; }
- if (kind === 'zones' && zonesId === id) zonesId = null;
- if (kind === 'followups' && followupId === id) followupId = null;
- await refresh(); await reloadCase(); toast('Moved to Trash', 'ok');
- }
-</script>
-
-<aside class="cmp-dock" aria-label="Detect">
- <header>
- <strong>Detect</strong>
- <button
- class="cmp-icon"
- class:on={showZones}
- aria-label={showZones ? 'Hide the analysis areas' : 'Show the analysis areas'}
- aria-pressed={showZones}
- title={showZones ? 'Hide the areas' : 'Show the areas'}
- onclick={() => (showZones = !showZones)}
- >
- <Icon name={showZones ? 'eye' : 'eyeOff'} size={15} />
- </button>
- <button class="cmp-icon" onclick={onclose} aria-label="Leave Detect mode" title="Back to side by side">
- <Icon name="x" size={14} />
- </button>
- </header>
-
- <div class="cmp-seg fill views">
- <button class:on={view === 'setup'} onclick={() => (view = 'setup')}>Setup</button>
- <button class:on={view === 'results'} disabled={!current && !layers.length} onclick={() => (view = 'results')}>
- Results{candidates.length ? ` · ${candidates.length}` : ''}
- </button>
- <button class:on={view === 'saved'} onclick={() => (view = 'saved')}>Saved</button>
- </div>
-
- <div class="cmp-dock-body">
- {#if needs}
- <p class="warn needs">
- {needs}
- <button class="btn btn-sm" onclick={onsettings}>Open Settings</button>
- </p>
- {/if}
- {#if error}<p class="warn" role="alert">{error}</p>{/if}
- {#if !catalogue}<p class="hint">Reading the local analyzer library…</p>{/if}
-
- {#if view === 'setup' && recipe}
- <!-- 1 · Area -->
- <section class="cmp-step" class:done={zones.length > 0} aria-label="Area">
- <header>
- <span class="cmp-step-n">1</span>
- <strong>Area</strong>
- {#if zones.length}<span class="count">{zones.length}</span>{/if}
- </header>
- <div class="row wrap">
- {#each [['rect', 'Rectangle'], ['polygon', 'Polygon'], ['ellipse', 'Circle']] as [kind, label]}
- <button class="btn btn-sm" class:active={drawing === kind} disabled={zones.length >= 32}
- onclick={() => { drawing = drawing === kind ? 'select' : kind; showZones = true; }}>{label}</button>
- {/each}
- <button class="btn btn-sm" disabled={zones.length >= 32} onclick={onusecurrentview}>Use current view</button>
- </div>
- {#if drawing !== 'select'}
- <p class="hint">{drawing === 'polygon' ? 'Click corners on either map; Enter finishes, Escape cancels.' : 'Drag on either map. Escape cancels.'}</p>
- {:else if !zones.length}
- <p class="hint">Draw on either map, take the current view, or open a saved set.</p>
- {/if}
- {#if zones.length}
- {#each zones as zone (zone.id)}
- <div class="row area-row">
- <button class="cmp-icon" aria-label={`Show ${zone.name}`} title={`Show ${zone.name}`}
- onclick={() => { selectedZone = zone.id; drawing = 'select'; focus(zone.points[0]); }}>
- <Icon name="pin" size={13} />
- </button>
- <input class="grow" aria-label="Area name" bind:value={zone.name} maxlength="120" />
- <button class="cmp-icon" aria-label={`Remove ${zone.name}`} title={`Remove ${zone.name}`} onclick={() => removeZone(zone.id)}>
- <Icon name="x" size={12} />
- </button>
- </div>
- {/each}
- <p class="hint" class:warn={tooMany}>{[
- `${round(cost.km2, cost.km2 < 10 ? 2 : 0)} km²`,
- Number.isFinite(cost.tiles) ? plural(cost.tiles, 'tile') : 'over the tile limit',
- tooMany ? '' : `${plural(frames, 'request')}, about ${duration}`,
- ].filter(Boolean).join(' · ')}</p>
- <div class="row">
- <input class="grow" aria-label="Area set name" bind:value={zonesTitle} maxlength="120" />
- <button class="btn btn-sm" disabled={busy} onclick={() => act(() => saveAreas())}>Save</button>
- {#if zonesId}<button class="btn btn-sm" disabled={busy} onclick={() => act(() => saveAreas(true))}>As new</button>{/if}
- </div>
- {/if}
- </section>
-
- <!-- 2 · Imagery -->
- <section class="cmp-step" class:done={pinned || !!mapPair} aria-label="Imagery">
- <header>
- <span class="cmp-step-n">2</span>
- <strong>Imagery</strong>
- <span class="chip">{pinned ? 'On the maps' : 'From the maps'}</span>
- </header>
- {#if tookOver}
- <p class="hint">Detect reads Sentinel-2, so the maps now show it.</p>
- {/if}
- <p class="pair">
- {#if !single}{sourceLabel(a)} <Icon name="arrowRight" size={11} />{/if} {sourceLabel(b)}
- </p>
- <div class="row">
- <button class="link" onclick={() => (showImagery = !showImagery)} aria-expanded={showImagery}>
- {showImagery ? 'Hide imagery settings' : 'Change dates or the rule…'}
- </button>
- {#if pinned && mapPair && !tookOver}<button class="link" onclick={followMaps}>Back to the map's imagery</button>{/if}
- </div>
- {#if showImagery}
- <label title="Keep explicit dates, compare to a fixed reference, or use the last completed run.">Dates
- <select aria-label="Date rule" bind:value={dateRule}>
- <option value="manual">Choose images</option>
- <option value="latest_reference">Latest against fixed reference</option>
- <option value="latest_previous">Latest against previous run</option>
- </select>
- </label>
- {#if !single || dateRule === 'manual'}
- <AcquisitionPicker
- list={passes}
- days={passDays}
- busy={passBusy}
- error={passError}
- truncated={passTruncated}
- searched={passSearched}
- areas={zones.length}
- {single}
- wantsReference={!single}
- wantsCompare={dateRule === 'manual'}
- a={a.date}
- b={b.date}
- ondays={(value) => { passDays = value; passSearched = false; passes = []; }}
- onlook={lookUpPasses}
- onpick={usePass}
- />
- {/if}
- {#each coverWarnings as note}<p class="warn">{note}</p>{/each}
- <label title="The picture you review. Detection reads the bands, whatever this shows.">Picture
- <select value={b.layer} onchange={(e) => { pinned = true; b = { ...b, layer: e.currentTarget.value }; a = { ...a, 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; some cloud can remain within a scene.">Maximum cloud cover · {b.maxcc}%
- <input type="range" min="0" max="100" value={b.maxcc} oninput={(e) => { pinned = true; b = { ...b, maxcc: Number(e.currentTarget.value) }; a = { ...a, maxcc: Number(e.currentTarget.value) }; }} />
- </label>
- {#if dateRule !== 'manual'}
- <p class="hint">Run looks up recent passes when you press it. Nothing downloads on its own.</p>
- {/if}
- <label class="check" title="Read only the tile cache and frames kept from earlier runs; a missing input stops the run rather than reaching the network.">
- <input type="checkbox" bind:checked={offline} /> Use local images only
- </label>
- {/if}
- </section>
-
- <!-- 3 · What to look for -->
- <section class="cmp-step done" aria-label="What to look for">
- <header><span class="cmp-step-n">3</span><strong>What to look for</strong></header>
- <div class="row">
- <label class="grow">
- <select aria-label="Analyzer" value={chosen} onchange={(e) => choose(e.currentTarget.value)}>
- <optgroup label="Built in">{#each catalogue?.builtins ?? [] as r}<option value={r.id}>{r.name}</option>{/each}</optgroup>
- {#if catalogue?.custom?.length}
- <optgroup label="Mine">{#each catalogue.custom as r}<option value={r.id}>{r.name}</option>{/each}</optgroup>
- {/if}
- {#if draft}
- <option value="custom">{recipe.name} — not saved yet</option>
- {:else if ![...(catalogue?.builtins ?? []), ...(catalogue?.custom ?? [])].some((r) => r.id === chosen)}
- <option value={chosen}>{recipe.name} (from a saved run)</option>
- {/if}
- </select>
- </label>
- <button class="cmp-icon" aria-label="New analyzer" aria-expanded={showNew}
- title="Make an analyzer of your own" onclick={() => (showNew = !showNew)}>
- <Icon name="plus" size={15} />
- </button>
- </div>
- {#if showNew}
- <div class="new-menu" role="group" aria-label="New analyzer">
- <button type="button" onclick={() => startNew('copy')}>
- Copy “{recipe.name}”<small>Its settings, under a name of your own.</small>
- </button>
- <button type="button" onclick={() => startNew('blank')}>
- Start from scratch<small>Any surface change, at a medium target size.</small>
- </button>
- </div>
- {/if}
- {#if recipe.description}<p class="hint">{recipe.description}</p>{/if}
- {#if capability.sizes}
- <div class="cmp-seg fill" role="group" aria-label="Target size">
- {#each SIZES as [name, label] (name)}
- {#if capability.sizes[name]}
- <button type="button" class:on={size === name} aria-pressed={size === name}
- title={sizeBand(capability.sizes[name])}
- onclick={() => setSize(name)}>{label}</button>
- {/if}
- {/each}
- </div>
- <p class="hint">
- {size ? sizeBand(capability.sizes[size]) : 'Sizes are set by hand below.'}
- </p>
- {/if}
- {#if capability.clouds}
- <CloudFilter
- clouds={recipe.parameters.ignore_clouds}
- shadows={recipe.parameters.ignore_shadows}
- ontoggle={setWeather}
- />
- {/if}
- <div class="row">
- <button class="link" onclick={() => (showDetection = !showDetection)} aria-expanded={showDetection}>
- {showDetection ? 'Hide thresholds' : 'Adjust thresholds…'}
- </button>
- <button class="link" onclick={() => (showRecipe = !showRecipe)} aria-expanded={showRecipe}>
- {showRecipe ? 'Hide this analyzer' : mine || draft ? 'Edit this analyzer…' : 'See how it is built…'}
- </button>
- </div>
- {#if showDetection}
- <label title="Higher finds fainter signals, and more noise with them.">Sensitivity · {recipe.parameters.sensitivity}
- <input aria-label="Analyzer sensitivity" type="range" min="0" max="100" bind:value={recipe.parameters.sensitivity} />
- </label>
- <div class="row">
- <label class="grow" title="Drop candidates smaller than this.">Min area (m²)
- <input aria-label="Minimum area" type="number" min="0" max="100000000" bind:value={recipe.parameters.min_area} />
- </label>
- <label class="grow" title="Drop candidates larger than this; 0 keeps them all.">Max area (m²)
- <input aria-label="Maximum area" type="number" min="0" max="100000000" bind:value={recipe.parameters.max_area} />
- </label>
- </div>
- {#if recipe.method === 'index'}
- <label>Index
- <select aria-label="Spectral index" bind:value={recipe.parameters.index}>
- {#each INDICES as [id, label] (id)}<option value={id}>{label}</option>{/each}
- </select>
- </label>
- {/if}
- {#if !single}
- <label title="Keep what brightened, what darkened, or both.">Direction
- <select bind:value={recipe.parameters.direction}><option value="both">Both</option><option value="gain">Gain</option><option value="loss">Loss</option></select>
- </label>
- {/if}
- {#if capability.clouds}
- <label class="check"><input type="checkbox" bind:checked={recipe.parameters.ignore_clouds} /> Exclude cloud and snow</label>
- <label class="check"><input type="checkbox" bind:checked={recipe.parameters.ignore_shadows} /> Exclude cloud shadow</label>
- <label title="Grow the mask past the edge the classification drew.">Mask margin · {recipe.parameters.cloud_margin}px
- <input aria-label="Cloud mask margin" type="range" min="0" max="10" bind:value={recipe.parameters.cloud_margin} />
- </label>
- {/if}
- <details>
- <summary>Noise and grouping</summary>
- <label title="Remove specks narrower than this; it also removes small real objects.">Noise cleanup · {recipe.parameters.cleanup}px<input type="range" min="0" max="3" bind:value={recipe.parameters.cleanup} /></label>
- <label title="Blur the reading first; zero keeps the finest detail.">Smoothing · {recipe.parameters.smoothing}px<input type="range" min="0" max="3" bind:value={recipe.parameters.smoothing} /></label>
- <label title="Join candidates this close; zero joins only touching ones.">Group within (m)<input type="number" min="0" max="500" bind:value={recipe.parameters.merge_metres} /></label>
- </details>
- {/if}
- {#if showRecipe}
- <label title="The name shown in the analyzer library across all cases.">Name<input aria-label="Analyzer name" bind:value={recipe.name} maxlength="120" /></label>
- <label title="What this analyzer looks for, and what it cannot tell you.">Description<textarea bind:value={recipe.description} maxlength="500"></textarea></label>
- <label title="The label each candidate carries. It does not change what is detected.">Candidate label<input bind:value={recipe.phenomenon} maxlength="120" /></label>
- <label title="What is measured. None of these recognise objects.">Method
- <select aria-label="Analyzer method" bind:value={recipe.method}>
- {#each catalogue?.methods ?? [] as method}<option value={method.id}>{method.label}</option>{/each}
- </select>
- </label>
- <div class="row">
- <label class="grow">Colour<input type="color" bind:value={recipe.colour} /></label>
- <label class="grow">Layer style
- <select bind:value={recipe.style}>
- <option value="both">Pins and outlines</option><option value="pins">Pins</option><option value="outlines">Outlines with pins</option>
- </select>
- </label>
- </div>
- <label class="check" title="Store a copy of these areas in the shared analyzer; past runs keep their own copy.">
- <input type="checkbox" bind:checked={attachZones} /> Keep these areas with the analyzer
- </label>
- <div class="row">
- {#if mine || draft}
- <button class="btn btn-sm" disabled={busy} onclick={() => act(() => saveRecipe())}>
- {draft ? 'Add to my analyzers' : 'Save changes'}
- </button>
- {/if}
- {#if !draft}
- <button class="btn btn-sm" disabled={busy} onclick={() => act(() => saveRecipe(true))}>Save as a copy</button>
- {/if}
- {#if mine}
- <button class="btn btn-sm danger" disabled={busy} onclick={() => act(() => deleteRecipe())}>Delete</button>
- {/if}
- </div>
- <p class="hint">
- {mine || draft ? 'Shared by every case, and carried by Settings backup.'
- : 'A built-in cannot be written over. Saving a copy keeps your version beside it.'}
- </p>
- {/if}
- </section>
- {/if}
-
- {#if view === 'results'}
- {#if current}
- <section class="run">
- <div class="row run-head">
- <strong class="grow">{current.title}</strong>
- {#if current.status === 'ready'}
- <button class="link" onclick={() => { hydrate(current.input); view = 'setup'; }}>Edit and rerun</button>
- {/if}
- </div>
- <p class="hint">{[
- statusLabel(current.status),
- current.status === 'ready' ? plural(current.total, 'tile') : `${current.progress}/${current.total} tiles`,
- current.input?.b ? dates(current.input) : '',
- ].filter(Boolean).join(' · ')}</p>
- {#if pending}
- <progress max={current.total} value={current.progress}></progress>
- <button class="btn btn-sm" disabled={busy}
- onclick={() => act(async () => acceptRun(await api.post(`${base()}/runs/${current.id}/cancel`, {})))}>Cancel</button>
- {/if}
- {#if current.message}<p class="hint" role="status">{current.message}</p>{/if}
- <!-- "Nothing found" and "never looked" are not the same answer. -->
- {#if sweptNote(current.swept)}<p class="warn">{sweptNote(current.swept)}</p>{/if}
- {#if current.status === 'ready' && !candidates.length}<p class="hint">Nothing passed these thresholds.</p>{/if}
- </section>
- {:else}
- <p class="hint">Run an analyzer, or open a saved run from Saved.</p>
- {/if}
-
- {#if candidate}
- <section class="candidate">
- <div class="row nav">
- <button class="cmp-icon" aria-label="Previous candidate" title="Previous candidate" onclick={() => step(-1)}><Icon name="chevronLeft" size={14} /></button>
- <span class="grow centre position">{candidates.findIndex((r) => r.id === candidateId) + 1} of {candidates.length}</span>
- <button class="cmp-icon" aria-label="Next candidate" title="Next candidate" onclick={() => step(1)}><Icon name="chevronRight" size={14} /></button>
- </div>
- <strong>{candidate.phenomenon}</strong>
- <img class="preview" src={`${base()}/runs/${current.id}/results/${candidate.id}/preview`}
- alt={methodOf(current.input.recipe.method).single ? 'Candidate evidence' : 'Candidate evidence: A on the left, B on the right'} />
- {#if reading(candidate, current.input)}
- <p class={`strength ${candidate.strength ?? ''}`}>{reading(candidate, current.input)}</p>
- {/if}
- <p class="facts">
- {Math.round(candidate.area)} m² · {Math.round(candidate.width)} × {Math.round(candidate.height)} m ·
- <button class="link inline" onclick={() => focus(candidate.coordinates)}>
- {candidate.coordinates[1].toFixed(5)}, {candidate.coordinates[0].toFixed(5)}
- </button>
- </p>
-
- <!-- Two verdicts and nothing in between: keeping is what writes to the
- case, dismissing is what takes a candidate off the map. -->
- {#if candidate.review === 'kept'}
- <p class="verdict kept"><Icon name="check" size={13} /> Kept as a pin in this case</p>
- <button class="link" disabled={busy} onclick={() => act(undoKeep)}>Undo and send the pin to Trash</button>
- {:else if candidate.review === 'dismissed'}
- <p class="verdict off"><Icon name="eyeOff" size={13} /> Dismissed · hidden on the map</p>
- <button class="link" disabled={busy} onclick={() => act(() => review('new'))}>Put it back among the candidates</button>
- {:else}
- <div class="row verdict-row">
- <button class="btn btn-primary grow" disabled={busy} onclick={() => act(keep)}>Keep as a pin</button>
- <button class="btn btn-sm" disabled={busy} onclick={() => act(() => review('dismissed'))}>Dismiss</button>
- </div>
- {/if}
- <p class="hint">{tally}</p>
- </section>
- {/if}
-
- {#if layers.length}
- <section>
- <strong>Result layers</strong>
- {#each layers as layer (layer.id)}
- <div class="row">
- <button class="cmp-icon" aria-label={`Toggle ${layer.title}`} title={`Toggle ${layer.title}`} aria-pressed={layer.visible}
- onclick={() => { layer.visible = !layer.visible; }}>
- <Icon name={layer.visible ? 'eye' : 'eyeOff'} size={15} />
- </button>
- <button class="link grow" onclick={() => { current = layer; candidateId = layer.results[0]?.id; }}>
- {layer.title} · {layer.count}
- </button>
- </div>
- {/each}
- </section>
- {/if}
- {/if}
-
- {#if view === 'saved'}
- <section>
- <strong>Watches</strong>
- <p class="hint">An analyzer, its areas and a date rule. Run one again whenever you want; nothing runs on its own.</p>
- {#if !lists.followups.length}<p class="hint">None saved in this case.</p>{/if}
- {#each lists.followups as row (row.id)}
- <div class="row">
- <button class="link grow" disabled={busy} onclick={() => act(() => openItem('followups', row.id))}>
- {row.title}<small>{row.created_at}</small>
- </button>
- <button class="btn btn-sm" disabled={busy || pending} onclick={() => act(() => runWatch(row.id))}>Run again</button>
- <button class="cmp-icon" disabled={busy} aria-label={`Delete ${row.title}`} title={`Delete ${row.title}`} onclick={() => act(() => removeItem('followups', row.id))}>
- <Icon name="trash" size={13} />
- </button>
- </div>
- {/each}
- </section>
- {#each [['zones', 'Area sets'], ['runs', 'Past runs']] as [kind, label]}
- <section>
- <strong>{label}</strong>
- {#if !lists[kind].length}<p class="hint">None saved in this case.</p>{/if}
- {#each lists[kind] as row (row.id)}
- <div class="row">
- <button class="link grow" disabled={busy} onclick={() => act(() => openItem(kind, row.id))}>
- {row.title}<small>{row.created_at}{row.status ? ` · ${statusLabel(row.status)}` : ''}</small>
- </button>
- <button class="cmp-icon" disabled={busy || ['queued', 'running'].includes(row.status)}
- aria-label={`Delete ${row.title}`} title={`Delete ${row.title}`} onclick={() => act(() => removeItem(kind, row.id))}>
- <Icon name="trash" size={13} />
- </button>
- </div>
- {/each}
- </section>
- {/each}
- {/if}
- </div>
-
- {#if view === 'setup'}
- <div class="cmp-dock-foot">
- <input aria-label="Analysis name" placeholder={recipe ? `${recipe.name} · ${new Date().toISOString().slice(0, 10)}` : 'Name'}
- bind:value={title} maxlength="120" />
- <button class="btn btn-primary" disabled={busy || !recipe || !!blocked} onclick={() => act(run)}>
- {busy ? 'Starting…' : `Run on ${zones.length || 'no'} area${zones.length === 1 ? '' : 's'}`}
- </button>
- {#if blocked}
- <span class="reason">{blocked}</span>
- {:else}
- <button class="link centre" disabled={busy} onclick={() => act(() => saveWatch(!followupId))}>
- {followupId ? 'Update this watch' : 'Save as a watch to run again later'}
- </button>
- {/if}
- </div>
- {/if}
-</aside>
-
-<style>
- .needs {
- display: grid;
- gap: 6px;
- justify-items: start;
- }
- .views { margin: 10px 12px 0; }
- /* The two ways to start one of your own, said in full rather than implied by
- a "duplicate" button next to a save. */
- .new-menu {
- display: grid;
- gap: 2px;
- padding: 4px;
- border: 1px solid var(--border);
- border-radius: var(--r-sm);
- background: var(--bg-2);
- }
- .new-menu button {
- display: grid;
- gap: 1px;
- padding: 6px 8px;
- border-radius: var(--r-sm);
- text-align: left;
- font-size: var(--fs-xs);
- color: var(--text-1);
- }
- .new-menu button:hover { background: var(--bg-3); }
- .new-menu small { color: var(--text-3); font-size: 10.5px; }
- .btn.danger { color: var(--warn); }
- .row.wrap { flex-wrap: wrap; }
- .area-row input { font-size: var(--fs-xs); }
- .count {
- padding: 1px 6px;
- border-radius: 99px;
- color: var(--text-2);
- background: var(--bg-3);
- font-size: 10px;
- }
- .chip {
- padding: 1px 6px;
- border-radius: 99px;
- color: var(--accent);
- background: var(--accent-soft);
- font-size: 10px;
- font-weight: 600;
- }
- .pair {
- display: flex;
- align-items: center;
- gap: 5px;
- margin: 0;
- color: var(--text-1);
- font-size: var(--fs-xs);
- overflow-wrap: anywhere;
- }
- section { display: grid; gap: 7px; }
- section.run, section.candidate { border-top: 1px solid var(--border); padding-top: 10px; }
- section > strong, .run-head strong { font-size: var(--fs-xs); }
- details { display: grid; gap: 8px; }
- details[open] { padding-top: 4px; }
- summary { color: var(--text-2); font-size: var(--fs-xs); cursor: pointer; }
- .link { color: var(--accent); font-size: var(--fs-xs); text-align: left; }
- .link:disabled { opacity: 0.5; }
- .link small { display: block; color: var(--text-3); font-size: 10px; }
- .link.inline { display: inline; font-family: var(--font-mono); font-size: 11px; }
- .centre { text-align: center; }
- .nav { justify-content: space-between; }
- .position { color: var(--text-2); font-size: var(--fs-xs); }
- .facts { margin: 0; color: var(--text-2); font-size: var(--fs-xs); line-height: 1.5; }
- .strength { margin: 0; font-size: var(--fs-xs); font-weight: 600; color: var(--text-1); }
- .strength.strong { color: var(--ok); }
- .strength.weak { color: var(--text-3); }
- .verdict { display: flex; align-items: center; gap: 5px; margin: 0; font-size: var(--fs-xs); font-weight: 600; }
- .verdict.kept { color: var(--ok); }
- .verdict.off { color: var(--text-3); }
- .verdict-row { gap: 6px; }
- .preview { width: 100%; max-height: 280px; object-fit: contain; border-radius: var(--r-sm); background: var(--bg-0); }
- progress { width: 100%; accent-color: var(--accent); }
- .active { outline: 1px solid var(--accent); }
-</style>
diff --git a/frontend/src/tools/compare/AnalyzerPanel.test.js b/frontend/src/tools/compare/AnalyzerPanel.test.js
deleted file mode 100644
index b300f5f..0000000
--- a/frontend/src/tools/compare/AnalyzerPanel.test.js
+++ /dev/null
@@ -1,297 +0,0 @@
-// @vitest-environment happy-dom
-import { beforeEach, afterEach, expect, it, vi } from 'vitest';
-import { flushSync, mount, unmount } from 'svelte';
-
-const sizes = {
- small: { min_area: 300, max_area: 0, cleanup: 0, smoothing: 0, merge_metres: 0 },
- medium: { min_area: 2000, max_area: 0, cleanup: 1, smoothing: 0, merge_metres: 30 },
- large: { min_area: 20000, max_area: 0, cleanup: 1, smoothing: 1, merge_metres: 100 },
-};
-const recipe = { id: 'large-change', name: 'Any surface change', description: 'Reflectance that moved',
- phenomenon: 'Surface change', method: 'surface', zones: [], colour: '#f6a81a', style: 'both',
- parameters: { sensitivity: 67, ...sizes.medium, index: 'ndvi', direction: 'both',
- ignore_clouds: true, ignore_shadows: true, cloud_margin: 5 } };
-const vessels = { ...recipe, id: 'boats', name: 'Vessels', method: 'vessels', phenomenon: 'Vessel candidate' };
-const methods = [
- { id: 'surface', label: 'Any reflectance change', single: false, clouds: true, sizes,
- measure: 'Reflectance moved by {value}%' },
- { id: 'vessels', label: 'Vessels', single: true, clouds: true, sizes,
- measure: '{value}× brighter than the water around it' },
- { id: 'hotspots', label: 'Hotspots', single: true, clouds: false, sizes,
- measure: 'Short-wave infrared {value}× the bands beside it' },
-];
-const catalogue = (extra = {}) => ({ builtins: [structuredClone(recipe), structuredClone(vessels)],
- custom: [], methods, max_tiles: 4096, max_results: 2000, grid: [13, 512], ...extra });
-const get = vi.fn();
-const post = vi.fn();
-const patch = vi.fn();
-const del = vi.fn();
-vi.mock('../../lib/api.js', () => ({ api: { get, post, patch, put: vi.fn(), del } }));
-vi.mock('../../lib/state.svelte.js', () => ({ ensureCase: async () => ({ id: 'case-a' }),
- reloadCase: async () => {}, toast: vi.fn() }));
-const { default: Panel } = await import('./AnalyzerPanel.svelte');
-let live, target;
-const settle = async () => { for (let i = 0; i < 50; i++) await Promise.resolve(); flushSync(); };
-const button = (text) => [...target.querySelectorAll('button')].find((b) => b.textContent.trim() === text);
-const maps = {
- a: { provider: 'sentinel2', sentinel: { date: '2026-05-04', layer: 'TRUE_COLOR', maxcc: 30 } },
- b: { provider: 'sentinel2', sentinel: { date: '2026-05-11', layer: 'TRUE_COLOR', maxcc: 30 } },
-};
-const area = [{ id: 'area', name: 'Area', kind: 'rect', points: [[2, 48], [2.001, 48.001]] }];
-
-beforeEach(() => {
- vi.clearAllMocks();
- get.mockImplementation(async (path) => path === '/api/compare/analyzers' ? catalogue() : []);
- target = document.createElement('div'); document.body.append(target);
-});
-afterEach(() => { if (live) unmount(live); target.remove(); });
-
-it('opening reads local libraries without downloading imagery or starting a calculation', async () => {
- live = mount(Panel, { target, props: { caseId: 'case-a' } });
- await settle();
- expect(get.mock.calls.map(([path]) => path).sort()).toEqual([
- '/api/cases/case-a/analysis/followups', '/api/cases/case-a/analysis/runs',
- '/api/cases/case-a/analysis/zones', '/api/compare/analyzers',
- ]);
- expect(post).not.toHaveBeenCalled();
- expect(button('Run on no areas').disabled).toBe(true);
- expect(target.textContent).toContain('Draw an area to analyze');
-});
-
-it('takes its imagery from the two maps, and only Run sends anything', async () => {
- post.mockImplementation(async (_, body) => ({ id: '123456789abc', title: body.title,
- status: 'failed', message: 'Offline fixture', progress: 0, total: 1, input: body, results: [] }));
- live = mount(Panel, { target, props: { caseId: 'case-a', zones: area, sources: maps } });
- await settle();
- // No click on an imagery control: the maps above the stage already said it.
- expect(target.textContent).toContain('From the maps');
- expect(target.textContent).toContain('2026-05-04');
- expect(post).not.toHaveBeenCalled();
- button('Run on 1 area').click(); await settle();
- expect(post).toHaveBeenCalledWith('/api/cases/case-a/analysis/runs', expect.objectContaining({
- zones: area,
- a: { provider: 'sentinel2', date: '2026-05-04', layer: 'TRUE_COLOR', maxcc: 30 },
- b: { provider: 'sentinel2', date: '2026-05-11', layer: 'TRUE_COLOR', maxcc: 30 },
- }));
- expect(target.textContent).toContain('Offline fixture');
-});
-
-it('takes the wheel when the maps show imagery Detect cannot read', async () => {
- const onsources = vi.fn();
- const wayback = { a: { provider: 'esri-wayback', wayback_release: 1 }, b: { provider: 'esri-wayback', wayback_release: 2 } };
- live = mount(Panel, { target, props: { caseId: 'case-a', zones: area, sources: wayback, onsources } });
- await settle();
- expect(target.textContent).toContain('Detect reads Sentinel-2, so the maps now show it.');
- expect(onsources).toHaveBeenCalledWith(expect.objectContaining({
- a: expect.objectContaining({ provider: 'sentinel2' }), b: expect.objectContaining({ provider: 'sentinel2' }),
- }));
- expect(target.querySelector('select[aria-label="Analyzer source"]')).toBe(null);
- expect(button('Run on 1 area').disabled).toBe(true);
- expect(target.textContent).toContain('Choose the image to compare');
-});
-
-it('prices an area in tiles and requests, and refuses one the engine would reject', async () => {
- const zones = [{ id: 'big', name: 'Whole region', kind: 'rect', points: [[2, 48], [8, 54]] }];
- get.mockImplementation(async (path) => path === '/api/compare/analyzers' ? catalogue({ max_tiles: 256 }) : []);
- live = mount(Panel, { target, props: { caseId: 'case-a', zones, sources: maps } });
- await settle();
- expect(button('Run on 1 area').disabled).toBe(true);
- expect(target.textContent).toContain('the limit is 256');
- unmount(live); target.remove();
- target = document.createElement('div'); document.body.append(target);
- live = mount(Panel, { target, props: { caseId: 'case-a', zones: area, sources: maps } });
- await settle();
- // one tile, a picture and a band product for each of two dates
- expect(target.textContent).toContain('1 tile · 4 requests');
- expect(post).not.toHaveBeenCalled();
-});
-
-it('sets a size as a whole set of numbers, and shows when it was tuned by hand', async () => {
- live = mount(Panel, { target, props: { caseId: 'case-a' } });
- await settle();
- const pressed = () => [...target.querySelectorAll('[aria-label="Target size"] button')]
- .filter((b) => b.getAttribute('aria-pressed') === 'true').map((b) => b.textContent.trim());
- expect(pressed()).toEqual(['Medium']);
- button('Small').click(); await settle();
- expect(pressed()).toEqual(['Small']);
- button('Adjust thresholds…').click(); await settle();
- expect(target.querySelector('[aria-label="Minimum area"]').value).toBe('300');
- const minimum = target.querySelector('[aria-label="Minimum area"]');
- minimum.value = '120'; minimum.dispatchEvent(new Event('input', { bubbles: true })); await settle();
- expect(pressed()).toEqual([]);
-});
-
-it('offers the cloud switch on by default, and none for a method that rejects cloud itself', async () => {
- live = mount(Panel, { target, props: { caseId: 'case-a' } });
- await settle();
- const chip = [...target.querySelectorAll('button')].find((b) => b.textContent.includes('Clouds & shadows'));
- expect(chip.getAttribute('aria-pressed')).toBe('true');
- expect(target.textContent).toContain('traced from the sun');
- unmount(live); target.remove();
- target = document.createElement('div'); document.body.append(target);
- get.mockImplementation(async (path) => path === '/api/compare/analyzers'
- ? catalogue({ builtins: [{ ...structuredClone(recipe), id: 'anomaly', method: 'hotspots' }] }) : []);
- live = mount(Panel, { target, props: { caseId: 'case-a' } });
- await settle();
- expect(target.textContent).not.toContain('Clouds & shadows');
-});
-
-it('starts an analyzer of your own from the plus, and cannot write over a built-in', async () => {
- post.mockImplementation(async (_, body) => ({ ...body, id: 'custom-copy' }));
- live = mount(Panel, { target, props: { caseId: 'case-a' } }); await settle();
- // A built-in offers to be read and copied, never saved over.
- button('See how it is built…').click(); await settle();
- expect(target.textContent).not.toContain('Works on Wayback');
- expect(button('Save changes')).toBeUndefined();
- expect(button('Delete')).toBeUndefined();
- button('Hide this analyzer').click(); await settle();
-
- target.querySelector('button[aria-label="New analyzer"]').click(); await settle();
- const copy = [...target.querySelectorAll('.new-menu button')]
- .find((entry) => entry.textContent.includes(`Copy “${recipe.name}”`));
- copy.click(); await settle();
- expect(target.querySelector('[aria-label="Analyzer"]').value).toBe('custom');
- expect(target.textContent).toContain('not saved yet');
- const name = target.querySelector('[aria-label="Analyzer name"]');
- expect(name.value).toBe(`${recipe.name} copy`);
- name.value = 'Weekly harbour'; name.dispatchEvent(new Event('input', { bubbles: true }));
- button('Add to my analyzers').click(); await settle();
- expect(post).toHaveBeenCalledWith('/api/compare/analyzers', expect.objectContaining({ id: 'custom', name: 'Weekly harbour' }));
-});
-
-it('edits and removes an analyzer of its own, which the library never did offer', async () => {
- const own = { ...structuredClone(recipe), id: 'custom-1', name: 'Weekly harbour' };
- get.mockImplementation(async (path) => path === '/api/compare/analyzers' ? catalogue({ custom: [own] }) : []);
- live = mount(Panel, { target, props: { caseId: 'case-a' } }); await settle();
- const select = target.querySelector('[aria-label="Analyzer"]');
- select.value = 'custom-1'; select.dispatchEvent(new Event('change', { bubbles: true }));
- await settle();
- button('Edit this analyzer…').click(); await settle();
- expect(button('Save changes')).toBeDefined();
- button('Delete').click(); await settle();
- expect(del).toHaveBeenCalledWith('/api/compare/analyzers/custom-1');
-});
-
-it('reviews candidates one at a time, says how strong each is, and only keeping reaches the case', async () => {
- const row = (id, lon, strength, value) => ({ id, coordinates: [lon, 48], bbox: [lon, 48, lon + 0.001, 48.001],
- area: 90, width: 15, height: 6, margin: 2, strength, measure: { value }, review: 'new',
- phenomenon: 'Surface change', parts: [{ frames: ['a', 'b'], box: [0, 0, 4, 4] }, { frames: ['c', 'd'], box: [0, 0, 2, 4] }] });
- const saved = { id: '123456789abc', title: 'Harbour sweep', status: 'ready', progress: 1, total: 1,
- count: 2, engine_version: 2, results: [row('0-1', 2, 'strong', 12.34), row('0-2', 2.002, 'weak', 8)],
- input: { title: 'Harbour sweep', zones: area, recipe: structuredClone(recipe),
- a: { provider: 'sentinel2', date: '2026-05-04' }, b: { provider: 'sentinel2', date: '2026-05-11' },
- offline: false, date_rule: 'manual', followup_id: null } };
- get.mockImplementation(async (path) => {
- if (path === '/api/compare/analyzers') return catalogue();
- if (path === '/api/cases/case-a/analysis/runs/123456789abc') return structuredClone(saved);
- return [];
- });
- patch.mockImplementation(async (_, body) => ({ ...saved.results[0], ...body }));
- post.mockImplementation(async () => ({ entity: { id: 'e1', type: 'place' },
- result: { ...saved.results[1], review: 'kept', entity_id: 'e1' } }));
-
- live = mount(Panel, { target, props: { caseId: 'case-a', opening: 'runs-123456789abc' } });
- await settle();
- expect(target.textContent).toContain('1 of 2');
- expect(target.textContent).toContain('Completed · 1 tile · 2026-05-04 → 2026-05-11');
- expect(target.textContent).toContain('Strong · Reflectance moved by 12.3%');
- expect(target.textContent).toContain('2 still to review · 0 kept, 0 dismissed');
- // a candidate across two tiles is one picture, not pages of parts
- expect(target.textContent).not.toContain('Evidence part');
- expect(target.textContent).not.toContain('Signal score');
- expect(target.querySelector('img.preview').getAttribute('src')).toBe(
- '/api/cases/case-a/analysis/runs/123456789abc/results/0-1/preview');
-
- // Dismissing is a verdict on this one, and it moves on to the next.
- button('Dismiss').click(); await settle();
- expect(patch).toHaveBeenCalledWith(
- '/api/cases/case-a/analysis/runs/123456789abc/results/0-1', { review: 'dismissed' });
- expect(post).not.toHaveBeenCalled();
- expect(target.textContent).toContain('2 of 2');
- expect(target.textContent).toContain('Weak · Reflectance moved by 8.0%');
-
- // Keeping is the one act that files a pin, and it says so where it happened.
- button('Keep as a pin').click(); await settle();
- expect(post).toHaveBeenCalledWith(
- '/api/cases/case-a/analysis/runs/123456789abc/results/0-2/promote',
- { title: 'Surface change · 48.0000, 2.0020' });
- expect(target.textContent).toContain('Kept as a pin in this case');
- expect(target.textContent).toContain('All 2 reviewed · 1 kept, 1 dismissed');
-});
-
-it('picks Copernicus dates from passes the areas have, not from a calendar', async () => {
- post.mockImplementation(async (path) => path === '/api/satellite/sentinel/acquisitions'
- ? { dates: [
- { date: '2026-05-11', cloud: 3, granules: 2, coverage: 1 },
- { date: '2026-05-04', cloud: 12, granules: 1, coverage: 0.62 },
- ], truncated: false }
- : {});
- live = mount(Panel, { target, props: { caseId: 'case-a', zones: area, sources: maps } });
- await settle();
- button('Change dates or the rule…').click(); await settle();
-
- // a bare date field offered every day since 2015 and knew nothing about any
- expect(target.querySelector('input[type="date"]')).toBe(null);
- // local-first: mounting the panel spends no Copernicus request
- expect(post).not.toHaveBeenCalled();
-
- button('Find passes').click(); await settle();
- expect(post).toHaveBeenCalledWith('/api/satellite/sentinel/acquisitions',
- expect.objectContaining({ zones: area }));
- expect(target.textContent).toContain('Full cover');
- expect(target.textContent).toContain('62% of the areas');
-});
-
-it('says what a partial pass will leave unswept before the run, not after', async () => {
- post.mockImplementation(async () => ({
- dates: [{ date: '2026-05-04', cloud: 12, granules: 1, coverage: 0.62 }], truncated: false,
- }));
- live = mount(Panel, { target, props: { caseId: 'case-a', zones: area, sources: maps } });
- await settle();
- button('Change dates or the rule…').click(); await settle();
- button('Find passes').click(); await settle();
- button('B').click(); await settle();
- expect(target.textContent).toContain('reaches 62% of the areas');
- expect(target.textContent).toContain('not swept');
-});
-
-it('runs a saved watch again without asking for its settings twice', async () => {
- const watch = { id: 'abcdef123456', title: 'Harbour weekly', created_at: '2026-09-01T00:00:00Z',
- zones: area, recipe: structuredClone(recipe), a: { provider: 'sentinel2', date: '2026-05-04' },
- b: { provider: 'sentinel2', date: '' }, offline: false, date_rule: 'latest_previous',
- followup_id: 'abcdef123456' };
- get.mockImplementation(async (path) => {
- if (path === '/api/compare/analyzers') return catalogue();
- if (path === '/api/cases/case-a/analysis/followups') return [{ id: watch.id, title: watch.title, created_at: watch.created_at }];
- if (path === `/api/cases/case-a/analysis/followups/${watch.id}`) return watch;
- return [];
- });
- post.mockImplementation(async (_, body) => ({ id: '123456789abc', title: body.title,
- status: 'queued', progress: 0, total: 1, input: body, results: [] }));
- live = mount(Panel, { target, props: { caseId: 'case-a' } });
- await settle();
- button('Saved').click(); await settle();
- button('Run again').click(); await settle();
- expect(post).toHaveBeenCalledWith('/api/cases/case-a/analysis/runs', expect.objectContaining({
- zones: area, date_rule: 'latest_previous', followup_id: watch.id,
- }));
-});
-
-it('reopens a run saved against Wayback without pretending it had a Sentinel-2 date', async () => {
- const old = { id: 'aaaaaaaaaaaa', title: 'Old harbour', status: 'ready', progress: 1, total: 1, count: 0,
- engine_version: 1, results: [],
- input: { title: 'Old harbour', zones: area, recipe: { ...structuredClone(recipe), method: 'colour' },
- a: { provider: 'esri-wayback', release: 1 }, b: { provider: 'esri-wayback', release: 2 },
- offline: false, date_rule: 'manual', followup_id: null } };
- get.mockImplementation(async (path) => {
- if (path === '/api/compare/analyzers') return catalogue();
- if (path === '/api/cases/case-a/analysis/runs/aaaaaaaaaaaa') return structuredClone(old);
- return [];
- });
- live = mount(Panel, { target, props: { caseId: 'case-a', opening: 'runs-aaaaaaaaaaaa' } });
- await settle();
- expect(target.textContent).toContain('Wayback release 1 → Wayback release 2');
- button('Edit and rerun').click(); await settle();
- expect(target.textContent).toContain('no date yet');
- expect(button('Run on 1 area').disabled).toBe(true);
-});
diff --git a/frontend/src/tools/compare/AnnotationCanvas.svelte b/frontend/src/tools/compare/AnnotationCanvas.svelte
index 46f349f..45b312f 100644
--- a/frontend/src/tools/compare/AnnotationCanvas.svelte
+++ b/frontend/src/tools/compare/AnnotationCanvas.svelte
@@ -1,20 +1,27 @@
<script>
import { onMount } from 'svelte';
import {
- STAMPED, glyphBox, markGlyph, markLabel, markSize, movedMark, nextMarkNumber, onSide,
- projectMark, stampInk,
+ ANGLED, STAMPED, TURNABLE, glyphBox, markCentre, markGlyph, markLabel, markSize, markTop,
+ movedMark, nextMarkNumber, onSide, projectMark, stampInk, turnedMark,
} from '../../lib/map/compareAnnotations.js';
+ import { compassAngle } from '../../lib/map/groundFrame.js';
+ import { relayWheel } from '../../lib/map/wheelRelay.js';
import { isSolidIcon } from '../../lib/proofIcons.js';
let { annotations = [], engine, letter = 'a', units = 'metric', active = true,
tool = $bindable('select'), selectedId = $bindable(null), colour = '#f6a81a',
strokeWidth = 4, fillOpacity = 0, annotationSide = 'both', glyph = 'point',
- stampSize = 16, editVertices = false, edgeOnly = false, onchange = () => {} } = $props();
+ stampSize = 16, editVertices = false, edgeOnly = false, bearing = 0, turnable = false,
+ onchange = () => {} } = $props();
let svg = $state();
let revision = $state(0);
let draft = $state(null);
let editor = $state(null);
let gesture = null;
+ // The turn in flight, which the grip follows round: a polygon has no sides of
+ // its own to carry the grip, so without it the grip would stay put under a
+ // pointer circling away from it.
+ let turning = $state(null);
/** Below this, a pointer press is a click: a shape is picked, never nudged. */
const DRAG_SLOP = 4;
@@ -22,6 +29,10 @@
// neither gains anything from grips: one is already dragged whole, the other
// would be buried under its own handles.
const GRIPPED = new Set(['arrow', 'line', 'measure', 'rect', 'ellipse', 'polygon']);
+ /** How far past a mark's top the turn grip stands, in screen pixels. */
+ const TURN_REACH = 26;
+ /** The step a turn snaps to with Shift held, in degrees. */
+ const TURN_STEP = 15;
$effect(() => {
if (!engine) return;
@@ -46,32 +57,29 @@
.map((mark) => ({ mark, shape: projectMark(mark, project), label: markLabel(mark, units),
vertices: editVertices && GRIPPED.has(mark.kind) ? mark.points.map(project) : [] }))
);
- const pathOf = (shape) => shape.path.map(([x, y], i) => `${i ? 'L' : 'M'}${x},${y}`).join(' ') + (shape.closed ? ' Z' : '');
/**
- * The wheel belongs to the map, wherever the pointer happens to be.
- *
- * This overlay is a sibling of the map rather than a child, so a wheel over a
- * mark stopped here and the view would not zoom until the pointer was moved
- * off whatever had been drawn. A press is the mark's; the wheel is handed down
- * to the picture under it.
+ * Where the grip that turns a mark stands: past a box's top edge along its own
+ * up axis, so it turns with the box, or straight above anything else.
*/
- function relayWheel(event) {
- const container = engine?.container;
- if (!container) return;
- const below = document
- .elementsFromPoint(event.clientX, event.clientY)
- .find((element) => !svg?.contains(element) && container.contains(element));
- if (!below) return;
- event.preventDefault();
- below.dispatchEvent(new WheelEvent('wheel', {
- deltaX: event.deltaX, deltaY: event.deltaY, deltaZ: event.deltaZ,
- deltaMode: event.deltaMode,
- clientX: event.clientX, clientY: event.clientY,
- ctrlKey: event.ctrlKey, shiftKey: event.shiftKey,
- altKey: event.altKey, metaKey: event.metaKey,
- bubbles: true, cancelable: true,
- }));
+ function turnGrip(mark, shape) {
+ const centre = project(markCentre(mark));
+ const top = markTop(mark);
+ let dir = [0, -1];
+ let reach = centre[1] - Math.min(...shape.path.map((point) => point[1]));
+ if (top) {
+ const at = project(top);
+ const length = Math.hypot(at[0] - centre[0], at[1] - centre[1]);
+ if (length > 0.5) { dir = [(at[0] - centre[0]) / length, (at[1] - centre[1]) / length]; reach = length; }
+ } else if (turning?.id === mark.id) {
+ const turn = (turning.degrees * Math.PI) / 180;
+ dir = [Math.sin(turn), -Math.cos(turn)];
+ reach = turning.reach;
+ }
+ const edge = [centre[0] + dir[0] * reach, centre[1] + dir[1] * reach];
+ return { edge, at: [edge[0] + dir[0] * TURN_REACH, edge[1] + dir[1] * TURN_REACH], reach };
}
+ const pathOf = (shape) => shape.path.map(([x, y], i) => `${i ? 'L' : 'M'}${x},${y}`).join(' ') + (shape.closed ? ' Z' : '');
+ const relay = (event) => relayWheel(event, { engine, root: svg });
function point(event) {
const box = svg?.getBoundingClientRect();
@@ -86,7 +94,11 @@
// its own colour's series, so deleting #2 and stamping again fills that
// hole, and a symbol carries the glyph in hand.
...(tool === 'number' ? { number: nextMarkNumber(annotations, colour) } : {}),
- ...(tool === 'icon' ? { glyph } : {}) };
+ ...(tool === 'icon' ? { glyph } : {}),
+ // A box drawn on a turned map runs along the screen it was drawn on. Its
+ // angle is the compass direction that was up; the app's bearing turns
+ // the map clockwise, which is that direction counted the other way.
+ ...(ANGLED.has(tool) ? { angle: turnable ? compassAngle(-bearing) : 0 } : {}) };
}
/**
@@ -172,7 +184,16 @@
return;
}
if (gesture && !dragging(event)) return;
- if (gesture?.kind === 'vertex') {
+ if (gesture?.kind === 'turn') {
+ const box = svg.getBoundingClientRect();
+ const [px, py] = gesture.pivot;
+ const heading = Math.atan2(event.clientY - box.top - py, event.clientX - box.left - px) * 180 / Math.PI;
+ let degrees = heading - gesture.heading;
+ if (event.shiftKey) degrees = Math.round(degrees / TURN_STEP) * TURN_STEP;
+ turning = { ...turning, degrees };
+ const turned = turnedMark(gesture.mark, gesture.centre, degrees);
+ onchange(annotations.map((mark) => mark.id === turned.id ? turned : mark), false);
+ } else if (gesture?.kind === 'vertex') {
const points = gesture.mark.points.map((p, i) => i === gesture.index ? at : p);
onchange(annotations.map((m) => m.id === gesture.mark.id ? { ...m, points } : m), false);
} else if (gesture?.kind === 'move') {
@@ -191,7 +212,8 @@
if (!gesture || gesture.kind === 'trail') return;
move(event);
svg.releasePointerCapture?.(event.pointerId);
- if (gesture.kind === 'move' || gesture.kind === 'vertex') {
+ turning = null;
+ if (gesture.kind === 'move' || gesture.kind === 'vertex' || gesture.kind === 'turn') {
// A press that never became a drag only selected something, so it leaves
// no entry to undo and no geometry to save.
if (gesture.live) onchange(annotations, true);
@@ -235,6 +257,20 @@
from: { x: event.clientX, y: event.clientY }, live: false };
svg.setPointerCapture?.(event.pointerId);
}
+ /** Take hold of a mark's turn grip: it turns about its centre as the pointer circles it. */
+ function turnStart(event, mark, grip) {
+ if (!active || event.button > 0) return;
+ event.preventDefault(); event.stopPropagation();
+ selectedId = mark.id;
+ const centre = markCentre(mark);
+ const pivot = project(centre);
+ const box = svg.getBoundingClientRect();
+ gesture = { kind: 'turn', mark: JSON.parse(JSON.stringify(mark)), centre, pivot,
+ heading: Math.atan2(event.clientY - box.top - pivot[1], event.clientX - box.left - pivot[0]) * 180 / Math.PI,
+ from: { x: event.clientX, y: event.clientY }, live: false };
+ turning = { id: mark.id, degrees: 0, reach: grip.reach };
+ svg.setPointerCapture?.(event.pointerId);
+ }
function edit(event, mark) {
if (mark.kind !== 'text') return;
event.stopPropagation();
@@ -294,7 +330,7 @@
<svg class="annotation-canvas" class:drawing={active && tool !== 'select'}
bind:this={svg} aria-label={`Annotations on imagery ${letter.toUpperCase()}`}
onpointerdown={begin} onpointermove={move} onpointerup={finish}
- onpointercancel={finish} ondblclick={finishPolygon} onwheel={relayWheel}>
+ onpointercancel={finish} ondblclick={finishPolygon} onwheel={relay}>
{#each marks as { mark, shape, label, vertices } (mark.id)}
<!-- svelte-ignore a11y_no_static_element_interactions -->
<g class="mark" class:area={edgeOnly} class:selected={selectedId === mark.id} style:color={mark.colour}
@@ -337,6 +373,16 @@
{/if}
</g>
{#if editVertices && active && selectedId === mark.id && tool === 'select'}
+ {#if turnable && TURNABLE.has(mark.kind)}
+ {@const grip = turnGrip(mark, shape)}
+ <!-- svelte-ignore a11y_no_static_element_interactions -->
+ <g class="turn" class:held={turning?.id === mark.id} onpointerdown={(e) => turnStart(e, mark, grip)}>
+ <title>Drag to turn · Shift snaps to 15°</title>
+ <line x1={grip.edge[0]} y1={grip.edge[1]} x2={grip.at[0]} y2={grip.at[1]} stroke={mark.colour} stroke-width="1.5" />
+ <circle class="grip" cx={grip.at[0]} cy={grip.at[1]} r="13" fill="transparent" />
+ <circle cx={grip.at[0]} cy={grip.at[1]} r="6" fill="#fff" stroke={mark.colour} stroke-width="2" />
+ </g>
+ {/if}
{#each vertices as at, i}
<!-- svelte-ignore a11y_no_static_element_interactions -->
<g class="vertex" onpointerdown={(e) => vertex(e, mark, i)}>
@@ -370,6 +416,10 @@
.drawing .mark, .drawing .mark .edge { pointer-events: none; }
.vertex { pointer-events: auto; cursor: crosshair; }
.vertex .grip { pointer-events: all; }
+ .turn { pointer-events: auto; cursor: grab; }
+ .turn.held { cursor: grabbing; }
+ .turn line { pointer-events: none; }
+ .turn .grip { pointer-events: all; }
.mark path { stroke-linecap: round; stroke-linejoin: round; }
.mark.selected { filter: drop-shadow(0 0 3px white); }
text { fill: white; stroke: #111; stroke-width: 3px; paint-order: stroke; font-family: system-ui, sans-serif; font-weight: 600; }
diff --git a/frontend/src/tools/compare/AnnotationCanvas.test.js b/frontend/src/tools/compare/AnnotationCanvas.test.js
index c12347f..bcee878 100644
--- a/frontend/src/tools/compare/AnnotationCanvas.test.js
+++ b/frontend/src/tools/compare/AnnotationCanvas.test.js
@@ -1,8 +1,10 @@
// @vitest-environment happy-dom
-import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { flushSync, mount, unmount } from 'svelte';
const { default: Canvas } = await import('./AnnotationCanvas.svelte');
+const { markRing } = await import('../../lib/map/compareAnnotations.js');
+const { fromMercator, toMercator } = await import('../../lib/map/groundFrame.js');
globalThis.ResizeObserver = class { observe() {} disconnect() {} };
@@ -22,11 +24,43 @@ function fakeEngine() {
const area = () => ({ id: 'z1', kind: 'rect', side: 'both', colour: '#38bdf8',
points: [[1, 1], [3, 3]], stroke_width: 2, fill_opacity: 0.08, font_size: 12, text: 'Area 1' });
-function press(node, type, x, y) {
- node.dispatchEvent(new MouseEvent(type, { bubbles: true, clientX: x, clientY: y }));
+/**
+ * A camera at one pixel to the metre, turned by the app's bearing: the map's
+ * clockwise turn, so the compass direction up is its negative. Its matrix is
+ * its own inverse, so the same one maps both ways.
+ */
+function turningEngine(bearing = 0) {
+ handlers = {};
+ const engine = { bearing };
+ const turn = (a, b) => {
+ const t = (-engine.bearing * Math.PI) / 180;
+ return [a * Math.cos(t) - b * Math.sin(t), -a * Math.sin(t) - b * Math.cos(t)];
+ };
+ Object.assign(engine, {
+ on: (name, handler) => { handlers[name] = handler; return () => delete handlers[name]; },
+ latLngToContainerPoint: ({ lon, lat }) => {
+ const [x, y] = turn(...toMercator(lon, lat));
+ return { x: 200 + x, y: 150 + y };
+ },
+ containerPointToLatLng: ({ x, y }) => {
+ const [lon, lat] = fromMercator(...turn(x - 200, y - 150));
+ return { lon, lat };
+ },
+ });
+ return engine;
+}
+
+function press(node, type, x, y, init = {}) {
+ node.dispatchEvent(new MouseEvent(type, { bubbles: true, clientX: x, clientY: y, ...init }));
flushSync();
}
+/** A mark's ring as the screen shows it, rounded to a hundredth of a pixel. */
+const onScreen = (engine, mark) => markRing(mark).map((point) => {
+ const at = engine.latLngToContainerPoint({ lon: point[0], lat: point[1] });
+ return [Math.round(at.x * 100) / 100, Math.round(at.y * 100) / 100];
+});
+
function stage(props) {
live = mount(Canvas, { target, props: { engine: fakeEngine(), ...props } });
flushSync();
@@ -126,3 +160,101 @@ it('anchors a measure on a point handed to it, and closes it on the next click',
expect(saved[0].points[0]).toEqual([1, 1]);
expect(saved[0].points[1][0]).toBeCloseTo(6);
});
+
+it('draws a box along a turned camera, not along north', () => {
+ const onchange = vi.fn();
+ const engine = turningEngine(30);
+ const svg = stage({ engine, annotations: [], tool: 'rect', bearing: 30, turnable: true, onchange });
+ press(svg, 'pointerdown', 100, 80);
+ press(svg, 'pointermove', 300, 200);
+ press(svg, 'pointerup', 300, 200);
+ const [box] = onchange.mock.calls.at(-1)[0];
+ // The map turned 30° clockwise puts compass 330° up.
+ expect(box.angle).toBe(330);
+ expect(onScreen(engine, box)).toEqual([[100, 80], [300, 80], [300, 200], [100, 200]]);
+});
+
+it('keeps a Detect area north-up, since its zones are north-up boxes', () => {
+ const onchange = vi.fn();
+ const svg = stage({ engine: turningEngine(30), annotations: [], tool: 'rect', bearing: 30, onchange });
+ press(svg, 'pointerdown', 100, 80);
+ press(svg, 'pointermove', 300, 200);
+ press(svg, 'pointerup', 300, 200);
+ expect(onchange.mock.calls.at(-1)[0][0].angle).toBe(0);
+});
+
+describe('turning a mark', () => {
+ const box = (engine) => {
+ const [first, second] = [{ x: 100, y: 100 }, { x: 300, y: 200 }]
+ .map((at) => engine.containerPointToLatLng(at)).map(({ lon, lat }) => [lon, lat]);
+ return { ...area(), points: [first, second], angle: 0 };
+ };
+ const grip = () => target.querySelector('.turn circle:last-of-type');
+ // The marks as the drag last left them; the release commits the parent's copy.
+ const lastDrag = (onchange) => onchange.mock.calls.filter(([, commit]) => !commit).at(-1)[0];
+
+ it('stands a grip past the top of the selected mark, only where turning is on', () => {
+ const engine = turningEngine();
+ stage({ engine, annotations: [box(engine)], editVertices: true, selectedId: 'z1', tool: 'select', turnable: true });
+ expect(Number(grip().getAttribute('cx'))).toBeCloseTo(200, 4);
+ expect(Number(grip().getAttribute('cy'))).toBeCloseTo(100 - 26, 4);
+ unmount(live);
+
+ stage({ engine, annotations: [box(engine)], editVertices: true, selectedId: 'z1', tool: 'select' });
+ expect(target.querySelector('.turn')).toBeNull();
+ unmount(live);
+
+ const note = { ...area(), kind: 'text', points: [[1, 1]], text: 'Here' };
+ stage({ annotations: [note], editVertices: true, selectedId: 'z1', tool: 'select', turnable: true });
+ expect(target.querySelector('.turn')).toBeNull();
+ });
+
+ it('turns a box about its centre as the grip is dragged round it', () => {
+ const onchange = vi.fn();
+ const engine = turningEngine();
+ const svg = stage({ engine, annotations: [box(engine)], editVertices: true, selectedId: 'z1',
+ tool: 'select', turnable: true, onchange });
+ // From straight above the centre to straight right of it: a quarter turn clockwise.
+ press(grip().parentNode, 'pointerdown', 200, 74);
+ press(svg, 'pointermove', 276, 150);
+ press(svg, 'pointerup', 276, 150);
+ const [turned] = lastDrag(onchange);
+ expect(onchange.mock.calls.at(-1)[1]).toBe(true); // one entry to undo, at the end
+ expect(turned.angle).toBeCloseTo(90, 6);
+ const ring = onScreen(engine, turned);
+ const xs = ring.map((point) => point[0]);
+ const ys = ring.map((point) => point[1]);
+ expect([Math.min(...xs), Math.max(...xs), Math.min(...ys), Math.max(...ys)]).toEqual([150, 250, 50, 250]);
+ });
+
+ it('snaps the turn to 15° with Shift held', () => {
+ const onchange = vi.fn();
+ const engine = turningEngine();
+ const svg = stage({ engine, annotations: [box(engine)], editVertices: true, selectedId: 'z1',
+ tool: 'select', turnable: true, onchange });
+ press(grip().parentNode, 'pointerdown', 200, 74);
+ // 37° clockwise from straight up.
+ const turn = (37 * Math.PI) / 180;
+ const at = [200 + 76 * Math.sin(turn), 150 - 76 * Math.cos(turn)];
+ press(svg, 'pointermove', ...at, { shiftKey: true });
+ press(svg, 'pointerup', ...at, { shiftKey: true });
+ expect(lastDrag(onchange)[0].angle).toBeCloseTo(30, 6);
+ });
+
+ it('turns a polygon by its points, having no sides of its own', () => {
+ const onchange = vi.fn();
+ const engine = turningEngine();
+ const points = [[100, 100], [300, 100], [200, 200]]
+ .map(([x, y]) => engine.containerPointToLatLng({ x, y })).map(({ lon, lat }) => [lon, lat]);
+ const svg = stage({ engine, annotations: [{ ...area(), kind: 'polygon', points }], editVertices: true,
+ selectedId: 'z1', tool: 'select', turnable: true, onchange });
+ press(grip().parentNode, 'pointerdown', 200, 74);
+ press(svg, 'pointermove', 200, 226);
+ press(svg, 'pointerup', 200, 226);
+ const [turned] = lastDrag(onchange);
+ const apex = engine.latLngToContainerPoint({ lon: turned.points[2][0], lat: turned.points[2][1] });
+ // Half a turn about the middle of what it spans: the apex points up now.
+ expect(apex.x).toBeCloseTo(200, 4);
+ expect(apex.y).toBeCloseTo(100, 4);
+ });
+});
diff --git a/frontend/src/tools/compare/ChangePanel.svelte b/frontend/src/tools/compare/ChangePanel.svelte
deleted file mode 100644
index 31fa072..0000000
--- a/frontend/src/tools/compare/ChangePanel.svelte
+++ /dev/null
@@ -1,243 +0,0 @@
-<script>
- /**
- * Difference mode's own column. It reads the pixels the two maps are showing
- * right now, so everything here is about *this view*, and nothing is saved.
- * Detect mode, next to it in the dock, freezes an area and keeps what it found.
- *
- * The reading follows the camera by itself, always. What it never does on a
- * pan is spend a request: a method that reads Sentinel-2 bands — a spectral
- * index, or the cloud filter over the picture methods — runs on the frames it
- * holds, and waits for Run once the camera leaves the ground they cover.
- */
- import { CHANGE_BASES, CHANGE_METHODS, CHANGE_INDICES, CHANGE_DISPLAYS, CHANGE_CLASSES,
- changeNeedsFrames, changeSettings, indexThreshold } from '../../lib/map/changeAssist.js';
- import CloudFilter from './CloudFilter.svelte';
- import Icon from '../../components/Icon.svelte';
-
- let {
- settings = $bindable(),
- status,
- result = null,
- busy = false,
- error = '',
- stale = false,
- onrun = () => {},
- onzone = () => {},
- onclose = () => {},
- } = $props();
-
- let tab = $state('detection');
- const runnable = $derived(status.ok && status.methods.includes(settings.method));
- // 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));
-</script>
-
-<aside class="cmp-dock" aria-label="Difference">
- <header>
- <strong>Difference</strong>
- <button
- class="cmp-icon"
- class:on={settings.blink}
- disabled={!settings.visible}
- onclick={() => (settings = { ...settings, blink: !settings.blink })}
- aria-label={settings.blink ? 'Stop blinking the highlights' : 'Blink the highlights'}
- aria-pressed={settings.blink}
- title="Blink the highlights on and off, which is easier to catch over busy imagery"
- >
- <Icon name="blink" size={15} />
- </button>
- <button
- class="cmp-icon"
- class:on={settings.visible}
- onclick={() => (settings = { ...settings, visible: !settings.visible })}
- aria-label={settings.visible ? 'Hide the difference overlay' : 'Show the difference overlay'}
- aria-pressed={settings.visible}
- title={settings.visible ? 'Hide the overlay' : 'Show the overlay'}
- >
- <Icon name={settings.visible ? 'eye' : 'eyeOff'} size={15} />
- </button>
- <button class="cmp-icon" onclick={onclose} aria-label="Leave Difference mode" title="Back to side by side">
- <Icon name="x" size={14} />
- </button>
- </header>
- <p class="cmp-dock-lead">
- Reads this view, and keeps nothing. Detect sweeps a fixed area at full resolution.
- </p>
-
- <div class="cmp-dock-body">
- {#if !status.ok}
- <p class="warn">{status.reason}</p>
- {/if}
- {#each status.notes ?? [] as note}<p class="hint">{note}</p>{/each}
- {#if error}<p class="warn" role="alert">{error}</p>{/if}
-
- {#if result}
- <div class="readout" class:stale>
- <strong>{Math.round(result.share * 100)}%</strong>
- <span>of the overlap highlighted</span>
- <small>{Math.round(result.coverage * 100)}% coverage · {Math.round(result.area)} m²</small>
- {#if stale}<small class="warn">Out of date. Run again to match this view.</small>{/if}
- </div>
- {/if}
-
- <div class="field">
- <span class="field-name">Highlights over</span>
- <div class="cmp-seg fill" aria-label="Image under the highlights">
- {#each CHANGE_BASES as entry}
- <button class:on={settings.base === entry.id} aria-pressed={settings.base === entry.id}
- onclick={() => (settings = { ...settings, base: entry.id })}>{entry.label}</button>
- {/each}
- </div>
- <p class="hint">
- {settings.base === 'side' ? 'Both images, the same highlights on each.'
- : `Image ${settings.base.toUpperCase()} alone, under the highlights.`}
- </p>
- </div>
-
- {#if status.clouds}
- <CloudFilter
- clouds={settings.ignore_clouds}
- shadows={settings.ignore_shadows}
- ontoggle={(on) => {
- settings = { ...settings, ignore_clouds: on, ignore_shadows: on };
- // The click is the act that asks for the sky, so the reading follows
- // it rather than leaving an unfiltered mask up behind an "on" switch.
- queueMicrotask(() => onrun());
- }}
- />
- {/if}
-
- {#if frames}
- <p class="hint">
- Reads Sentinel-2 bands, one request a side. They are kept with a margin around
- this view: following the map costs nothing inside it, and waits for Run past it.
- </p>
- {/if}
-
- <div class="settings-tabs" role="tablist" aria-label="Difference parameters">
- {#each [['detection', 'Detection'], ['display', 'Display'], ['filters', 'Filters']] as [id, label]}
- <button role="tab" aria-selected={tab === id} class:on={tab === id} onclick={() => (tab = id)}>{label}</button>
- {/each}
- </div>
-
- {#if tab === 'detection'}
- <label title="Colour compares appearance; structure compares edges; index compares Sentinel-2 spectral bands.">Method
- <select aria-label="Method" bind:value={settings.method}>
- {#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="Select the spectral quantity to compare 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>
- </label>
- {:else}
- <label title="Automatic adapts to this view; manual keeps a sensitivity-based threshold.">Threshold
- <select bind:value={settings.threshold}><option value="auto">Automatic</option><option value="manual">Manual</option></select>
- </label>
- {/if}
- <label title="Higher values show weaker differences and more noise.">Sensitivity · {settings.sensitivity}
- <input aria-label="Change sensitivity" type="range" min="0" max="100" bind:value={settings.sensitivity} />
- </label>
- {#if settings.method === 'index'}
- <p class="hint">Highlights {index?.label} moved by {indexThreshold(settings.sensitivity).toFixed(2)} or more, the line Detect draws.</p>
- {/if}
- <button class="btn btn-sm" onclick={() => (settings = { ...settings, normalize: 'none', smoothing: 0, cleanup: 0, alignment: 0, threshold: 'manual', sensitivity: 90 })}>
- Preserve fine changes
- </button>
- {/if}
-
- {#if tab === 'display'}
- <label title="Show the detected pixels as classes, a signal heatmap or outlines.">Display
- <select bind:value={settings.display}>{#each CHANGE_DISPLAYS as display}<option value={display.id}>{display.label}</option>{/each}</select>
- </label>
- <label title="Change only the overlay colours; Thermal is a palette, not a thermal sensor.">Palette
- <select bind:value={settings.palette}><option value="directional">Directional</option><option value="colourblind">Colour-blind</option><option value="thermal">Thermal</option></select>
- </label>
- <div class="classes">{#each CHANGE_CLASSES as entry}<label class="check"><input type="checkbox" bind:group={settings.classes} value={entry} /> {entry}</label>{/each}</div>
- <label title="Fade the result overlay to inspect the imagery beneath it.">Overlay · {settings.opacity}%
- <input aria-label="Change overlay opacity" type="range" min="0" max="100" bind:value={settings.opacity} />
- </label>
- {/if}
-
- {#if tab === 'filters'}
- <label title="Reduce exposure differences; this may suppress broad real changes.">Tone matching
- <select bind:value={settings.normalize}>
- <option value="auto">Automatic</option><option value="none">None</option>
- <option value="mean">Mean brightness</option><option value="histogram">Histogram</option>
- </select>
- </label>
- {#if settings.normalize === 'auto'}
- <p class="hint">
- {status.family === 'sentinel2'
- ? 'Nothing to match: both passes are corrected to surface reflectance.'
- : 'Histogram, because two releases carry two renderings.'}
- </p>
- {/if}
- <label title="Search for a small image offset before comparing pixels.">Alignment · ±{settings.alignment}px<input type="range" min="0" max="8" bind:value={settings.alignment} /></label>
- <label title="Reduce pixel noise before thresholding; zero preserves small details.">Smoothing · {settings.smoothing}px<input type="range" min="0" max="4" bind:value={settings.smoothing} /></label>
- <label title="Remove isolated speckles; larger settings can also remove small real changes.">Cleanup · {settings.cleanup}<input type="range" min="0" max="3" bind:value={settings.cleanup} /></label>
- <label title="Discard connected regions below this ground area.">Minimum area (m²)<input type="number" min="0" max="1000000" bind:value={settings.min_area} /></label>
- {#if status.clouds}
- <label class="check" title="Exclude cloud, read from Sentinel-2's scene classification."><input type="checkbox" bind:checked={settings.ignore_clouds} /> Mask clouds</label>
- <label class="check" title="Exclude the shadow cloud casts, which moves with the sun."><input type="checkbox" bind:checked={settings.ignore_shadows} /> Mask shadows</label>
- <label title="Grow the cloud and shadow mask, to take the soft edge a mask leaves behind.">Mask margin · {settings.cloud_margin} m<input aria-label="Cloud mask margin" type="range" min="0" max="200" step="10" bind:value={settings.cloud_margin} /></label>
- {/if}
- <label class="check"><input type="checkbox" bind:checked={settings.zones} /> List change zones</label>
- <button class="link" onclick={() => (settings = changeSettings())}>Reset settings</button>
- {/if}
-
- {#if result && settings.zones}
- <section>
- <strong>{result.zoneCount} change zones{result.zoneCount > result.zones.length ? ` · largest ${result.zones.length}` : ''}</strong>
- <div class="zone-list">
- {#each result.zones as zone (zone.id)}
- <button onclick={() => onzone(zone)}>
- <span class="zone-strength {zone.strength}">{zone.strength}</span>
- Zone {zone.id} · {zone.kind} · {Math.round(zone.area)} m²
- </button>
- {/each}
- </div>
- </section>
- {/if}
- </div>
-
- <div class="cmp-dock-foot">
- <button class="btn btn-primary" disabled={busy || !runnable} onclick={() => onrun()}>
- {busy ? 'Reading…' : 'Read this view'}
- </button>
- {#if !runnable}
- <span class="reason">{status.ok ? 'This method needs another imagery source.' : status.reason}</span>
- {:else if stale && result}
- <span class="reason warn">These highlights are from an earlier read.</span>
- {/if}
- </div>
-</aside>
-
-<style>
- .readout {
- display: grid;
- gap: 2px;
- padding: 9px 10px;
- border: 1px solid var(--border);
- border-radius: var(--r-sm);
- background: var(--bg-2);
- }
- .readout strong { font-size: var(--fs-lg); color: var(--accent); }
- .readout span { font-size: var(--fs-xs); color: var(--text-2); }
- .readout small { font-size: 10.5px; color: var(--text-3); }
- .readout.stale { opacity: 0.7; }
- .field { display: grid; gap: 5px; }
- .field-name { color: var(--text-2); font-size: var(--fs-xs); }
- .settings-tabs { display: flex; gap: 3px; border-bottom: 1px solid var(--border); }
- .settings-tabs button { flex: 1; padding: 7px 4px; color: var(--text-2); font-size: var(--fs-xs); }
- .settings-tabs button.on { color: var(--accent); border-bottom: 2px solid var(--accent); }
- .classes { display: flex; flex-wrap: wrap; gap: 10px; }
- section { display: grid; gap: 6px; border-top: 1px solid var(--border); padding-top: 10px; font-size: var(--fs-xs); }
- .zone-list { display: grid; gap: 4px; max-height: 170px; overflow: auto; }
- .zone-list button { padding: 5px; text-align: left; background: var(--bg-2); border-radius: var(--r-sm); font-size: 11px; }
- .zone-list button:hover { background: var(--bg-3); }
- .zone-strength { font-weight: 600; text-transform: capitalize; color: var(--text-2); }
- .zone-strength.strong { color: var(--accent); }
- .link { color: var(--accent); font-size: var(--fs-xs); text-align: left; }
-</style>
diff --git a/frontend/src/tools/compare/ChangePanel.test.js b/frontend/src/tools/compare/ChangePanel.test.js
deleted file mode 100644
index 35e5004..0000000
--- a/frontend/src/tools/compare/ChangePanel.test.js
+++ /dev/null
@@ -1,121 +0,0 @@
-// @vitest-environment happy-dom
-import { describe, expect, it, vi } from 'vitest';
-import { flushSync, mount, unmount } from 'svelte';
-import ChangePanel from './ChangePanel.svelte';
-import { changeSettings } from '../../lib/map/changeAssist.js';
-
-const ready = { ok: true, label: 'Two dated passes', methods: ['colour', 'brightness'], notes: [],
- family: 'sentinel2', clouds: true };
-
-function render(props = {}) {
- const target = document.createElement('div');
- document.body.append(target);
- const live = mount(ChangePanel, {
- target,
- props: { settings: changeSettings(), status: ready, ...props },
- });
- flushSync();
- return { target, done: () => { unmount(live); target.remove(); } };
-}
-
-const button = (target, name) =>
- [...target.querySelectorAll('button')].find((node) =>
- node.getAttribute('aria-label') === name || node.textContent.trim() === name);
-
-describe('Difference panel', () => {
- it('hides and restores the overlay from the eye, without recomputing', () => {
- const onrun = vi.fn();
- const { target, done } = render({ onrun });
- const eye = () => target.querySelector('button[aria-label*="difference overlay"]');
- expect(eye().getAttribute('aria-label')).toBe('Hide the difference overlay');
- eye().click();
- flushSync();
- expect(eye().getAttribute('aria-label')).toBe('Show the difference overlay');
- expect(eye().getAttribute('aria-pressed')).toBe('false');
- eye().click();
- flushSync();
- expect(eye().getAttribute('aria-pressed')).toBe('true');
- expect(onrun).not.toHaveBeenCalled();
- done();
- });
-
- it('refuses to run a pair it cannot read, and says why', () => {
- const { target, done } = render({
- status: { ok: false, reason: 'Date both passes first', methods: [] },
- });
- expect(button(target, 'Read this view').disabled).toBe(true);
- expect(target.textContent).toContain('Date both passes first');
- done();
- });
-
- it('runs only when asked', () => {
- const onrun = vi.fn();
- const { target, done } = render({ onrun });
- const run = button(target, 'Read this view');
- expect(run.disabled).toBe(false);
- run.click();
- expect(onrun).toHaveBeenCalledTimes(1);
- done();
- });
-
- it('blinks the highlights on and off, which only touches the overlay', () => {
- const onrun = vi.fn();
- const { target, done } = render({ onrun });
- const blink = () => target.querySelector('button[aria-label$="the highlights"]');
- expect(blink().getAttribute('aria-pressed')).toBe('false');
- blink().click();
- flushSync();
- expect(blink().getAttribute('aria-label')).toBe('Stop blinking the highlights');
- expect(onrun).not.toHaveBeenCalled();
- // nothing to blink once the overlay is hidden
- target.querySelector('button[aria-label*="difference overlay"]').click();
- flushSync();
- expect(blink().disabled).toBe(true);
- done();
- });
-
- it('offers the cloud filter only where a scene classification exists', () => {
- const { target, done } = render();
- expect(target.textContent).toContain('Clouds & shadows');
- done();
- const esri = render({ status: { ...ready, family: 'esri', clouds: false } });
- expect(esri.target.textContent).not.toContain('Clouds & shadows');
- esri.done();
- });
-
- it('says when a reading reads bands, and never asks to be turned on', () => {
- // The reading always follows the camera. Reading bands is a different
- // question: it is what costs a request, and only off the held ground.
- const { target, done } = render({ settings: changeSettings({ ignore_clouds: true }) });
- expect(target.textContent).toContain('one request a side');
- done();
- const free = render();
- expect(free.target.textContent).not.toContain('one request a side');
- expect(free.target.textContent).not.toContain('Follow the map');
- free.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.
- const onrun = vi.fn();
- const { target, done } = render({ onrun });
- target.querySelector('.cloud-filter button').click();
- flushSync();
- await Promise.resolve();
- expect(onrun).toHaveBeenCalledTimes(1);
- done();
- });
-
- it('says so in the footer when the highlights are from an earlier read', () => {
- const { target, done } = render({ stale: true, result: { share: 0.1, coverage: 1, area: 20, zones: [], zoneCount: 0 } });
- expect(target.querySelector('.cmp-dock-foot').textContent).toContain('from an earlier read');
- done();
- });
-
- it('states the index change it draws the line at', () => {
- const { target, done } = render({ settings: changeSettings({ method: 'index', index: 'nbr' }) });
- expect(target.textContent).toContain('NBR moved by 0.25');
- done();
- });
-});
diff --git a/frontend/src/tools/compare/CloudFilter.svelte b/frontend/src/tools/compare/CloudFilter.svelte
index 290e162..12dcf0f 100644
--- a/frontend/src/tools/compare/CloudFilter.svelte
+++ b/frontend/src/tools/compare/CloudFilter.svelte
@@ -2,7 +2,7 @@
/**
* Cloud and the shadow it casts, as one thing to click.
*
- * It sits at the top of Detect's third step and of Difference's column rather
+ * It sits in Detect's What step and at the top of Difference's column rather
* than inside the thresholds, because cloud is the first thing that goes
* wrong in a reading and hunting for the switch that fixes it is the wrong
* first minute. The split between cloud and shadow, and the margin, stay with
diff --git a/frontend/src/tools/compare/DifferenceBar.svelte b/frontend/src/tools/compare/DifferenceBar.svelte
new file mode 100644
index 0000000..48d9083
--- /dev/null
+++ b/frontend/src/tools/compare/DifferenceBar.svelte
@@ -0,0 +1,305 @@
+<script>
+ /**
+ * Difference's controls, in the stage footer beside the view's own. The
+ * highlights lie over whichever view is on, so nothing here moves the maps;
+ * the full settings open above the strip only when asked for.
+ *
+ * The strip keeps one width whatever the reading is doing, since the panel
+ * 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.
+ */
+ import { CHANGE_BASES, CHANGE_METHODS, CHANGE_INDICES, CHANGE_DISPLAYS, CHANGE_CLASSES,
+ changeNeedsFrames, changeSettings, indexThreshold } from '../../lib/map/changeAssist.js';
+ import CloudFilter from './CloudFilter.svelte';
+ import Icon from '../../components/Icon.svelte';
+
+ let {
+ settings = $bindable(),
+ status,
+ result = null,
+ busy = false,
+ error = '',
+ stale = false,
+ onrun = () => {},
+ onzone = () => {},
+ } = $props();
+
+ let open = $state(false);
+ let tab = $state('detection');
+ const runnable = $derived(status.ok && status.methods.includes(settings.method));
+ // 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));
+
+ // 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
+ // them, and the gear would otherwise close it on the way down and reopen it.
+ let barEl = $state();
+ $effect(() => {
+ if (!open) return;
+ const key = (event) => {
+ if (event.key === 'Escape') open = false;
+ };
+ const outside = (event) => {
+ if (barEl?.contains(event.target)) return;
+ open = false;
+ };
+ window.addEventListener('keydown', key);
+ document.addEventListener('pointerdown', outside, true);
+ return () => {
+ window.removeEventListener('keydown', key);
+ document.removeEventListener('pointerdown', outside, true);
+ };
+ });
+</script>
+
+<div class="difference-bar cmp-glass" aria-label="Difference" bind:this={barEl}>
+ <span class="name">Difference</span>
+ <div class="cmp-seg" aria-label="Image under the highlights">
+ {#each CHANGE_BASES as entry}
+ <button class:on={settings.base === entry.id} aria-pressed={settings.base === entry.id}
+ title={entry.id === 'both' ? 'Highlights on both images' : `Highlights on image ${entry.label} only`}
+ onclick={() => (settings = { ...settings, base: entry.id })}>{entry.label}</button>
+ {/each}
+ </div>
+ <button
+ class="cmp-icon"
+ class:on={settings.blink}
+ onclick={() => (settings = { ...settings, blink: !settings.blink })}
+ aria-label={settings.blink ? 'Stop blinking the highlights' : 'Blink the highlights'}
+ aria-pressed={settings.blink}
+ title="Blink the highlights, easier to catch over busy imagery"
+ >
+ <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>
+ <button
+ class="cmp-icon"
+ class:on={open}
+ aria-expanded={open}
+ aria-label="Difference settings"
+ title="Difference settings"
+ onclick={() => (open = !open)}
+ >
+ <Icon name="settings" size={15} />
+ </button>
+
+ {#if open}
+ <aside class="cmp-dock settings" aria-label="Difference settings">
+ <header>
+ <strong>Difference settings</strong>
+ <button class="cmp-icon" onclick={() => (open = false)} aria-label="Close the settings" title="Close">
+ <Icon name="x" size={14} />
+ </button>
+ </header>
+ <div class="cmp-dock-body">
+ {#each status.notes ?? [] as note}<p class="hint">{note}</p>{/each}
+
+ <!-- One box whatever the reading is doing, so a read never reflows the panel. -->
+ <div class="readout" class:stale={stale || busy} aria-live="polite">
+ {#if error}
+ <strong class="warn">No reading</strong>
+ <span role="alert">{error}</span>
+ {:else if result}
+ <strong>{Math.round(result.share * 100)}%</strong>
+ <span>of the overlap highlighted</span>
+ {:else}
+ <strong class="dim">–</strong>
+ <span>{busy ? 'Reading this view' : 'Not read yet'}</span>
+ {/if}
+ <small>
+ {#if busy}Reading…{:else if stale && result}From an earlier read{:else if result}{Math.round(result.coverage * 100)}% coverage · {Math.round(result.area)} m²{:else}&nbsp;{/if}
+ </small>
+ </div>
+
+ {#if status.clouds}
+ <CloudFilter
+ clouds={settings.ignore_clouds}
+ shadows={settings.ignore_shadows}
+ ontoggle={(on) => {
+ settings = { ...settings, ignore_clouds: on, ignore_shadows: on };
+ // The click is the act that asks for the sky, so the reading follows
+ // it rather than leaving an unfiltered mask up behind an "on" switch.
+ queueMicrotask(() => onrun());
+ }}
+ />
+ {/if}
+
+ {#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.
+ </p>
+ {/if}
+
+ <div class="settings-tabs" role="tablist" aria-label="Difference parameters">
+ {#each [['detection', 'Detection'], ['display', 'Display'], ['filters', 'Filters']] as [id, label]}
+ <button role="tab" aria-selected={tab === id} class:on={tab === id} onclick={() => (tab = id)}>{label}</button>
+ {/each}
+ </div>
+
+ {#if tab === 'detection'}
+ <label title="Colour compares appearance; structure compares edges; index compares Sentinel-2 spectral bands.">Method
+ <select aria-label="Method" bind:value={settings.method}>
+ {#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="Select the spectral quantity to compare 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>
+ </label>
+ {:else}
+ <label title="Automatic adapts to this view; manual keeps a sensitivity-based threshold.">Threshold
+ <select bind:value={settings.threshold}><option value="auto">Automatic</option><option value="manual">Manual</option></select>
+ </label>
+ {/if}
+ <label title="Higher values show weaker differences and more noise.">Sensitivity · {settings.sensitivity}
+ <input aria-label="Change sensitivity" type="range" min="0" max="100" bind:value={settings.sensitivity} />
+ </label>
+ {#if settings.method === 'index'}
+ <p class="hint">Highlights {index?.label} moved by {indexThreshold(settings.sensitivity).toFixed(2)} or more.</p>
+ {/if}
+ <button class="btn btn-sm" onclick={() => (settings = { ...settings, normalize: 'none', smoothing: 0, cleanup: 0, alignment: 0, threshold: 'manual', sensitivity: 90 })}>
+ Preserve fine changes
+ </button>
+ {/if}
+
+ {#if tab === 'display'}
+ <label title="Show the detected pixels as classes, a signal heatmap or outlines.">Display
+ <select bind:value={settings.display}>{#each CHANGE_DISPLAYS as display}<option value={display.id}>{display.label}</option>{/each}</select>
+ </label>
+ <label title="Change only the overlay colours; Thermal is a palette, not a thermal sensor.">Palette
+ <select bind:value={settings.palette}><option value="directional">Directional</option><option value="colourblind">Colour-blind</option><option value="thermal">Thermal</option></select>
+ </label>
+ <div class="classes">{#each CHANGE_CLASSES as entry}<label class="check"><input type="checkbox" bind:group={settings.classes} value={entry} /> {entry}</label>{/each}</div>
+ <label title="Fade the highlights to inspect the imagery beneath them.">Overlay · {settings.opacity}%
+ <input aria-label="Change overlay opacity" type="range" min="0" max="100" bind:value={settings.opacity} />
+ </label>
+ {/if}
+
+ {#if tab === 'filters'}
+ <label title="Reduce exposure differences; this may suppress broad real changes.">Tone matching
+ <select bind:value={settings.normalize}>
+ <option value="auto">Automatic</option><option value="none">None</option>
+ <option value="mean">Mean brightness</option><option value="histogram">Histogram</option>
+ </select>
+ </label>
+ {#if settings.normalize === 'auto'}
+ <p class="hint">
+ {status.family === 'sentinel2'
+ ? 'Nothing to match: both passes are corrected to surface reflectance.'
+ : status.family === 'sentinel1'
+ ? 'Nothing to match: both passes are calibrated backscatter.'
+ : 'Histogram, because two releases carry two renderings.'}
+ </p>
+ {/if}
+ <label title="Search for a small image offset before comparing pixels.">Alignment · ±{settings.alignment}px<input type="range" min="0" max="8" bind:value={settings.alignment} /></label>
+ <label title="Reduce pixel noise before thresholding; zero preserves small details.">Smoothing · {settings.smoothing}px<input type="range" min="0" max="4" bind:value={settings.smoothing} /></label>
+ <label title="Remove isolated speckles; larger settings can also remove small real changes.">Cleanup · {settings.cleanup}<input type="range" min="0" max="3" bind:value={settings.cleanup} /></label>
+ <label title="Discard connected regions below this ground area.">Minimum area (m²)<input type="number" min="0" max="1000000" bind:value={settings.min_area} /></label>
+ {#if status.clouds}
+ <label class="check" title="Exclude cloud, read from Sentinel-2's scene classification."><input type="checkbox" bind:checked={settings.ignore_clouds} /> Mask clouds</label>
+ <label class="check" title="Exclude the shadow cloud casts, which moves with the sun."><input type="checkbox" bind:checked={settings.ignore_shadows} /> Mask shadows</label>
+ <label title="Grow the cloud and shadow mask, to take the soft edge a mask leaves behind.">Mask margin · {settings.cloud_margin} m<input aria-label="Cloud mask margin" type="range" min="0" max="200" step="10" bind:value={settings.cloud_margin} /></label>
+ {/if}
+ <label class="check"><input type="checkbox" bind:checked={settings.zones} /> List change zones</label>
+ <button class="link" onclick={() => (settings = changeSettings())}>Reset settings</button>
+ {/if}
+
+ {#if result && settings.zones}
+ <section>
+ <strong>{result.zoneCount} change zones{result.zoneCount > result.zones.length ? ` · largest ${result.zones.length}` : ''}</strong>
+ <div class="zone-list">
+ {#each result.zones as zone (zone.id)}
+ <button onclick={() => onzone(zone)}>
+ <span class="zone-strength {zone.strength}">{zone.strength}</span>
+ Zone {zone.id} · {zone.kind} · {Math.round(zone.area)} m²
+ </button>
+ {/each}
+ </div>
+ </section>
+ {/if}
+ </div>
+ </aside>
+ {/if}
+</div>
+
+<style>
+ .difference-bar {
+ position: relative;
+ flex: 0 0 auto;
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ min-height: 42px;
+ padding: 5px 6px 5px 10px;
+ }
+ .text-btn {
+ padding: 4px 8px;
+ border-radius: 6px;
+ color: var(--glass-muted);
+ font-size: 11.5px;
+ font-weight: 600;
+ }
+ .text-btn:hover:not(:disabled) {
+ color: var(--glass-ink);
+ 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; }
+ .text-btn.read.busy:disabled { opacity: 0.75; }
+ .name {
+ font-size: var(--fs-xs);
+ letter-spacing: 0.04em;
+ text-transform: uppercase;
+ color: var(--glass-dim);
+ }
+ /* Opened on request, over the stage: the maps keep their width. One height
+ for every tab, so switching tabs or a zone list arriving never moves the
+ header under the pointer. */
+ .settings.cmp-dock {
+ position: absolute;
+ right: 0;
+ bottom: calc(100% + 8px);
+ z-index: 30;
+ width: clamp(290px, 24vw, 360px);
+ height: min(540px, 62vh);
+ border: 1px solid var(--border);
+ border-radius: var(--r-md, 8px);
+ box-shadow: 0 12px 32px rgba(0, 0, 0, 0.35);
+ overflow: hidden;
+ }
+ .readout {
+ display: grid;
+ gap: 2px;
+ padding: 9px 10px;
+ border: 1px solid var(--border);
+ border-radius: var(--r-sm);
+ background: var(--bg-2);
+ }
+ .readout strong { font-size: var(--fs-lg); color: var(--accent); font-variant-numeric: tabular-nums; }
+ .readout strong.warn { color: var(--warn); }
+ .readout strong.dim { color: var(--text-3); }
+ .readout span { overflow: hidden; font-size: var(--fs-xs); color: var(--text-2); text-overflow: ellipsis; white-space: nowrap; }
+ .readout small { font-size: 10.5px; color: var(--text-3); }
+ .readout.stale strong { opacity: 0.6; }
+ .settings-tabs { display: flex; gap: 3px; border-bottom: 1px solid var(--border); }
+ .settings-tabs button { flex: 1; padding: 7px 4px; color: var(--text-2); font-size: var(--fs-xs); }
+ .settings-tabs button.on { color: var(--accent); border-bottom: 2px solid var(--accent); }
+ .classes { display: flex; flex-wrap: wrap; gap: 10px; }
+ section { display: grid; gap: 6px; border-top: 1px solid var(--border); padding-top: 10px; font-size: var(--fs-xs); }
+ .zone-list { display: grid; gap: 4px; max-height: 170px; overflow: auto; }
+ .zone-list button { padding: 5px; text-align: left; background: var(--bg-2); border-radius: var(--r-sm); font-size: 11px; }
+ .zone-list button:hover { background: var(--bg-3); }
+ .zone-strength { font-weight: 600; text-transform: capitalize; color: var(--text-2); }
+ .zone-strength.strong { color: var(--accent); }
+ .link { color: var(--accent); font-size: var(--fs-xs); text-align: left; }
+</style>
diff --git a/frontend/src/tools/compare/DifferenceBar.test.js b/frontend/src/tools/compare/DifferenceBar.test.js
new file mode 100644
index 0000000..ee36934
--- /dev/null
+++ b/frontend/src/tools/compare/DifferenceBar.test.js
@@ -0,0 +1,174 @@
+// @vitest-environment happy-dom
+import { describe, expect, it, vi } from 'vitest';
+import { flushSync, mount, unmount } from 'svelte';
+import DifferenceBar from './DifferenceBar.svelte';
+import { changeSettings } from '../../lib/map/changeAssist.js';
+
+const ready = { ok: true, label: 'Two dated passes', methods: ['colour', 'brightness'], notes: [],
+ family: 'sentinel2', clouds: true };
+
+function render(props = {}, { open = false } = {}) {
+ const target = document.createElement('div');
+ document.body.append(target);
+ const live = mount(DifferenceBar, {
+ target,
+ props: { settings: changeSettings(), status: ready, ...props },
+ });
+ flushSync();
+ if (open) {
+ target.querySelector('button[aria-label="Difference settings"]').click();
+ flushSync();
+ }
+ return { target, done: () => { unmount(live); target.remove(); } };
+}
+
+const button = (target, name) =>
+ [...target.querySelectorAll('button')].find((node) =>
+ node.getAttribute('aria-label') === name || node.textContent.trim() === name);
+
+const base = (target, label) =>
+ [...target.querySelectorAll('[aria-label="Image under the highlights"] button')]
+ .find((entry) => entry.textContent.trim() === label);
+
+describe('Difference strip', () => {
+ it('lays the highlights over both images by default, and over one on request', () => {
+ const { target, done } = render();
+ expect(base(target, 'Both').getAttribute('aria-pressed')).toBe('true');
+ base(target, 'A').click();
+ flushSync();
+ expect(base(target, 'A').getAttribute('aria-pressed')).toBe('true');
+ expect(base(target, 'Both').getAttribute('aria-pressed')).toBe('false');
+ done();
+ });
+
+ it('keeps its settings closed until asked, then opens them over the stage', () => {
+ const { target, done } = render();
+ expect(target.querySelector('.settings')).toBeNull();
+ const gear = target.querySelector('button[aria-label="Difference settings"]');
+ expect(gear.getAttribute('aria-expanded')).toBe('false');
+ gear.click();
+ flushSync();
+ expect(target.querySelector('aside.settings')).not.toBeNull();
+ expect(target.textContent).toContain('Sensitivity');
+ window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' }));
+ flushSync();
+ expect(target.querySelector('.settings')).toBeNull();
+ done();
+ });
+
+ it('refuses to read a pair it cannot read, and says why', () => {
+ const { target, done } = render({
+ status: { ok: false, reason: 'Date both passes first', methods: [] },
+ });
+ expect(button(target, 'Read').disabled).toBe(true);
+ expect(button(target, 'Read').title).toBe('Date both passes first');
+ done();
+ });
+
+ it('reads only when asked', () => {
+ const onrun = vi.fn();
+ const { target, done } = render({ onrun });
+ const run = button(target, 'Read');
+ expect(run.disabled).toBe(false);
+ run.click();
+ expect(onrun).toHaveBeenCalledTimes(1);
+ done();
+ });
+
+ it('blinks the highlights on and off, which only touches the overlay', () => {
+ const onrun = vi.fn();
+ const { target, done } = render({ onrun });
+ const blink = () => target.querySelector('button[aria-label$="the highlights"]');
+ expect(blink().getAttribute('aria-pressed')).toBe('false');
+ blink().click();
+ flushSync();
+ expect(blink().getAttribute('aria-label')).toBe('Stop blinking the highlights');
+ expect(onrun).not.toHaveBeenCalled();
+ done();
+ });
+
+ 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 });
+ expect(target.querySelector('.readout').textContent).toContain('From an earlier read');
+ done();
+ });
+
+ it('keeps the strip the same through a read, so the panel hanging from it stays put', () => {
+ // The strip once grew a status label on every read and error, which moved
+ // the open panel under the pointer.
+ const shape = (target) => [...target.querySelector('.difference-bar').children]
+ .filter((node) => !node.matches('aside')).map((node) => node.tagName);
+ 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 });
+ expect(shape(reading.target)).toEqual(before);
+ expect(reading.target.querySelector('.readout [role="alert"]').textContent).toBe('Could not compare these pixels');
+ reading.done();
+ });
+
+ it('closes the panel on a press off the strip, but not on one inside it or on the gear', () => {
+ const { target, done } = render({}, { open: true });
+ const press = (node) => node.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true }));
+ press(target.querySelector('aside.settings select'));
+ flushSync();
+ expect(target.querySelector('aside.settings')).not.toBeNull();
+ // Reading with the settings open is tuning them, not leaving them.
+ press(button(target, 'Read'));
+ flushSync();
+ expect(target.querySelector('aside.settings')).not.toBeNull();
+ // The gear's own press must not close it, or its click would reopen it.
+ const gear = target.querySelector('button[aria-label="Difference settings"]');
+ press(gear);
+ gear.click();
+ flushSync();
+ expect(target.querySelector('aside.settings')).toBeNull();
+ gear.click();
+ flushSync();
+ expect(target.querySelector('aside.settings')).not.toBeNull();
+ press(document.body);
+ flushSync();
+ expect(target.querySelector('aside.settings')).toBeNull();
+ done();
+ });
+
+ it('offers the cloud filter only where a scene classification exists', () => {
+ const { target, done } = render({}, { open: true });
+ expect(target.textContent).toContain('Clouds & shadows');
+ done();
+ const esri = render({ status: { ...ready, family: 'esri', clouds: false } }, { open: true });
+ expect(esri.target.textContent).not.toContain('Clouds & shadows');
+ esri.done();
+ });
+
+ it('says when a reading reads bands, and never asks to be turned on', () => {
+ // The reading always follows the camera. Reading bands is a different
+ // question: it is what costs a request, and only off the held ground.
+ const { target, done } = render({ settings: changeSettings({ ignore_clouds: true }) }, { open: true });
+ expect(target.textContent).toContain('one request a side');
+ done();
+ const free = render({}, { open: true });
+ expect(free.target.textContent).not.toContain('one request a side');
+ expect(free.target.textContent).not.toContain('Follow the map');
+ free.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.
+ const onrun = vi.fn();
+ const { target, done } = render({ onrun }, { open: true });
+ target.querySelector('.cloud-filter button').click();
+ flushSync();
+ await Promise.resolve();
+ expect(onrun).toHaveBeenCalledTimes(1);
+ done();
+ });
+
+ 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');
+ done();
+ });
+});
diff --git a/frontend/src/tools/compare/ExportFrame.svelte b/frontend/src/tools/compare/ExportFrame.svelte
index 0b67be4..66a6785 100644
--- a/frontend/src/tools/compare/ExportFrame.svelte
+++ b/frontend/src/tools/compare/ExportFrame.svelte
@@ -3,10 +3,13 @@
* The rectangle an export is framed to, drawn over the compared imagery.
*
* The frame is held on the ground, so it stays on the same roofs when the
- * camera moves. In Side by side, B shows the same box read-only. In an
- * overlaid mode, one stage-level frame spans whichever pixels are visible.
+ * camera moves. It keeps the bearing it was drawn at, so a turned camera
+ * turns it with the ground rather than reshaping it. In Side by side, B shows
+ * the same box read-only. In an overlaid mode, one stage-level frame spans
+ * whichever pixels are visible.
*/
import { boundedRect, frameSpan } from '../../lib/map/exportFrame.js';
+ import { boxCorners, compassAngle, turnedBox } from '../../lib/map/groundFrame.js';
import { formatDistance } from '../../lib/measure.js';
let { engine, frame = null, drawing = false, readonly = false, units = 'metric', bearing = 0,
@@ -37,13 +40,20 @@
w: Math.abs(second[0] - first[0]),
h: Math.abs(second[1] - first[1]),
});
+ const cornersOf = ({ x, y, w, h }) => [[x, y], [x + w, y], [x + w, y + h], [x, y + h]];
- const rect = $derived.by(() => {
- if (draft) return box(draft.from, draft.to);
+ /** The frame's four corners on screen: a box while drawn, its ground after. */
+ const corners = $derived.by(() => {
+ if (draft) return cornersOf(box(draft.from, draft.to));
if (!frame?.points || !engine) return null;
- return box(project(frame.points[0]), project(frame.points[1]));
+ return boxCorners(turnedBox(frame.points, frame.angle ?? 0)).map(project);
});
- const span = $derived(frame?.points && !draft ? frameSpan(frame.points, bearing) : null);
+ const outline = $derived(corners ? `M${corners.map((point) => point.join(',')).join(' L')} Z` : '');
+ // The tag hangs off the topmost corner, which is the top-left one until the camera turns.
+ const tagAt = $derived(corners?.reduce((top, point) =>
+ (point[1] < top[1] - 0.5 || (Math.abs(point[1] - top[1]) <= 0.5 && point[0] < top[0]) ? point : top)));
+ const drawnSize = $derived(draft ? box(draft.from, draft.to) : null);
+ const span = $derived(frame?.points && !draft ? frameSpan(frame.points, frame.angle ?? 0) : null);
function at(event) {
const bounds = root?.getBoundingClientRect();
@@ -88,7 +98,8 @@
const bounds = root.getBoundingClientRect();
const cut = boundedRect(drawn, { width: bounds.width, height: bounds.height });
const corners = [ground([cut.x, cut.y]), ground([cut.x + cut.w, cut.y + cut.h])];
- if (corners.every(Boolean)) onframe({ points: corners });
+ // The compass direction that is up, which is the app's clockwise turn counted back.
+ if (corners.every(Boolean)) onframe({ points: corners, angle: compassAngle(-bearing) });
else oncancel();
}
@@ -113,18 +124,17 @@
onpointerup={finish}
onpointercancel={finish}
>
- {#if rect}
+ {#if corners}
<svg class="frame-shape" aria-hidden="true">
{#if drawing}
- <path class="dim" fill-rule="evenodd"
- d={`M0,0 H99999 V99999 H0 Z M${rect.x},${rect.y} h${rect.w} v${rect.h} h${-rect.w} Z`} />
+ <path class="dim" fill-rule="evenodd" d={`M0,0 H99999 V99999 H0 Z ${outline}`} />
{/if}
- <rect class="edge" x={rect.x + 0.5} y={rect.y + 0.5} width={Math.max(0, rect.w - 1)} height={Math.max(0, rect.h - 1)} />
+ <path class="edge" d={outline} />
</svg>
{#if !readonly}
- <span class="frame-tag" style:left={`${rect.x}px`} style:top={`${rect.y}px`}>
+ <span class="frame-tag" style:left={`${tagAt[0]}px`} style:top={`${tagAt[1]}px`}>
{#if span}Export frame · {formatDistance(span.width, units)} × {formatDistance(span.height, units)}
- {:else}{Math.round(rect.w)} × {Math.round(rect.h)}{/if}
+ {:else if drawnSize}{Math.round(drawnSize.w)} × {Math.round(drawnSize.h)}{/if}
</span>
{/if}
{:else if drawing}
@@ -137,7 +147,7 @@
.export-frame.drawing { z-index: 600; pointer-events: auto; cursor: crosshair; touch-action: none; }
.frame-shape { position: absolute; inset: 0; width: 100%; height: 100%; }
.dim { fill: rgba(9, 11, 14, .55); }
- .edge { fill: none; stroke: #e8a33d; stroke-width: 2; stroke-dasharray: 7 5; }
+ .edge { fill: none; stroke: #e8a33d; stroke-width: 2; stroke-dasharray: 7 5; stroke-linejoin: miter; }
.readonly .edge { stroke: rgba(232, 163, 61, .6); stroke-dasharray: 4 6; }
.frame-tag {
position: absolute; transform: translateY(-100%); margin-top: -4px;
diff --git a/frontend/src/tools/compare/ExportFrame.test.js b/frontend/src/tools/compare/ExportFrame.test.js
index c748168..6f7dc2c 100644
--- a/frontend/src/tools/compare/ExportFrame.test.js
+++ b/frontend/src/tools/compare/ExportFrame.test.js
@@ -7,6 +7,7 @@
*/
import { afterEach, beforeEach, expect, it, vi } from 'vitest';
import { flushSync, mount, unmount } from 'svelte';
+import { fromMercator, toMercator } from '../../lib/map/groundFrame.js';
const { default: ExportFrame } = await import('./ExportFrame.svelte');
@@ -25,6 +26,37 @@ function fakeEngine() {
};
}
+/**
+ * A camera at one pixel to the metre, turned by the app's bearing: the map's
+ * clockwise turn, so the compass direction up is its negative. Its matrix is
+ * its own inverse, so the same one maps both ways.
+ */
+function turningEngine() {
+ handlers = {};
+ const engine = { bearing: 0 };
+ const turn = (a, b) => {
+ const t = (-engine.bearing * Math.PI) / 180;
+ return [a * Math.cos(t) - b * Math.sin(t), -a * Math.sin(t) - b * Math.cos(t)];
+ };
+ Object.assign(engine, {
+ on: (name, handler) => { handlers[name] = handler; return () => delete handlers[name]; },
+ latLngToContainerPoint: ({ lon, lat }) => {
+ const [x, y] = turn(...toMercator(lon, lat));
+ return { x: 200 + x, y: 150 + y };
+ },
+ containerPointToLatLng: ({ x, y }) => {
+ const [lon, lat] = fromMercator(...turn(x - 200, y - 150));
+ return { lon, lat };
+ },
+ });
+ return engine;
+}
+
+/** The frame's four corners on screen, read off its outline. */
+const corners = () => [...edge().getAttribute('d').matchAll(/(-?[\d.e-]+),(-?[\d.e-]+)/g)]
+ .map((match) => [Number(match[1]), Number(match[2])]);
+const side = (a, b) => Math.hypot(b[0] - a[0], b[1] - a[1]);
+
function press(node, type, x, y) {
node.dispatchEvent(new MouseEvent(type, { bubbles: true, clientX: x, clientY: y }));
flushSync();
@@ -39,6 +71,9 @@ function stage(props) {
}
const edge = () => target.querySelector('.edge');
+/** The corner xs of the drawn outline, which is a path now that it can turn. */
+const edgeXs = () => [...edge().getAttribute('d').matchAll(/(-?[\d.]+),(-?[\d.]+)/g)]
+ .map((match) => Number(match[1]));
beforeEach(() => { target = document.createElement('div'); document.body.append(target); });
afterEach(() => { if (live) unmount(live); target.remove(); });
@@ -51,18 +86,20 @@ it('hands back the ground the drag covered', () => {
press(root, 'pointermove', 380, 300);
press(root, 'pointerup', 380, 300);
- expect(onframe).toHaveBeenCalledWith({ points: [[2, 0], [38, 30]] });
+ // The bearing the box was drawn at travels with it, so it can be turned back upright.
+ expect(onframe).toHaveBeenCalledWith({ points: [[2, 0], [38, 30]], angle: 0 });
});
it('keeps the frame on its ground when the camera moves', () => {
stage({ frame: { points: [[5, 4], [25, 19]] } });
- expect(edge().getAttribute('x')).toBe('50.5');
+ expect(Math.min(...edgeXs())).toBeCloseTo(50, 6);
+ expect(Math.max(...edgeXs())).toBeCloseTo(250, 6);
origin.x = 120;
handlers['view-move']();
flushSync();
- expect(edge().getAttribute('x')).toBe('-69.5');
- expect(edge().getAttribute('width')).toBe('199');
+ expect(Math.min(...edgeXs())).toBeCloseTo(-70, 6);
+ expect(Math.max(...edgeXs()) - Math.min(...edgeXs())).toBeCloseTo(200, 6);
});
it('treats a press that barely travels as a click, not a frame', () => {
@@ -102,3 +139,40 @@ it('shows B the same box without letting it be drawn on', () => {
press(root, 'pointerup', 250, 190);
expect(onframe).not.toHaveBeenCalled();
});
+
+it('records the bearing it was drawn at', () => {
+ const onframe = vi.fn();
+ const engine = turningEngine();
+ engine.bearing = 35;
+ const root = stage({ engine, drawing: true, bearing: 35, onframe });
+ press(root, 'pointerdown', 40, 30);
+ press(root, 'pointermove', 380, 280);
+ press(root, 'pointerup', 380, 280);
+ // The map turned 35° clockwise puts compass 325° up.
+ expect(onframe.mock.calls[0][0].angle).toBe(325);
+});
+
+it('keeps its shape when the camera turns, turning with the ground', () => {
+ // The frame used to be the screen box around its two corners, which stretched
+ // and squashed as the camera turned.
+ const engine = turningEngine();
+ engine.bearing = 20;
+ const drawn = [{ x: 100, y: 80 }, { x: 300, y: 200 }]
+ .map((at) => engine.containerPointToLatLng(at)).map(({ lon, lat }) => [lon, lat]);
+ stage({ engine, frame: { points: drawn, angle: 340 } });
+ const [a, b, c] = corners();
+ expect(a[0]).toBeCloseTo(100, 4);
+ expect(c[1]).toBeCloseTo(200, 4);
+ expect(side(a, b)).toBeCloseTo(200, 4);
+ expect(side(b, c)).toBeCloseTo(120, 4);
+
+ engine.bearing = 65;
+ handlers['view-move']();
+ flushSync();
+ const [e, f, g, h] = corners();
+ expect(side(e, f)).toBeCloseTo(200, 4);
+ expect(side(f, g)).toBeCloseTo(120, 4);
+ expect(side(e, g)).toBeCloseTo(side(f, h), 4);
+ // The map turned 45° further clockwise, and the frame with the ground.
+ expect((Math.atan2(f[1] - e[1], f[0] - e[0]) * 180) / Math.PI).toBeCloseTo(45, 4);
+});
diff --git a/frontend/src/tools/compare/ModeControl.svelte b/frontend/src/tools/compare/ModeControl.svelte
index 9e44925..9de6961 100644
--- a/frontend/src/tools/compare/ModeControl.svelte
+++ b/frontend/src/tools/compare/ModeControl.svelte
@@ -2,8 +2,7 @@
/**
* The one control a reading mode needs, at the foot of the stage: B's
* opacity for a fade, speed and a manual flip for blink, the divider's
- * position for a swipe. The computing modes are not here — they own a panel
- * beside the stage instead, because a detection needs more than one row.
+ * position for a swipe. Difference's own strip sits beside it when on.
*/
import Icon from '../../components/Icon.svelte';
import { BLINK_SPEEDS, percentage } from '../../lib/map/compare.js';
diff --git a/frontend/src/tools/compare/ModeControl.test.js b/frontend/src/tools/compare/ModeControl.test.js
index d78ddf8..8fbc75a 100644
--- a/frontend/src/tools/compare/ModeControl.test.js
+++ b/frontend/src/tools/compare/ModeControl.test.js
@@ -23,11 +23,9 @@ describe('Compare mode footer', () => {
done();
});
- it('stays out of the computing modes, which own a panel instead', () => {
- for (const mode of ['side', 'change', 'analysis']) {
- const { target, done } = render({ mode });
- expect(target.textContent.trim()).toBe('');
- done();
- }
+ it('has nothing to offer side by side', () => {
+ const { target, done } = render({ mode: 'side' });
+ expect(target.textContent.trim()).toBe('');
+ done();
});
});
diff --git a/frontend/src/tools/compare/ModeDock.render.test.js b/frontend/src/tools/compare/ModeDock.render.test.js
index 659e2ba..e2ab2a4 100644
--- a/frontend/src/tools/compare/ModeDock.render.test.js
+++ b/frontend/src/tools/compare/ModeDock.render.test.js
@@ -2,65 +2,34 @@ import { describe, expect, it } from 'vitest';
import { render } from 'svelte/server';
import { readFileSync } from 'node:fs';
import ModeDock from './ModeDock.svelte';
-import AnalyzerPanel from './AnalyzerPanel.svelte';
const compare = readFileSync(new URL('../Compare.svelte', import.meta.url), 'utf8');
-/** Each named group, with the labels of the modes inside it. */
-function groups(body) {
- return body
- .split('role="group" aria-label="')
- .slice(1)
- .map((chunk) => [
- chunk.slice(0, chunk.indexOf('"')),
- [...chunk.matchAll(/<span class="svelte-[^"]*">([^<]+)<\/span>/g)].map((label) => label[1]),
- ]);
-}
+const labels = (body) =>
+ [...body.matchAll(/<span class="svelte-[^"]*">([^<]+)<\/span>/g)].map((label) => label[1]);
describe('the mode dock', () => {
- const ready = { ok: true, reason: '' };
-
- it('names its two kinds of choice apart', () => {
- const { body } = render(ModeDock, { props: { mode: 'side', change: ready } });
- expect(groups(body)).toEqual([
- ['View', ['Side by side', 'Swipe', 'Fade', 'Blink']],
- ['Analysis', ['Difference', 'Detect']],
- ]);
- });
-
- it('says what an analysis still needs on the button itself', () => {
- const { body } = render(ModeDock, {
- props: {
- mode: 'side',
- change: { ok: false, reason: 'Add imagery A and B first.' },
- detect: { ok: false, reason: 'Detect reads Copernicus Sentinel-2: add your credentials in Settings → Imagery.' },
- },
- });
- expect(body).toMatch(/class="mode-btn[^"]*blocked[^"]*"[^>]*title="Add imagery A and B first\."/);
- expect(body).toMatch(/class="mode-btn[^"]*blocked[^"]*"[^>]*title="Detect reads Copernicus Sentinel-2/);
- // a ready mode keeps its name and key as the tooltip
+ it('offers the four views, and Difference beside them on a pair it can read', () => {
+ const { body } = render(ModeDock, { props: { mode: 'side', differenceable: true } });
+ expect(labels(body)).toEqual(['Side by side', 'Swipe', 'Fade', 'Blink', 'Difference']);
expect(body).toContain('title="Swipe (2)"');
});
- it('marks nothing when every analysis can run', () => {
- const { body } = render(ModeDock, { props: { mode: 'change', change: ready, detect: ready } });
- expect(body).not.toContain('blocked');
+ it('does not offer Difference on a pair it cannot read', () => {
+ const { body } = render(ModeDock, { props: { mode: 'side', differenceable: false } });
+ expect(labels(body)).toEqual(['Side by side', 'Swipe', 'Fade', 'Blink']);
});
-});
-describe('Detect without Copernicus', () => {
- it('asks only once the provider list has been read, and never locks the panel', () => {
- expect(compare).toContain("imagery.providers.length && !imagery.find('sentinel2')");
- // saved areas and runs stay reachable: setMode refuses Difference, not Detect
- expect(compare).toContain("if (next === 'change' && !changeStatus.ok) {");
- expect(compare).not.toContain("next === 'analysis' && !detectStatus.ok");
+ it('keeps the view pressed while Difference is on over it', () => {
+ const { body } = render(ModeDock, { props: { mode: 'blink', difference: true, differenceable: true } });
+ const pressed = [...body.matchAll(/aria-pressed="true"[^>]*>[\s\S]*?<span class="svelte-[^"]*">([^<]+)</g)]
+ .map((match) => match[1]);
+ expect(pressed).toEqual(['Blink', 'Difference']);
});
- it('says so at the top of the panel, with the way to Settings', () => {
- const { body } = render(AnalyzerPanel, {
- props: { caseId: 'c1', needs: 'Detect reads Copernicus Sentinel-2: add your credentials in Settings → Imagery.' },
- });
- expect(body).toContain('Detect reads Copernicus Sentinel-2');
- expect(body).toContain('Open Settings');
+ it('has no door to Detect, which is its own tab', () => {
+ const { body } = render(ModeDock, { props: { mode: 'side', differenceable: true } });
+ expect(body).not.toContain('Detect');
+ expect(compare).not.toContain('detectHandoff');
});
});
diff --git a/frontend/src/tools/compare/ModeDock.svelte b/frontend/src/tools/compare/ModeDock.svelte
index d7eedc9..fae851c 100644
--- a/frontend/src/tools/compare/ModeDock.svelte
+++ b/frontend/src/tools/compare/ModeDock.svelte
@@ -1,43 +1,49 @@
<script>
/** How the pair is read, in one row at the top of the stage. */
import Icon from '../../components/Icon.svelte';
- import { COMPARE_MODES } from '../../lib/map/compare.js';
+ import { COMPARE_MODES, DIFFERENCE_KEY } from '../../lib/map/compare.js';
- let { mode, change, detect = { ok: true }, onmode = () => {}, onswap = () => {} } = $props();
-
- // Two kinds of choice, named: how the pair is shown, and what gets computed
- // over it. A computing mode says what it needs before it is pressed.
- const GROUPS = [
- { id: 'read', label: 'View' },
- { id: 'find', label: 'Analysis' },
- ];
- const needs = $derived({ change, analysis: detect });
+ let {
+ mode,
+ difference = false,
+ differenceable = false,
+ onmode = () => {},
+ ondifference = () => {},
+ onswap = () => {},
+ } = $props();
</script>
<div class="mode-dock cmp-glass" role="toolbar" aria-label="Comparison view">
- {#each GROUPS as group (group.id)}
- <div class="group" role="group" aria-label={group.label}>
- <span class="group-name">{group.label}</span>
- <div class="cmp-seg">
- {#each COMPARE_MODES.filter((entry) => entry.group === group.id) as entry (entry.id)}
- {@const missing = needs[entry.id] && !needs[entry.id].ok ? needs[entry.id].reason : ''}
- <button
- class="mode-btn"
- class:on={mode === entry.id}
- class:blocked={Boolean(missing)}
- class:find={entry.group === 'find'}
- aria-pressed={mode === entry.id}
- title={missing || `${entry.label} (${entry.key})`}
- onclick={() => onmode(entry.id)}
- >
- <Icon name={entry.icon} size={14} />
- <span>{entry.label}</span>
- {#if missing}<Icon name="alert" size={11} />{/if}
- </button>
- {/each}
- </div>
+ <div class="cmp-seg" role="group" aria-label="View">
+ {#each COMPARE_MODES as entry (entry.id)}
+ <button
+ class="mode-btn"
+ class:on={mode === entry.id}
+ aria-pressed={mode === entry.id}
+ title={`${entry.label} (${entry.key})`}
+ onclick={() => onmode(entry.id)}
+ >
+ <Icon name={entry.icon} size={14} />
+ <span>{entry.label}</span>
+ </button>
+ {/each}
+ </div>
+ <!-- Offered only on a pair a pixel reading can be fair to. It lays its
+ highlights over the view above rather than replacing it. -->
+ {#if differenceable}
+ <div class="cmp-seg">
+ <button
+ class="mode-btn difference"
+ class:on={difference}
+ aria-pressed={difference}
+ title={`Highlight what differs between A and B (${DIFFERENCE_KEY})`}
+ onclick={() => ondifference(!difference)}
+ >
+ <Icon name="changes" size={14} />
+ <span>Difference</span>
+ </button>
</div>
- {/each}
+ {/if}
<button class="cmp-icon" onclick={onswap} title="Swap A and B" aria-label="Swap A and B">
<Icon name="swap" size={15} />
</button>
@@ -47,34 +53,11 @@
.mode-dock {
display: flex;
align-items: center;
- gap: 10px;
+ gap: 8px;
padding: 4px 6px;
}
- .group {
- display: flex;
- align-items: center;
- gap: 6px;
- }
- .group-name {
- font-size: var(--fs-xs);
- letter-spacing: 0.04em;
- text-transform: uppercase;
- color: var(--glass-dim);
- }
- .mode-btn.blocked:not(.on) {
- color: var(--glass-dim);
- }
- .mode-btn.blocked :global(svg:last-child) {
- color: var(--warn);
- }
- /* A computing mode stays legible as one when it is on: the pair is unchanged
- underneath and something is being laid over it. */
- .mode-btn.find.on {
- color: var(--accent);
- }
@media (max-width: 1100px) {
- .mode-btn:not(.find) span,
- .group-name {
+ .mode-btn:not(.difference) span {
display: none;
}
}
diff --git a/frontend/src/tools/compare/PassStrip.svelte b/frontend/src/tools/compare/PassStrip.svelte
new file mode 100644
index 0000000..cef722a
--- /dev/null
+++ b/frontend/src/tools/compare/PassStrip.svelte
@@ -0,0 +1,330 @@
+<script>
+ /**
+ * Every dated picture of the point under the crosshair, and the bracket that
+ * dates a change on them.
+ *
+ * It opens on the archive A and B share, lists what that archive holds for
+ * the middle of the view from oldest to newest, and puts any row on either
+ * side with one press. Narrowing starts from A (the thing absent) and B (the
+ * thing there) and shows the middle picture on B, one question at a time,
+ * until the two ends are neighbours. The pure part is `lib/map/passStrip.js`.
+ *
+ * The list costs one request for the Copernicus archives and none for Esri,
+ * and is read only when the strip opens or the analyst asks again. Pictures
+ * are asked for separately, at their price.
+ */
+ import { untrack } from 'svelte';
+ import { api } from '../../lib/api.js';
+ import Icon from '../../components/Icon.svelte';
+ import { orbitMark } from '../../lib/radar.js';
+ import {
+ THUMB,
+ answerProbe,
+ between,
+ bracketSentence,
+ entryOf,
+ lookupPath,
+ lookupWindow,
+ nextProbe,
+ startBracket,
+ stripEntries,
+ thumbTiles,
+ undoAnswer,
+ } from '../../lib/map/passStrip.js';
+
+ let {
+ /** 'sentinel2' | 'sentinel1' | 'esri-wayback', the archive both sides show. */
+ archive,
+ /** Both sides as a saved comparison keeps them. */
+ a,
+ b,
+ view,
+ viewWidth = 1000,
+ provider = null,
+ maxcc = 100,
+ /** The provider id a row's picture is drawn from. */
+ variantFor,
+ onassign = () => {},
+ onbilled = () => {},
+ onclose = () => {},
+ } = $props();
+
+ const NAMES = { sentinel2: 'Sentinel-2', sentinel1: 'Sentinel-1 radar', 'esri-wayback': 'Esri Wayback' };
+ const metered = $derived(archive !== 'esri-wayback');
+
+ let answer = $state(null);
+ let busy = $state(false);
+ let note = $state('');
+ let readAt = $state(null);
+ let pictures = $state(null); // the view the pictures were drawn for, or null
+ let bracket = $state(null);
+ let copied = $state(false);
+
+ // Radar compares one track: the track is the pass on B, or on A.
+ const track = $derived(archive === 'sentinel1' ? (b?.radar?.time || a?.radar?.time || '') : '');
+ const entries = $derived(stripEntries(archive, answer, { maxcc, track }));
+ const onA = $derived(entryOf(entries, archive, a));
+ const onB = $derived(entryOf(entries, archive, b));
+ const moved = $derived(!!readAt && distance(readAt, view) > 1000);
+ const left = $derived(bracket ? between(entries, bracket).length : 0);
+ const done = $derived(!!bracket && !bracket.probe && !left);
+ const canNarrow = $derived(!bracket && !!startBracket(entries, onA, onB));
+ const perPicture = $derived(pictures ? thumbTiles({ ...pictures }, provider).length : 0);
+ const priced = $derived(thumbTiles({ ...view, viewWidth }, provider).length * entries.length);
+
+ function distance(from, to) {
+ const rad = Math.PI / 180;
+ const dy = (to.lat - from.lat) * 111_320;
+ const dx = (to.lon - from.lon) * 111_320 * Math.cos(from.lat * rad);
+ return Math.hypot(dx, dy);
+ }
+
+ async function read() {
+ busy = true;
+ note = '';
+ const at = { lat: view.lat, lon: view.lon, zoom: view.zoom };
+ try {
+ answer = await api.get(lookupPath(archive, at, lookupWindow(a, b)));
+ readAt = at;
+ bracket = null;
+ pictures = null;
+ if (metered) onbilled();
+ } catch (error) {
+ note = `Could not read the pictures of this point: ${error.message}`;
+ } finally {
+ busy = false;
+ }
+ }
+
+ // Read once when the strip opens on an archive; after that only on request.
+ let readFor = '';
+ $effect(() => {
+ const key = archive;
+ if (key === readFor) return;
+ readFor = key;
+ untrack(() => void read());
+ });
+
+ function assign(letter, entry) {
+ if (!entry.usable && archive === 'sentinel2') return;
+ onassign(letter, entry);
+ }
+
+ function probe(next) {
+ const row = nextProbe(entries, next);
+ bracket = row ? { ...next, probe: row.key } : next;
+ const before = entries.find((entry) => entry.key === bracket.before);
+ const after = entries.find((entry) => entry.key === bracket.after);
+ if (before) onassign('a', before);
+ if (row) onassign('b', row);
+ else if (after) onassign('b', after);
+ }
+
+ function narrow() {
+ const start = startBracket(entries, onA, onB);
+ if (start) probe(start);
+ }
+
+ function answerIt(verdict) {
+ probe(answerProbe(bracket, verdict));
+ }
+
+ function undo() {
+ probe(undoAnswer(bracket));
+ }
+
+ async function copy() {
+ try {
+ await navigator.clipboard.writeText(bracketSentence(entries, bracket, NAMES[archive]));
+ copied = true;
+ setTimeout(() => (copied = false), 1500);
+ } catch {
+ copied = false;
+ }
+ }
+
+ const label = (entry) => (entry.time ? `${entry.date} ${entry.time.slice(0, 5)}` : entry.date);
+ const tileUrl = (entry, tile) => `/api/tiles/${variantFor(entry)}/${tile.z}/${tile.x}/${tile.y}`;
+</script>
+
+<section class="strip cmp-glass" aria-label="Pictures of this point">
+ <header>
+ <strong>{NAMES[archive]}</strong>
+ <span class="hint">{entries.length ? `${entries.length} pictures of the crosshair, oldest first` : ''}</span>
+ <span class="grow"></span>
+ {#if moved}
+ <button class="linkish" onclick={read}>The map moved · read here</button>
+ {/if}
+ {#if entries.length && !pictures}
+ <button class="btn btn-sm" onclick={() => (pictures = { ...view, viewWidth })}
+ title="Draw each picture of the view in the strip">
+ Show pictures{metered ? ` · about ${priced} requests` : ''}
+ </button>
+ {:else if pictures}
+ <button class="btn btn-sm" onclick={() => (pictures = null)}>Hide pictures</button>
+ {/if}
+ <button class="cmp-icon" onclick={onclose} aria-label="Close the pictures strip" title="Close"><Icon name="x" size={13} /></button>
+ </header>
+
+ {#if busy}
+ <p class="hint">Reading the archive…</p>
+ {:else if note}
+ <p class="warn" role="alert">{note}</p>
+ {:else if answer && !entries.length}
+ <p class="hint">The archive holds no picture of this point in the window around A and B.</p>
+ {/if}
+
+ {#if entries.length}
+ <ol class="row" class:big={!!pictures}>
+ {#each entries as entry (entry.key)}
+ {@const isA = onA?.key === entry.key}
+ {@const isB = onB?.key === entry.key}
+ {@const inside = bracket && between(entries, bracket).includes(entry)}
+ <li class:off={!entry.usable} class:inside class:probe={bracket?.probe === entry.key}>
+ <button class="card" disabled={!entry.usable && archive === 'sentinel2'}
+ onclick={(event) => assign(event.altKey ? 'a' : 'b', entry)}
+ title={entry.usable ? 'Show on B · Alt to show on A'
+ : archive === 'sentinel1' ? 'Another track: it sees the ground from another angle'
+ : 'Over the cloud ceiling'}>
+ {#if pictures}
+ <span class="thumb" style:width={`${THUMB.width}px`} style:height={`${THUMB.height}px`}>
+ {#each thumbTiles(pictures, provider) as tile (`${tile.z}/${tile.x}/${tile.y}`)}
+ <img alt="" loading="lazy" src={tileUrl(entry, tile)} style:left={`${tile.left}px`}
+ style:top={`${tile.top}px`} style:width={`${tile.size}px`} style:height={`${tile.size}px`} />
+ {/each}
+ </span>
+ {/if}
+ <span class="when mono">{label(entry)} {orbitMark(entry.orbit)}</span>
+ {#if entry.note && !entry.time}<span class="note">{entry.note}</span>{/if}
+ </button>
+ <span class="tags">
+ {#if isA}<span class="tag a">A</span>{/if}
+ {#if isB}<span class="tag b">B</span>{/if}
+ {#if !isA}<button class="set" onclick={() => assign('a', entry)} aria-label={`Show ${label(entry)} on A`}>A</button>{/if}
+ </span>
+ </li>
+ {/each}
+ </ol>
+ {#if pictures && perPicture > 1}
+ <p class="hint">Each picture takes {perPicture} tiles here; they are cached once read.</p>
+ {/if}
+ {/if}
+
+ {#if entries.length}
+ <footer class="bracket">
+ {#if !bracket}
+ {#if canNarrow}
+ <span class="hint">A shows it absent and B present? Narrow it down one picture at a time.</span>
+ <button class="btn btn-sm btn-primary" onclick={narrow}>Date it</button>
+ {:else}
+ <span class="hint">Put a picture without it on A and one with it on B, A the older, to date when it appeared.</span>
+ {/if}
+ {:else if bracket.probe}
+ <span class="question">Is it there on B, <strong class="mono">{label(entries.find((entry) => entry.key === bracket.probe))}</strong>?
+ <span class="hint">{left} left to check</span></span>
+ <button class="btn btn-sm" onclick={() => answerIt('there')}>It is there</button>
+ <button class="btn btn-sm" onclick={() => answerIt('absent')}>Not yet</button>
+ <button class="btn btn-sm" onclick={() => answerIt('unclear')} title="Cloud, a smear, or a look that settles nothing">Can’t tell</button>
+ {#if bracket.history.length}<button class="linkish" onclick={undo}>Undo</button>{/if}
+ {:else if done}
+ <span class="question">{bracketSentence(entries, bracket, NAMES[archive])}</span>
+ <button class="btn btn-sm" onclick={copy}>{copied ? 'Copied' : 'Copy'}</button>
+ {#if bracket.history.length}<button class="linkish" onclick={undo}>Undo</button>{/if}
+ <button class="linkish" onclick={() => (bracket = null)}>Done</button>
+ {/if}
+ </footer>
+ {/if}
+</section>
+
+<style>
+ .strip {
+ display: grid;
+ gap: 6px;
+ margin: 6px 8px 0;
+ padding: 6px 8px;
+ }
+ header {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ font-size: var(--fs-xs);
+ }
+ .grow { flex: 1; }
+ .hint { color: var(--glass-muted, var(--text-3)); font-size: 10.5px; margin: 0; }
+ .warn { color: var(--warn, #e2a03f); font-size: var(--fs-xs); margin: 0; }
+ .row {
+ display: flex;
+ gap: 4px;
+ margin: 0;
+ padding: 2px 0 4px;
+ overflow-x: auto;
+ list-style: none;
+ }
+ li {
+ position: relative;
+ flex: 0 0 auto;
+ display: grid;
+ border: 1px solid transparent;
+ border-radius: var(--r-sm);
+ }
+ li.inside { border-color: color-mix(in srgb, var(--accent) 40%, transparent); }
+ li.probe { border-color: var(--accent); }
+ li.off { opacity: 0.45; }
+ .card {
+ display: grid;
+ justify-items: start;
+ gap: 2px;
+ padding: 4px 22px 4px 6px;
+ border-radius: var(--r-sm);
+ color: var(--glass-ink, var(--text-1));
+ font-size: 10.5px;
+ text-align: left;
+ }
+ .card:hover:not(:disabled) { background: var(--glass-hover, var(--bg-3)); }
+ .thumb {
+ position: relative;
+ display: block;
+ overflow: hidden;
+ border-radius: 3px;
+ background: #14171d;
+ }
+ .thumb img { position: absolute; image-rendering: auto; }
+ .note { color: var(--glass-muted, var(--text-3)); font-size: 10px; }
+ .tags {
+ position: absolute;
+ top: 3px;
+ right: 3px;
+ display: flex;
+ gap: 2px;
+ }
+ .tag, .set {
+ min-width: 15px;
+ padding: 0 3px;
+ border-radius: 3px;
+ font-size: 9.5px;
+ font-weight: 700;
+ line-height: 14px;
+ text-align: center;
+ }
+ .tag.a { background: var(--side-a, #38bdf8); color: #0b0d11; }
+ .tag.b { background: var(--side-b, #f59e0b); color: #0b0d11; }
+ .set { display: none; border: 1px solid var(--glass-line, var(--border)); color: var(--glass-muted, var(--text-3)); }
+ li:hover .set { display: block; }
+ .bracket {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: 8px;
+ font-size: var(--fs-xs);
+ }
+ .question { color: var(--glass-ink, var(--text-1)); }
+ .linkish {
+ background: none;
+ border: 0;
+ padding: 0;
+ color: var(--accent);
+ font-size: var(--fs-xs);
+ cursor: pointer;
+ text-decoration: underline;
+ }
+</style>
diff --git a/frontend/src/tools/compare/PassStrip.svelte.test.js b/frontend/src/tools/compare/PassStrip.svelte.test.js
new file mode 100644
index 0000000..52c8b3c
--- /dev/null
+++ b/frontend/src/tools/compare/PassStrip.svelte.test.js
@@ -0,0 +1,84 @@
+// @vitest-environment happy-dom
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { flushSync, mount, unmount } from 'svelte';
+
+const get = vi.fn();
+vi.mock('../../lib/api.js', () => ({ api: { get } }));
+const { default: PassStrip } = await import('./PassStrip.svelte');
+
+const DAYS = ['2026-05-03', '2026-05-08', '2026-05-13', '2026-05-18', '2026-05-23'];
+const side = (date) => ({ present: true, provider: 'sentinel2', sentinel: { date, layer: 'TRUE_COLOR', maxcc: 100 } });
+
+let live;
+let target;
+const settle = async () => { for (let i = 0; i < 40; i++) await Promise.resolve(); flushSync(); };
+const button = (text) => [...target.querySelectorAll('button')].find((node) => node.textContent.trim().startsWith(text));
+
+function open(props) {
+ const state = $state({ a: side(DAYS[0]), b: side(DAYS[4]) });
+ const onassign = vi.fn((letter, entry) => { state[letter] = side(entry.date); });
+ live = mount(PassStrip, {
+ target,
+ props: {
+ archive: 'sentinel2',
+ get a() { return state.a; },
+ get b() { return state.b; },
+ view: { lat: 51.9, lon: 4.0, zoom: 14 },
+ viewWidth: 900,
+ provider: { tile_size: 512, max_native_zoom: 14, max_zoom: 18 },
+ variantFor: (entry) => `sentinel2~TRUE_COLOR~${entry.date}~${entry.date}`,
+ onassign,
+ onbilled: vi.fn(),
+ ...props,
+ },
+ });
+ return { state, onassign };
+}
+
+beforeEach(() => {
+ get.mockReset();
+ get.mockResolvedValue({ dates: DAYS.map((date) => ({ date, cloud: 4, granules: 1 })).reverse() });
+ target = document.createElement('div');
+ document.body.append(target);
+});
+afterEach(() => {
+ if (live) unmount(live);
+ live = null;
+ target.remove();
+});
+
+it('reads the archive once, oldest first, and draws no picture until asked', async () => {
+ open();
+ await settle();
+ expect(get).toHaveBeenCalledOnce();
+ expect(get.mock.calls[0][0]).toContain('/api/satellite/sentinel/dates?lat=51.9&lon=4');
+ const cards = [...target.querySelectorAll('li')];
+ expect(cards.map((node) => node.querySelector('.when').textContent.trim())).toEqual(DAYS);
+ expect(target.querySelector('img')).toBe(null);
+ expect(button('Show pictures').textContent).toMatch(/about \d+ requests/);
+ button('Show pictures').click(); await settle();
+ expect(target.querySelector('img').getAttribute('src')).toMatch(/^\/api\/tiles\/sentinel2~TRUE_COLOR~2026-05-03~2026-05-03\/10\//);
+});
+
+it('shows a picture on B with a press, and on A from its own button', async () => {
+ const { onassign } = open();
+ await settle();
+ target.querySelectorAll('li .card')[2].click();
+ expect(onassign).toHaveBeenLastCalledWith('b', expect.objectContaining({ date: '2026-05-13' }));
+ target.querySelectorAll('li')[1].querySelector('.set').click();
+ expect(onassign).toHaveBeenLastCalledWith('a', expect.objectContaining({ date: '2026-05-08' }));
+});
+
+it('dates a change by halving the gap, and says what it found', async () => {
+ open();
+ await settle();
+ button('Date it').click(); await settle();
+ expect(target.textContent).toContain('Is it there on B, 2026-05-13?');
+ button('It is there').click(); await settle();
+ expect(target.textContent).toContain('Is it there on B, 2026-05-08?');
+ button('Not yet').click(); await settle();
+ expect(target.textContent).toContain(
+ 'Absent on 2026-05-08, present on 2026-05-13 (Sentinel-2).');
+ button('Undo').click(); await settle();
+ expect(target.textContent).toContain('Is it there on B, 2026-05-08?');
+});
diff --git a/frontend/src/tools/compare/SourceCard.svelte b/frontend/src/tools/compare/SourceCard.svelte
index 66b2d00..d927699 100644
--- a/frontend/src/tools/compare/SourceCard.svelte
+++ b/frontend/src/tools/compare/SourceCard.svelte
@@ -13,6 +13,7 @@
providerId = $bindable(),
s2,
wayback,
+ s1 = null,
shown,
dated = null,
layerCount = 0,
@@ -23,15 +24,17 @@
} = $props();
const lower = $derived(letter.toLowerCase());
+ // A Sentinel chip already names the day it was taken. A Wayback chip names
+ // when Esri published the mosaic, so the day under it still needs saying.
const showsDate = $derived(
- dated?.date && shown.provider?.id !== 'sentinel2' && shown.provider?.id !== 'esri-wayback'
+ dated?.date && !['sentinel2', 'sentinel1'].includes(shown.provider?.id)
);
</script>
<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} {shown} dateChip />
+ <ImageryChip {imagery} bind:providerId s2={s2} {wayback} {s1} {shown} dateChip />
</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/compare/SourceCard.test.js b/frontend/src/tools/compare/SourceCard.test.js
index 6631ecb..3835e53 100644
--- a/frontend/src/tools/compare/SourceCard.test.js
+++ b/frontend/src/tools/compare/SourceCard.test.js
@@ -93,6 +93,20 @@ describe('SourceCard', () => {
expect(layerIcons(body)).toBe(1);
});
+ it('dates a Wayback picture apart from the release that published it', () => {
+ const { body } = render(SourceCard, {
+ props: props({
+ providerId: 'esri-wayback',
+ wayback: release({ date: '2026-08-05' }),
+ shown: { fallenBack: false, blocked: false, provider: imagery.find('esri-wayback') },
+ dated: { date: '2015-05-10', source: 'Maxar' },
+ }),
+ });
+ expect(body).toContain('2026-08-05');
+ expect(body).toContain('2015-05-10');
+ expect(body).toContain('Acquired around this date (Maxar)');
+ });
+
it('shows the acquisition date beside a provider that has no picker', () => {
const { body } = render(SourceCard, {
props: props({
diff --git a/frontend/src/tools/compare/AcquisitionPicker.svelte b/frontend/src/tools/detect/AcquisitionPicker.svelte
similarity index 68%
rename from frontend/src/tools/compare/AcquisitionPicker.svelte
rename to frontend/src/tools/detect/AcquisitionPicker.svelte
index 0f14793..4d2317c 100644
--- a/frontend/src/tools/compare/AcquisitionPicker.svelte
+++ b/frontend/src/tools/detect/AcquisitionPicker.svelte
@@ -11,8 +11,9 @@
* and how much of it was cloud.
*/
import Icon from '../../components/Icon.svelte';
- import { LOOKBACK_WINDOWS, coverClass, coverLabel } from '../../lib/map/acquisitions.js';
+ import { LOOKBACK_WINDOWS, coverClass, coverLabel, passKey } from '../../lib/map/acquisitions.js';
import { cloudClass, cloudLabel } from '../../lib/sentinel.js';
+ import { orbitMark, sameTrack } from '../../lib/radar.js';
let {
list = [],
@@ -25,15 +26,24 @@
single = false,
wantsReference = true,
wantsCompare = true,
- a = '',
- b = '',
+ /** Sentinel-1 passes: a time and a direction instead of a cloud figure. */
+ radar = false,
+ /** The chosen sources, `{ date, time }` each, or null. */
+ a = null,
+ b = null,
ondays,
onlook,
onpick,
} = $props();
+
+ /** Whether a row is the pass a side names: a typed radar day matches its day. */
+ function names(source, entry) {
+ if (!source?.date || source.date !== entry.date) return false;
+ return !source.time || !entry.time || source.time === entry.time;
+ }
</script>
-<div class="passes" aria-label="Sentinel-2 passes over the areas">
+<div class="passes" aria-label={radar ? 'Sentinel-1 passes over the areas' : 'Sentinel-2 passes over the areas'}>
<div class="head">
<div class="cmp-seg" aria-label="How far back to look">
{#each LOOKBACK_WINDOWS as option (option.id)}
@@ -65,29 +75,40 @@
<p class="warn">The catalogue stopped at 100 passes, so older ones are missing. Shorten the window for a complete list.</p>
{/if}
<ul class="list">
- {#each list as entry (entry.date)}
- <li class:chosen={entry.date === a || entry.date === b}>
+ {#each list as entry (passKey(entry))}
+ {@const pairedA = !single && radar && a?.time && !sameTrack(entry.time, a.time)}
+ {@const pairedB = !single && radar && b?.time && !sameTrack(entry.time, b.time)}
+ <li class:chosen={names(a, entry) || names(b, entry)}>
<div class="facts">
<strong class="cmp-mono">{entry.date}</strong>
+ {#if radar}
+ <span class="cmp-mono time" title={entry.orbit ? `Flying ${entry.orbit === 'descending' ? 'south' : 'north'}` : undefined}>
+ {entry.time?.slice(0, 5)} UTC {orbitMark(entry.orbit)}</span>
+ {/if}
<span class="badge {coverClass(entry.coverage)}">{coverLabel(entry.coverage)}</span>
- <span class="badge {cloudClass(entry.cloud)}">{cloudLabel(entry.cloud) || 'cloud unknown'}</span>
+ {#if !radar}
+ <span class="badge {cloudClass(entry.cloud)}">{cloudLabel(entry.cloud) || 'cloud unknown'}</span>
+ {/if}
</div>
<div class="cmp-seg" aria-label={`Use ${entry.date}`}>
{#if wantsReference && !single}
<button
type="button"
- class:on={a === entry.date}
- aria-pressed={a === entry.date}
- title="Use as the reference image"
+ class:on={names(a, entry)}
+ aria-pressed={names(a, entry)}
+ disabled={pairedB}
+ title={pairedB ? 'Another track than B: it sees the ground from another angle' : 'Use as A, the picture before'}
onclick={() => onpick('a', entry)}
>A</button>
{/if}
{#if wantsCompare}
<button
type="button"
- class:on={b === entry.date}
- aria-pressed={b === entry.date}
- title={single ? 'Use as the image to inspect' : 'Use as the image to compare'}
+ class:on={names(b, entry)}
+ aria-pressed={names(b, entry)}
+ disabled={pairedA}
+ title={pairedA ? 'Another track than A: it sees the ground from another angle'
+ : single ? 'Use this pass' : 'Use as B, the picture to look in'}
onclick={() => onpick('b', entry)}
>{single ? 'Use' : 'B'}</button>
{/if}
@@ -97,7 +118,8 @@
</ul>
<p class="hint">
<Icon name="info" size={11} />
- A pass covers what its swath reached that day, not the whole map.
+ {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.'}
</p>
{/if}
</div>
@@ -165,6 +187,10 @@
gap: 6px;
flex-wrap: wrap;
}
+ .time {
+ color: var(--text-2);
+ font-size: 10.5px;
+ }
.facts strong {
color: var(--text-1);
font-size: var(--fs-xs);
diff --git a/frontend/src/tools/compare/AcquisitionPicker.test.js b/frontend/src/tools/detect/AcquisitionPicker.test.js
similarity index 80%
rename from frontend/src/tools/compare/AcquisitionPicker.test.js
rename to frontend/src/tools/detect/AcquisitionPicker.test.js
index cb5a82a..13ac9eb 100644
--- a/frontend/src/tools/compare/AcquisitionPicker.test.js
+++ b/frontend/src/tools/detect/AcquisitionPicker.test.js
@@ -95,4 +95,20 @@ describe('the acquisition picker', () => {
expect(target.textContent).toContain('No pass reaches these areas');
done();
});
+
+ it('lists radar passes by time and direction, and holds a pair to one track', () => {
+ const radar = [
+ { date: '2026-05-14', time: '17:33:02', orbit: 'ascending', cloud: null, coverage: 1 },
+ { date: '2026-05-14', time: '05:42:10', orbit: 'descending', cloud: null, coverage: 1 },
+ ];
+ const { target, done } = render({ list: radar, radar: true, a: { date: '2026-05-02', time: '05:42:40' } });
+ expect(rows(target)).toHaveLength(2);
+ expect(rows(target)[1].textContent).toContain('05:42 UTC ↓');
+ expect(target.textContent).not.toContain('cloud');
+ // the evening pass is another track than A's: it cannot be its pair
+ const [evening, morning] = rows(target).map((row) => [...row.querySelectorAll('button')].at(-1));
+ expect(evening.disabled).toBe(true);
+ expect(morning.disabled).toBe(false);
+ done();
+ });
});
diff --git a/frontend/src/tools/compare/AnalysisOverlay.svelte b/frontend/src/tools/detect/AnalysisOverlay.svelte
similarity index 72%
rename from frontend/src/tools/compare/AnalysisOverlay.svelte
rename to frontend/src/tools/detect/AnalysisOverlay.svelte
index 4e0dde7..be11c5f 100644
--- a/frontend/src/tools/compare/AnalysisOverlay.svelte
+++ b/frontend/src/tools/detect/AnalysisOverlay.svelte
@@ -1,6 +1,9 @@
<script>
import { displayGroups } from '../../lib/map/analyzers.js';
+ import { candidatePaths } from '../../lib/map/detectReview.js';
+ import { relayWheel } from '../../lib/map/wheelRelay.js';
let { engine, layers = [], selected = null, onpick = () => {}, active = true } = $props();
+ let svg = $state(null);
let revision = $state(0);
$effect(() => {
if (!engine) return;
@@ -16,15 +19,14 @@
const shown = $derived.by(() => {
if (!engine || !active) return [];
return layers.filter((layer) => layer.visible).map((layer) => ({ ...layer,
- boxes: visible(layer.results).map((row) => ({ id: row.id, points: box(row) })),
+ boxes: visible(layer.results).map((row) => ({ id: row.id, manual: row.origin === 'manual',
+ path: candidatePaths(row.geometry ?? rectangle(row), project) })),
groups: displayGroups(visible(layer.results), project),
}));
});
- function box(row) {
+ function rectangle(row) {
const [w, s, e, n] = row.bbox;
- return [[w, n], [e, n], [e, s], [w, s]].map((point) => {
- const p = project(point); return `${p.x},${p.y}`;
- }).join(' ');
+ return { type: 'Polygon', coordinates: [[[w, n], [e, n], [e, s], [w, s], [w, n]]] };
}
function pick(layer, group) {
if (group.rows.length > 1 && engine) {
@@ -34,18 +36,20 @@
}
</script>
-<svg class="analysis-overlay" aria-label="Analysis candidates">
+<svg class="analysis-overlay" bind:this={svg} aria-label="Analysis candidates"
+ onwheel={(event) => relayWheel(event, { engine, root: svg })}>
{#each shown as layer (layer.id)}
{#if layer.input.recipe.style !== 'pins'}
{#each layer.boxes as shape (shape.id)}
- <polygon points={shape.points} fill={layer.input.recipe.colour} fill-opacity="0.08"
- stroke={layer.input.recipe.colour} stroke-width="1.5" />
+ <path d={shape.path} fill={layer.input.recipe.colour} fill-opacity="0.08" fill-rule="evenodd"
+ stroke={layer.input.recipe.colour} stroke-width="1.5" stroke-dasharray={shape.manual ? '5 3' : undefined} />
{/each}
{/if}
{#each layer.groups as group, i (i)}
- {@const kept = group.rows.every((row) => row.review === 'kept')}
+ {@const kept = group.rows.every((row) => row.review === 'kept' || row.review === 'noted')}
<g role="button" tabindex="0" aria-label={group.rows.length > 1 ? `${group.rows.length} candidates` : group.rows[0].phenomenon}
- onclick={() => pick(layer, group)} onkeydown={(e) => { if (e.key === 'Enter' || e.key === ' ') pick(layer, group); }}>
+ onclick={(event) => { if (event.button === 0) pick(layer, group); }}
+ onkeydown={(e) => { if (e.key === 'Enter' || e.key === ' ') pick(layer, group); }}>
<!-- The one under review wears a ring, so the panel and the map are
never about two different candidates. -->
{#if group.rows.some((row) => row.id === selected)}
@@ -53,7 +57,8 @@
fill="none" stroke="#fff" stroke-width="2" />
{/if}
<circle cx={group.x} cy={group.y} r={group.rows.length > 1 ? 13 : 6}
- fill={layer.input.recipe.colour} stroke="#fff" stroke-width="1.5" />
+ fill={layer.input.recipe.colour} stroke="#fff" stroke-width="1.5"
+ stroke-dasharray={group.rows.some((row) => row.origin === 'manual') ? '3 2' : undefined} />
{#if group.rows.length > 1}<text x={group.x} y={group.y + 4}>{group.rows.length}</text>
{:else if kept}<circle cx={group.x} cy={group.y} r="2" fill="#fff" />{/if}
</g>
diff --git a/frontend/src/tools/detect/AnalyzerLibrary.svelte b/frontend/src/tools/detect/AnalyzerLibrary.svelte
new file mode 100644
index 0000000..f1af258
--- /dev/null
+++ b/frontend/src/tools/detect/AnalyzerLibrary.svelte
@@ -0,0 +1,224 @@
+<script>
+ /**
+ * What a detection can look for, shared by every case.
+ *
+ * A built-in is a method calibrated on real scenes. One of your own starts as
+ * a copy of the closest built-in, which is the only way to make one: the
+ * method comes with it, and what is yours is how picky it is, what it is
+ * called and how it looks on the map. Saying that up front is the point of
+ * this page; a method picked from a list of six told nobody what they were
+ * choosing between.
+ */
+ import { api } from '../../lib/api.js';
+ import { toast } from '../../lib/state.svelte.js';
+ import { analyzerGroups, analyzerLock, clone } from '../../lib/map/analyzers.js';
+ import AnalyzerSettings from './AnalyzerSettings.svelte';
+ import Icon from '../../components/Icon.svelte';
+
+ let { catalogue, onchanged = async () => {}, onsaved = () => {} } = $props();
+
+ /** 'list', 'base' (what a new one starts from) or 'edit'. */
+ let mode = $state('list');
+ let recipe = $state(null);
+ let readonly = $state(false);
+ let busy = $state(false);
+ let error = $state('');
+
+ const builtins = $derived(catalogue?.builtins ?? []);
+ const custom = $derived(catalogue?.custom ?? []);
+ const methodOf = (method) => catalogue?.methods?.find((m) => m.id === method) ?? {};
+ const capability = $derived(methodOf(recipe?.method));
+ const isNew = $derived(recipe?.id === 'custom');
+
+ async function act(fn) {
+ if (busy) return;
+ busy = true; error = '';
+ try { await fn(); } catch (e) { error = e.message; }
+ finally { busy = false; }
+ }
+
+ function view(entry) {
+ recipe = clone(entry);
+ readonly = builtins.some((r) => r.id === entry.id);
+ mode = 'edit';
+ }
+
+ /** Built-ins can't be written over, so a copy is how an analyst keeps a tuned version. */
+ function copy(entry) {
+ recipe = { ...clone(entry), id: 'custom', name: `${entry.name} copy` };
+ readonly = false;
+ mode = 'edit';
+ }
+
+ function back() {
+ mode = 'list';
+ recipe = null;
+ }
+
+ async function save() {
+ const saved = await api.post('/api/compare/analyzers', clone(recipe));
+ await onchanged();
+ onsaved(saved);
+ toast('Analyzer saved for all cases', 'ok');
+ back();
+ }
+
+ async function remove(entry) {
+ await api.del(`/api/compare/analyzers/${entry.id}`);
+ await onchanged();
+ toast('Analyzer removed from the library', 'ok');
+ }
+</script>
+
+{#if mode === 'list'}
+ <div class="cmp-dock-body">
+ {#if error}<p class="warn" role="alert">{error}</p>{/if}
+ <p class="hint">An analyzer is what a detection looks for: one calibrated method and how picky it is. Yours start as a copy of the closest built-in.</p>
+ <button class="btn btn-primary" onclick={() => (mode = 'base')}><Icon name="plus" size={14} /> New analyzer</button>
+
+ <section aria-label="My analyzers">
+ <strong>Mine</strong>
+ {#if !custom.length}<p class="hint">None yet.</p>{/if}
+ {#each custom as entry (entry.id)}
+ <div class="row entry">
+ <button class="pick grow" style={`--tint: ${entry.colour}`} disabled={busy} onclick={() => view(entry)}>
+ <span class="swatch" aria-hidden="true"></span>
+ <span class="name">{entry.name}<small>{methodOf(entry.method).label ?? entry.method}</small></span>
+ </button>
+ <button class="cmp-icon" title="Edit" aria-label={`Edit ${entry.name}`} disabled={busy} onclick={() => view(entry)}>
+ <Icon name="edit" size={13} />
+ </button>
+ <button class="cmp-icon" title="Delete" aria-label={`Delete ${entry.name}`} disabled={busy}
+ onclick={() => act(() => remove(entry))}><Icon name="trash" size={13} /></button>
+ </div>
+ {/each}
+ </section>
+
+ <section aria-label="Built-in analyzers">
+ <strong>Built in</strong>
+ {#each analyzerGroups({ ...catalogue, custom: [] }) as group (group.label)}
+ <p class="group">{group.label}</p>
+ {#each group.list as entry (entry.id)}
+ {@const trust = catalogue?.reliability?.[entry.id]}
+ {@const locked = analyzerLock(entry, catalogue)}
+ <div class="row entry">
+ <button class="pick grow" style={`--tint: ${entry.colour}`} onclick={() => view(entry)} title={locked || undefined}>
+ <span class="swatch" aria-hidden="true"></span>
+ <span class="name">{entry.name}{#if trust} <span class="trust {trust}">({trust})</span>{/if}{#if locked} <span class="lock"><Icon name="key" size={10} /> set up</span>{/if}<small>{entry.description}</small></span>
+ </button>
+ <button class="cmp-icon" title="Copy to tune" aria-label={`Copy ${entry.name}`} onclick={() => copy(entry)}>
+ <Icon name="copy" size={13} />
+ </button>
+ </div>
+ {/each}
+ {/each}
+ </section>
+ </div>
+{:else if mode === 'base'}
+ <div class="cmp-dock-body">
+ <h3>Start from</h3>
+ <p class="hint">Pick the analyzer closest to what you want to find. Its method comes with it; you tune the rest.</p>
+ <div class="bases">
+ {#each [...builtins, ...custom] as entry (entry.id)}
+ <button class="pick base" style={`--tint: ${entry.colour}`} onclick={() => copy(entry)}>
+ <span class="swatch" aria-hidden="true"></span>
+ <span class="name">{entry.name}<small>{entry.description || methodOf(entry.method).label}</small></span>
+ </button>
+ {/each}
+ </div>
+ </div>
+ <div class="cmp-dock-foot"><button class="btn btn-sm" onclick={back}>Cancel</button></div>
+{:else if recipe}
+ <div class="cmp-dock-body">
+ {#if error}<p class="warn" role="alert">{error}</p>{/if}
+ <h3>{isNew ? 'New analyzer' : readonly ? recipe.name : `Edit ${recipe.name}`}</h3>
+ <p class="measures"><span>Measures</span> {capability.label ?? recipe.method}</p>
+ {#if readonly}<p class="hint">A built-in can't be changed. Copy it to tune your own.</p>{/if}
+ <fieldset class="fields" disabled={readonly}>
+ <label title="The name shown in the analyzer library across all cases.">Name
+ <input aria-label="Analyzer name" bind:value={recipe.name} maxlength="120" />
+ </label>
+ <label title="What this analyzer looks for, and what it cannot tell you.">Description
+ <textarea bind:value={recipe.description} maxlength="500"></textarea>
+ </label>
+ </fieldset>
+ <AnalyzerSettings bind:recipe {capability} expanded {readonly} />
+ <details>
+ <summary>Label and colour</summary>
+ <fieldset class="fields" disabled={readonly}>
+ <label title="The label each candidate carries. It does not change what is detected.">Candidate label
+ <input bind:value={recipe.phenomenon} maxlength="120" />
+ </label>
+ <div class="row">
+ <label class="grow">Colour<input type="color" bind:value={recipe.colour} /></label>
+ <label class="grow">Layer style
+ <select bind:value={recipe.style}>
+ <option value="both">Pins and outlines</option><option value="pins">Pins</option><option value="outlines">Outlines with pins</option>
+ </select>
+ </label>
+ </div>
+ </fieldset>
+ </details>
+ </div>
+ <div class="cmp-dock-foot">
+ <div class="row">
+ <button class="btn btn-sm" onclick={back}>{readonly ? 'Back' : 'Cancel'}</button>
+ {#if readonly}
+ <button class="btn btn-primary grow" onclick={() => copy(recipe)}>Copy to tune</button>
+ {:else}
+ <button class="btn btn-primary grow" disabled={busy || !recipe.name.trim()} onclick={() => act(save)}>
+ {isNew ? 'Add to my analyzers' : 'Save changes'}
+ </button>
+ {/if}
+ </div>
+ {#if !readonly}<span class="reason">Shared by every case, and carried by Settings backup.</span>{/if}
+ </div>
+{/if}
+
+<style>
+ section { display: grid; gap: 4px; }
+ section > strong {
+ margin-bottom: 2px;
+ color: var(--text-2);
+ font-size: var(--fs-xs);
+ font-weight: 700;
+ letter-spacing: 0.06em;
+ text-transform: uppercase;
+ }
+ h3 { margin: 0; font-size: var(--fs-sm); font-weight: 700; }
+ .entry { gap: 2px; }
+ .pick {
+ display: flex;
+ align-items: flex-start;
+ gap: 8px;
+ min-width: 0;
+ padding: 6px 8px;
+ border-radius: var(--r-sm);
+ text-align: left;
+ }
+ .pick:hover:not(:disabled) { background: var(--bg-2); }
+ .base { border: 1px solid var(--border); background: var(--bg-2); }
+ .base:hover { border-color: var(--accent); }
+ .bases { display: grid; gap: 6px; }
+ .swatch { flex: 0 0 auto; width: 9px; height: 9px; margin-top: 4px; border-radius: 50%; background: var(--tint); }
+ .name { display: grid; gap: 2px; min-width: 0; color: var(--text-1); font-size: var(--fs-xs); font-weight: 600; }
+ .name small { color: var(--text-3); font-size: 10.5px; font-weight: 400; line-height: 1.4; }
+ .measures { margin: 0; color: var(--text-1); font-size: var(--fs-xs); }
+ .measures span { margin-right: 4px; color: var(--text-3); font-weight: 700; }
+ .fields { display: grid; gap: 8px; min-width: 0; margin: 0; padding: 0; border: 0; }
+ details { display: grid; gap: 8px; }
+ details[open] { padding-top: 4px; }
+ summary { color: var(--text-2); font-size: var(--fs-xs); cursor: pointer; }
+ .group {
+ margin: 8px 0 2px;
+ color: var(--text-3);
+ font-size: 10px;
+ font-weight: 700;
+ letter-spacing: 0.06em;
+ text-transform: uppercase;
+ }
+ .trust { color: var(--text-3); font-size: 10.5px; font-weight: 400; }
+ .trust.reliable { color: var(--ok, #46a758); }
+ .trust.rough { color: var(--warn, #e2a03f); }
+ .lock { display: inline-flex; align-items: center; gap: 3px; color: var(--accent); font-size: 10.5px; font-weight: 400; }
+</style>
diff --git a/frontend/src/tools/detect/AnalyzerSettings.svelte b/frontend/src/tools/detect/AnalyzerSettings.svelte
new file mode 100644
index 0000000..ad2d134
--- /dev/null
+++ b/frontend/src/tools/detect/AnalyzerSettings.svelte
@@ -0,0 +1,116 @@
+<script>
+ /**
+ * How picky an analyzer is: the target size first, then the cloud switch,
+ * then the thresholds behind a link. One component, so a detection tuned for
+ * one run and an analyzer tuned for the library read the same numbers the
+ * same way. What the method can do comes from the catalogue, never from its
+ * name.
+ */
+ import CloudFilter from '../compare/CloudFilter.svelte';
+ import { sizeBand, sizeOf } from '../../lib/map/analyzers.js';
+
+ const SIZES = [['small', 'Small'], ['medium', 'Medium'], ['large', 'Large'], ['all', 'All']];
+ const INDICES = [
+ ['ndvi', 'NDVI · vegetation'], ['nbr', 'NBR · burn scars'], ['mndwi', 'MNDWI · open water'],
+ ['ndwi', 'NDWI · open water'], ['bsi', 'BSI · bare soil'], ['ndbi', 'NDBI · built-up'],
+ ];
+
+ let {
+ recipe = $bindable(),
+ capability = {},
+ /** Thresholds shown outright rather than behind a link. */
+ expanded = false,
+ readonly = false,
+ } = $props();
+
+ let showThresholds = $state(false);
+ const open = $derived(expanded || showThresholds);
+ const single = $derived(!!capability.single);
+ const size = $derived(sizeOf(recipe.parameters, capability.sizes));
+
+ function setSize(name) {
+ if (readonly || !capability.sizes?.[name]) return;
+ recipe.parameters = { ...recipe.parameters, ...capability.sizes[name] };
+ }
+
+ function setWeather(on) {
+ if (readonly) return;
+ recipe.parameters = { ...recipe.parameters, ignore_clouds: on, ignore_shadows: on };
+ }
+</script>
+
+<fieldset class="settings" disabled={readonly}>
+ {#if capability.sizes}
+ <div class="cmp-seg fill" role="group" aria-label="Target size">
+ {#each SIZES as [name, label] (name)}
+ {#if capability.sizes[name]}
+ <button type="button" class:on={size === name} aria-pressed={size === name}
+ title={sizeBand(capability.sizes[name])} onclick={() => setSize(name)}>{label}</button>
+ {/if}
+ {/each}
+ </div>
+ <p class="hint">{size ? sizeBand(capability.sizes[size]) : 'Sizes are set by hand below.'}</p>
+ {/if}
+ {#if capability.clouds}
+ <CloudFilter clouds={recipe.parameters.ignore_clouds} shadows={recipe.parameters.ignore_shadows}
+ ontoggle={setWeather} />
+ {/if}
+ {#if !expanded}
+ <button type="button" class="link" onclick={() => (showThresholds = !showThresholds)} aria-expanded={showThresholds}>
+ {showThresholds ? 'Hide thresholds' : 'Adjust thresholds…'}
+ </button>
+ {/if}
+ {#if open}
+ <label title="Higher finds fainter signals, and more noise with them.">Sensitivity · {recipe.parameters.sensitivity}
+ <input aria-label="Analyzer sensitivity" type="range" min="0" max="100" bind:value={recipe.parameters.sensitivity} />
+ </label>
+ <div class="row">
+ <label class="grow" title="Drop candidates smaller than this.">Min area (m²)
+ <input aria-label="Minimum area" type="number" min="0" max="100000000" bind:value={recipe.parameters.min_area} />
+ </label>
+ <label class="grow" title="Drop candidates larger than this; 0 keeps them all.">Max area (m²)
+ <input aria-label="Maximum area" type="number" min="0" max="100000000" bind:value={recipe.parameters.max_area} />
+ </label>
+ </div>
+ {#if recipe.method === 'index'}
+ <label>Index
+ <select aria-label="Spectral index" bind:value={recipe.parameters.index}>
+ {#each INDICES as [id, label] (id)}<option value={id}>{label}</option>{/each}
+ </select>
+ </label>
+ {/if}
+ {#if !single}
+ <label title="Keep what brightened, what darkened, or both.">Direction
+ <select bind:value={recipe.parameters.direction}><option value="both">Both</option><option value="gain">Gain</option><option value="loss">Loss</option></select>
+ </label>
+ {/if}
+ {#if capability.clouds}
+ <label class="check"><input type="checkbox" bind:checked={recipe.parameters.ignore_clouds} /> Exclude cloud and snow</label>
+ <label class="check"><input type="checkbox" bind:checked={recipe.parameters.ignore_shadows} /> Exclude cloud shadow</label>
+ <label title="Grow the mask past the edge the classification drew.">Mask margin · {recipe.parameters.cloud_margin}px
+ <input aria-label="Cloud mask margin" type="range" min="0" max="10" bind:value={recipe.parameters.cloud_margin} />
+ </label>
+ {/if}
+ <details>
+ <summary>Noise and grouping</summary>
+ <label title="Remove specks narrower than this; it also removes small real objects.">Noise cleanup · {recipe.parameters.cleanup}px<input type="range" min="0" max="3" bind:value={recipe.parameters.cleanup} /></label>
+ <label title="Blur the reading first; zero keeps the finest detail.">Smoothing · {recipe.parameters.smoothing}px<input type="range" min="0" max="3" bind:value={recipe.parameters.smoothing} /></label>
+ <label title="Join candidates this close; zero joins only touching ones.">Group within (m)<input type="number" min="0" max="500" bind:value={recipe.parameters.merge_metres} /></label>
+ </details>
+ {/if}
+</fieldset>
+
+<style>
+ .settings {
+ display: grid;
+ gap: 8px;
+ min-width: 0;
+ margin: 0;
+ padding: 0;
+ border: 0;
+ }
+ details { display: grid; gap: 8px; }
+ details[open] { padding-top: 4px; }
+ summary { color: var(--text-2); font-size: var(--fs-xs); cursor: pointer; }
+ .link { justify-self: start; color: var(--accent); font-size: var(--fs-xs); text-align: left; }
+</style>
diff --git a/frontend/src/tools/detect/AreaDates.svelte b/frontend/src/tools/detect/AreaDates.svelte
new file mode 100644
index 0000000..f48ce1e
--- /dev/null
+++ b/frontend/src/tools/detect/AreaDates.svelte
@@ -0,0 +1,96 @@
+<script>
+ import { api } from '../../lib/api.js';
+ import { acquisitionQuery, coverageWarning, passKey } from '../../lib/map/acquisitions.js';
+ import AcquisitionPicker from './AcquisitionPicker.svelte';
+ import DateField from '../../components/DateField.svelte';
+
+ let {
+ zones, pairs = $bindable([]), single = false, baselineOnly = false,
+ /** Which collection the passes come from: radar passes carry a time. */
+ sensor = 'sentinel2',
+ onshow = () => {},
+ } = $props();
+ const radar = $derived(sensor === 'sentinel1');
+ let looking = $state(null);
+ let passes = $state([]);
+ let days = $state(90);
+ let busy = $state(false);
+ let error = $state('');
+ let searched = $state(false);
+ let truncated = $state(false);
+ let generation = 0;
+ const pairFor = (id) => pairs.find((p) => p.area_id === id);
+
+ async function lookup(zone) {
+ looking = zone.id; busy = true; error = ''; searched = false; passes = [];
+ const mine = ++generation;
+ try {
+ const found = await api.post('/api/satellite/sentinel/acquisitions',
+ acquisitionQuery([zone], days, new Date(), sensor));
+ if (mine !== generation) return;
+ passes = found.dates ?? []; searched = true; truncated = !!found.truncated;
+ } catch (e) { if (mine === generation) error = e.message; }
+ finally { if (mine === generation) busy = false; }
+ }
+ /** A typed day has no time yet: the engine settles which pass of it at launch. */
+ function pick(id, letter, date, time = '') {
+ pairs = pairs.map((pair) => pair.area_id !== id ? pair : {
+ ...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 } : {}) });
+ }
+ const at = (source) => (radar && source?.time ? `${source.time.slice(0, 5)} UTC` : '');
+</script>
+
+<div class="dates-table">
+ <table aria-label="Dates per area">
+ <thead><tr><th>Area</th>{#if !single}<th>A · before</th>{/if}{#if !baselineOnly}<th>{single ? 'Image' : 'B · after'}</th>{/if}<th></th></tr></thead>
+ <tbody>
+ {#each zones as zone (zone.id)}
+ {@const pair = pairFor(zone.id)}
+ {#if pair}
+ <tr>
+ <th>{zone.name}</th>
+ {#if !single}
+ <td><DateField day reading={false} label={`Reference for ${zone.name}`} value={pair.a.date}
+ onchange={(value) => pick(zone.id, 'a', value ?? '')} />
+ {#if at(pair.a)}<small class="mono">{at(pair.a)}</small>{/if}
+ {#if pair.date_rule === 'latest_previous'}<small>Then the pass before</small>{/if}</td>
+ {/if}
+ {#if !baselineOnly}
+ <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}
+ <td><button class="btn btn-sm" disabled={busy} onclick={() => lookup(zone)} aria-label={`Find passes for ${zone.name}`}>Find passes</button></td>
+ </tr>
+ {/if}
+ {/each}
+ </tbody>
+ </table>
+</div>
+{#if looking}
+ {@const pair = pairFor(looking)}
+ <p class="hint">{zones.find((zone) => zone.id === looking)?.name}</p>
+ <AcquisitionPicker list={passes} {days} {busy} {error} {searched} {truncated} areas={1} {radar}
+ {single} wantsReference={!single} wantsCompare={!baselineOnly} a={pair?.a ?? null} b={pair?.b ?? null}
+ ondays={(value) => (days = value)} onlook={() => lookup(zones.find((zone) => zone.id === looking))}
+ onpick={(letter, entry) => pick(looking, letter, entry.date, entry.time ?? '')} />
+ {#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}
+ {/each}
+{/if}
+
+<style>
+ .dates-table { overflow: auto; }
+ table { width: 100%; border-collapse: collapse; font-size: var(--fs-xs); }
+ th, td { padding: 7px 5px; border-bottom: 1px solid var(--border); text-align: left; vertical-align: top; }
+ td :global(.date-field) { width: 145px; }
+ small { display: block; color: var(--text-3); max-width: 150px; }
+ .mono { font-family: var(--font-mono); }
+ .link { color: var(--accent); font-size: var(--fs-xs); }
+</style>
diff --git a/frontend/src/tools/detect/AreasPanel.svelte b/frontend/src/tools/detect/AreasPanel.svelte
new file mode 100644
index 0000000..7136aaa
--- /dev/null
+++ b/frontend/src/tools/detect/AreasPanel.svelte
@@ -0,0 +1,225 @@
+<script>
+ /**
+ * The case's shared areas: the ground this case watches, named and coloured
+ * once and referenced by every routine and pass that sweeps it.
+ *
+ * A row reads like the map: the colour it is drawn in, its name, how big it
+ * is and what uses it. Pressing a row frames it; editing is asked for rather
+ * than always on screen, so the list stays a list.
+ *
+ * A new shape reaches every routine that watches the area, from its next
+ * run, since a routine reads its areas when it runs. A finished run froze
+ * its own copy and keeps the ground it swept. Saving the shape as a new area
+ * leaves the routines on the old one.
+ */
+ import { untrack } from 'svelte';
+ import { api } from '../../lib/api.js';
+ import { ensureCase, prefs, reloadCase } from '../../lib/state.svelte.js';
+ import { zoneRing } from '../../lib/map/analyzers.js';
+ import { formatArea, polygonArea } from '../../lib/measure.js';
+ import { plural } from '../../lib/map/detections.js';
+ import Icon from '../../components/Icon.svelte';
+ import Modal from '../../components/Modal.svelte';
+
+ let { caseId, areas = [], routines = [], selectedArea = null, hidden = $bindable([]),
+ zones = $bindable([]), drawing = $bindable('select'),
+ /** The shape the map shows its corners for. */
+ selectedZone = $bindable(null),
+ onrefresh = async () => {}, onusecurrentview = () => {}, onframe = () => {} } = $props();
+
+ let error = $state('');
+ let busy = $state(false);
+ let removing = $state(null);
+ let editing = $state(null);
+ /** The area whose corners are on the map, and whether it was drawn before. */
+ let reshaping = $state(null);
+
+ const users = $derived(removing ? routines.filter((routine) => routine.zones?.some((z) => z.id === removing.id)) : []);
+ const usedBy = (area) => routines.filter((routine) => routine.zones?.some((z) => z.id === area.id)).length;
+ const size = (area) => formatArea(
+ polygonArea(area.geometry.coordinates[0].slice(0, -1).map(([lon, lat]) => ({ lon, lat }))),
+ prefs.units
+ );
+ const ringOf = (area) => [{ kind: 'polygon', points: area.geometry.coordinates[0] }];
+
+ async function act(fn) {
+ busy = true; error = '';
+ try { await fn(); await onrefresh(); await reloadCase(); }
+ catch (e) { error = e.message; }
+ finally { busy = false; }
+ }
+ async function save(zone) {
+ const owner = await ensureCase();
+ const ring = zoneRing(zone);
+ await api.post(`/api/cases/${owner.id}/analysis/areas`, { name: zone.name, colour: '#38bdf8',
+ geometry: { type: 'Polygon', coordinates: [[...ring, ring[0]]] } });
+ zones = zones.filter((z) => z.id !== zone.id); drawing = 'select';
+ }
+ async function update(area, patch) {
+ await api.put(`/api/cases/${caseId}/analysis/areas/${area.id}`, {
+ name: area.name, colour: area.colour, geometry: area.geometry, ...patch,
+ });
+ }
+ /** The area put on the map as a shape to drag, in place of its own outline. */
+ function reshape(area) {
+ reshaping = { area, wasHidden: hidden.includes(area.id) };
+ zones = [...zones.filter((zone) => zone.id !== area.id),
+ { id: area.id, name: area.name, kind: 'polygon', points: area.geometry.coordinates[0].slice(0, -1) }];
+ if (!reshaping.wasHidden) hidden = [...hidden, area.id];
+ drawing = 'select';
+ selectedZone = area.id;
+ editing = null;
+ onframe(ringOf(area));
+ }
+
+ function endReshape() {
+ if (!reshaping) return;
+ const { area, wasHidden } = reshaping;
+ zones = zones.filter((zone) => zone.id !== area.id);
+ if (!wasHidden) hidden = hidden.filter((id) => id !== area.id);
+ if (selectedZone === area.id) selectedZone = null;
+ reshaping = null;
+ }
+
+ async function saveShape(asNew) {
+ const { area } = reshaping;
+ const ring = zoneRing(zones.find((zone) => zone.id === area.id));
+ const geometry = { type: 'Polygon', coordinates: [[...ring, ring[0]]] };
+ if (asNew) {
+ await api.post(`/api/cases/${caseId}/analysis/areas`, { name: `${area.name} · new shape`, colour: area.colour, geometry });
+ } else {
+ await update(area, { geometry });
+ }
+ endReshape();
+ }
+
+ // Leaving the tab halfway puts the area back as it was.
+ $effect(() => () => untrack(endReshape));
+
+ const toggle = (id) => (hidden = hidden.includes(id) ? hidden.filter((value) => value !== id) : [...hidden, id]);
+</script>
+
+<div class="area-actions">
+ <button class="btn btn-sm" class:active={drawing === 'polygon'}
+ onclick={() => (drawing = drawing === 'polygon' ? 'select' : 'polygon')}>Draw an area</button>
+ <button class="btn btn-sm" onclick={onusecurrentview}>Use current view</button>
+ {#if areas.length > 1}
+ <button class="btn btn-sm" onclick={() => onframe(areas.flatMap(ringOf))}>Show all</button>
+ {/if}
+</div>
+{#if error}<p class="warn" role="alert">{error}</p>{/if}
+{#if drawing === 'polygon'}<p class="hint">Click corners; Enter finishes, Escape cancels.</p>{/if}
+
+{#if reshaping}
+ {@const watching = usedBy(reshaping.area)}
+ <div class="reshape" role="group" aria-label={`Reshaping ${reshaping.area.name}`}>
+ <p><strong>{reshaping.area.name}</strong> · drag its corners on the map.</p>
+ <p class="hint">{watching
+ ? `${plural(watching, 'routine')} ${watching === 1 ? 'watches' : 'watch'} it: the next runs sweep the new shape.`
+ : 'No routine watches it yet.'} Finished runs keep the ground they swept.</p>
+ <div class="area-actions">
+ <button class="btn btn-sm btn-primary" disabled={busy} onclick={() => act(() => saveShape(false))}>Save shape</button>
+ <button class="btn btn-sm" disabled={busy} title="Keep this area as it was, and its routines on it"
+ onclick={() => act(() => saveShape(true))}>Save as a new area</button>
+ <button class="btn btn-sm" disabled={busy} onclick={endReshape}>Cancel</button>
+ </div>
+ </div>
+{/if}
+
+{#each zones.filter((zone) => zone.id !== reshaping?.area.id) as zone (zone.id)}
+ <div class="draft">
+ <input aria-label="Area name" bind:value={zone.name} maxlength="120" />
+ <button class="btn btn-sm btn-primary" disabled={busy} onclick={() => act(() => save(zone))}>Save as area</button>
+ </div>
+{/each}
+
+{#if !areas.length}
+ <div class="empty">
+ <p>No shared area in this case yet.</p>
+ <p class="hint">Draw one here and every routine can watch it.</p>
+ </div>
+{/if}
+
+{#each areas as area (area.id)}
+ {@const off = hidden.includes(area.id)}
+ <div class="area-row" class:selected={selectedArea === area.id} class:off>
+ <button class="cmp-icon" aria-label={off ? `Show ${area.name}` : `Hide ${area.name}`} aria-pressed={!off}
+ title={off ? 'Show on the map' : 'Hide on the map'} onclick={() => toggle(area.id)}>
+ <Icon name={off ? 'eyeOff' : 'eye'} size={14} />
+ </button>
+ <span class="swatch" style={`--tint: ${area.colour}`}></span>
+ <button class="name" title="Frame this area" onclick={() => onframe(ringOf(area))}>
+ <strong>{area.name}</strong>
+ <small>{size(area)}{usedBy(area) ? ` · ${plural(usedBy(area), 'routine')}` : ''}</small>
+ </button>
+ <button class="cmp-icon" aria-label={`Edit ${area.name}`} title="Rename, recolour or reshape"
+ onclick={() => (editing = editing === area.id ? null : area.id)}><Icon name="edit" size={13} /></button>
+ <button class="cmp-icon" title="Delete area" aria-label={`Delete ${area.name}`} disabled={busy}
+ onclick={() => (removing = area)}><Icon name="trash" size={13} /></button>
+ </div>
+ {#if editing === area.id}
+ <div class="edit">
+ <input type="color" aria-label={`Colour of ${area.name}`} value={area.colour} disabled={busy}
+ onchange={(e) => act(() => update(area, { colour: e.currentTarget.value }))} />
+ <input aria-label={`Rename ${area.name}`} value={area.name} maxlength="120" disabled={busy}
+ onchange={(e) => act(() => update(area, { name: e.currentTarget.value }))} />
+ <button class="btn btn-sm" disabled={busy || !!reshaping} onclick={() => reshape(area)}>Reshape on the map</button>
+ </div>
+ {/if}
+{/each}
+
+{#if removing}
+ <Modal title={`Delete ${removing.name}?`} onclose={() => (removing = null)}>
+ {#if users.length}
+ <p>Remove this area from these routines first:</p>
+ <ul>{#each users as routine (routine.id)}<li>{routine.title}</li>{/each}</ul>
+ {:else}
+ <p>The area moves to Trash. Existing runs keep their own copy.</p>
+ <button class="btn btn-danger" disabled={busy} onclick={() => act(async () => {
+ await api.del(`/api/cases/${caseId}/analysis/areas/${removing.id}`); removing = null;
+ })}>Move to Trash</button>
+ {/if}
+ {#if error}<p class="warn" role="alert">{error}</p>{/if}
+ </Modal>
+{/if}
+
+<style>
+ .area-actions, .draft, .edit { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; }
+ .draft, .edit { padding: 7px 0; }
+ .reshape {
+ display: grid;
+ gap: 6px;
+ padding: 8px 9px;
+ border: 1px solid var(--accent);
+ border-radius: var(--r-sm);
+ background: var(--accent-soft);
+ }
+ .reshape p { margin: 0; font-size: var(--fs-xs); }
+ .area-row {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ padding: 5px 4px;
+ border-radius: var(--r-sm);
+ }
+ .area-row:hover { background: var(--bg-2); }
+ .area-row.selected { background: var(--accent-soft); }
+ .area-row.off .name { opacity: 0.55; }
+ .swatch { flex: 0 0 auto; width: 10px; height: 10px; border-radius: 3px; background: var(--tint); }
+ .name { display: grid; flex: 1; gap: 1px; min-width: 0; text-align: left; }
+ .name strong { overflow: hidden; font-size: var(--fs-xs); font-weight: 600; text-overflow: ellipsis; white-space: nowrap; }
+ .name small { color: var(--text-3); font-size: 10.5px; }
+ .name:hover strong { color: var(--accent); }
+ .empty {
+ display: grid;
+ gap: 4px;
+ padding: 14px 12px;
+ border: 1px dashed var(--border);
+ border-radius: var(--r-sm);
+ text-align: center;
+ }
+ .empty p { margin: 0; font-size: var(--fs-xs); color: var(--text-2); }
+ input:not([type]) { flex: 1; width: 100px; }
+ input[type='color'] { width: 26px; height: 26px; padding: 0; }
+ .active { outline: 1px solid var(--accent); }
+</style>
diff --git a/frontend/src/tools/detect/DetectAreas.render.test.js b/frontend/src/tools/detect/DetectAreas.render.test.js
new file mode 100644
index 0000000..9c17f3f
--- /dev/null
+++ b/frontend/src/tools/detect/DetectAreas.render.test.js
@@ -0,0 +1,85 @@
+// @vitest-environment happy-dom
+import { afterEach, expect, it, vi } from 'vitest';
+import { flushSync, mount, unmount } from 'svelte';
+import DetectAreas from './DetectAreas.svelte';
+
+const engine = {
+ on: vi.fn(() => () => {}),
+ latLngToContainerPoint: vi.fn(({ lat, lon }) => ({ x: (lon - 2) * 1000, y: (48 - lat) * 1000 })),
+};
+// The fake projection is 1000 px per degree, so the first area draws 100 px
+// across and the second only 10.
+const groups = [
+ { id: 'w1', title: 'Harbour weekly', colour: '#38bdf8',
+ zones: [{ id: 'z1', name: 'Anchorage', kind: 'rect', points: [[2, 48], [2.1, 47.9]] }] },
+ { id: 'w2', title: 'Airfield', colour: '#f97316',
+ zones: [{ id: 'z2', name: 'Apron', kind: 'rect', points: [[2.2, 48.2], [2.21, 48.19]] }] },
+];
+
+let live, target;
+afterEach(() => { if (live) unmount(live); target?.remove(); });
+
+function open(props = {}) {
+ target = document.createElement('div');
+ document.body.append(target);
+ live = mount(DetectAreas, { target, props: { engine, groups, ...props } });
+ flushSync();
+}
+
+// The drawn outline; the one beside it is the wider invisible one a press reads.
+const outlines = () => [...target.querySelectorAll('polygon:not(.hit)')];
+
+it('draws every watched area in its own colour, named by what watches it', () => {
+ open();
+ const shapes = outlines();
+ expect(shapes).toHaveLength(2);
+ expect(shapes.map((shape) => shape.getAttribute('stroke'))).toEqual(['#38bdf8', '#f97316']);
+ // zoomed out, a name longer than its own shape would bury the map, so only
+ // the area with room for one carries it
+ expect([...target.querySelectorAll('text')].map((label) => label.textContent))
+ .toEqual(['Harbour weekly']);
+ // a rectangle is drawn as its four ground corners, projected
+ expect(shapes[0].getAttribute('points').split(' ')).toHaveLength(4);
+});
+
+it('presses through to the routine that owns the area', () => {
+ const onpick = vi.fn();
+ open({ onpick });
+ target.querySelector('g.area').dispatchEvent(new MouseEvent('click', { bubbles: true, button: 0 }));
+ expect(onpick).toHaveBeenCalledWith('w1');
+ // The middle button turns the map under the area rather than opening it.
+ target.querySelector('g.area').dispatchEvent(new MouseEvent('click', { bubbles: true, button: 1 }));
+ expect(onpick).toHaveBeenCalledTimes(1);
+});
+
+it('hands the wheel down to the map it is drawn over', () => {
+ const container = document.createElement('div');
+ const canvas = document.createElement('canvas');
+ container.append(canvas);
+ document.body.append(container);
+ const zoomed = vi.fn();
+ canvas.addEventListener('wheel', zoomed);
+ open({ engine: { ...engine, container } });
+ const svg = target.querySelector('.detect-areas');
+ document.elementsFromPoint = () => [svg, canvas];
+ svg.dispatchEvent(new WheelEvent('wheel', { bubbles: true, cancelable: true, deltaY: -120 }));
+ expect(zoomed).toHaveBeenCalled();
+ expect(zoomed.mock.calls[0][0].deltaY).toBe(-120);
+ container.remove();
+});
+
+it('picks up a press on the outline only, so the fill is still the map', () => {
+ open();
+ // A wide invisible outline is the hit target; the drawn one takes no press.
+ expect([...target.querySelectorAll('polygon.hit')]).toHaveLength(2);
+});
+
+it('draws the one under the pointer heavier, and names it whatever its size', () => {
+ open({ highlight: ['w2'] });
+ const [one, two] = outlines();
+ expect(one.getAttribute('stroke-width')).toBe('1.5');
+ expect(two.getAttribute('stroke-width')).toBe('2.5');
+ expect(Number(two.getAttribute('fill-opacity'))).toBeGreaterThan(Number(one.getAttribute('fill-opacity')));
+ expect([...target.querySelectorAll('text')].map((label) => label.textContent))
+ .toEqual(['Harbour weekly', 'Airfield']);
+});
diff --git a/frontend/src/tools/detect/DetectAreas.svelte b/frontend/src/tools/detect/DetectAreas.svelte
new file mode 100644
index 0000000..5434318
--- /dev/null
+++ b/frontend/src/tools/detect/DetectAreas.svelte
@@ -0,0 +1,100 @@
+<script>
+ /**
+ * Every watched area of the case, drawn on the map at once, each in its
+ * routine's colour and named by it. This is what makes the list a map rather
+ * than a filing cabinet: the areas are the work, so you should be able to see
+ * them all, and press one to open what watches it.
+ *
+ * Read-only on purpose. Areas are edited inside the detection that owns them.
+ */
+ import { zoneRing } from '../../lib/map/analyzers.js';
+ import { relayWheel } from '../../lib/map/wheelRelay.js';
+
+ let { engine, groups = [], highlight = [], onpick = () => {} } = $props();
+
+ let svg = $state(null);
+ /** Open an area from its outline, and only from a plain left press: the
+ * middle and right buttons turn and pan the map under it. */
+ function press(event, id) {
+ if (event.button > 0) return;
+ onpick(id);
+ }
+
+ /** How wide an area has to draw, in pixels, before it is worth naming. */
+ const NAMED = 44;
+
+ let revision = $state(0);
+ $effect(() => {
+ if (!engine) return;
+ return engine.on('view-move', () => revision++);
+ });
+ // Reading the camera's revision inside the projection is what keeps every
+ // outline on its ground through a pan, a zoom or a turn.
+ const project = ([lon, lat]) => {
+ revision;
+ return engine?.latLngToContainerPoint({ lon, lat }) ?? { x: 0, y: 0 };
+ };
+
+ const shapes = $derived.by(() => {
+ if (!engine) return [];
+ return groups.flatMap((group) => (group.zones ?? []).map((zone) => {
+ const points = zoneRing(zone).map(project);
+ const top = points.reduce((best, point) => (point.y < best.y ? point : best), points[0]);
+ const xs = points.map((point) => point.x);
+ const ys = points.map((point) => point.y);
+ return {
+ key: `${group.id}-${zone.id}`,
+ id: group.id,
+ title: group.title,
+ colour: group.colour || '#38bdf8',
+ outline: points.map((point) => `${point.x},${point.y}`).join(' '),
+ // Zoomed out, an area is a few pixels wide and its name is longer than
+ // the shape: the names would pile on top of each other and say nothing.
+ // So a name shows where there is room for it, or where the pointer is.
+ room: Math.max(...xs) - Math.min(...xs) >= NAMED || Math.max(...ys) - Math.min(...ys) >= NAMED,
+ label: { x: top?.x ?? 0, y: (top?.y ?? 0) - 7 },
+ };
+ }));
+ });
+</script>
+
+<svg class="detect-areas" bind:this={svg} aria-label="Watched areas"
+ onwheel={(event) => relayWheel(event, { engine, root: svg })}>
+ {#each shapes as shape (shape.key)}
+ {@const on = highlight.includes(shape.id)}
+ <g class="area" class:on role="button" tabindex="0" aria-label={`Open ${shape.title}`}
+ onclick={(event) => press(event, shape.id)}
+ onkeydown={(e) => { if (e.key === 'Enter' || e.key === ' ') onpick(shape.id); }}>
+ <polygon points={shape.outline} fill={shape.colour} fill-opacity={on ? 0.22 : 0.08}
+ stroke={shape.colour} stroke-width={on ? 2.5 : 1.5} />
+ <!-- A thin line is hard to hit, so the press reads a wider invisible one. -->
+ <polygon class="hit" points={shape.outline} />
+ <!-- Named in the colour it is drawn in, so the list and the map agree. -->
+ {#if shape.room || on}<text x={shape.label.x} y={shape.label.y} fill={shape.colour}>{shape.title}</text>{/if}
+ </g>
+ {/each}
+</svg>
+
+<style>
+ .detect-areas {
+ position: absolute;
+ inset: 0;
+ width: 100%;
+ height: 100%;
+ z-index: 540;
+ pointer-events: none;
+ overflow: hidden;
+ }
+ /* An area is grabbed by its outline. Inside it the map is the map: the wheel
+ zooms, a drag pans, and the middle button turns, exactly as it does on
+ ground nothing is drawn over. */
+ .area { pointer-events: none; }
+ .hit { fill: none; stroke: transparent; stroke-width: 12; pointer-events: stroke; cursor: pointer; }
+ text {
+ font: 600 11px/1 var(--font-sans);
+ paint-order: stroke;
+ stroke: rgb(0 0 0 / 0.65);
+ stroke-width: 3px;
+ stroke-linejoin: round;
+ }
+</style>
diff --git a/frontend/src/tools/detect/DetectDetection.svelte b/frontend/src/tools/detect/DetectDetection.svelte
new file mode 100644
index 0000000..6ed7cfd
--- /dev/null
+++ b/frontend/src/tools/detect/DetectDetection.svelte
@@ -0,0 +1,153 @@
+<script>
+ /**
+ * One routine's own page: what it is for, what it has found across every run
+ * it has made, and the way to run it again.
+ *
+ * A routine is only worth saving if it remembers, so **Findings** is the
+ * first thing on it: every candidate kept as a pin or kept here, newest run
+ * first, each one a press away from the evidence it came from. Running it
+ * again asks which pass to read rather than deciding silently, because that
+ * choice costs a Copernicus request and an analyst usually knows which day
+ * they are chasing.
+ */
+ import { STRENGTHS, describeMeasure } from '../../lib/map/analyzers.js';
+ import { isActive, plural, ruleLabel, runState } from '../../lib/map/detections.js';
+ import Icon from '../../components/Icon.svelte';
+
+ let {
+ detection,
+ /** The routine as saved: its areas, analyzer and rule. Null while loading. */
+ detail = null,
+ findings = [],
+ methods = [],
+ busy = false,
+ onrun = () => {},
+ onexport = () => {},
+ oncancel = () => {},
+ onedit = () => {},
+ ondelete = () => {},
+ onopenrun = () => {},
+ onopenfinding = () => {},
+ } = $props();
+
+ let tab = $state('findings');
+ const methodOf = (method) => methods.find((m) => m.id === method) ?? {};
+ const single = $derived(!!methodOf(detection.method).single);
+ const state = $derived(runState(detection.active ?? detection.latest));
+ const reading = (row) => [
+ STRENGTHS[row.strength],
+ describeMeasure(methodOf(detection.method).measure, row.measure, detail?.recipe?.parameters?.index),
+ ].filter(Boolean).join(' · ');
+
+</script>
+
+<div class="cmp-dock-body">
+ <section class="head">
+ <h3>{detection.title}</h3>
+ {#if detection.note}<p class="note">{detection.note}</p>{/if}
+ <p class="meta">{[detection.analyzer, plural(detection.areas ?? 0, 'area'),
+ ruleLabel(detection.date_rule, single)].filter(Boolean).join(' · ')}</p>
+ <p class={`state ${state.tone}`}>{state.text}</p>
+ {#if detection.active?.status === 'running'}
+ <progress max={detection.active.total || 1} value={detection.active.progress ?? 0}></progress>
+ {/if}
+ <div class="row">
+ {#if detection.active}
+ <button class="btn btn-sm grow" disabled={busy} onclick={() => oncancel(detection.active)}>Stop this run</button>
+ {:else}
+ <button class="btn btn-primary grow" disabled={busy || !detail}
+ onclick={onrun}>
+ Run routine
+ </button>
+ {/if}
+ <button class="cmp-icon" title="Snapshot what it kept as a SAT layer" aria-label="Export as layer"
+ disabled={busy} onclick={onexport}><Icon name="layers" size={13} /></button>
+ <button class="cmp-icon" title="Edit this routine" aria-label={`Edit ${detection.title}`} disabled={busy}
+ onclick={onedit}><Icon name="edit" size={13} /></button>
+ <button class="cmp-icon" title="Delete this routine" aria-label={`Delete ${detection.title}`} disabled={busy}
+ onclick={ondelete}><Icon name="trash" size={13} /></button>
+ </div>
+ </section>
+
+ <div class="cmp-seg fill" role="group" aria-label="What to show">
+ <button class:on={tab === 'findings'} onclick={() => (tab = 'findings')}>
+ Findings{findings.length ? ` · ${findings.length}` : ''}
+ </button>
+ <button class:on={tab === 'runs'} onclick={() => (tab = 'runs')}>
+ Runs{detection.history.length ? ` · ${detection.history.length}` : ''}
+ </button>
+ </div>
+
+ {#if tab === 'findings'}
+ {#if !findings.length}
+ <p class="hint">Nothing kept yet. Candidates you keep, as a pin or here, gather on this page.</p>
+ {/if}
+ {#each findings as row (`${row.run_id}-${row.id}`)}
+ <button class="finding" disabled={busy} onclick={() => onopenfinding(row)}>
+ <span class="line">
+ <strong>{row.date || row.run_title}</strong>
+ <span class={`chip ${row.review}`}>{row.review === 'kept' ? 'Pinned' : 'Kept here'}</span>
+ </span>
+ <span class="what">{row.phenomenon}{reading(row) ? ` · ${reading(row)}` : ''}</span>
+ <span class="where">{row.coordinates[1].toFixed(4)}, {row.coordinates[0].toFixed(4)}</span>
+ </button>
+ {/each}
+ {:else}
+ {#if !detection.history.length}<p class="hint">Not run yet.</p>{/if}
+ {#each detection.history as run (run.id)}
+ {@const past = runState(run)}
+ <div class="row">
+ <button class="past grow" disabled={busy} onclick={() => onopenrun(run)}>
+ <span class={past.tone}>{past.text}</span>
+ <small>{run.dates?.[0] && run.dates[0] !== run.dates[1] ? `against ${run.dates[0]}` : 'one image'}</small>
+ </button>
+ {#if isActive(run)}
+ <button class="cmp-icon" title="Stop this run" aria-label={`Stop ${run.title}`} disabled={busy}
+ onclick={() => oncancel(run)}><Icon name="square" size={12} /></button>
+ {/if}
+ </div>
+ {/each}
+ {/if}
+</div>
+
+<style>
+ .head { display: grid; gap: 7px; }
+ h3 { margin: 0; font-size: var(--fs-sm); font-weight: 700; }
+ .note { margin: 0; color: var(--text-2); font-size: var(--fs-xs); line-height: 1.45; }
+ .meta, .state { margin: 0; font-size: var(--fs-xs); }
+ .meta { color: var(--text-3); }
+ .state { color: var(--text-2); }
+ .state.new { color: var(--accent); font-weight: 600; }
+ .state.busy { color: var(--info); }
+ .state.warn { color: var(--warn); }
+ progress { width: 100%; height: 6px; accent-color: var(--accent); }
+ .link { color: var(--accent); font-size: var(--fs-xs); text-align: left; justify-self: start; }
+ .finding, .past {
+ display: grid;
+ gap: 2px;
+ min-width: 0;
+ padding: 6px 8px;
+ border-radius: var(--r-sm);
+ text-align: left;
+ }
+ .finding { border: 1px solid var(--border); background: var(--bg-2); }
+ .finding:hover:not(:disabled), .past:hover:not(:disabled) { border-color: var(--accent); background: var(--bg-3); }
+ .line { display: flex; align-items: center; gap: 7px; }
+ .line strong { color: var(--text-1); font-size: var(--fs-xs); }
+ .chip {
+ padding: 1px 6px;
+ border-radius: 99px;
+ font-size: 10px;
+ font-weight: 600;
+ color: var(--text-2);
+ background: var(--bg-3);
+ }
+ .chip.kept { color: var(--ok); background: color-mix(in srgb, var(--ok) 14%, transparent); }
+ .chip.noted { color: var(--accent); background: var(--accent-soft); }
+ .what { color: var(--text-2); font-size: var(--fs-xs); line-height: 1.4; }
+ .where { color: var(--text-3); font-family: var(--font-mono); font-size: 10.5px; }
+ .past small { color: var(--text-3); font-size: 10.5px; }
+ .past .new { color: var(--accent); font-weight: 600; }
+ .past .busy { color: var(--info); }
+ .past .warn { color: var(--warn); }
+</style>
diff --git a/frontend/src/tools/detect/DetectHome.svelte b/frontend/src/tools/detect/DetectHome.svelte
new file mode 100644
index 0000000..bb54527
--- /dev/null
+++ b/frontend/src/tools/detect/DetectHome.svelte
@@ -0,0 +1,268 @@
+<script>
+ /**
+ * Where Detect opens: the routines of this case, and the single passes that
+ * were swept once. The kind is chosen at the **+**, before any question is
+ * asked, because it is what makes the difference between the two: a pass is
+ * reviewed and done with, a routine is a place you keep coming back to.
+ */
+ import Icon from '../../components/Icon.svelte';
+ import { isActive, plural, ruleLabel, runDays, runState, savedGroups } from '../../lib/map/detections.js';
+
+ let {
+ tab = 'routines',
+ routines = [],
+ passes = [],
+ /** The saved runs drawn on the map, so a row can turn its own off. */
+ layers = $bindable([]),
+ methods = [],
+ busy = false,
+ onnew = () => {},
+ onrun = () => {},
+ onrunall = () => {},
+ oncancel = () => {},
+ onopen = () => {},
+ onopenrun = () => {},
+ ondelete = () => {},
+ onhover = () => {},
+ /** Put the map on some ground, so a layer turned on is a layer seen. */
+ onframe = () => {},
+ /** Snapshot what was kept into a SAT layer: `('runs' | 'followups', id)`. */
+ onexport = () => {},
+ } = $props();
+
+ const single = (method) => !!methods.find((entry) => entry.id === method)?.single;
+ const idle = $derived(routines.filter((item) => !item.active));
+ const groups = $derived(savedGroups(routines, passes));
+ /** Groups folded shut; every group opens unfolded. */
+ let folded = $state({});
+
+ const layerOf = (run) => layers.find((row) => row.id === run.id);
+ /** A SAT layer holds what was kept or pinned, so a run with none has nothing to give it. */
+ const kept = (runs) => runs.reduce((total, run) => total + (run.status === 'ready' ? run.marked ?? 0 : 0), 0);
+ /** A routine's runs share its title, so under it a run is named by its days too. */
+ const rowName = (group, run) => (group.kind === 'routine' && runDays(run) ? `${run.title} · ${runDays(run)}` : run.title);
+ const layerTitle = (count) => (count ? 'Add to the SAT layers: what was kept or pinned'
+ : 'Keep or pin a candidate first: the SAT layer holds only those');
+ const groupLayers = (group) => group.runs.map(layerOf).filter(Boolean);
+
+ /** Turn runs on or off together; turning them on frames the ground they cover. */
+ function showRuns(shown, visible) {
+ for (const layer of shown) layer.visible = visible;
+ if (visible) onframe(shown.flatMap((layer) => layer.input?.zones ?? []));
+ }
+
+</script>
+
+<div class="home">
+ {#if tab === 'routines'}
+ <section aria-label="Routines">
+ {#if routines.length > 1}
+ <div class="row head">
+ <span class="grow"></span>
+ <button class="btn btn-sm" disabled={busy || !idle.length} onclick={onrunall}
+ title="Queue every routine that is not already working">
+ <Icon name="play" size={11} /> Run all
+ </button>
+ </div>
+ {/if}
+ {#if !routines.length}
+ <div class="empty">
+ <p>No routine in this case yet.</p>
+ <p class="hint">A routine is an area, what to look for there and what each pass compares against.</p>
+ <button class="btn btn-sm" onclick={() => onnew('routine')}>Create a routine</button>
+ </div>
+ {/if}
+ {#each routines as item (item.id)}
+ {@const state = runState(item.active ?? item.latest)}
+ <article class="card" style={`--tint: ${item.colour || 'var(--accent)'}`}>
+ <div class="row">
+ <button class="title grow" disabled={busy} title="Open this routine" onclick={() => onopen(item)}
+ onmouseenter={() => onhover(item.id)} onmouseleave={() => onhover(null)}
+ onfocus={() => onhover(item.id)} onblur={() => onhover(null)}>{item.title}</button>
+ {#if item.active}
+ <button class="cmp-icon" title="Stop this run" aria-label={`Stop ${item.title}`} disabled={busy}
+ onclick={() => oncancel(item.active)}><Icon name="square" size={12} /></button>
+ {:else}
+ <button class="cmp-icon go" title="Run the newest pass" aria-label={`Run ${item.title}`} disabled={busy}
+ onclick={() => onrun(item)}><Icon name="play" size={13} /></button>
+ {/if}
+ <button class="cmp-icon" title="Delete" aria-label={`Delete ${item.title}`} disabled={busy}
+ onclick={() => ondelete('followups', item)}><Icon name="trash" size={13} /></button>
+ </div>
+ {#if item.note}<p class="note">{item.note}</p>{/if}
+ <p class="meta">{[item.analyzer, plural(item.areas ?? 0, 'area'),
+ ruleLabel(item.date_rule, single(item.method))].filter(Boolean).join(' · ')}</p>
+ <p class={`state ${state.tone}`}>{state.text}</p>
+ {#if item.active?.status === 'running'}
+ <progress max={item.active.total || 1} value={item.active.progress ?? 0}></progress>
+ {/if}
+ </article>
+ {/each}
+ </section>
+ {/if}
+
+ {#if tab === 'saved'}
+ <section aria-label="Saved runs">
+ {#if !passes.length}
+ <div class="empty">
+ <p>Nothing has been swept in this case yet.</p>
+ <p class="hint">A run lands here when it finishes, whichever tool you are in.</p>
+ <button class="btn btn-sm" onclick={() => onnew('once')}>Sweep an area once</button>
+ </div>
+ {/if}
+ {#each groups as group (group.id)}
+ {@const shown = groupLayers(group)}
+ {@const allOn = shown.length > 0 && shown.every((layer) => layer.visible)}
+ <div class="group" style={`--tint: ${group.colour || 'var(--text-3)'}`}>
+ <div class="row group-head">
+ <button class="fold grow" aria-expanded={!folded[group.id]}
+ onclick={() => (folded = { ...folded, [group.id]: !folded[group.id] })}>
+ <Icon name={folded[group.id] ? 'chevronRight' : 'chevronDown'} size={12} />
+ {#if group.kind === 'routine'}<span class="swatch" aria-hidden="true"></span>{/if}
+ <span class="name">{group.title}</span>
+ <small>{plural(group.runs.length, 'run')}</small>
+ </button>
+ {#if group.kind === 'routine'}
+ <button class="cmp-icon" disabled={busy || !kept(group.runs)} title={layerTitle(kept(group.runs))}
+ aria-label={`Add ${group.title} to the SAT layers`} onclick={() => onexport('followups', group.id)}>
+ <Icon name="layers" size={13} />
+ </button>
+ {/if}
+ {#if shown.length}
+ <button class="cmp-icon" aria-pressed={allOn} onclick={() => showRuns(shown, !allOn)}
+ aria-label={`${allOn ? 'Hide' : 'Show'} every run of ${group.title} on the map`}
+ title={allOn ? 'Hide them all on the map' : 'Show them all on the map'}>
+ <Icon name={allOn ? 'eye' : 'eyeOff'} size={14} />
+ </button>
+ {/if}
+ </div>
+ {#if !folded[group.id]}
+ {#each group.runs as run (run.id)}
+ {@const state = runState(run)}
+ {@const layer = layerOf(run)}
+ {@const name = rowName(group, run)}
+ <div class="row single">
+ <button class="past grow" disabled={busy} onclick={() => onopenrun(run)}>
+ {#if group.kind === 'routine'}
+ <span class={state.tone}>{state.text}</span>
+ {#if runDays(run)}<small class="what">{runDays(run)}</small>{/if}
+ {:else}
+ <span>{run.title}</span>
+ <small class={state.tone}>{state.text}</small>
+ <small class="what">{[run.analyzer, run.areas ? plural(run.areas, 'area') : ''].filter(Boolean).join(' · ')}</small>
+ {/if}
+ </button>
+ {#if run.status === 'ready'}
+ <button class="cmp-icon" disabled={busy || !kept([run])} title={layerTitle(kept([run]))}
+ aria-label={`Add ${name} to the SAT layers`} onclick={() => onexport('runs', run.id)}>
+ <Icon name="layers" size={13} />
+ </button>
+ {/if}
+ {#if layer}
+ <button class="cmp-icon" aria-label={`${layer.visible ? 'Hide' : 'Show'} ${name} on the map`}
+ aria-pressed={layer.visible} title={layer.visible ? 'Hide on the map' : 'Show on the map'}
+ onclick={() => showRuns([layer], !layer.visible)}>
+ <Icon name={layer.visible ? 'eye' : 'eyeOff'} size={14} />
+ </button>
+ {/if}
+ {#if isActive(run)}
+ <button class="cmp-icon" title="Stop this run" aria-label={`Stop ${name}`} disabled={busy}
+ onclick={() => oncancel(run)}><Icon name="square" size={12} /></button>
+ {:else}
+ <button class="cmp-icon" title="Delete" aria-label={`Delete ${name}`} disabled={busy}
+ onclick={() => ondelete('runs', run)}><Icon name="trash" size={13} /></button>
+ {/if}
+ </div>
+ {/each}
+ {/if}
+ </div>
+ {/each}
+ </section>
+ {/if}
+</div>
+
+<style>
+ .home { display: grid; gap: 16px; }
+ section { display: grid; gap: 8px; }
+ .empty {
+ display: grid;
+ gap: 4px;
+ padding: 14px 12px;
+ border: 1px dashed var(--border);
+ border-radius: var(--r-sm);
+ text-align: center;
+ }
+ .empty p { margin: 0; font-size: var(--fs-xs); color: var(--text-2); }
+ .empty button { justify-self: center; margin-top: 4px; }
+ .card {
+ display: grid;
+ gap: 3px;
+ padding: 8px 6px 8px 10px;
+ border: 1px solid var(--border);
+ border-left: 3px solid var(--tint);
+ border-radius: var(--r-sm);
+ background: var(--bg-2);
+ }
+ .card .row { gap: 2px; }
+ .title {
+ min-width: 0;
+ overflow: hidden;
+ color: var(--text-1);
+ font-size: var(--fs-sm);
+ font-weight: 600;
+ text-align: left;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ .title:hover:not(:disabled) { color: var(--accent); }
+ .go { color: var(--accent); }
+ .note, .meta, .state { margin: 0; font-size: var(--fs-xs); line-height: 1.4; }
+ .note { color: var(--text-2); }
+ .meta { color: var(--text-3); }
+ .state { color: var(--text-2); }
+ .state.new { color: var(--accent); font-weight: 600; }
+ .state.busy { color: var(--info); }
+ .state.warn { color: var(--warn); }
+ progress { width: 100%; height: 6px; accent-color: var(--accent); }
+ .past {
+ display: grid;
+ gap: 1px;
+ min-width: 0;
+ padding: 4px 6px;
+ border-radius: var(--r-sm);
+ color: var(--text-2);
+ font-size: var(--fs-xs);
+ text-align: left;
+ }
+ .past:hover:not(:disabled) { background: var(--bg-3); }
+ .past span { color: var(--text-1); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+ .past small { color: var(--text-2); font-size: 10.5px; }
+ .past small.new { color: var(--accent); font-weight: 600; }
+ .past small.busy { color: var(--info); }
+ .past small.warn { color: var(--warn); }
+ .past small.what { color: var(--text-3); }
+ .past span.new { color: var(--accent); font-weight: 600; }
+ .past span.busy { color: var(--info); }
+ .past span.warn { color: var(--warn); }
+ .single { gap: 2px; padding-left: 14px; }
+ .group { display: grid; gap: 2px; }
+ .group-head { gap: 2px; }
+ .fold {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ min-width: 0;
+ padding: 3px 4px;
+ border-radius: var(--r-sm);
+ color: var(--text-2);
+ font-size: 10.5px;
+ font-weight: 700;
+ letter-spacing: 0.04em;
+ text-align: left;
+ text-transform: uppercase;
+ }
+ .fold:hover { background: var(--bg-2); color: var(--text-1); }
+ .fold .name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+ .fold small { flex: 0 0 auto; color: var(--text-3); font-weight: 400; letter-spacing: 0; text-transform: none; white-space: nowrap; }
+ .swatch { flex: 0 0 auto; width: 8px; height: 8px; border-radius: 2px; background: var(--tint); }
+</style>
diff --git a/frontend/src/tools/detect/DetectPanel.svelte b/frontend/src/tools/detect/DetectPanel.svelte
new file mode 100644
index 0000000..dc97d7b
--- /dev/null
+++ b/frontend/src/tools/detect/DetectPanel.svelte
@@ -0,0 +1,639 @@
+<script>
+ /**
+ * Detect's column: the case's routines and single passes, one detection's own
+ * page, the step-by-step build of a new one, the review of what a run found,
+ * and the library of what detections can look for.
+ *
+ * It opens on the list because that is what an analyst comes back to. Runs
+ * are queued in the case and keep going whichever tool is open; the top bar
+ * follows them (lib/detectRuns.svelte.js) and this list reads the same rows.
+ * Opening the panel reads local state only. Starting a run is what fetches
+ * imagery.
+ */
+ import { onMount, untrack } from 'svelte';
+ import { api } from '../../lib/api.js';
+ import { ensureCase, reloadCase, toast } from '../../lib/state.svelte.js';
+ import { detectRuns, refreshRuns } from '../../lib/detectRuns.svelte.js';
+ import { clone } from '../../lib/map/analyzers.js';
+ import { detectionsWithRuns, isActive, plural } from '../../lib/map/detections.js';
+ import AnalyzerLibrary from './AnalyzerLibrary.svelte';
+ import DetectDetection from './DetectDetection.svelte';
+ import DetectHome from './DetectHome.svelte';
+ import DetectReview from './DetectReview.svelte';
+ import DetectWizard from './DetectWizard.svelte';
+ import Icon from '../../components/Icon.svelte';
+ import Modal from '../../components/Modal.svelte';
+ import AreaDates from './AreaDates.svelte';
+ import AreasPanel from './AreasPanel.svelte';
+
+ let {
+ caseId,
+ collapsed = $bindable(false),
+ manual = $bindable(null),
+ zones = $bindable([]),
+ drawing = $bindable('select'),
+ selectedZone = $bindable(null),
+ layers = $bindable([]),
+ showZones = $bindable(true),
+ /** The candidate the review is on, so the map can ring the same one. */
+ selectedResult = $bindable(null),
+ /** Every watched area of the case, for the map to draw while the list is up. */
+ areaGroups = $bindable([]),
+ /** The areas the pointer is on, drawn heavier on the map. */
+ highlight = $bindable([]),
+ /** A saved item to open (`runs-<id>`, `followups-<id>`, `zones-<id>`). */
+ opening = null,
+ onopened = () => {},
+ onfocus = () => {},
+ /** Frame a set of areas on the map, so opening a routine shows all of it. */
+ onframe = () => {},
+ onusecurrentview = () => {},
+ /** Put a Copernicus pass on the map, so the picture matches the work. */
+ onshow = () => {},
+ onleavepass = () => {},
+ } = $props();
+
+ const TITLES = { new: 'New detection', review: 'Results', library: 'Analyzers' };
+
+ let catalogue = $state(null);
+ let lists = $state({ zones: [], followups: [], areas: [] });
+ let hiddenAreas = $state([]);
+ let launch = $state(null);
+ let repeatRequest = $state(null);
+ let repeatQueue = $state([]);
+ let selectedArea = $state(null);
+ /** 'home', 'detection', 'new', 'review' or 'library'. */
+ let view = $state('home');
+ let tab = $state('routines');
+ let picking = $state(false);
+ /** The wizard's starting point while one is open; a new object mounts a fresh one. */
+ let draft = $state(null);
+ /** Where the library goes back to, and where the review returns to. */
+ let libraryFrom = $state('home');
+ let offer = $state(null);
+ /** The routine being looked at: its saved body and what it has found. */
+ let detectionId = $state(null);
+ let detail = $state(null);
+ let findings = $state([]);
+ let current = $state(null);
+ let candidateId = $state(null);
+ let busy = $state(false);
+ let error = $state('');
+ /** Undefined until the first case is seen, so mounting is not a case switch. */
+ let loadedCase;
+ /** Whether this case's areas have framed the map once. */
+ let framed = false;
+ let generation = 0;
+
+ const base = (id = caseId) => `/api/cases/${id}/analysis`;
+ const runs = $derived(detectRuns.caseId === caseId ? detectRuns.rows : []);
+ const routines = $derived(detectionsWithRuns(lists.followups, runs));
+ const detection = $derived(routines.find((row) => row.id === detectionId) ?? null);
+ const methodOf = (method) => catalogue?.methods?.find((m) => m.id === method) ?? {};
+ const pending = $derived(isActive(current));
+ const kindTitle = $derived(draft?.kind === 'routine' ? (draft.followupId ? 'Edit routine' : 'New routine') : 'New pass');
+
+ $effect(() => { selectedResult = view === 'review' ? candidateId : null; });
+ // The map draws every watched area while the list is up, and only the open
+ // detection's or run's ground once one is open: what is on screen is what is
+ // in hand. One drawing either way, in the area's own colour, so the same
+ // ground is never outlined twice in two colours.
+ const openZones = $derived(
+ view === 'detection' ? detail?.zones ?? [] : view === 'review' ? current?.input?.zones ?? [] : null
+ );
+ $effect(() => {
+ if (!showZones) { areaGroups = []; return; }
+ if (openZones) {
+ areaGroups = openZones.map((zone) => ({
+ id: zone.id, title: zone.name,
+ colour: lists.areas.find((area) => area.id === zone.id)?.colour || '#38bdf8',
+ zones: [zone],
+ }));
+ return;
+ }
+ areaGroups = lists.areas.filter((area) => !hiddenAreas.includes(area.id)).map((area) => ({
+ id: area.id, title: area.name, colour: area.colour, zones: [areaZone(area)],
+ }));
+ });
+
+ async function act(fn) {
+ if (busy) return;
+ busy = true; error = '';
+ try { await fn(); } catch (e) { error = e.message; }
+ finally { busy = false; }
+ }
+
+ async function loadCatalogue() {
+ catalogue = await api.get('/api/compare/analyzers');
+ }
+
+ async function refresh(id = caseId) {
+ if (!id) return;
+ const epoch = generation;
+ const [zoneSets, followups, areas] = await Promise.all([
+ api.get(`${base(id)}/zones`), api.get(`${base(id)}/followups`), api.get(`${base(id)}/areas`),
+ ]);
+ if (epoch !== generation) return;
+ lists = { zones: zoneSets, followups, areas };
+ // Opening Detect on a case that already watches ground should show that
+ // ground, not the home view it has nothing to do with. Once per case: after
+ // that the camera is the analyst's.
+ if (!framed && areas.length) {
+ framed = true;
+ onframe(areas.map(areaZone));
+ }
+ }
+
+ const areaZone = (area) => ({ id: area.id, name: area.name, kind: 'polygon',
+ points: area.geometry.coordinates[0].slice(0, -1) });
+
+ onMount(() => {
+ let alive = true;
+ loadCatalogue().catch((e) => { if (alive) error = e.message; });
+ return () => { alive = false; generation++; };
+ });
+
+ // Another case is other work: its areas, drafts and result layers are not
+ // this one's. Mounting is not a switch, so re-entering Detect keeps its place.
+ $effect(() => {
+ const id = caseId;
+ if (id === loadedCase) return;
+ const switching = loadedCase !== undefined;
+ loadedCase = id; generation++;
+ untrack(() => {
+ current = null; candidateId = null; draft = null;
+ detectionId = null; detail = null; findings = [];
+ if (switching) {
+ layers = []; zones = []; selectedZone = null; drawing = 'select'; view = 'home';
+ }
+ lists = { zones: [], followups: [], areas: [] };
+ framed = false;
+ hiddenAreas = []; launch = null; repeatRequest = null; repeatQueue = []; manual = null;
+ onleavepass();
+ if (id) {
+ void refresh(id).catch((e) => (error = e.message));
+ void refreshRuns(id).catch((e) => (error = e.message));
+ }
+ });
+ });
+
+ // Saved work is local and visible on landing, including runs made by routines.
+ $effect(() => {
+ const ready = runs.filter((run) => run.status === 'ready').map((run) => run.id);
+ const epoch = generation;
+ untrack(() => {
+ for (const id of ready.filter((id) => !layers.some((layer) => layer.id === id))) {
+ void api.get(`${base()}/runs/${id}`).then((run) => {
+ if (epoch === generation && run?.input && !layers.some((layer) => layer.id === id)) {
+ layers = [...layers, { ...run, visible: true }];
+ }
+ }).catch((e) => (error = e.message));
+ }
+ });
+ });
+
+ // A run under review that is still working is read again until it settles.
+ $effect(() => {
+ if (!pending || !caseId) return;
+ const id = current.id;
+ const owner = caseId;
+ const epoch = generation;
+ let stopped = false;
+ let timer;
+ async function poll() {
+ try {
+ const run = await api.get(`${base(owner)}/runs/${id}`);
+ if (stopped || epoch !== generation) return;
+ acceptRun(run);
+ if (isActive(run)) timer = setTimeout(poll, 900);
+ } catch (e) { if (!stopped) error = e.message; }
+ }
+ timer = setTimeout(poll, 900);
+ return () => { stopped = true; clearTimeout(timer); };
+ });
+
+ $effect(() => {
+ if (!opening || !caseId) return;
+ const match = /^(areas|zones|followups|runs)-([a-f0-9]{12})$/.exec(opening);
+ untrack(() => {
+ onopened();
+ if (match) void act(() => openItem(match[1], match[2]));
+ });
+ });
+
+ function acceptRun(run) {
+ current = run;
+ if (run.status === 'ready') {
+ const old = layers.find((r) => r.id === run.id);
+ layers = [...layers.filter((r) => r.id !== run.id), { ...clone(run), visible: old?.visible ?? true }];
+ if (!run.results.some((r) => r.id === candidateId)) candidateId = run.results[0]?.id ?? null;
+ }
+ }
+
+ function goHome() {
+ picking = false;
+ manual = null;
+ onleavepass();
+ view = 'home';
+ draft = null;
+ detectionId = null; detail = null; findings = [];
+ zones = []; selectedZone = null; drawing = 'select';
+ }
+
+ function startWizard(seed) {
+ manual = null;
+ onleavepass();
+ offer = null;
+ draft = seed;
+ selectedZone = null; drawing = 'select';
+ view = 'new';
+ }
+
+ /** A run saved against Wayback names no Copernicus day, so the map keeps its own. */
+ const day = (source) => (['sentinel2', 'sentinel1'].includes(source?.provider) && source.date ? source : null);
+
+ async function openDetection(id) {
+ const epoch = generation;
+ const [body, found] = await Promise.all([
+ api.get(`${base()}/followups/${id}`), api.get(`${base()}/followups/${id}/findings`),
+ ]);
+ if (epoch !== generation) return;
+ detectionId = id; detail = body; findings = found;
+ zones = [];
+ draft = null;
+ view = 'detection';
+ onleavepass();
+ onframe(body.zones ?? []);
+ }
+
+ async function openRun(id, resultId = null) {
+ manual = null;
+ const epoch = generation;
+ const run = await api.get(`${base()}/runs/${id}`);
+ if (epoch !== generation) return;
+ draft = null;
+ candidateId = resultId;
+ acceptRun(run);
+ if (resultId) candidateId = resultId;
+ zones = [];
+ const shown = day(run.input.b);
+ if (shown) onshow(shown);
+ libraryFrom = detectionId && run.input.followup_id === detectionId ? 'detection' : 'home';
+ view = 'review';
+ tab = 'saved';
+ }
+
+ async function editDetection(id) {
+ const epoch = generation;
+ const body = await api.get(`${base()}/followups/${id}`);
+ if (epoch !== generation) return;
+ zones = clone(body.zones);
+ startWizard({ body, followupId: id, kind: 'routine' });
+ }
+
+ async function openItem(kind, id) {
+ collapsed = false;
+ if (kind === 'areas') { openTab('areas'); return; }
+ if (kind === 'runs') return openRun(id);
+ if (kind === 'followups') return openDetection(id);
+ const set = await api.get(`${base()}/zones/${id}`);
+ zones = clone(set.zones);
+ startWizard({ kind: 'once', zonesId: id, zonesTitle: set.title });
+ }
+
+ function newDetection(kind) {
+ collapsed = false; picking = false;
+ zones = [];
+ startWizard({ kind });
+ }
+
+ function editRun() {
+ if (!current) return;
+ const watch = current.input?.followup_id;
+ if (watch && lists.followups.some((row) => row.id === watch)) return act(() => editDetection(watch));
+ zones = clone(current.input.zones);
+ startWizard({ kind: 'once', body: { ...clone(current.input), followup_id: null }, fromRun: true });
+ }
+
+ function openLibrary() {
+ libraryFrom = view === 'new' ? 'new' : view === 'detection' ? 'detection' : 'home';
+ view = 'library';
+ }
+
+ function back() {
+ if (view === 'library') {
+ view = libraryFrom === 'new' && draft ? 'new' : libraryFrom === 'detection' && detection ? 'detection' : 'home';
+ return;
+ }
+ if (view === 'review' && libraryFrom === 'detection' && detection) {
+ void act(() => openDetection(detection.id));
+ return;
+ }
+ if (view === 'new' && draft?.followupId && detection) {
+ void act(() => openDetection(detection.id));
+ return;
+ }
+ goHome();
+ }
+
+ /**
+ * Save, run, or both, as the last step asked. A routine runs through its own
+ * route, so the run belongs to it and gathers on its page; a single pass is
+ * a run and nothing else.
+ */
+ async function submit({ input, followupId, kind, run }) {
+ const owner = await ensureCase();
+ if (kind === 'routine') {
+ const saved = followupId
+ ? await api.put(`${base(owner.id)}/followups/${followupId}`, input)
+ : await api.post(`${base(owner.id)}/followups`, input);
+ if (run) {
+ const started = await api.post(`${base(owner.id)}/followups/${saved.id}/run`, {});
+ if (started.duplicates) repeatRequest = started;
+ }
+ draft = null;
+ await Promise.all([refresh(owner.id), refreshRuns(owner.id)]);
+ await reloadCase();
+ await openDetection(saved.id);
+ } else {
+ const started = await api.post(`${base(owner.id)}/runs`, input);
+ if (started.duplicates) { repeatRequest = started; return; }
+ draft = null;
+ await Promise.all([refresh(owner.id), refreshRuns(owner.id)]);
+ await reloadCase();
+ await openRun(started.id);
+ }
+ toast(run ? 'Detection started. Carry on elsewhere; the top bar follows it.' : 'Routine saved', 'ok', 5000);
+ }
+
+ async function runDetection(item, pass = {}) {
+ const started = await api.post(`${base()}/followups/${item.id}/run`, pass);
+ if (started.duplicates) repeatRequest = started;
+ else { launch = null; onleavepass(); }
+ await refreshRuns(caseId);
+ }
+
+ async function prepareLaunch(item) {
+ const body = await api.get(`${base()}/followups/${item.id}`);
+ launch = { ...body, area_dates: (body.area_dates ?? body.zones.map((zone) => ({
+ area_id: zone.id, a: body.a, b: body.b, date_rule: body.date_rule,
+ }))).map((pair) => ({ ...pair, b: { ...pair.b, date: '' } })) };
+ }
+
+ async function repeat() {
+ const started = await api.post(`${base()}/runs`, { ...repeatRequest.input, run_anyway: true });
+ nextRepeat(); launch = null;
+ await refreshRuns(caseId);
+ await openRun(started.id);
+ }
+
+ async function exportLayer(kind, id) {
+ await api.post(`${base()}/${kind}/${id}/export`, {});
+ await reloadCase();
+ toast('Snapshot saved in SAT layers', 'ok');
+ }
+
+ function nextRepeat() {
+ repeatRequest = repeatQueue[0] ?? null;
+ repeatQueue = repeatQueue.slice(1);
+ }
+
+ /** Every routine not already working, queued one behind the other. */
+ async function runAll() {
+ const problems = [];
+ let started = 0;
+ for (const item of routines.filter((entry) => !entry.active)) {
+ try {
+ const response = await api.post(`${base()}/followups/${item.id}/run`, {});
+ if (response.duplicates) repeatQueue = [...repeatQueue, response];
+ else started++;
+ } catch (e) {
+ problems.push(`${item.title}: ${e.message}`);
+ }
+ }
+ await refreshRuns(caseId);
+ if (started) toast(`${plural(started, 'routine')} queued`, 'ok');
+ if (!repeatRequest && repeatQueue.length) nextRepeat();
+ if (problems.length) error = problems.join(' · ');
+ }
+
+ async function cancelRun(run) {
+ const answer = await api.post(`${base()}/runs/${run.id}/cancel`, {});
+ if (current?.id === run.id) acceptRun(answer);
+ await refreshRuns(caseId);
+ }
+
+ async function removeItem(kind, row) {
+ await api.del(`${base()}/${kind}/${row.id}`);
+ if (kind === 'runs') {
+ layers = layers.filter((r) => r.id !== row.id);
+ if (current?.id === row.id) current = null;
+ }
+ if (kind === 'followups' && detectionId === row.id) goHome();
+ await Promise.all([refresh(), refreshRuns(caseId)]);
+ await reloadCase();
+ toast('Moved to Trash', 'ok');
+ }
+
+ /** A verdict changes what a routine is holding, so its page hears about it. */
+ async function afterVerdict(run) {
+ acceptRun(run);
+ if (!detectionId) return;
+ findings = await api.get(`${base()}/followups/${detectionId}/findings`);
+ }
+
+ export async function addManual(geometry) {
+ if (!manual || !current) return;
+ const areaId = manual.areaId;
+ await act(async () => {
+ const row = await api.post(`${base()}/runs/${current.id}/results`, { area_id: areaId, geometry });
+ acceptRun({ ...current, results: [...current.results, row], count: current.count + 1 });
+ candidateId = row.id; manual = null;
+ await refreshRuns(caseId);
+ });
+ }
+
+ /** A candidate picked on the map opens its review. */
+ export function pick(runId, resultId) {
+ collapsed = false;
+ void act(() => openRun(runId, resultId));
+ }
+
+ /** Shared areas have their own page, independent of the routines using them. */
+ export function openArea(id) {
+ selectedArea = id;
+ openTab('areas');
+ }
+
+ function openTab(next) {
+ collapsed = false; tab = next; goHome();
+ }
+</script>
+
+<aside class="cmp-dock" class:collapsed aria-label="Detect">
+ <nav class="dock-tabs" class:rail={collapsed} aria-label="Detect sections">
+ <button class="cmp-icon" aria-label={collapsed ? 'Expand Detect panel' : 'Collapse Detect panel'}
+ title="Toggle Detect panel (])" onclick={() => (collapsed = !collapsed)}>
+ <Icon name={collapsed ? 'chevronLeft' : 'chevronRight'} size={16} />
+ </button>
+ {#each [['routines', 'Routines', 'clock'], ['saved', 'Saved', 'bookmark'], ['areas', 'Areas', 'polygon']] as [id, label, icon]}
+ <button class="section-tab" class:on={tab === id && view === 'home'} aria-label={label} aria-pressed={tab === id && view === 'home'}
+ title={label} onclick={() => openTab(id)}><Icon name={icon} size={15} />{#if !collapsed}{label}{/if}</button>
+ {/each}
+ <button class="cmp-icon" aria-label="Analyzers" title="Make and tune what detections look for"
+ onclick={openLibrary}><Icon name="sliders" size={15} /></button>
+ </nav>
+ <div class="dock-content" hidden={collapsed}>
+ <div class="new-action">
+ <button class="btn btn-primary" aria-expanded={picking} onclick={() => (picking = !picking)}><Icon name="plus" size={14} /> New detection</button>
+ {#if picking}
+ <!-- The kind is the first question because it changes every one after
+ it, so each says in a line what it commits you to. -->
+ <div class="new-menu cmp-glass" role="group" aria-label="New detection">
+ <button class="kind" aria-label="New one pass" onclick={() => newDetection('once')}>
+ <strong>One pass</strong><small>Sweep two dates you name, review it, done.</small>
+ </button>
+ <button class="kind" aria-label="New routine" onclick={() => newDetection('routine')}>
+ <strong>Routine</strong><small>Ground you come back to. Each run picks its own pass.</small>
+ </button>
+ </div>
+ {/if}
+ </div>
+ {#if view !== 'home'}
+ <header>
+ <button class="cmp-icon" aria-label="Back" title="Back" onclick={back}>
+ <Icon name="chevronLeft" size={15} />
+ </button>
+ <strong>{view === 'new' ? kindTitle : view === 'detection' ? 'Routine' : TITLES[view]}</strong>
+ </header>
+ {/if}
+
+
+ {#if !catalogue}
+ <div class="cmp-dock-body">
+ {#if error}<p class="warn" role="alert">{error}</p>{/if}
+ <p class="hint">Reading the local analyzer library…</p>
+ </div>
+ {:else}
+ {#if draft}
+ <!-- Kept while the library is open over it, so a detection half made
+ survives a detour to make the analyzer it needs. -->
+ <div class="pane" hidden={view !== 'new'}>
+ {#key draft}
+ <DetectWizard {caseId} {catalogue} areaSets={lists.zones} areas={lists.areas} seed={draft} {offer} {busy}
+ bind:zones bind:drawing bind:selectedZone bind:showZones
+ {onfocus} {onusecurrentview} {onshow} onlibrary={openLibrary}
+ onareas={(id) => refresh(id)} onsubmit={(request) => act(() => submit(request))} />
+ {/key}
+ </div>
+ {/if}
+
+ {#if view === 'home'}
+ <div class="cmp-dock-body">
+ {#if error}<p class="warn" role="alert">{error}</p>{/if}
+ {#if tab === 'areas'}
+ <AreasPanel {caseId} areas={lists.areas} {selectedArea} routines={lists.followups} bind:hidden={hiddenAreas} bind:zones bind:drawing bind:selectedZone
+ onrefresh={() => refresh()} {onusecurrentview} {onframe} />
+ {:else}
+ <DetectHome {tab} {routines} passes={runs} methods={catalogue.methods} {busy} bind:layers
+ onnew={newDetection}
+ onrun={(item) => act(() => prepareLaunch(item))} onrunall={() => act(runAll)}
+ oncancel={(run) => act(() => cancelRun(run))}
+ onopen={(item) => act(() => openDetection(item.id))}
+ onopenrun={(run) => act(() => openRun(run.id))}
+ ondelete={(kind, row) => act(() => removeItem(kind, row))}
+ {onframe} onexport={(kind, id) => act(() => exportLayer(kind, id))}
+ onhover={(id) => {
+ const hovered = lists.followups.find((row) => row.id === id);
+ highlight = hovered ? (hovered.zones ?? []).map((zone) => zone.id) : [];
+ }} />
+ {/if}
+ </div>
+ {:else if view === 'detection'}
+ <div class="cmp-dock-body-host">
+ {#if error}<p class="warn dock-error" role="alert">{error}</p>{/if}
+ {#if detection}
+ <DetectDetection {detection} {detail} {findings} methods={catalogue.methods} {busy}
+ onrun={() => act(() => prepareLaunch(detection))}
+ onexport={() => act(() => exportLayer('followups', detection.id))}
+ oncancel={(run) => act(() => cancelRun(run))}
+ onedit={() => act(() => editDetection(detection.id))}
+ ondelete={() => act(() => removeItem('followups', detection))}
+ onopenrun={(run) => act(() => openRun(run.id))}
+ onopenfinding={(row) => act(async () => {
+ onfocus(row.coordinates);
+ await openRun(row.run_id, row.id);
+ })} />
+ {:else}
+ <div class="cmp-dock-body"><p class="hint">This routine is gone.</p></div>
+ {/if}
+ </div>
+ {:else if view === 'review'}
+ <div class="cmp-dock-body-host">
+ {#if error}<p class="warn" role="alert">{error}</p>{/if}
+ {#if current}
+ <DetectReview {caseId} run={current} methods={catalogue.methods} active={!collapsed} bind:candidateId
+ onaccept={afterVerdict} {onfocus} {onshow} onedit={editRun}
+ onadd={(areaId, kind) => {
+ manual = { areaId, kind };
+ const pair = current.area_runs?.find((pair) => pair.area_id === areaId);
+ if (pair) onshow(pair.b);
+ onframe(current.input.zones.filter((zone) => zone.id === areaId));
+ }}
+ onexport={() => act(() => exportLayer('runs', current.id))} />
+ {:else}
+ <p class="hint">Open a run from the list.</p>
+ {/if}
+ </div>
+ {:else if view === 'library'}
+ <AnalyzerLibrary {catalogue} onchanged={loadCatalogue}
+ onsaved={(recipe) => { if (draft) offer = recipe.id; }} />
+ {/if}
+ {/if}
+ </div>
+</aside>
+
+{#if launch}
+ <Modal title={`Run ${launch.title}`} width="760px" onclose={() => { launch = null; onleavepass(); }}>
+ <AreaDates zones={launch.zones} bind:pairs={launch.area_dates} single={!!methodOf(launch.recipe.method).single}
+ sensor={methodOf(launch.recipe.method).sensor} {onshow} />
+ {#if error}<p class="warn" role="alert">{error}</p>{/if}
+ <button class="btn btn-primary" disabled={busy} onclick={() => act(() => runDetection(launch, { area_dates: clone(launch.area_dates) }))}>
+ {launch.zones.length > 1 ? `Run ${plural(launch.zones.length, 'area')}` : 'Run this area'}
+ </button>
+ </Modal>
+{/if}
+{#if repeatRequest}
+ <Modal title="Already run between these dates" width="560px" onclose={nextRepeat}>
+ {#each repeatRequest.duplicates as match (`${match.run_id}-${match.area_id}`)}
+ <p>{match.area_name} · {match.a.date} → {match.b.date} · see run {match.title}</p>
+ <button class="btn btn-sm" onclick={() => { nextRepeat(); launch = null; void act(() => openRun(match.run_id)); }}>Open</button>
+ {/each}
+ <button class="btn btn-primary" disabled={busy} onclick={() => act(repeat)}>Run anyway</button>
+ </Modal>
+{/if}
+
+<style>
+ .cmp-dock.collapsed { flex: 0 0 42px; width: 42px; min-width: 42px; }
+ .dock-content { display: flex; flex: 1; flex-direction: column; min-height: 0; }
+ .dock-content[hidden] { display: none; }
+ .dock-content > header { display: flex; align-items: center; gap: 7px; padding: 6px 10px; border-bottom: 1px solid var(--border); }
+ .dock-content > header strong { flex: 1; font-size: var(--fs-xs); }
+ .dock-tabs { display: flex; align-items: center; gap: 2px; padding: 5px; border-bottom: 1px solid var(--border); }
+ .dock-tabs.rail { flex-direction: column; }
+ .section-tab { display: flex; flex: 1; align-items: center; justify-content: center; gap: 5px; min-height: 30px; padding: 5px; border-radius: var(--r-sm); font-size: var(--fs-xs); color: var(--text-2); }
+ .section-tab:hover { background: var(--bg-2); color: var(--text-1); }
+ .section-tab.on { color: var(--accent); background: var(--accent-soft); }
+ .rail .section-tab { flex: 0 0 32px; width: 32px; }
+ .new-action { position: relative; padding: 8px 10px; }
+ .new-action > button { width: 100%; }
+ .new-menu { position: absolute; top: 100%; left: 10px; right: 10px; z-index: 700; display: grid; gap: 2px; padding: 6px; }
+ .kind { display: grid; gap: 2px; padding: 7px 9px; border-radius: var(--r-sm); text-align: left; }
+ .kind:hover { background: var(--bg-3); }
+ .kind strong { font-size: var(--fs-xs); }
+ .kind small { color: var(--text-3); font-size: 10.5px; line-height: 1.35; }
+ .pane { display: contents; }
+ .pane[hidden] { display: none; }
+ .cmp-dock-body-host { display: contents; }
+ .dock-error { padding: 10px 12px 0; }
+</style>
diff --git a/frontend/src/tools/detect/DetectPanel.test.js b/frontend/src/tools/detect/DetectPanel.test.js
new file mode 100644
index 0000000..a3c24c0
--- /dev/null
+++ b/frontend/src/tools/detect/DetectPanel.test.js
@@ -0,0 +1,720 @@
+// @vitest-environment happy-dom
+import { beforeEach, afterEach, expect, it, vi } from 'vitest';
+import { flushSync, mount, unmount } from 'svelte';
+
+const sizes = {
+ small: { min_area: 300, max_area: 0, cleanup: 0, smoothing: 0, merge_metres: 0 },
+ medium: { min_area: 2000, max_area: 0, cleanup: 1, smoothing: 0, merge_metres: 30 },
+ large: { min_area: 20000, max_area: 0, cleanup: 1, smoothing: 1, merge_metres: 100 },
+};
+const recipe = { id: 'large-change', name: 'Any surface change', description: 'Reflectance that moved',
+ phenomenon: 'Surface change', method: 'surface', colour: '#f6a81a', style: 'both',
+ parameters: { sensitivity: 67, ...sizes.medium, index: 'ndvi', direction: 'both',
+ ignore_clouds: true, ignore_shadows: true, cloud_margin: 5 } };
+const vessels = { ...recipe, id: 'boats', name: 'Vessels', method: 'vessels', phenomenon: 'Vessel candidate' };
+const methods = [
+ { id: 'surface', label: 'Any reflectance change', single: false, clouds: true, sizes,
+ measure: 'Reflectance moved by {value}%' },
+ { id: 'vessels', label: 'Vessels: infrared contrast over water', single: true, clouds: true, sizes,
+ measure: '{value}× brighter than the water around it' },
+ { id: 'hotspots', label: 'Hotspots', single: true, clouds: false, sizes,
+ measure: 'Short-wave infrared {value}× the bands beside it' },
+];
+const catalogue = (extra = {}) => ({ builtins: [structuredClone(recipe), structuredClone(vessels)],
+ custom: [], methods, max_tiles: 4096, max_results: 2000, grid: [13, 512], ...extra });
+const get = vi.fn();
+const post = vi.fn();
+const put = vi.fn();
+const patch = vi.fn();
+const del = vi.fn();
+const toast = vi.fn();
+vi.mock('../../lib/api.js', () => ({ api: { get, post, patch, put, del } }));
+vi.mock('../../lib/state.svelte.js', () => ({ ensureCase: async () => ({ id: 'case-a' }),
+ reloadCase: async () => {}, toast, uiState: {}, prefs: { units: 'metric' } }));
+const { default: Panel } = await import('./DetectPanel.svelte');
+const { refreshRuns } = await import('../../lib/detectRuns.svelte.js');
+
+let live, target;
+const settle = async () => { for (let i = 0; i < 120; i++) await Promise.resolve(); flushSync(); };
+const button = (text) => [...document.querySelectorAll('button')].find((b) => b.textContent.trim() === text);
+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 area = [{ id: 'area', name: 'Area', kind: 'rect', points: [[2, 48], [2.001, 48.001]] }];
+const WATCH = 'abcdef123456';
+const RUN = '123456789abc';
+const watchRow = (extra = {}) => ({ id: WATCH, title: 'Harbour weekly', created_at: '2026-09-01T00:00:00Z',
+ analyzer: 'Vessels', method: 'vessels', colour: '#38bdf8', areas: 1, zones: area,
+ date_rule: 'latest_previous', note: 'Weekly look at the anchorage', ...extra });
+const watchBody = (extra = {}) => ({ id: WATCH, title: 'Harbour weekly', note: 'Weekly look at the anchorage',
+ zones: area, recipe: structuredClone(vessels), a: { provider: 'sentinel2', date: '2026-09-01' },
+ b: { provider: 'sentinel2', date: '' }, offline: false, date_rule: 'latest_previous', followup_id: null, ...extra });
+const runRow = (extra = {}) => ({ id: RUN, title: 'Harbour weekly', followup_id: WATCH, status: 'ready',
+ progress: 1, total: 1, count: 4, to_review: 3, marked: 1, dates: ['2026-09-01', '2026-09-06'],
+ created_at: '2026-09-06T10:00:00Z', ...extra });
+const finding = (extra = {}) => ({ id: '0-1', run_id: RUN, run_title: 'Harbour weekly', date: '2026-09-06',
+ coordinates: [42.95, 14.81], phenomenon: 'Vessel candidate', strength: 'strong', measure: { value: 6.2 },
+ review: 'noted', area: 90, width: 15, height: 6, ...extra });
+
+/** A GET answered from a table of paths, with the libraries empty by default. */
+function answer(table = {}) {
+ get.mockImplementation(async (path) => {
+ if (path in table) return structuredClone(table[path]);
+ return path === '/api/compare/analyzers' ? catalogue() : [];
+ });
+}
+
+async function open(props = {}) {
+ live = mount(Panel, { target, props: { caseId: 'case-a', ...props } });
+ await settle();
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ answer();
+ target = document.createElement('div'); document.body.append(target);
+});
+afterEach(async () => {
+ if (live) unmount(live);
+ live = null;
+ target.remove();
+ document.body.innerHTML = '';
+ await refreshRuns(null);
+});
+
+// -- the list ------------------------------------------------------------------
+
+it('opens on the case list, reading local libraries and nothing else', async () => {
+ await open();
+ expect(get.mock.calls.map(([path]) => path).sort()).toEqual([
+ '/api/cases/case-a/analysis/areas', '/api/cases/case-a/analysis/followups', '/api/cases/case-a/analysis/runs',
+ '/api/cases/case-a/analysis/zones', '/api/compare/analyzers',
+ ]);
+ expect(post).not.toHaveBeenCalled();
+ expect(target.textContent).toContain('No routine in this case yet.');
+ expect(heading()).toBeUndefined();
+});
+
+it('asks which kind before asking anything else', async () => {
+ await open();
+ button('New detection').click(); await settle();
+ expect(labelled('New one pass')).toBeDefined();
+ expect(labelled('New routine')).toBeDefined();
+ labelled('New one pass').click(); await settle();
+ expect(heading()).toBe('Where to look');
+ expect(target.textContent).toContain('New pass');
+});
+
+it('shows a routine with what it is for and where its last run stands', async () => {
+ answer({ '/api/cases/case-a/analysis/followups': [watchRow()], '/api/cases/case-a/analysis/runs': [runRow()],
+ [`/api/cases/case-a/analysis/followups/${WATCH}`]: watchBody() });
+ post.mockResolvedValue({ id: 'fedcba987654', status: 'queued' });
+ await open();
+ expect(target.textContent).toContain('Weekly look at the anchorage');
+ expect(target.textContent).toContain('Vessels · 1 area · newest pass');
+ expect(target.textContent).toContain('2026-09-06 · 3 to review');
+ labelled('Run Harbour weekly').click(); await settle();
+ expect(post).not.toHaveBeenCalled();
+ expect(document.querySelector('[aria-label="Dates per area"]')).not.toBe(null);
+ button('Run this area').click(); await settle();
+ expect(post).toHaveBeenCalledWith(`/api/cases/case-a/analysis/followups/${WATCH}/run`, {
+ area_dates: [expect.objectContaining({ area_id: 'area', b: expect.objectContaining({ date: '' }) })],
+ });
+});
+
+it('queues every routine that is not already working', async () => {
+ answer({
+ '/api/cases/case-a/analysis/followups': [watchRow(), watchRow({ id: 'bbbbbbbbbbbb', title: 'Airfield' })],
+ '/api/cases/case-a/analysis/runs': [runRow({ status: 'running', progress: 2, total: 9, count: 0 })],
+ });
+ post.mockResolvedValue({ status: 'queued' });
+ await open();
+ expect(target.textContent).toContain('Running · 2/9 tiles');
+ button('Run all').click(); await settle();
+ expect(post.mock.calls.map(([path]) => path)).toEqual(['/api/cases/case-a/analysis/followups/bbbbbbbbbbbb/run']);
+ expect(toast).toHaveBeenCalledWith('1 routine queued', 'ok');
+});
+
+it('groups the saved runs by routine, and puts one on the map beside its trash', async () => {
+ const once = runRow({ id: 'cccccccccccc', title: 'Port sweep', followup_id: null, analyzer: 'Vessels', areas: 1,
+ count: 0, to_review: 0, marked: 0 });
+ const full = (row) => ({ ...row, engine_version: 2, frames: {}, results: [],
+ input: { title: row.title, zones: area, recipe: structuredClone(vessels), note: '', followup_id: row.followup_id,
+ a: { provider: 'sentinel2', date: '2026-09-01' }, b: { provider: 'sentinel2', date: '2026-09-06' },
+ offline: false, date_rule: 'manual' } });
+ answer({
+ '/api/cases/case-a/analysis/followups': [watchRow()],
+ '/api/cases/case-a/analysis/runs': [runRow(), once],
+ [`/api/cases/case-a/analysis/runs/${RUN}`]: full(runRow()),
+ '/api/cases/case-a/analysis/runs/cccccccccccc': full(once),
+ });
+ const onframe = vi.fn();
+ await open({ onframe });
+ button('Saved').click(); await settle();
+ expect([...target.querySelectorAll('.fold .name')].map((node) => node.textContent)).toEqual(['Harbour weekly', 'One passes']);
+ // under its routine a run is told apart by its days, the routine being named above
+ expect(target.textContent).toContain('2026-09-06 · 3 to review');
+ expect(target.textContent).toContain('2026-09-01 → 2026-09-06');
+ expect(target.textContent).toContain('Vessels · 1 area');
+ // every finished run is on the map from the start, and turns off beside its trash
+ const eye = labelled('Hide Port sweep on the map');
+ expect(eye.nextElementSibling.getAttribute('aria-label')).toBe('Delete Port sweep');
+ eye.click(); await settle();
+ expect(onframe).not.toHaveBeenCalled();
+ labelled('Show Port sweep on the map').click(); await settle();
+ expect(onframe).toHaveBeenCalledWith(area);
+ // a routine's runs go off and on together
+ labelled('Hide every run of Harbour weekly on the map').click(); await settle();
+ expect(labelled('Show Harbour weekly · 2026-09-01 → 2026-09-06 on the map')).not.toBe(null);
+ // what was kept goes to the SAT layers from here, a routine's runs into its one layer
+ post.mockResolvedValue({});
+ labelled('Add Harbour weekly to the SAT layers').click(); await settle();
+ expect(post).toHaveBeenCalledWith(`/api/cases/case-a/analysis/followups/${WATCH}/export`, {});
+ labelled('Add Harbour weekly · 2026-09-01 → 2026-09-06 to the SAT layers').click(); await settle();
+ expect(post).toHaveBeenCalledWith(`/api/cases/case-a/analysis/runs/${RUN}/export`, {});
+ expect(toast).toHaveBeenCalledWith('Snapshot saved in SAT layers', 'ok');
+ // a run with nothing kept has nothing to give a layer, and says so
+ const empty = labelled('Add Port sweep to the SAT layers');
+ expect(empty.disabled).toBe(true);
+ expect(empty.getAttribute('title')).toContain('Keep or pin a candidate first');
+ // and a group folds shut
+ const fold = [...target.querySelectorAll('.fold')].find((node) => node.textContent.includes('Harbour weekly'));
+ fold.click(); await settle();
+ expect(fold.getAttribute('aria-expanded')).toBe('false');
+ expect(target.textContent).not.toContain('2026-09-06 · 3 to review');
+});
+
+it('reshapes a shared area on the map, saying what its routines will sweep', async () => {
+ const ring = [[2, 48], [2.01, 48], [2.01, 48.01], [2, 48.01], [2, 48]];
+ const shared = { id: 'aaaaaaaaaaaa', name: 'North site', colour: '#38bdf8', geometry: { type: 'Polygon', coordinates: [ring] } };
+ answer({
+ '/api/cases/case-a/analysis/areas': [shared],
+ '/api/cases/case-a/analysis/followups': [watchRow({ zones: [{ id: shared.id, name: shared.name, kind: 'polygon', points: ring.slice(0, -1) }] })],
+ });
+ put.mockResolvedValue({});
+ post.mockResolvedValue({});
+ const onframe = vi.fn();
+ await open({ onframe });
+ button('Areas').click(); await settle();
+ labelled('Edit North site').click(); await settle();
+ button('Reshape on the map').click(); await settle();
+ // the map goes to the area, and the panel says who follows the new shape
+ expect(onframe).toHaveBeenCalledWith([{ kind: 'polygon', points: ring }]);
+ expect(target.textContent).toContain('1 routine watches it: the next runs sweep the new shape.');
+ expect(target.textContent).toContain('Finished runs keep the ground they swept.');
+ button('Cancel').click(); await settle();
+ expect(target.querySelector('[aria-label="Reshaping North site"]')).toBe(null);
+ expect(put).not.toHaveBeenCalled();
+
+ labelled('Edit North site').click(); await settle();
+ button('Reshape on the map').click(); await settle();
+ button('Save shape').click(); await settle();
+ expect(put).toHaveBeenCalledWith('/api/cases/case-a/analysis/areas/aaaaaaaaaaaa',
+ { name: 'North site', colour: '#38bdf8', geometry: { type: 'Polygon', coordinates: [ring] } });
+
+ // a new area leaves the old one, and its routines, as they were
+ labelled('Edit North site').click(); await settle();
+ button('Reshape on the map').click(); await settle();
+ button('Save as a new area').click(); await settle();
+ expect(post).toHaveBeenCalledWith('/api/cases/case-a/analysis/areas',
+ { name: 'North site · new shape', colour: '#38bdf8', geometry: { type: 'Polygon', coordinates: [ring] } });
+ expect(put).toHaveBeenCalledTimes(1);
+});
+
+// -- a routine's own page ---------------------------------------------------------
+
+it('opens a routine on what it has found, and runs it again on a chosen pass', async () => {
+ answer({
+ '/api/cases/case-a/analysis/followups': [watchRow()],
+ '/api/cases/case-a/analysis/runs': [runRow()],
+ [`/api/cases/case-a/analysis/followups/${WATCH}`]: watchBody(),
+ [`/api/cases/case-a/analysis/followups/${WATCH}/findings`]: [finding(), finding({ id: '0-2', review: 'kept' })],
+ });
+ post.mockImplementation(async (path) => (path.endsWith('/acquisitions')
+ ? { dates: [{ date: '2026-09-16', cloud: 4, granules: 1, coverage: 1 }], truncated: false }
+ : { id: 'fedcba987654', status: 'queued' }));
+ await open();
+ button('Harbour weekly').click(); await settle();
+ expect(heading()).toBe('Harbour weekly');
+ expect(target.textContent).toContain('Weekly look at the anchorage');
+ // what it has found, across every run, with how each one was kept
+ expect(target.textContent).toContain('Kept here');
+ expect(target.textContent).toContain('Pinned');
+ expect(target.textContent).toContain('Vessel candidate · Strong · 6.2× brighter than the water around it');
+
+ // a routine is relaunched against a day, and asks which one
+ button('Run routine').click(); await settle();
+ button('Find passes').click(); await settle();
+ expect(post).toHaveBeenCalledWith('/api/satellite/sentinel/acquisitions', expect.objectContaining({ zones: area }));
+ button('Use').click(); await settle();
+ button('Run this area').click(); await settle();
+ expect(post).toHaveBeenCalledWith(`/api/cases/case-a/analysis/followups/${WATCH}/run`, { area_dates: [expect.objectContaining({ b: expect.objectContaining({ date: '2026-09-16' }) })] });
+});
+
+it('lists a routine\'s runs, and opens one on its candidates', async () => {
+ const saved = { ...runRow(), engine_version: 2, frames: {}, results: [],
+ input: { title: 'Harbour weekly', zones: area, recipe: structuredClone(vessels), followup_id: WATCH,
+ a: { provider: 'sentinel2', date: '2026-09-01' }, b: { provider: 'sentinel2', date: '2026-09-06' },
+ offline: false, date_rule: 'latest_previous' } };
+ answer({
+ '/api/cases/case-a/analysis/followups': [watchRow()],
+ '/api/cases/case-a/analysis/runs': [runRow()],
+ [`/api/cases/case-a/analysis/followups/${WATCH}`]: watchBody(),
+ [`/api/cases/case-a/analysis/runs/${RUN}`]: saved,
+ });
+ await open();
+ button('Harbour weekly').click(); await settle();
+ starts('Runs').click(); await settle();
+ starts('2026-09-06 · 3 to review').click(); await settle();
+ expect(target.textContent).toContain('Completed · 1 tile · 2026-09-06');
+});
+
+// -- building one ------------------------------------------------------------------
+
+it('walks a single pass through its steps and runs it once', async () => {
+ answer({ '/api/cases/case-a/analysis/zones/aaaaaaaaaaaa': { id: 'aaaaaaaaaaaa', title: 'Port', zones: area } });
+ post.mockResolvedValue({ id: RUN, status: 'queued', input: {}, results: [], total: 1, progress: 0 });
+ await open({ opening: 'zones-aaaaaaaaaaaa' });
+ expect(heading()).toBe('Where to look');
+ expect(target.textContent).toContain('1 tile · 4 requests a run');
+ button('Next: What').click(); await settle();
+ expect(heading()).toBe('What to look for');
+ button('Next: When').click(); await settle();
+ expect(heading()).toBe('Which two images');
+ // 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');
+ 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();
+ expect(target.textContent).toContain('Choose A, the picture before.');
+ // the passes are listed in the step itself, and only when asked for
+ expect(post).not.toHaveBeenCalled();
+ post.mockImplementationOnce(async () => ({
+ dates: [{ date: '2026-08-01', cloud: 2, granules: 1, coverage: 1 }], truncated: false }));
+ button('Find passes').click(); await settle();
+ expect(post).toHaveBeenCalledWith('/api/satellite/sentinel/acquisitions', expect.objectContaining({ zones: area }));
+ button('A').click(); await settle();
+ expect(button('Next: Start').disabled).toBe(false);
+ button('Next: Start').click(); await settle();
+ expect(heading()).toBe('Name and start');
+ expect(target.textContent).toContain('2026-08-01 → 2026-09-06');
+ const note = target.querySelector('[aria-label="Detection description"]');
+ note.value = 'Checking the strike'; note.dispatchEvent(new Event('input', { bubbles: true }));
+ button('Run this pass').click(); await settle();
+ expect(post).toHaveBeenCalledWith('/api/cases/case-a/analysis/runs', expect.objectContaining({
+ zones: area, date_rule: 'manual', note: 'Checking the strike', followup_id: null,
+ area_dates: [expect.objectContaining({ a: expect.objectContaining({ date: '2026-08-01' }), b: expect.objectContaining({ date: '2026-09-06' }) })],
+ }));
+});
+
+it('asks a routine what each pass compares against, not which day to read', async () => {
+ const set = { id: 'aaaaaaaaaaaa', title: 'Port', zones: area, areas: 1 };
+ let saved = [];
+ get.mockImplementation(async (path) => {
+ if (path === '/api/compare/analyzers') return catalogue();
+ if (path === '/api/cases/case-a/analysis/zones') return [set];
+ if (path === '/api/cases/case-a/analysis/zones/aaaaaaaaaaaa') return structuredClone(set);
+ if (path === '/api/cases/case-a/analysis/followups') return structuredClone(saved);
+ if (path === `/api/cases/case-a/analysis/followups/${WATCH}`) return watchBody();
+ return [];
+ });
+ post.mockImplementation(async (path, body) => {
+ if (path.endsWith('/acquisitions')) {
+ return { dates: [{ date: '2026-08-01', cloud: 2, granules: 1, coverage: 1 }], truncated: false };
+ }
+ if (path.endsWith('/followups')) {
+ saved = [watchRow()];
+ return { ...body, id: WATCH };
+ }
+ return { id: RUN, status: 'queued' };
+ });
+ await open();
+ button('New detection').click(); await settle();
+ labelled('New routine').click(); await settle();
+ expect(target.textContent).toContain('New routine');
+ button('Port1 area').click(); await settle();
+ 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('The pass before');
+ expect(target.textContent).toContain('Only the first run');
+ expect(target.textContent).toContain('Choose A, the picture the first run compares with.');
+ // a routine names no B: the list offers A alone
+ button('Find passes').click(); await settle();
+ 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');
+ 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' }) })],
+ }));
+ 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('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)] }),
+ '/api/cases/case-a/analysis/zones/aaaaaaaaaaaa': { id: 'aaaaaaaaaaaa', title: 'Port', zones: area },
+ });
+ post.mockImplementation(async (path) => (path.endsWith('/acquisitions')
+ ? { dates: [{ date: '2026-09-16', cloud: 4, granules: 1, coverage: 1 }], truncated: false }
+ : { id: RUN, status: 'queued', input: {}, results: [], total: 1, progress: 0 }));
+ await open({ opening: 'zones-aaaaaaaaaaaa' });
+ button('Next: What').click(); await settle();
+ 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.querySelector('[aria-label="Day of A"]')).toBe(null);
+ expect(button('Next: Start').disabled).toBe(false);
+ button('A day I choose').click(); await settle();
+ expect(button('Next: Start').disabled).toBe(true);
+ expect(target.textContent).toContain('Choose the day, or take the newest pass.');
+ button('Find passes').click(); await settle();
+ button('Use').click(); await settle();
+ button('Next: Start').click(); await settle();
+ expect(target.textContent).toContain('2026-09-16');
+ 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-16' }) })],
+ }));
+});
+
+it('gives every area the same days, and keeps a table for areas that differ', async () => {
+ const two = [...area, { id: 'far', name: 'Far', kind: 'rect', points: [[9, 40], [9.001, 40.001]] }];
+ answer({ '/api/cases/case-a/analysis/zones/aaaaaaaaaaaa': { id: 'aaaaaaaaaaaa', title: 'Port', zones: two } });
+ post.mockImplementation(async (path) => (path.endsWith('/acquisitions')
+ ? { dates: [{ date: '2026-08-01', cloud: 2, granules: 2, coverage: 1 }], truncated: false }
+ : { id: RUN, status: 'queued', input: {}, results: [], total: 1, progress: 0 }));
+ await open({ opening: 'zones-aaaaaaaaaaaa' });
+ button('Next: What').click(); await settle();
+ button('Next: When').click(); await settle();
+ expect(target.textContent).toContain('Passes over these areas');
+ // one lookup over both, so a pass that covers them all says so
+ button('Find passes').click(); await settle();
+ expect(post).toHaveBeenCalledWith('/api/satellite/sentinel/acquisitions', expect.objectContaining({ zones: two }));
+ button('A').click(); await settle();
+ expect(target.textContent).toContain('The same days for all 2 areas.');
+ button('Set them per area…').click(); await settle();
+ const far = document.querySelector('[aria-label="Reference for Far"]');
+ far.value = '20/07/2026'; far.dispatchEvent(new Event('input', { bubbles: true })); await settle();
+ button('Done').click(); await settle();
+ expect(target.textContent).toContain('The areas have days of their own.');
+ expect(target.textContent).toContain('A 2026-07-20 → B newest pass');
+ button('Next: Start').click(); await settle();
+ expect(target.textContent).toContain('Its own days for each area');
+ button('Run this pass').click(); await settle();
+ expect(post).toHaveBeenCalledWith('/api/cases/case-a/analysis/runs', expect.objectContaining({
+ area_dates: [
+ expect.objectContaining({ area_id: 'area', a: expect.objectContaining({ date: '2026-08-01' }) }),
+ expect.objectContaining({ area_id: 'far', a: expect.objectContaining({ date: '2026-07-20' }) }),
+ ],
+ }));
+});
+
+it('asks a routine of one image for nothing but its picture', async () => {
+ const set = { id: 'aaaaaaaaaaaa', title: 'Port', zones: area, areas: 1 };
+ answer({ '/api/compare/analyzers': catalogue({ builtins: [structuredClone(vessels)] }),
+ '/api/cases/case-a/analysis/zones': [set], '/api/cases/case-a/analysis/zones/aaaaaaaaaaaa': set });
+ await open();
+ button('New detection').click(); await settle();
+ labelled('New routine').click(); await settle();
+ button('Port1 area').click(); await settle();
+ 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(button('Find passes')).toBeUndefined();
+ expect(button('Next: Start').disabled).toBe(false);
+ button('Next: Start').click(); await settle();
+ expect(target.textContent).toContain('Each run: the newest pass');
+ expect(post).not.toHaveBeenCalled();
+});
+
+it('holds a routine to one fixed picture when asked', async () => {
+ const set = { id: 'aaaaaaaaaaaa', title: 'Port', zones: area, areas: 1 };
+ answer({ '/api/cases/case-a/analysis/zones': [set], '/api/cases/case-a/analysis/zones/aaaaaaaaaaaa': set,
+ [`/api/cases/case-a/analysis/followups/${WATCH}`]: watchBody({ date_rule: 'latest_reference' }) });
+ post.mockImplementation(async (_, body) => ({ ...body, id: WATCH }));
+ await open();
+ button('New detection').click(); await settle();
+ labelled('New routine').click(); await settle();
+ button('Port1 area').click(); await settle();
+ button('Next: What').click(); await settle();
+ button('Next: When').click(); await settle();
+ [...target.querySelectorAll('[role="radio"]')].find((node) => node.textContent.includes('A fixed picture')).click();
+ await settle();
+ expect(target.textContent).toContain('Every run compares with');
+ expect(target.textContent).toContain('Choose A, the picture every run compares with.');
+ 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');
+ button('Save without running').click(); await settle();
+ expect(post).toHaveBeenCalledWith('/api/cases/case-a/analysis/followups', expect.objectContaining({
+ date_rule: 'latest_reference',
+ area_dates: [expect.objectContaining({ date_rule: 'latest_reference', a: expect.objectContaining({ date: '2026-08-01' }),
+ b: expect.objectContaining({ date: '' }) })],
+ }));
+});
+
+it('refuses an area the engine would reject before the next step', async () => {
+ const zones = [{ id: 'big', name: 'Whole region', kind: 'rect', points: [[2, 48], [8, 54]] }];
+ answer({
+ '/api/compare/analyzers': catalogue({ max_tiles: 256 }),
+ '/api/cases/case-a/analysis/zones/aaaaaaaaaaaa': { id: 'aaaaaaaaaaaa', title: 'Region', zones },
+ });
+ await open({ opening: 'zones-aaaaaaaaaaaa' });
+ expect(button('Next: What').disabled).toBe(true);
+ expect(target.textContent).toContain('the limit is 256');
+ expect(post).not.toHaveBeenCalled();
+});
+
+it('sets a size as a whole set of numbers, and shows when it was tuned by hand', async () => {
+ answer({ '/api/cases/case-a/analysis/zones/aaaaaaaaaaaa': { id: 'aaaaaaaaaaaa', title: 'Port', zones: area } });
+ await open({ opening: 'zones-aaaaaaaaaaaa' });
+ button('Next: What').click(); await settle();
+ const pressed = () => [...target.querySelectorAll('[aria-label="Target size"] button')]
+ .filter((b) => b.getAttribute('aria-pressed') === 'true').map((b) => b.textContent.trim());
+ expect(pressed()).toEqual(['Medium']);
+ button('Small').click(); await settle();
+ expect(pressed()).toEqual(['Small']);
+ button('Adjust thresholds…').click(); await settle();
+ const minimum = target.querySelector('[aria-label="Minimum area"]');
+ expect(minimum.value).toBe('300');
+ minimum.value = '120'; minimum.dispatchEvent(new Event('input', { bubbles: true })); await settle();
+ expect(pressed()).toEqual([]);
+});
+
+it('offers the cloud switch on by default, and none for a method that rejects cloud itself', async () => {
+ answer({ '/api/cases/case-a/analysis/zones/aaaaaaaaaaaa': { id: 'aaaaaaaaaaaa', title: 'Port', zones: area } });
+ await open({ opening: 'zones-aaaaaaaaaaaa' });
+ button('Next: What').click(); await settle();
+ const chip = [...document.querySelectorAll('button')].find((b) => b.textContent.includes('Clouds & shadows'));
+ expect(chip.getAttribute('aria-pressed')).toBe('true');
+ expect(target.textContent).toContain('traced from the sun');
+ unmount(live); target.innerHTML = '';
+ answer({
+ '/api/compare/analyzers': catalogue({ builtins: [{ ...structuredClone(recipe), id: 'anomaly', method: 'hotspots' }] }),
+ '/api/cases/case-a/analysis/zones/aaaaaaaaaaaa': { id: 'aaaaaaaaaaaa', title: 'Port', zones: area },
+ });
+ await open({ opening: 'zones-aaaaaaaaaaaa' });
+ button('Next: What').click(); await settle();
+ expect(target.textContent).not.toContain('Clouds & shadows');
+});
+
+it('says what a partial pass will leave unswept before the run, not after', async () => {
+ answer({ '/api/cases/case-a/analysis/zones/aaaaaaaaaaaa': { id: 'aaaaaaaaaaaa', title: 'Port', zones: area } });
+ post.mockResolvedValue({ dates: [{ date: '2026-05-04', cloud: 12, granules: 1, coverage: 0.62 }], truncated: false });
+ await open({ opening: 'zones-aaaaaaaaaaaa' });
+ button('Next: What').click(); await settle();
+ button('Next: When').click(); await settle();
+ // Pass lookups stay explicit.
+ expect(target.querySelector('input[type="date"]')).toBe(null);
+ expect(post).not.toHaveBeenCalled();
+ button('Find passes').click(); await settle();
+ button('B').click(); await settle();
+ expect(document.body.textContent).toContain('reaches 62% of the areas');
+ expect(document.body.textContent).toContain('not swept');
+});
+
+// -- the analyzers -------------------------------------------------------------------
+
+it('makes an analyzer of its own from the closest built-in, and never writes over one', async () => {
+ post.mockImplementation(async (_, body) => ({ ...body, id: 'custom-copy' }));
+ await open();
+ labelled('Analyzers').click(); await settle();
+ expect(target.textContent).toContain('Yours start as a copy of the closest built-in.');
+ starts('Vessels').click(); await settle();
+ expect(target.textContent).toContain('Measures Vessels: infrared contrast over water');
+ expect(button('Save changes')).toBeUndefined();
+ expect(button('Copy to tune')).toBeDefined();
+ button('Back').click(); await settle();
+
+ button('New analyzer').click(); await settle();
+ expect(heading()).toBe('Start from');
+ [...target.querySelectorAll('button.base')].find((b) => b.textContent.includes(recipe.name)).click(); await settle();
+ const name = target.querySelector('[aria-label="Analyzer name"]');
+ expect(name.value).toBe(`${recipe.name} copy`);
+ name.value = 'Weekly harbour'; name.dispatchEvent(new Event('input', { bubbles: true }));
+ button('Add to my analyzers').click(); await settle();
+ expect(post).toHaveBeenCalledWith('/api/compare/analyzers',
+ expect.objectContaining({ id: 'custom', name: 'Weekly harbour', method: 'surface' }));
+});
+
+it('edits and removes an analyzer of its own', async () => {
+ const own = { ...structuredClone(recipe), id: 'custom-1', name: 'Weekly harbour' };
+ answer({ '/api/compare/analyzers': catalogue({ custom: [own] }) });
+ await open();
+ labelled('Analyzers').click(); await settle();
+ labelled('Edit Weekly harbour').click(); await settle();
+ expect(button('Save changes')).toBeDefined();
+ button('Cancel').click(); await settle();
+ labelled('Delete Weekly harbour').click(); await settle();
+ expect(del).toHaveBeenCalledWith('/api/compare/analyzers/custom-1');
+});
+
+// -- review --------------------------------------------------------------------------
+
+it('offers three verdicts, and only the pin reaches the case', async () => {
+ const row = (id, lon, strength, value) => ({ id, coordinates: [lon, 48], bbox: [lon, 48, lon + 0.001, 48.001],
+ area: 90, width: 15, height: 6, margin: 2, strength, measure: { value }, review: 'new',
+ phenomenon: 'Surface change', parts: [{ frames: ['a', 'b'], box: [0, 0, 4, 4] }] });
+ const saved = { id: RUN, title: 'Harbour sweep', status: 'ready', progress: 1, total: 1,
+ count: 2, engine_version: 2, results: [row('0-1', 2, 'strong', 12.34), row('0-2', 2.002, 'weak', 8)],
+ input: { title: 'Harbour sweep', zones: area, recipe: structuredClone(recipe), note: '',
+ a: { provider: 'sentinel2', date: '2026-05-04' }, b: { provider: 'sentinel2', date: '2026-05-11' },
+ offline: false, date_rule: 'manual', followup_id: null } };
+ answer({ [`/api/cases/case-a/analysis/runs/${RUN}`]: saved });
+ patch.mockImplementation(async (_, body) => ({ ...saved.results[0], ...body }));
+ post.mockImplementation(async () => ({ entity: { id: 'e1', type: 'place' },
+ result: { ...saved.results[1], review: 'kept', entity_id: 'e1' } }));
+ await open({ opening: `runs-${RUN}` });
+ expect(target.textContent).toContain('1 of 2');
+ expect(target.textContent).toContain('Strong · Reflectance moved by 12.3%');
+ expect(target.textContent).toContain('Keep stays in this run. Pin creates a place and evidence in Files.');
+
+ // kept here: no pin, no entity, and it stays among what the detection holds
+ button('Keep').click(); await settle();
+ expect(patch).toHaveBeenCalledWith(`/api/cases/case-a/analysis/runs/${RUN}/results/0-1`, { review: 'noted' });
+ expect(post).not.toHaveBeenCalled();
+ expect(target.textContent).toContain('2 of 2');
+
+ button('Pin').click(); await settle();
+ expect(document.querySelector('[role="dialog"][aria-label="Pin candidate"]')).not.toBe(null);
+ expect(post).not.toHaveBeenCalled();
+ expect(document.querySelector('[value="area"]').checked).toBe(true);
+ button('Save pin').click(); await settle();
+ expect(post).toHaveBeenCalledWith(`/api/cases/case-a/analysis/runs/${RUN}/results/0-2/promote`,
+ { title: 'Surface change · 48.0000, 2.0020', description: '', after_only: false, shape: 'area' });
+ expect(target.textContent).toContain('Kept as a pin in this case');
+ expect(target.textContent).toContain('1 pinned, 1 kept here');
+});
+
+it('walks the queue from the keys, and narrows it to what is still to review', async () => {
+ const row = (id, lon, review) => ({ id, coordinates: [lon, 48], bbox: [lon, 48, lon + 0.001, 48.001],
+ area: 90, width: 15, height: 6, margin: 2, strength: 'strong', measure: { value: 3 }, review,
+ phenomenon: 'Surface change', parts: [{ frames: ['a', 'b'], box: [0, 0, 4, 4] }] });
+ const saved = { id: RUN, title: 'Harbour sweep', status: 'ready', progress: 1, total: 1,
+ count: 3, engine_version: 2,
+ results: [row('0-1', 2, 'new'), row('0-2', 2.002, 'noted'), row('0-3', 2.004, 'new')],
+ input: { title: 'Harbour sweep', zones: area, recipe: structuredClone(recipe), note: '',
+ a: { provider: 'sentinel2', date: '2026-05-04' }, b: { provider: 'sentinel2', date: '2026-05-11' },
+ offline: false, date_rule: 'manual', followup_id: null } };
+ answer({ [`/api/cases/case-a/analysis/runs/${RUN}`]: saved });
+ patch.mockImplementation(async (_, body) => ({ ...saved.results[0], ...body }));
+ const onfocus = vi.fn();
+ await open({ opening: `runs-${RUN}`, onfocus });
+
+ // Opening a run puts the map on the candidate the panel is about, close
+ // enough to read: judging what you cannot see is guesswork.
+ expect(onfocus).toHaveBeenCalledWith([2, 48], 16);
+
+ // The arrows walk it…
+ document.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowRight', bubbles: true }));
+ await settle();
+ expect(target.textContent).toContain('2 of 3');
+ // …and the verdicts are one key each, on a candidate that still wants one.
+ document.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowRight', bubbles: true }));
+ await settle();
+ document.dispatchEvent(new KeyboardEvent('keydown', { key: 'k', bubbles: true }));
+ await settle();
+ expect(patch).toHaveBeenCalledWith(`/api/cases/case-a/analysis/runs/${RUN}/results/0-3`, { review: 'noted' });
+
+ // The crops are small in a narrow column, so the same picture opens big.
+ labelled('Enlarge the evidence').click(); await settle();
+ expect(document.querySelector('[role="dialog"] img.big')).not.toBe(null);
+ document.querySelector('[role="dialog"] button[aria-label="Close"]').click(); await settle();
+
+ // A hundred candidates are worked in passes, so the queue narrows.
+ button('To review 1').click(); await settle();
+ expect(target.textContent).toContain('1 of 1');
+});
+
+it('reopens a run saved against Wayback without pretending it had a Sentinel-2 date', async () => {
+ const old = { id: 'aaaaaaaaaaaa', title: 'Old harbour', status: 'ready', progress: 1, total: 1, count: 0,
+ engine_version: 1, results: [],
+ input: { title: 'Old harbour', zones: area, recipe: { ...structuredClone(recipe), method: 'colour' },
+ a: { provider: 'esri-wayback', release: 1 }, b: { provider: 'esri-wayback', release: 2 },
+ offline: false, date_rule: 'manual', followup_id: null } };
+ answer({ '/api/cases/case-a/analysis/runs/aaaaaaaaaaaa': old });
+ await open({ opening: 'runs-aaaaaaaaaaaa' });
+ expect(target.textContent).toContain('Wayback release 1 → Wayback release 2');
+ button('Edit and rerun').click(); await settle();
+ expect(heading()).toBe('Where to look');
+ button('Next: What').click(); await settle();
+ button('Next: When').click(); await settle();
+ expect(target.textContent).toContain('Choose A, the picture before.');
+ expect(button('Next: Start').disabled).toBe(true);
+});
+
+// -- radar and the second look ---------------------------------------------------------
+
+it('opens a candidate in Compare on the passes that found it', async () => {
+ const { uiState } = await import('../../lib/state.svelte.js');
+ const row = { id: '0-1', coordinates: [2, 48], bbox: [2, 48, 2.001, 48.001], area: 90, width: 15, height: 6,
+ margin: 2, strength: 'strong', measure: { value: 3 }, review: 'new', phenomenon: 'Surface change',
+ parts: [{ frames: ['a', 'b'], box: [0, 0, 4, 4] }],
+ sources: { a: { provider: 'sentinel2', date: '2026-05-04' }, b: { provider: 'sentinel2', date: '2026-05-11' } } };
+ const saved = { id: RUN, title: 'Harbour sweep', status: 'ready', progress: 1, total: 1, count: 1,
+ engine_version: 2, results: [row],
+ input: { title: 'Harbour sweep', zones: area, recipe: structuredClone(recipe), note: '',
+ a: { provider: 'sentinel2', date: '2026-05-04' }, b: { provider: 'sentinel2', date: '2026-05-11' },
+ offline: false, date_rule: 'manual', followup_id: null } };
+ answer({ [`/api/cases/case-a/analysis/runs/${RUN}`]: saved });
+ await open({ opening: `runs-${RUN}` });
+ button('Compare').click(); await settle();
+ expect(uiState.tool).toBe('compare');
+ expect(uiState.compareAt).toMatchObject({ lat: 48, lon: 2, zoom: 16, dates: ['2026-05-04', '2026-05-11'] });
+ // nothing is asked of Copernicus to decide it: the candidate names its passes
+ expect(post).not.toHaveBeenCalled();
+});
+
+it('says a radar analyzer needs its layer before a detection is built on it', async () => {
+ const radar = { ...structuredClone(recipe), id: 'radar-vessels', name: 'Vessels by radar',
+ method: 'sar-vessels', phenomenon: 'Vessel candidate (radar)' };
+ const radarMethod = { id: 'sar-vessels', label: 'Radar', single: true, clouds: false, sensor: 'sentinel1',
+ frames: 3, sizes, measure: '{value} dB brighter than the sea around it' };
+ const table = { '/api/cases/case-a/analysis/zones/aaaaaaaaaaaa': { id: 'aaaaaaaaaaaa', title: 'Port', zones: area } };
+ get.mockImplementation(async (path) => (path === '/api/compare/analyzers'
+ ? catalogue({ builtins: [radar], methods: [...methods, radarMethod], radar_layer: '' })
+ : path in table ? structuredClone(table[path]) : []));
+ await open({ opening: 'zones-aaaaaaaaaaaa' });
+ // the water it is judged against is one more request a tile
+ expect(target.textContent).toContain('1 tile · 3 requests a run');
+ button('Next: What').click(); await settle();
+ expect(target.textContent).toContain('not set up yet');
+ expect(button('How to add it, in Settings → Imagery')).toBeDefined();
+ expect(button('Next: When').disabled).toBe(true);
+});
+
+it('lists the analyzers by what they look for, each saying how far it can be trusted', async () => {
+ const radar = { ...structuredClone(recipe), id: 'radar-vessels', name: 'Vessels by radar', method: 'sar-vessels' };
+ const radarMethod = { id: 'sar-vessels', label: 'Radar', single: true, clouds: false, sensor: 'sentinel1',
+ frames: 3, sizes, measure: '{value} dB' };
+ const table = { '/api/cases/case-a/analysis/zones/aaaaaaaaaaaa': { id: 'aaaaaaaaaaaa', title: 'Port', zones: area } };
+ get.mockImplementation(async (path) => (path === '/api/compare/analyzers'
+ ? catalogue({ builtins: [structuredClone(vessels), radar, structuredClone(recipe)],
+ methods: [...methods, radarMethod], radar_layer: '', copernicus_key: true,
+ groups: [{ id: 'vessels', label: 'Vessels', recipes: ['radar-vessels', 'boats'] },
+ { id: 'any', label: 'Any change', recipes: ['large-change'] }],
+ reliability: { 'radar-vessels': 'reliable', boats: 'approximate', 'large-change': 'rough' } })
+ : path in table ? structuredClone(table[path]) : []));
+ await open({ opening: 'zones-aaaaaaaaaaaa' });
+ button('Next: What').click(); await settle();
+ const groups = [...target.querySelectorAll('.choices .group')].map((node) => node.textContent);
+ expect(groups).toEqual(['Vessels', 'Any change']);
+ const radarRow = [...target.querySelectorAll('.choice')].find((node) => node.textContent.includes('Vessels by radar'));
+ expect(radarRow.textContent).toContain('(reliable)');
+ expect(radarRow.textContent).toContain('set up');
+ expect(radarRow.getAttribute('title')).toBe('Needs the Sentinel-1 layer');
+ expect(target.textContent).toContain('(rough)');
+});
diff --git a/frontend/src/tools/detect/DetectReview.show.svelte.test.js b/frontend/src/tools/detect/DetectReview.show.svelte.test.js
new file mode 100644
index 0000000..02f6a85
--- /dev/null
+++ b/frontend/src/tools/detect/DetectReview.show.svelte.test.js
@@ -0,0 +1,62 @@
+// @vitest-environment happy-dom
+import { afterEach, expect, it, vi } from 'vitest';
+import { flushSync, mount, unmount } from 'svelte';
+
+/**
+ * Opening a run puts its pass on the map, and the map's own state must not
+ * feed back into the review. A radar pass is an object, so writing it always
+ * looked new: the review's effect re-ran on it until Svelte stopped the page,
+ * and the overlay and the tabs froze where they were.
+ */
+const RUN = '123456789abc';
+const area = [{ id: 'area', name: 'Area', kind: 'rect', points: [[2, 48], [2.001, 48.001]] }];
+const pass = { provider: 'sentinel1', date: '2026-09-22', layer: 'RADAR', maxcc: 100, time: '02:06:41' };
+const other = { ...pass, date: '2026-09-10', time: '02:06:40' };
+const row = (id, source) => ({ id, coordinates: [2, 48], bbox: [2, 48, 2.001, 48.001], area: 90, width: 15,
+ height: 6, margin: 2, strength: 'strong', measure: { value: 3 }, review: 'new', phenomenon: 'Vessel candidate (radar)',
+ parts: [{ frames: ['a'], box: [0, 0, 4, 4] }], sources: { a: source, b: source } });
+const recipe = { id: 'radar-vessels', name: 'Vessels by radar', method: 'sar-vessels', colour: '#38bdf8', style: 'both',
+ phenomenon: 'Vessel candidate (radar)', parameters: {} };
+const run = { id: RUN, title: 'Vessels by radar', status: 'ready', progress: 1, total: 1, count: 3, engine_version: 2,
+ results: [row('0-1', pass), row('0-2', pass), row('0-3', other)],
+ input: { title: 'Vessels by radar', zones: area, recipe, note: '', a: pass, b: pass, offline: false,
+ date_rule: 'manual', followup_id: null } };
+const catalogue = { builtins: [recipe], custom: [], max_tiles: 4096, max_results: 2000, grid: [13, 512],
+ methods: [{ id: 'sar-vessels', single: true, sensor: 'sentinel1', frames: 3, sizes: {}, measure: '{value} dB' }] };
+
+vi.mock('../../lib/api.js', () => ({ api: {
+ get: async (path) => (path === '/api/compare/analyzers' ? structuredClone(catalogue)
+ : path.endsWith(`/runs/${RUN}`) ? structuredClone(run) : []),
+ post: vi.fn(), put: vi.fn(), patch: vi.fn(), del: vi.fn(),
+} }));
+vi.mock('../../lib/state.svelte.js', () => ({ ensureCase: async () => ({ id: 'case-a' }),
+ reloadCase: async () => {}, toast: vi.fn(), uiState: {}, prefs: { units: 'metric' } }));
+const { default: Panel } = await import('./DetectPanel.svelte');
+
+let live, target;
+const settle = async () => { for (let i = 0; i < 120; i++) await Promise.resolve(); flushSync(); };
+afterEach(() => { if (live) unmount(live); live = null; target?.remove(); });
+
+it('shows a radar pass once, however the map writes it back', async () => {
+ // what Detect does: the shown pass is read and replaced by a fresh object
+ const map = $state({ pass: null });
+ const shown = [];
+ const onshow = (source) => { shown.push(`${source.date} ${source.time}`); void map.pass; map.pass = { ...source }; };
+ const errors = [];
+ const onerror = (event) => errors.push(event.message ?? String(event));
+ window.addEventListener('error', onerror);
+ target = document.createElement('div'); document.body.append(target);
+ live = mount(Panel, { target, props: { caseId: 'case-a', opening: `runs-${RUN}`, onshow } });
+ await settle();
+ expect(target.textContent).toContain('1 of 3');
+ // stepping to a candidate on the same pass leaves the map alone
+ document.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowRight', bubbles: true })); await settle();
+ expect(target.textContent).toContain('2 of 3');
+ document.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowRight', bubbles: true })); await settle();
+ expect(target.textContent).toContain('3 of 3');
+ window.removeEventListener('error', onerror);
+ expect(errors).toEqual([]);
+ // opening the run and the review each name its pass; a loop names it hundreds of times
+ expect(shown.length).toBeLessThanOrEqual(3);
+ expect([...new Set(shown)]).toEqual(['2026-09-22 02:06:41', '2026-09-10 02:06:40']);
+});
diff --git a/frontend/src/tools/detect/DetectReview.svelte b/frontend/src/tools/detect/DetectReview.svelte
new file mode 100644
index 0000000..2c32786
--- /dev/null
+++ b/frontend/src/tools/detect/DetectReview.svelte
@@ -0,0 +1,372 @@
+<script>
+ /**
+ * What one run found, reviewed one candidate at a time. Pinning is the only
+ * act that creates case evidence; dismissing deletes the candidate. A
+ * run still working shows how far it got and can be stopped from here.
+ */
+ import { untrack } from 'svelte';
+ import { api } from '../../lib/api.js';
+ import { reloadCase, toast, uiState } from '../../lib/state.svelte.js';
+ import { refreshRuns } from '../../lib/detectRuns.svelte.js';
+ import { STRENGTHS, describeMeasure, sourceLabel } from '../../lib/map/analyzers.js';
+ import { sweptNote } from '../../lib/map/acquisitions.js';
+ import { isActive, plural } from '../../lib/map/detections.js';
+ import Icon from '../../components/Icon.svelte';
+ import Modal from '../../components/Modal.svelte';
+ import { comparePairFor, pinDefaults } from '../../lib/map/detectReview.js';
+
+ let {
+ caseId,
+ run,
+ /** Whether the review is on screen: the dock keeps it mounted while
+ * collapsed, and a key must not change a verdict nobody can see. */
+ active = true,
+ methods = [],
+ candidateId = $bindable(null),
+ onaccept = () => {},
+ onfocus = () => {},
+ onedit = () => {},
+ onshow = () => {},
+ onexport = () => {},
+ onadd = () => {},
+ } = $props();
+
+ let busy = $state(false);
+ let error = $state('');
+ let filter = $state('all');
+ let enlarged = $state(false);
+ let pin = $state(null);
+ let adding = $state(false);
+ let manualArea = $state('');
+
+ const base = $derived(`/api/cases/${caseId}/analysis/runs/${run.id}`);
+ const methodOf = (method) => methods.find((m) => m.id === method) ?? {};
+ const pending = $derived(isActive(run));
+ const all = $derived(run.results ?? []);
+ /** Which candidates the arrows walk. A sweep of a hundred is worked in
+ * passes — the ones nobody has judged, then what was kept — so the queue
+ * narrows rather than being scrolled. */
+ const candidates = $derived(filter === 'all' ? all : all.filter((row) => matches(row, filter)));
+ const candidate = $derived(all.find((r) => r.id === candidateId));
+ const matches = (row, name) => (name === 'new' ? row.review === 'new'
+ : name === 'kept' ? row.review === 'noted' : row.review === 'kept');
+ const position = $derived(candidates.findIndex((r) => r.id === candidateId));
+ const counts = $derived.by(() => {
+ const tally = { kept: 0, noted: 0, dismissed: 0, new: 0 };
+ for (const row of candidates) tally[row.review] = (tally[row.review] ?? 0) + 1;
+ return tally;
+ });
+ const verdicts = $derived([
+ counts.kept ? `${counts.kept} pinned` : '',
+ counts.noted ? `${counts.noted} kept here` : '',
+ counts.dismissed ? `${counts.dismissed} dismissed` : '',
+ ].filter(Boolean).join(', ') || 'no verdict yet');
+ const tally = $derived(
+ counts.new === 0 ? `All ${candidates.length} reviewed · ${verdicts}`
+ : `${counts.new} still to review · ${verdicts}`
+ );
+ const previewAlt = $derived(methodOf(run.input.recipe.method).single
+ ? 'Candidate evidence' : 'Candidate evidence: A on the left, B on the right');
+ const statusLabel = (status) => ({ queued: 'Queued', running: 'Running', ready: 'Completed',
+ failed: 'Failed', cancelled: 'Cancelled', no_new_imagery: 'No new imagery' }[status] ?? status);
+ const dates = (input) => methodOf(input.recipe.method).single || !(input.a?.date || input.a?.release)
+ ? sourceLabel(input.b) : `${sourceLabel(input.a)} → ${sourceLabel(input.b)}`;
+ /** A candidate's reading, in the words its method's catalogue entry gives. */
+ const reading = (row, input) => [
+ STRENGTHS[row.strength],
+ describeMeasure(methodOf(input.recipe.method).measure, row.measure, input.recipe.parameters.index),
+ ].filter(Boolean).join(' · ');
+ /** Sentinel-2 reads 10 m to the pixel, so a candidate metres across is only
+ * worth judging from close in: the review asks for that zoom, not the
+ * wide frame the area list leaves behind. */
+ const focus = (coordinates) => onfocus(coordinates, 16);
+ // The map shows the pass a candidate was read on, and only a different pass
+ // changes it. Showing it writes the map's own state, which this must not
+ // read back: a radar pass is an object, so every write looked new, and the
+ // effect fed itself until Svelte stopped the whole page.
+ let shownPass = '';
+ $effect(() => {
+ const source = candidate?.sources?.b ?? run.area_runs?.find((p) => p.status === 'ready')?.b ?? run.input?.b;
+ const key = source?.date ? [source.provider, source.date, source.time ?? '', source.layer ?? ''].join('|') : '';
+ if (!key || key === shownPass) return;
+ shownPass = key;
+ untrack(() => onshow(source));
+ });
+ // The map goes where the panel is: judging a candidate you cannot see is
+ // guesswork, and that held whenever a run was opened rather than stepped
+ // through. Only a change of candidate moves the camera, so panning is free.
+ let shownCandidate = '';
+ $effect(() => {
+ const row = candidate;
+ if (!row || row.id === shownCandidate) return;
+ shownCandidate = row.id;
+ focus(row.coordinates);
+ });
+
+ /**
+ * A sweep leaves a queue of candidates, and a queue is worked with the hands
+ * on the keys: the arrows walk it, K, D and P are the three verdicts.
+ */
+ function shortcut(event) {
+ if (!active || !run || run.status !== 'ready' || busy || pin || enlarged || event.ctrlKey || event.metaKey || event.altKey
+ || event.target?.closest?.('input, textarea, select, [contenteditable="true"]')) return;
+ const key = event.key.toLowerCase();
+ if (event.key === 'ArrowLeft') step(-1);
+ else if (event.key === 'ArrowRight') step(1);
+ else if (!candidate) return;
+ else if (key === 'k' && !['kept', 'noted'].includes(candidate.review)) void act(() => review('noted'));
+ else if (key === 'd' && candidate.review !== 'kept') void act(() => review('dismissed'));
+ else if (key === 'p' && candidate.review !== 'kept') openPin();
+ else return;
+ event.preventDefault();
+ }
+
+ async function act(fn) {
+ if (busy) return;
+ busy = true; error = '';
+ try { await fn(); } catch (e) { error = e.message; }
+ finally { busy = false; }
+ }
+
+ async function applyResult(row) {
+ const results = row.review === 'dismissed' ? run.results.filter((r) => r.id !== row.id)
+ : run.results.map((r) => (r.id === row.id ? row : r));
+ await onaccept({ ...run, results, count: results.length });
+ if (row.review === 'dismissed') candidateId = results.find((r) => r.review === 'new')?.id ?? results[0]?.id ?? null;
+ await refreshRuns(caseId);
+ }
+
+ /** Reviewing is a queue: a verdict moves on to the next one still waiting. */
+ function advance() {
+ const index = all.findIndex((r) => r.id === candidateId);
+ for (let i = 1; i <= all.length; i++) {
+ const row = all[(index + i) % all.length];
+ if (row?.review === 'new') { candidateId = row.id; focus(row.coordinates); return; }
+ }
+ }
+
+ async function review(value) {
+ await applyResult(await api.patch(`${base}/results/${candidateId}`, { review: value }));
+ if (value === 'noted') advance();
+ }
+
+ /**
+ * A second look before the verdict: Compare on the passes that found it, or
+ * on today's high-resolution picture for something present on one pass.
+ */
+ function openInCompare() {
+ const pair = comparePairFor(candidate, {
+ single: !!methodOf(run.input.recipe.method).single, method: run.input.recipe.method,
+ });
+ if (!pair) return;
+ uiState.compareAt = pair;
+ uiState.tool = 'compare';
+ }
+
+ /** The pin's name has to mean something in the case, long after this run. */
+ function openPin() { pin = pinDefaults(candidate, !!methodOf(run.input.recipe.method).single); }
+
+ async function keep() {
+ const answer = await api.post(`${base}/results/${candidateId}/promote`, pin);
+ pin = null;
+ await applyResult(answer.result);
+ await reloadCase();
+ toast('Pin and evidence saved in this case', 'ok');
+ advance();
+ }
+
+ async function undoKeep() {
+ const answer = await api.del(`${base}/results/${candidateId}/promote`);
+ await applyResult(answer.result);
+ await reloadCase();
+ toast('The pin went to Trash', 'ok');
+ }
+
+ async function cancel() {
+ onaccept(await api.post(`${base}/cancel`, {}));
+ await refreshRuns(caseId);
+ }
+
+ function step(direction) {
+ if (!candidates.length) return;
+ const index = position >= 0 ? position : direction > 0 ? -1 : 0;
+ const row = candidates[(index + direction + candidates.length) % candidates.length];
+ if (row) { candidateId = row.id; focus(row.coordinates); }
+ }
+</script>
+
+<svelte:window onkeydown={shortcut} />
+<div class="cmp-dock-body review-body">
+{#if error}<p class="warn" role="alert">{error}</p>{/if}
+
+<section class="run">
+ <div class="row run-head">
+ <strong class="grow">{run.title}</strong>
+ {#if !pending}
+ <button class="link" onclick={onedit}>{run.input?.followup_id ? 'Edit this detection' : 'Edit and rerun'}</button>
+ {/if}
+ </div>
+ <p class="hint">{[
+ statusLabel(run.status),
+ run.status === 'ready' ? plural(run.total, 'tile') : `${run.progress}/${run.total} tiles`,
+ run.input?.b ? dates(run.input) : '',
+ ].filter(Boolean).join(' · ')}</p>
+ {#if pending}
+ <progress max={run.total || 1} value={run.progress}></progress>
+ <p class="hint">It keeps going if you leave Detect; the top bar shows how far it got.</p>
+ <button class="btn btn-sm" disabled={busy} onclick={() => act(cancel)}>Cancel</button>
+ {/if}
+ {#if run.message}<p class="hint" role="status">{run.message}</p>{/if}
+ <!-- "Nothing found" and "never looked" are not the same answer. -->
+ {#if sweptNote(run.swept)}<p class="warn">{sweptNote(run.swept)}</p>{/if}
+ {#if run.status === 'ready' && !candidates.length}<p class="hint">Nothing passed these thresholds.</p>{/if}
+ {#if run.status === 'ready'}
+ <div class="row"><button class="btn btn-sm" onclick={() => {
+ adding = !adding;
+ manualArea = candidate?.area_id ?? run.area_runs?.find((p) => p.status === 'ready')?.area_id ?? run.input.zones[0]?.id ?? '';
+ }}>Add candidate</button>
+ <button class="btn btn-sm" onclick={onexport}>Export as layer</button></div>
+ {#if adding}
+ <label>Area<select aria-label="Manual candidate area" bind:value={manualArea}>
+ <option value="">Choose an area</option>
+ {#each run.input.zones as area (area.id)}
+ {#if !run.area_runs || run.area_runs.some((p) => p.area_id === area.id && p.status === 'ready')}
+ <option value={area.id}>{area.name}</option>
+ {/if}
+ {/each}
+ </select></label>
+ <div class="row"><button class="btn btn-sm" disabled={!manualArea} onclick={() => onadd(manualArea, 'point')}>Add point</button>
+ <button class="btn btn-sm" disabled={!manualArea} onclick={() => onadd(manualArea, 'polygon')}>Draw candidate</button></div>
+ {/if}
+ {/if}
+</section>
+
+{#if candidate}
+ <section class="candidate">
+ <div class="row filters" role="group" aria-label="Which candidates to walk">
+ {#each [['all', 'All', all.length], ['new', 'To review', counts.new], ['kept', 'Kept', counts.noted], ['pinned', 'Pinned', counts.kept]] as [id, label, n]}
+ {#if id === 'all' || n}
+ <button class="chip" class:on={filter === id} aria-pressed={filter === id}
+ onclick={() => (filter = id)}>{label} <span class="n">{n}</span></button>
+ {/if}
+ {/each}
+ </div>
+ <div class="row nav">
+ <button class="cmp-icon" aria-label="Previous candidate" title="Previous candidate (←)" onclick={() => step(-1)}><Icon name="chevronLeft" size={14} /></button>
+ <span class="grow centre position">{position >= 0 ? `${position + 1} of ${candidates.length}` : 'outside this filter'}</span>
+ <button class="cmp-icon" aria-label="Next candidate" title="Next candidate (→)" onclick={() => step(1)}><Icon name="chevronRight" size={14} /></button>
+ </div>
+ <strong class:manual={candidate.origin === 'manual'}>{candidate.phenomenon}{candidate.origin === 'manual' ? ' · Manual' : ''}</strong>
+ {#if candidate.area_name}<p class="hint">{candidate.area_name} · {candidate.sources?.a.date !== candidate.sources?.b.date ? `${candidate.sources?.a.date} → ` : ''}{candidate.sources?.b.date}</p>{/if}
+ <!-- The column is narrow, and a pair of 20-metre crops in it is small. One
+ press opens the same picture at the size of the window. -->
+ <button class="preview-open" title="See it bigger" aria-label="Enlarge the evidence"
+ onclick={() => (enlarged = true)}>
+ <img class="preview" src={`${base}/results/${candidate.id}/preview`} alt={previewAlt} />
+ </button>
+ {#if reading(candidate, run.input)}
+ <p class={`strength ${candidate.strength ?? ''}`}>{reading(candidate, run.input)}</p>
+ {/if}
+ <p class="facts">
+ {Math.round(candidate.area)} m² · {Math.round(candidate.width)} × {Math.round(candidate.height)} m ·
+ <button class="link inline" onclick={() => focus(candidate.coordinates)}>
+ {candidate.coordinates[1].toFixed(5)}, {candidate.coordinates[0].toFixed(5)}
+ </button>
+ </p>
+ <button class="btn btn-sm compare" onclick={openInCompare}
+ title={methodOf(run.input.recipe.method).single
+ ? 'Hold it against today’s high-resolution picture in Compare'
+ : 'Read the two passes that found it in Compare'}>
+ <Icon name="compare" size={13} /> Compare
+ </button>
+
+ </section>
+{/if}
+</div>
+
+{#if run.status === 'ready'}
+ <footer class="cmp-dock-foot review-actions" aria-label="Candidate review">
+ <div class="review-status">
+ {#if candidate?.review === 'kept'}
+ <p class="verdict kept"><Icon name="check" size={13} /> Kept as a pin in this case</p>
+ <button class="link" disabled={busy} onclick={() => act(undoKeep)}>Undo and send the pin to Trash</button>
+ {:else if candidate?.review === 'noted'}
+ <p class="verdict noted"><Icon name="bookmark" size={13} /> Kept in this detection</p>
+ {:else if candidate?.review === 'dismissed'}
+ <button class="link" disabled={busy} onclick={() => act(() => review('new'))}>Put it back among the candidates</button>
+ {:else}
+ <p class="hint">Keep stays in this run. Pin creates a place and evidence in Files.</p>
+ <p class="keys">K keep · D dismiss · P pin · ← → walk the queue</p>
+ {/if}
+ </div>
+ <div class="verdict-row">
+ <button class="btn btn-sm" disabled={busy || !candidate || ['kept', 'noted'].includes(candidate.review)} onclick={() => act(() => review('noted'))}>Keep</button>
+ <button class="btn btn-sm" disabled={busy || !candidate || candidate.review === 'kept'} onclick={() => act(() => review('dismissed'))}>Dismiss</button>
+ <button class="btn btn-primary" disabled={busy || !candidate || candidate.review === 'kept'} onclick={openPin}>Pin</button>
+ </div>
+ <p class="hint tally" title={tally}>{tally}</p>
+ </footer>
+{/if}
+
+{#if enlarged && candidate}
+ <Modal title={candidate.phenomenon} width="min(1100px, 92vw)" onclose={() => (enlarged = false)}>
+ <img class="big" src={`${base}/results/${candidate.id}/preview`} alt={previewAlt} />
+ </Modal>
+{/if}
+
+{#if pin}
+ <Modal title="Pin candidate" onclose={() => (pin = null)}>
+ <div class="pin-form">
+ <label>Name<input class="input" aria-label="Pin name" bind:value={pin.title} maxlength="120" /></label>
+ <label>Description<textarea class="textarea" aria-label="Pin description" bind:value={pin.description} maxlength="4000"></textarea></label>
+ <label class="check"><input type="checkbox" bind:checked={pin.after_only} /> After image only</label>
+ <fieldset><legend>Geometry</legend>
+ <label class="check"><input type="radio" bind:group={pin.shape} value="point" /> Point</label>
+ <label class="check"><input type="radio" bind:group={pin.shape} value="area" disabled={candidate.geometry?.type === 'Point'} /> Area</label>
+ </fieldset>
+ {#if error}<p class="warn" role="alert">{error}</p>{/if}
+ <button class="btn btn-primary" disabled={busy || !pin.title.trim()} onclick={() => act(keep)}>Save pin</button>
+ </div>
+ </Modal>
+{/if}
+
+<style>
+ .pin-form { display: grid; gap: 10px; }
+ .pin-form label { display: grid; gap: 4px; }
+ .pin-form .check { display: flex; align-items: center; gap: 8px; }
+ .pin-form fieldset { display: flex; gap: 20px; padding: 8px 10px; border: 1px solid var(--border); border-radius: var(--r-sm); }
+ .manual { border-bottom: 1px dashed var(--accent); }
+ section { display: grid; gap: 7px; }
+ section.candidate, section:not(.run) { border-top: 1px solid var(--border); padding-top: 10px; }
+ section > strong, .run-head strong { font-size: var(--fs-xs); }
+ .link { color: var(--accent); font-size: var(--fs-xs); text-align: left; }
+ .link:disabled { opacity: 0.5; }
+ .link.inline { display: inline; font-family: var(--font-mono); font-size: 11px; }
+ .centre { text-align: center; }
+ .nav { justify-content: space-between; }
+ .position { color: var(--text-2); font-size: var(--fs-xs); }
+ .filters { flex-wrap: wrap; gap: 4px; }
+ .chip { padding: 2px 8px; border: 1px solid var(--border); border-radius: 999px; color: var(--text-2); font-size: 10.5px; }
+ .chip:hover { color: var(--text-1); }
+ .chip.on { color: var(--accent); border-color: var(--accent); background: var(--accent-soft); }
+ .chip .n { color: var(--text-3); }
+ .chip.on .n { color: inherit; }
+ .compare { justify-self: start; }
+ .facts { margin: 0; color: var(--text-2); font-size: var(--fs-xs); line-height: 1.5; }
+ .strength { margin: 0; font-size: var(--fs-xs); font-weight: 600; color: var(--text-1); }
+ .strength.strong { color: var(--ok); }
+ .strength.weak { color: var(--text-3); }
+ .verdict { display: flex; align-items: center; gap: 5px; margin: 0; font-size: var(--fs-xs); font-weight: 600; }
+ .verdict.kept { color: var(--ok); }
+ .verdict.noted { color: var(--accent); }
+ .review-actions { flex: 0 0 auto; grid-template-rows: 52px 32px 17px; }
+ .keys { margin: 2px 0 0; color: var(--text-3); font-size: 10.5px; }
+ .review-status { display: grid; align-content: center; overflow: auto; }
+ .verdict-row { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 6px; }
+ .tally { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+ .preview-open { display: block; width: 100%; padding: 0; border-radius: var(--r-sm); cursor: zoom-in; }
+ .preview-open:hover { outline: 1px solid var(--accent); }
+ .preview { display: block; width: 100%; height: 210px; object-fit: contain; border-radius: var(--r-sm); background: var(--bg-0); }
+ .big { width: 100%; max-height: 78vh; object-fit: contain; background: var(--bg-0); }
+ progress { width: 100%; accent-color: var(--accent); }
+</style>
diff --git a/frontend/src/tools/detect/DetectWizard.svelte b/frontend/src/tools/detect/DetectWizard.svelte
new file mode 100644
index 0000000..f372d3e
--- /dev/null
+++ b/frontend/src/tools/detect/DetectWizard.svelte
@@ -0,0 +1,592 @@
+<script>
+ /**
+ * A detection, built one step at a time: where to look, what to look for,
+ * which imagery, then a name and the start.
+ *
+ * The kind is settled before any of it, because it changes the questions. A
+ * **one pass** sweeps two dates you name and is reviewed once. A **routine**
+ * is a place you come back to: it holds a baseline rather than a date, and
+ * the pass is chosen at each launch, so this step asks what each run should
+ * compare against instead of which day to read.
+ *
+ * Nothing here fetches anything but Find passes, which waits to be pressed.
+ */
+ import { untrack } from 'svelte';
+ import { api } from '../../lib/api.js';
+ import { ensureCase, reloadCase, toast } from '../../lib/state.svelte.js';
+ import {
+ SECONDS_PER_FRAME,
+ analyzerGroups,
+ analyzerLock,
+ clone,
+ coverage,
+ framesPerTile,
+ readableDuration,
+ sizeOf,
+ zoneRing,
+ } from '../../lib/map/analyzers.js';
+ import { plural } from '../../lib/map/detections.js';
+ import { openCopernicusSettings } from '../../lib/navigate.js';
+ import { uniform, whenNeed, whenSummary } from '../../lib/map/detectWhen.js';
+ import AnalyzerSettings from './AnalyzerSettings.svelte';
+ import WhenStep from './WhenStep.svelte';
+ import Icon from '../../components/Icon.svelte';
+
+ let {
+ caseId,
+ catalogue,
+ /** Saved area sets of this case. */
+ areaSets = [],
+ areas = [],
+ /** Where it starts: `{ kind, body, followupId, fromRun, zonesId, zonesTitle }`. */
+ seed = {},
+ /** An analyzer just made in the library, to pick. */
+ offer = null,
+ busy = false,
+ zones = $bindable([]),
+ drawing = $bindable('select'),
+ selectedZone = $bindable(null),
+ showZones = $bindable(true),
+ onfocus = () => {},
+ onusecurrentview = () => {},
+ /** Put a date on the map, so what is on screen is what a run would sweep. */
+ onshow = () => {},
+ onsubmit = () => {},
+ onlibrary = () => {},
+ onareas = async () => {},
+ } = $props();
+
+ const EMPTY_SOURCE = { provider: 'sentinel2', date: '', layer: 'TRUE_COLOR', maxcc: 30 };
+ const STEPS = [[1, 'Where'], [2, 'What'], [3, 'When'], [4, 'Start']];
+ const SIZE_NAMES = { small: 'Small', medium: 'Medium', large: 'Large', all: 'All sizes' };
+
+ let step = $state(1);
+ let kind = $state('once');
+ let recipe = $state(null);
+ let chosen = $state('');
+ let title = $state('');
+ let note = $state('');
+ let a = $state({ ...EMPTY_SOURCE });
+ let b = $state({ ...EMPTY_SOURCE });
+ /** A routine compares each pass with the one before it, or with its baseline. */
+ let against = $state('previous');
+ let offline = $state(false);
+ let followupId = $state(null);
+ let zonesId = $state(null);
+ let zonesTitle = $state('Analysis areas');
+ let pairs = $state([]);
+ /** A one pass reads B on a chosen day rather than the newest pass. */
+ let chooseB = $state(false);
+ /** The passes last looked up, kept while the areas stay the same. */
+ let lookup = $state(null);
+ let working = $state(false);
+ let error = $state('');
+
+ const builtins = $derived(catalogue?.builtins ?? []);
+ const custom = $derived(catalogue?.custom ?? []);
+ const methodOf = (method) => catalogue?.methods?.find((m) => m.id === method) ?? {};
+ const capability = $derived(methodOf(recipe?.method));
+ /** A vessel or a fire is present on a date, not a difference between two. */
+ const isSingle = $derived(!!capability.single);
+ /** Radar reads Sentinel-1 through the layer Settings found, and has no clouds. */
+ const radar = $derived(capability.sensor === 'sentinel1');
+ const routine = $derived(kind === 'routine');
+ /** Picked from a saved detection whose analyzer is no longer in the library. */
+ const unlisted = $derived(!!recipe && ![...builtins, ...custom].some((r) => r.id === chosen));
+ const cost = $derived(coverage(zones, catalogue?.grid ?? null));
+ const tooMany = $derived(!!catalogue && cost.tiles > catalogue.max_tiles);
+ const frames = $derived(cost.tiles * (capability.frames ?? framesPerTile({ single: isSingle })));
+ const duration = $derived(readableDuration(frames * SECONDS_PER_FRAME));
+ const size = $derived(recipe ? sizeOf(recipe.parameters, capability.sizes) : '');
+ const round = (value, digits = 1) => Number(value.toFixed(digits));
+ /** Ground area, left unsaid when the areas are past measuring. */
+ const area = $derived(Number.isFinite(cost.km2) ? `${round(cost.km2, cost.km2 < 10 ? 2 : 0)} km²` : '');
+
+ const areaNeeds = $derived(
+ !zones.length ? 'Draw an area to look in.'
+ : tooMany ? (Number.isFinite(cost.tiles)
+ ? `These areas need ${cost.tiles} tiles; the limit is ${catalogue.max_tiles}. Draw smaller areas.`
+ : `These areas are far past the ${catalogue.max_tiles}-tile limit. Draw smaller areas.`)
+ : ''
+ );
+ // Said here rather than discovered when the run comes back failed. A routine
+ // that compares each pass with the one before it still needs a first one.
+ const imageryNeeds = $derived(
+ whenNeed({ single: isSingle, routine, against, followupId, pairs, chooseB })
+ );
+ // A locked analyzer can still be picked and read about; a run of it cannot
+ // start, and saying why here beats a run that comes back failed.
+ const groups = $derived(analyzerGroups(catalogue));
+ const lock = $derived(analyzerLock(recipe, catalogue));
+ const radarNeeds = $derived(
+ !lock ? ''
+ : radar && catalogue?.copernicus_key !== false
+ ? 'Radar analyzers read a Sentinel-1 layer of your Copernicus configuration, not set up yet.'
+ : 'Detect reads Copernicus, and no key is set up yet. It is free.'
+ );
+ const needsOf = (n) => (n === 1 ? areaNeeds : n === 2 ? radarNeeds : n === 3 ? imageryNeeds : '');
+ const blocked = $derived(areaNeeds || radarNeeds || imageryNeeds);
+ /** A step opens once every one before it has what it needs. */
+ const reachable = (n) => STEPS.every(([k]) => k >= n || !needsOf(k));
+ const defaultName = $derived(
+ !recipe ? 'Detection'
+ : zones.length === 1 ? `${recipe.name} · ${zones[0].name}`
+ : `${recipe.name} · ${plural(zones.length, 'area')}`
+ );
+ const timing = $derived(whenSummary({ single: isSingle, routine, against, pairs, radar }));
+
+ /** 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
+ * engine names the collection whatever the analyzer turns out to be. */
+ const sentinelSource = (source) => ['sentinel2', 'sentinel1'].includes(source?.provider)
+ ? { ...EMPTY_SOURCE, ...clone(source) } : { ...EMPTY_SOURCE };
+
+ function choose(id) {
+ const found = [...builtins, ...custom].find((r) => r.id === id);
+ if (!found) return;
+ recipe = clone(found);
+ chosen = id;
+ }
+
+ // Where the detection starts, read once: the panel mounts a fresh wizard for
+ // every new seed, so this never has to undo an earlier one.
+ untrack(() => {
+ kind = seed.kind ?? (seed.followupId ? 'routine' : 'once');
+ if (!seed.body) {
+ choose(builtins[0]?.id);
+ zonesId = seed.zonesId ?? null;
+ zonesTitle = seed.zonesTitle ?? zonesTitle;
+ return;
+ }
+ const body = seed.body;
+ pairs = clone(body.area_dates ?? []);
+ title = body.title;
+ note = body.note ?? '';
+ recipe = clone(body.recipe);
+ chosen = body.recipe.id;
+ a = sentinelSource(body.a);
+ b = sentinelSource(body.b);
+ offline = !!body.offline;
+ against = body.date_rule === 'latest_reference' ? 'reference' : 'previous';
+ chooseB = kind !== 'routine' && (!!body.b?.date || pairs.some((pair) => pair.b?.date));
+ followupId = seed.followupId ?? null;
+ step = seed.followupId ? 4 : 1;
+ });
+
+ $effect(() => {
+ if (offer) untrack(() => choose(offer));
+ });
+
+ // Leaving the first step must not leave the map armed to draw an area.
+ $effect(() => {
+ if (step !== 1) untrack(() => { drawing = 'select'; });
+ });
+
+ // A new area takes the days every other one shares, so one choice keeps
+ // standing for all of them; it starts empty only among areas that differ.
+ $effect(() => {
+ const current = zones.map((zone) => zone.id);
+ untrack(() => {
+ const shared = pairs.length && uniform(pairs) ? pairs[0] : null;
+ pairs = current.map((id) => pairs.find((pair) => pair.area_id === id) ?? (shared
+ ? { ...clone(shared), area_id: id }
+ : {
+ area_id: id, a: clone(a), b: { ...clone(b), date: seed.body?.b?.date ?? '' },
+ date_rule: routine && against === 'previous' ? 'latest_previous' : 'latest_reference',
+ }));
+ });
+ });
+
+ async function act(fn) {
+ if (working) return;
+ working = true; error = '';
+ try { await fn(); } catch (e) { error = e.message; }
+ finally { working = false; }
+ }
+
+ function setPicture(patch) {
+ a = { ...a, ...patch };
+ b = { ...b, ...patch };
+ pairs = pairs.map((pair) => ({ ...pair, a: { ...pair.a, ...patch }, b: { ...pair.b, ...patch } }));
+ }
+
+ function removeZone(id) {
+ zones = zones.filter((z) => z.id !== id);
+ if (selectedZone === id) selectedZone = null;
+ }
+
+ async function saveAreas(asNew = false) {
+ const owner = await ensureCase();
+ const base = `/api/cases/${owner.id}/analysis/zones`;
+ const data = { title: zonesTitle, zones: clone(zones) };
+ const saved = zonesId && !asNew ? await api.put(`${base}/${zonesId}`, data) : await api.post(base, data);
+ zonesId = saved.id;
+ await onareas(owner.id);
+ await reloadCase();
+ toast('Areas saved in this case', 'ok');
+ }
+
+ async function openAreas(id) {
+ const body = await api.get(`/api/cases/${caseId}/analysis/zones/${id}`);
+ zones = clone(body.zones);
+ zonesTitle = body.title;
+ zonesId = id;
+ showZones = true;
+ }
+
+ async function removeAreas(id) {
+ await api.del(`/api/cases/${caseId}/analysis/zones/${id}`);
+ if (zonesId === id) zonesId = null;
+ await onareas(caseId);
+ await reloadCase();
+ toast('Moved to Trash', 'ok');
+ }
+
+ async function saveArea(zone) {
+ const owner = await ensureCase();
+ const ring = zoneRing(zone);
+ const saved = await api.post(`/api/cases/${owner.id}/analysis/areas`, {
+ name: zone.name, colour: recipe.colour, geometry: { type: 'Polygon', coordinates: [[...ring, ring[0]]] },
+ });
+ pairs = pairs.map((pair) => pair.area_id === zone.id ? { ...pair, area_id: saved.id } : pair);
+ zones = zones.map((entry) => entry.id === zone.id ? { ...entry, id: saved.id } : entry);
+ await onareas(owner.id); await reloadCase();
+ }
+ function useArea(area) {
+ if (zones.some((zone) => zone.id === area.id)) return;
+ zones = [...zones, { id: area.id, name: area.name, kind: 'polygon', points: clone(area.geometry.coordinates[0].slice(0, -1)) }];
+ }
+
+ function submit(run) {
+ onsubmit({
+ kind,
+ followupId,
+ run,
+ input: {
+ title: title.trim() || defaultName, note: note.trim(), zones: clone(zones),
+ recipe: clone(recipe), a: clone(a), b: clone(b),
+ area_dates: pairs.map((pair) => ({ ...clone(pair),
+ a: isSingle ? { ...clone(a), date: '' } : clone(pair.a),
+ b: routine ? { ...clone(pair.b), date: '' } : clone(pair.b),
+ date_rule: routine ? (!isSingle && against === 'previous' ? 'latest_previous' : 'latest_reference')
+ : pair.b.date ? 'manual' : 'latest_reference',
+ })),
+ date_rule: routine ? (against === 'reference' ? 'latest_reference' : 'latest_previous') : 'manual',
+ // A latest-date lookup reaches Copernicus, so only fixed dates run offline.
+ offline: routine ? false : offline,
+ followup_id: followupId,
+ },
+ });
+ }
+</script>
+
+<nav class="stepper" aria-label="Steps">
+ {#each STEPS as [n, label] (n)}
+ <button type="button" class:current={step === n} class:done={n < step}
+ aria-current={step === n ? 'step' : undefined}
+ disabled={n > step && !reachable(n)} onclick={() => (step = n)}>
+ <span class="n">{n}</span>{label}
+ </button>
+ {/each}
+</nav>
+
+<div class="cmp-dock-body">
+ {#if error}<p class="warn" role="alert">{error}</p>{/if}
+
+ {#if step === 1}
+ <section class="step" aria-label="Where to look">
+ <h3>Where to look</h3>
+ <!-- The case's own ground comes first: picking an area it already
+ watches is one press, and drawing is for ground it does not. -->
+ {#if areas.length}
+ <div class="shared">
+ {#each areas as area (area.id)}
+ {@const on = zones.some((zone) => zone.id === area.id)}
+ <button class="area-chip" class:on aria-pressed={on} disabled={!on && zones.length >= 32}
+ onclick={() => (on ? removeZone(area.id) : useArea(area))}>
+ <span class="swatch" style={`--tint: ${area.colour}`}></span>{area.name}
+ </button>
+ {/each}
+ </div>
+ {/if}
+ <div class="row wrap">
+ {#each [['rect', 'Rectangle'], ['polygon', 'Polygon'], ['ellipse', 'Circle']] as [shape, label]}
+ <button class="btn btn-sm" class:active={drawing === shape} disabled={zones.length >= 32}
+ onclick={() => { drawing = drawing === shape ? 'select' : shape; showZones = true; }}>{label}</button>
+ {/each}
+ <button class="btn btn-sm" disabled={zones.length >= 32} onclick={onusecurrentview}>Use current view</button>
+ </div>
+ {#if drawing !== 'select'}
+ <p class="hint">{drawing === 'polygon' ? 'Click corners on the map; Enter finishes, Escape cancels.' : 'Drag on the map. Escape cancels.'}</p>
+ {:else if !zones.length}
+ <p class="hint">{areas.length ? 'Pick an area above, draw on the map, or take the current view.' : 'Draw on the map, or take the current view.'}</p>
+ {/if}
+ {#each zones as zone (zone.id)}
+ <div class="row area-row">
+ <button class="cmp-icon" aria-label={`Show ${zone.name}`} title={`Show ${zone.name}`}
+ onclick={() => { selectedZone = zone.id; drawing = 'select'; onfocus(zone.points[0]); }}>
+ <Icon name="pin" size={13} />
+ </button>
+ <input class="grow" aria-label="Area name" bind:value={zone.name} maxlength="120" />
+ {#if !areas.some((area) => area.id === zone.id)}
+ <button class="btn btn-sm" disabled={working} onclick={() => act(() => saveArea(zone))}>Save as area</button>
+ {/if}
+ <button class="cmp-icon" aria-label={`Remove ${zone.name}`} title={`Remove ${zone.name}`}
+ onclick={() => removeZone(zone.id)}>
+ <Icon name="x" size={12} />
+ </button>
+ </div>
+ {/each}
+ {#if zones.length}
+ <p class="hint" class:warn={tooMany}>{[
+ area,
+ Number.isFinite(cost.tiles) ? plural(cost.tiles, 'tile') : 'over the tile limit',
+ tooMany ? '' : `${plural(frames, 'request')} a run, about ${duration}`,
+ ].filter(Boolean).join(' · ')}</p>
+ {/if}
+ {#if areaSets.length}
+ <details>
+ <summary>Saved area sets · {areaSets.length}</summary>
+ {#each areaSets as set (set.id)}
+ <div class="row">
+ <button class="link grow" disabled={working} onclick={() => act(() => openAreas(set.id))}>
+ {set.title}<small>{plural(set.areas ?? 0, 'area')}</small>
+ </button>
+ <button class="cmp-icon" disabled={working} aria-label={`Delete ${set.title}`} title={`Delete ${set.title}`}
+ onclick={() => act(() => removeAreas(set.id))}><Icon name="trash" size={13} /></button>
+ </div>
+ {/each}
+ </details>
+ {/if}
+ {#if zones.length}
+ <details>
+ <summary>Save these areas as a set</summary>
+ <div class="row">
+ <input class="grow" aria-label="Area set name" bind:value={zonesTitle} maxlength="120" />
+ <button class="btn btn-sm" disabled={working} onclick={() => act(() => saveAreas())}>Save</button>
+ {#if zonesId}<button class="btn btn-sm" disabled={working} onclick={() => act(() => saveAreas(true))}>As new</button>{/if}
+ </div>
+ </details>
+ {/if}
+ </section>
+ {:else if step === 2}
+ <section class="step" aria-label="What to look for">
+ <h3>What to look for</h3>
+ <div class="choices" role="radiogroup" aria-label="Analyzer">
+ {#each groups as group (group.label)}
+ <p class="group">{group.label}</p>
+ {#each group.list as entry (entry.id)}
+ {@const locked = analyzerLock(entry, catalogue)}
+ {@const trust = catalogue?.reliability?.[entry.id]}
+ <button type="button" role="radio" aria-checked={chosen === entry.id} class="choice"
+ class:on={chosen === entry.id} class:locked={!!locked} style={`--tint: ${entry.colour}`}
+ title={locked || undefined} onclick={() => choose(entry.id)}>
+ <span class="swatch" aria-hidden="true"></span>{entry.name}
+ {#if trust}<span class="trust {trust}">({trust})</span>{/if}
+ {#if locked}<small class="lock"><Icon name="key" size={11} /> set up</small>{/if}
+ </button>
+ {/each}
+ {/each}
+ {#if unlisted}
+ <p class="group">This detection</p>
+ <button type="button" role="radio" aria-checked="true" class="choice on" style={`--tint: ${recipe.colour}`}>
+ <span class="swatch" aria-hidden="true"></span>{recipe.name}<small>as saved</small>
+ </button>
+ {/if}
+ </div>
+ {#if recipe.description}<p class="hint">{recipe.description}</p>{/if}
+ <AnalyzerSettings bind:recipe {capability} />
+ <button class="link" onclick={onlibrary}>Make an analyzer of your own…</button>
+ </section>
+ {:else if step === 3}
+ <WhenStep {zones} bind:pairs {routine} single={isSingle} sensor={capability.sensor} {followupId}
+ bind:against bind:chooseB bind:lookup {onshow} />
+ {#if radar}
+ {#if !routine}
+ <label class="check" title="Use cached or retained frames without downloading">
+ <input type="checkbox" bind:checked={offline} /> Use local images only
+ </label>
+ {/if}
+ {:else}
+ <details>
+ <summary>Picture and cloud ceiling</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
+ </label>
+ {/if}
+ </details>
+ {/if}
+ {:else}
+ <section class="step" aria-label="Name and start">
+ <h3>{followupId ? 'This routine' : routine ? 'Name the routine' : 'Name and start'}</h3>
+ <label>Name
+ <input aria-label="Detection name" placeholder={defaultName} bind:value={title} maxlength="120" />
+ </label>
+ <label title="Purpose recorded with each run">What it is for
+ <textarea aria-label="Detection description" rows="2" bind:value={note} maxlength="500"
+ placeholder={routine ? 'Weekly look at the anchorage' : 'Checking the strike reported on the 12th'}></textarea>
+ </label>
+ <div class="recap">
+ <button type="button" onclick={() => (step = 1)} title="Change the areas">
+ <span class="k">Where</span>
+ <span class="v">{[plural(zones.length, 'area'), area, Number.isFinite(cost.tiles) ? plural(cost.tiles, 'tile') : 'over the tile limit'].filter(Boolean).join(' · ')}</span>
+ </button>
+ <button type="button" onclick={() => (step = 2)} title="Change what it looks for">
+ <span class="k">What</span>
+ <span class="v">{recipe.name}{size ? ` · ${SIZE_NAMES[size]}` : ' · tuned by hand'}</span>
+ </button>
+ <button type="button" onclick={() => (step = 3)} title="Change the imagery">
+ <span class="k">When</span>
+ <span class="v">{timing}</span>
+ </button>
+ </div>
+ {#if !tooMany}
+ <p class="hint">{plural(frames, 'request')} a run, about {duration}. It keeps going if you leave Detect.</p>
+ {/if}
+ </section>
+ {/if}
+</div>
+
+<div class="cmp-dock-foot">
+ <div class="row">
+ {#if step > 1}<button class="btn btn-sm" onclick={() => step--}>Back</button>{/if}
+ {#if step < 4}
+ <button class="btn btn-primary grow" disabled={!!needsOf(step)} onclick={() => step++}>Next: {STEPS[step][1]}</button>
+ {:else}
+ <button class="btn btn-primary grow" disabled={busy || !!blocked} onclick={() => submit(true)}>
+ {busy ? 'Starting…' : !routine ? 'Run this pass' : followupId ? 'Save and run' : 'Save and run the first pass'}
+ </button>
+ {/if}
+ </div>
+ {#if step < 4 && needsOf(step)}
+ <span class="reason">{needsOf(step)}</span>
+ {#if step === 2 && radarNeeds}
+ <button class="link centre" onclick={openCopernicusSettings}>How to add it, in Settings → Imagery</button>
+ {/if}
+ {:else if step === 4 && blocked}
+ <span class="reason warn">{blocked}</span>
+ {:else if step === 4 && routine}
+ <button class="link centre" disabled={busy} onclick={() => submit(false)}>
+ {followupId ? 'Save changes without running' : 'Save without running'}
+ </button>
+ {/if}
+</div>
+
+<style>
+ .shared { display: flex; flex-wrap: wrap; gap: 5px; }
+ .area-chip {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ padding: 4px 9px;
+ border: 1px solid var(--border);
+ border-radius: 999px;
+ color: var(--text-2);
+ font-size: var(--fs-xs);
+ }
+ .area-chip:hover:not(:disabled) { color: var(--text-1); border-color: var(--text-3); }
+ .area-chip.on { color: var(--accent); border-color: var(--accent); background: var(--accent-soft); }
+ .area-chip .swatch { width: 8px; height: 8px; border-radius: 2px; background: var(--tint); }
+ .stepper {
+ display: grid;
+ grid-template-columns: repeat(4, 1fr);
+ gap: 2px;
+ padding: 8px 10px;
+ border-bottom: 1px solid var(--border);
+ }
+ .stepper button {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ gap: 5px;
+ padding: 4px 2px;
+ border-radius: var(--r-sm);
+ color: var(--text-3);
+ font-size: var(--fs-xs);
+ font-weight: 600;
+ }
+ .stepper button:hover:not(:disabled) { background: var(--bg-2); color: var(--text-1); }
+ .stepper button:disabled { opacity: 0.45; cursor: not-allowed; }
+ .stepper .n {
+ display: grid;
+ place-items: center;
+ width: 17px;
+ height: 17px;
+ border-radius: 50%;
+ background: var(--bg-3);
+ font: 700 10px/1 var(--font-sans);
+ }
+ .stepper .done { color: var(--text-2); }
+ .stepper .done .n { color: var(--bg-0); background: var(--accent); }
+ .stepper .current { color: var(--accent); background: var(--accent-soft); }
+ .stepper .current .n { color: var(--bg-0); background: var(--accent); }
+ .step { display: grid; gap: 9px; }
+ h3 { margin: 0; font-size: var(--fs-sm); font-weight: 700; }
+ .row.wrap { flex-wrap: wrap; }
+ .active { outline: 1px solid var(--accent); }
+ .area-row input { font-size: var(--fs-xs); }
+ details { display: grid; gap: 8px; }
+ details[open] { padding-bottom: 2px; }
+ summary { color: var(--text-2); font-size: var(--fs-xs); cursor: pointer; }
+ .link { color: var(--accent); font-size: var(--fs-xs); text-align: left; justify-self: start; }
+ .link:disabled { opacity: 0.5; }
+ .link small { display: block; color: var(--text-3); font-size: 10px; }
+ .centre { justify-self: center; text-align: center; }
+ .choices { display: grid; gap: 2px; }
+ .group {
+ margin: 6px 0 2px;
+ color: var(--text-3);
+ font-size: 10px;
+ font-weight: 700;
+ letter-spacing: 0.06em;
+ text-transform: uppercase;
+ }
+ .group:first-child { margin-top: 0; }
+ .choice {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 5px 8px;
+ border: 1px solid transparent;
+ border-radius: var(--r-sm);
+ color: var(--text-1);
+ font-size: var(--fs-xs);
+ text-align: left;
+ }
+ .choice:hover { background: var(--bg-2); }
+ .choice.on { border-color: var(--accent); background: var(--accent-soft); font-weight: 600; }
+ .choice small { margin-left: auto; color: var(--text-3); font-weight: 400; }
+ .choice.locked { color: var(--text-2); }
+ .choice .lock { display: inline-flex; align-items: center; gap: 3px; color: var(--accent); }
+ .trust { color: var(--text-3); font-size: 10.5px; font-weight: 400; }
+ .trust.reliable { color: var(--ok, #46a758); }
+ .trust.rough { color: var(--warn, #e2a03f); }
+ .swatch { flex: 0 0 auto; width: 9px; height: 9px; border-radius: 50%; background: var(--tint); }
+ .recap {
+ display: grid;
+ border: 1px solid var(--border);
+ border-radius: var(--r-sm);
+ overflow: hidden;
+ }
+ .recap button {
+ display: grid;
+ grid-template-columns: 52px 1fr;
+ gap: 8px;
+ padding: 7px 9px;
+ text-align: left;
+ font-size: var(--fs-xs);
+ }
+ .recap button + button { border-top: 1px solid var(--border); }
+ .recap button:hover { background: var(--bg-2); }
+ .recap .k { color: var(--text-3); font-weight: 700; }
+ .recap .v { color: var(--text-1); overflow-wrap: anywhere; }
+</style>
diff --git a/frontend/src/tools/detect/WhenStep.svelte b/frontend/src/tools/detect/WhenStep.svelte
new file mode 100644
index 0000000..3bd65c9
--- /dev/null
+++ b/frontend/src/tools/detect/WhenStep.svelte
@@ -0,0 +1,249 @@
+<script>
+ /**
+ * 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.
+ * The passes over the areas are listed under the question, because picking
+ * from what exists beats typing a day that may have no picture.
+ *
+ * One choice stands for every area; the per-area table is for areas far
+ * enough apart to sit under different swaths. The pure part is
+ * `lib/map/detectWhen.js`. The lookup waits to be pressed.
+ */
+ import { untrack } from 'svelte';
+ import { api } from '../../lib/api.js';
+ import { acquisitionQuery, areaKey, coverageWarning, passKey } from '../../lib/map/acquisitions.js';
+ import { areaLine, setSide, sharedSide, uniform, withRule } from '../../lib/map/detectWhen.js';
+ import AcquisitionPicker from './AcquisitionPicker.svelte';
+ import AreaDates from './AreaDates.svelte';
+ import DateField from '../../components/DateField.svelte';
+ import Modal from '../../components/Modal.svelte';
+
+ let {
+ zones = [],
+ pairs = $bindable([]),
+ routine = false,
+ /** A vessel or a fire is read on one image; a change needs two. */
+ single = false,
+ sensor = 'sentinel2',
+ followupId = null,
+ against = $bindable('previous'),
+ /** A one pass reads B on a day of its own rather than the newest pass. */
+ chooseB = $bindable(false),
+ /** The last lookup, held by the wizard so stepping back does not pay for it twice. */
+ lookup = $bindable(null),
+ onshow = () => {},
+ } = $props();
+
+ const AGAINST = [
+ ['previous', 'The pass before', 'What changed since the last run'],
+ ['reference', 'A fixed picture', 'Everything changed since that day'],
+ ];
+
+ const radar = $derived(sensor === 'sentinel1');
+ let days = $state(untrack(() => lookup?.days ?? 90));
+ let busy = $state(false);
+ let error = $state('');
+ let perArea = $state(false);
+ let generation = 0;
+
+ const key = $derived(areaKey(zones));
+ const fresh = $derived(lookup?.key === key ? lookup : null);
+ const a = $derived(sharedSide(pairs, 'a'));
+ const b = $derived(sharedSide(pairs, 'b'));
+ const same = $derived(uniform(pairs));
+ const several = $derived(zones.length > 1);
+ const ground = $derived(several ? 'these areas' : 'the area');
+ const heading = $derived(routine ? (single ? 'Which image, each run' : 'Which images, each run')
+ : single ? 'Which image' : 'Which two images');
+ const waived = $derived(routine && !!followupId && against === 'previous');
+ const aTitle = $derived(!routine ? 'Before' : against === 'previous' ? 'First run compares with' : 'Every run compares with');
+ const aHint = $derived(
+ !routine ? 'The picture without the change.'
+ : against === 'reference' ? 'The same picture, run after run.'
+ : 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 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))))
+ .filter(Boolean));
+
+ async function look() {
+ busy = true; error = '';
+ const mine = ++generation;
+ try {
+ const found = await api.post('/api/satellite/sentinel/acquisitions',
+ acquisitionQuery(zones, days, new Date(), sensor));
+ if (mine !== generation) return;
+ lookup = { key, days, list: found.dates ?? [], 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. */
+ 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 } : {}) });
+ }
+
+ function newest() {
+ chooseB = false;
+ pairs = setSide(pairs, 'b', '', '', radar);
+ }
+
+ function compareWith(value) {
+ against = value;
+ pairs = withRule(pairs, value);
+ }
+
+ const time = (side) => (radar && side?.time ? `${side.time.slice(0, 5)} UTC` : '');
+</script>
+
+<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>
+ {:else}
+ {#if routine}
+ <p class="lead">Each run takes the newest pass 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}
+ aria-checked={against === value} onclick={() => compareWith(value)}>
+ <strong>{title}</strong><span>{detail}</span>
+ </button>
+ {/each}
+ </div>
+ {/if}
+
+ <div class="slots">
+ {#if !single}
+ <div class="slot" class:missing={!a?.date && !waived}>
+ <span class="tag a" aria-hidden="true">A</span>
+ <div class="body">
+ <span class="k">{aTitle}</span>
+ <div class="line">
+ <DateField day reading={false} label="Day of A" value={a?.date ?? ''}
+ placeholder={same || !several ? 'dd/mm/yyyy' : 'per area'} onchange={(value) => pick('a', value ?? '')} />
+ {#if time(a)}<small class="mono">{time(a)}</small>{/if}
+ </div>
+ <small>{aHint}</small>
+ </div>
+ </div>
+ {/if}
+ {#if !routine}
+ <div class="slot" class:missing={chooseB && !b?.date}>
+ {#if !single}<span class="tag b" aria-hidden="true">B</span>{/if}
+ <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={() => (chooseB = true)}>A day I choose</button>
+ </div>
+ {#if chooseB}
+ <div class="line">
+ <DateField day reading={false} label={single ? 'Day of the image' : 'Day of B'} value={b?.date ?? ''}
+ placeholder={same || !several ? 'dd/mm/yyyy' : 'per area'} onchange={(value) => pick('b', value ?? '')} />
+ {#if time(b)}<small class="mono">{time(b)}</small>{/if}
+ </div>
+ <small>Type it, or pick it in the passes below.</small>
+ {:else}
+ <small>Looked up when the run starts{cloudy}.</small>
+ {/if}
+ </div>
+ </div>
+ {/if}
+ </div>
+
+ <p class="passes-title"><strong>Passes over {ground}</strong>
+ <span>{radar ? 'with their time and track' : 'with their cloud cover'}</span></p>
+ <AcquisitionPicker list={fresh?.list ?? []} {days} {busy} {error} searched={!!fresh} truncated={!!fresh?.truncated}
+ areas={zones.length} {radar} {single} wantsReference={!single} wantsCompare={!routine}
+ a={single ? null : a} b={routine ? null : b}
+ ondays={(value) => (days = value)} onlook={look}
+ onpick={(letter, entry) => pick(letter, entry.date, entry.time ?? '')} />
+ {#each warnings as warning (warning)}<p class="warn">{warning}</p>{/each}
+ {/if}
+
+ {#if several && !(routine && single)}
+ <p class="hint">{same ? `The same days for all ${zones.length} areas.` : 'The areas have days of their own.'}
+ <button class="link" onclick={() => (perArea = true)}>Set them per area…</button></p>
+ {#if !same}
+ <ul class="dates">
+ {#each zones as zone (zone.id)}
+ {@const pair = pairs.find((row) => row.area_id === zone.id)}
+ <li><span class="who">{zone.name}</span><span class="what">{areaLine(pair, { single, routine, radar })}</span></li>
+ {/each}
+ </ul>
+ {/if}
+ {/if}
+</section>
+
+{#if perArea}
+ <Modal title="Dates per area" width="760px" onclose={() => (perArea = false)}>
+ <AreaDates {zones} bind:pairs {single} baselineOnly={routine} {sensor} {onshow} />
+ <button class="btn btn-primary" onclick={() => (perArea = false)}>Done</button>
+ </Modal>
+{/if}
+
+<style>
+ .step { display: grid; gap: 9px; }
+ h3 { margin: 0; font-size: var(--fs-sm); font-weight: 700; }
+ .lead { margin: 0; color: var(--text-1); font-size: var(--fs-xs); line-height: 1.45; }
+ .options { display: grid; gap: 4px; }
+ .option {
+ display: grid;
+ gap: 1px;
+ padding: 6px 9px;
+ border: 1px solid var(--border);
+ border-radius: var(--r-sm);
+ color: var(--text-1);
+ font-size: var(--fs-xs);
+ text-align: left;
+ }
+ .option:hover { background: var(--bg-2); }
+ .option.on { border-color: var(--accent); background: var(--accent-soft); }
+ .option span { color: var(--text-3); font-size: 10.5px; }
+ .slots {
+ display: grid;
+ border: 1px solid var(--border);
+ border-radius: var(--r-sm);
+ }
+ .slot { display: flex; gap: 9px; padding: 8px 9px; }
+ .slot + .slot { border-top: 1px solid var(--border); }
+ .slot.missing { background: color-mix(in srgb, var(--warn, #e2a03f) 7%, transparent); }
+ .tag {
+ flex: 0 0 auto;
+ display: grid;
+ place-items: center;
+ width: 18px;
+ height: 18px;
+ border-radius: 4px;
+ color: #0b0d11;
+ font: 700 10.5px/1 var(--font-sans);
+ }
+ .tag.a { background: var(--side-a, #38bdf8); }
+ .tag.b { background: var(--side-b, #f59e0b); }
+ .body { display: grid; gap: 5px; min-width: 0; flex: 1; }
+ .k { color: var(--text-1); font-size: var(--fs-xs); font-weight: 600; }
+ .line { display: flex; align-items: center; gap: 8px; }
+ .line :global(.date-field) { width: 145px; }
+ small { color: var(--text-3); font-size: 10.5px; line-height: 1.35; }
+ .mono { font-family: var(--font-mono); color: var(--text-2); }
+ .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; }
+ .link { color: var(--accent); font-size: var(--fs-xs); }
+ .dates { display: grid; gap: 3px; margin: 0; padding: 0; list-style: none; }
+ .dates li { display: flex; gap: 8px; font-size: var(--fs-xs); }
+ .dates .who { flex: 1; min-width: 0; overflow: hidden; color: var(--text-2); text-overflow: ellipsis; white-space: nowrap; }
+ .dates .what { color: var(--text-3); font-family: var(--font-mono); font-size: 10.5px; }
+</style>
diff --git a/frontend/src/tools/detect/uistate.fixture.svelte.js b/frontend/src/tools/detect/uistate.fixture.svelte.js
new file mode 100644
index 0000000..f05a3d9
--- /dev/null
+++ b/frontend/src/tools/detect/uistate.fixture.svelte.js
@@ -0,0 +1,6 @@
+/**
+ * A reactive stand-in for the app's `uiState` in tests that drive the keys one
+ * tool writes and another reads (a saved item to open, a pair handed over).
+ * A plain object would take the write and never wake the effect behind it.
+ */
+export const uiState = $state({ tool: 'detect', openAnalyzer: null });
diff --git a/frontend/src/tools/compare/compare.css b/frontend/src/tools/mapdock.css
similarity index 97%
rename from frontend/src/tools/compare/compare.css
rename to frontend/src/tools/mapdock.css
index e4a20bb..cb777d7 100644
--- a/frontend/src/tools/compare/compare.css
+++ b/frontend/src/tools/mapdock.css
@@ -1,5 +1,7 @@
-/* Compare uses the same theme tokens as the other tools. */
-.compare-tool {
+/* The dock two map tools share: Compare's reading modes and Detect's column.
+ Both take the app's theme tokens and name them once here. */
+.compare-tool,
+.detect-tool {
--cmp-a: var(--info);
--cmp-b: var(--accent);
--glass: var(--bg-1);
diff --git a/frontend/src/tools/satellite/ImageryChip.svelte b/frontend/src/tools/satellite/ImageryChip.svelte
index 28bb599..2c34720 100644
--- a/frontend/src/tools/satellite/ImageryChip.svelte
+++ b/frontend/src/tools/satellite/ImageryChip.svelte
@@ -15,7 +15,9 @@
import Icon from '../../components/Icon.svelte';
import SentinelPicker from './SentinelPicker.svelte';
import WaybackPicker from './WaybackPicker.svelte';
+ import RadarPicker from './RadarPicker.svelte';
import { WAYBACK_ID } from '../../lib/wayback.js';
+ import { RADAR_ID } from '../../lib/radar.js';
import {
SENTINEL_ID,
cloudClass,
@@ -34,6 +36,8 @@
s2 = null,
/** This surface's Wayback release, when that basemap is on it. */
wayback = null,
+ /** This surface's Sentinel-1 pass, when that basemap is on it. */
+ 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.
@@ -45,10 +49,12 @@
let menuEl = $state();
let s2MenuEl = $state();
let wbMenuEl = $state();
+ let s1MenuEl = $state();
const asked = $derived(imagery.find(providerId));
const isSentinel = $derived(asked?.id === SENTINEL_ID);
const isWayback = $derived(asked?.id === WAYBACK_ID);
+ const isRadar = $derived(asked?.id === RADAR_ID);
const usagePill = $derived(imagery.pill(asked));
function pick(provider) {
@@ -76,6 +82,15 @@
return () => document.removeEventListener('mousedown', outside, true);
});
+ $effect(() => {
+ if (!s1?.menuOpen) return;
+ const outside = (e) => {
+ if (s1MenuEl && !s1MenuEl.contains(e.target)) s1.menuOpen = false;
+ };
+ document.addEventListener('mousedown', outside, true);
+ return () => document.removeEventListener('mousedown', outside, true);
+ });
+
$effect(() => {
if (!wayback?.menuOpen) return;
const outside = (e) => {
@@ -117,6 +132,9 @@
{#if isWayback && wayback}
<WaybackPicker bind:menuEl={wbMenuEl} wb={wayback} />
{/if}
+ {#if isRadar && s1}
+ <RadarPicker bind:menuEl={s1MenuEl} {s1} />
+ {/if}
<div class="chip-wrap" bind:this={menuEl}>
<button
class="chip"
diff --git a/frontend/src/tools/satellite/MapSurface.svelte b/frontend/src/tools/satellite/MapSurface.svelte
index 5b4058f..ca9ebcc 100644
--- a/frontend/src/tools/satellite/MapSurface.svelte
+++ b/frontend/src/tools/satellite/MapSurface.svelte
@@ -27,6 +27,7 @@
import { createMapEngine } from '../../lib/map/engine.js';
import { createBasemaps, OVERLAY_IDS } from '../../lib/map/basemap.js';
import { DEFAULT_LAYER, DEFAULT_MAXCC, SENTINEL_ID } from '../../lib/sentinel.js';
+ import { RADAR_ID, orbitMark } from '../../lib/radar.js';
import Icon from '../../components/Icon.svelte';
import Compass from '../../components/Compass.svelte';
import ImageryChip from './ImageryChip.svelte';
@@ -41,6 +42,8 @@
s2 = null,
/** This surface's Wayback release (state/wayback.svelte.js), likewise. */
wayback = null,
+ /** This surface's Sentinel-1 pass (state/radar.svelte.js), likewise. */
+ s1 = null,
/** What is laid over the imagery: an id (`OVERLAY_IDS`), or `{ id, params }`
* for one whose address is a question — FIRMS's sensor and window. The
* tool decides which are offered; the surface only puts them on. */
@@ -110,8 +113,10 @@
imagery.displayed(providerId, view.zoom, {
...(s2?.variant ?? {}),
release: wayback?.release ?? null,
+ pass: s1?.pass ?? null,
})
);
+ const radarPass = $derived(shown.provider?.id === RADAR_ID ? s1?.pass ?? null : null);
/** A pinned Sentinel-2 day *is* the acquisition date — the one provider that
* can answer "when was this taken?" without being asked. */
@@ -120,7 +125,9 @@
);
$effect(() => {
- dated = pinnedDay
+ dated = radarPass
+ ? { date: radarPass.date, exact: true, source: 'Sentinel-1' }
+ : pinnedDay
? { date: pinnedDay, exact: true, source: 'Sentinel-2' }
: shown.provider?.id === SENTINEL_ID
? s2?.latest ? { date: s2.latest, exact: false, source: 'Sentinel-2' } : null
@@ -135,7 +142,7 @@
/** What a capture of this surface must record: the pixels' own provenance. */
export function provenance() {
- return { provider: shown.id, imageryDate: pinnedDay ?? imageryDate?.date ?? null };
+ return { provider: shown.id, imageryDate: radarPass?.date ?? pinnedDay ?? imageryDate?.date ?? null };
}
// Svelte only honours a cleanup returned from a *synchronous* onMount, and the
@@ -296,7 +303,7 @@
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} {shown} />
+ <ImageryChip {imagery} bind:providerId {s2} {wayback} {s1} {shown} />
<!-- …and when the pixels under the crosshair were taken. Under the provider
rather than in the opposite corner: it describes that same picture, and
@@ -329,6 +336,16 @@
>
{/if}
</span>
+ {:else if s1 && shown.provider?.id === RADAR_ID}
+ <!-- The pass is the picker's own chip; this says what it means. -->
+ <span class="date-pill mono" class:exact={!!radarPass}
+ title={radarPass ? `Sentinel-1 pass flying ${radarPass.orbit === 'descending' ? 'south' : 'north'}`
+ : 'Sentinel-1: most recent pass (open the picker to date it)'}>
+ <Icon name="clock" size={11} />
+ {radarPass ? `${radarPass.date} ${radarPass.time.slice(0, 5)} UTC ${orbitMark(radarPass.orbit)}` : ''}
+ {#if !radarPass}<span class="tag">most recent</span>{/if}
+ <span class="tag layer">radar</span>
+ </span>
{:else if imageryDate?.supported}
<span
class="date-pill mono"
diff --git a/frontend/src/tools/satellite/RadarPicker.svelte b/frontend/src/tools/satellite/RadarPicker.svelte
new file mode 100644
index 0000000..a57d3f9
--- /dev/null
+++ b/frontend/src/tools/satellite/RadarPicker.svelte
@@ -0,0 +1,219 @@
+<script>
+ import Icon from '../../components/Icon.svelte';
+ import { monthLabel } from '../../lib/sentinel.js';
+ import { orbitMark, passLabel, sameTrack } from '../../lib/radar.js';
+
+ /**
+ * Which Sentinel-1 pass this surface shows, month by month.
+ *
+ * `s1` is the store from `state/radar.svelte.js`. A row is one pass, named by
+ * its day and its UTC time, with the way the satellite was flying: dawn
+ * passes fly south, dusk passes north, and the two see a place from opposite
+ * sides. Beside a second radar map the rows on that map's track are marked,
+ * since only those compare like with like.
+ */
+ let { menuEl = $bindable(), s1 } = $props();
+
+ const peer = $derived(s1.peer);
+ const shown = $derived(s1.pass);
+</script>
+
+<div class="s1-wrap" bind:this={menuEl}>
+ <button
+ class="chip"
+ class:on={s1.menuOpen}
+ onclick={() => s1.toggleMenu()}
+ title={s1.busy ? 'Reading this month’s radar passes…' : 'Sentinel-1 pass'}
+ aria-label="Sentinel-1 pass"
+ aria-expanded={s1.menuOpen}
+ aria-busy={s1.busy}
+ >
+ <Icon name="clock" size={13} />
+ <span class="mono">{passLabel(shown)}</span>
+ {#if shown?.orbit}<span class="mark" aria-hidden="true">{orbitMark(shown.orbit)}</span>{/if}
+ {#if s1.busy}<span class="spinner" aria-hidden="true"></span>{/if}
+ </button>
+
+ {#if s1.menuOpen}
+ <div class="s1-menu card">
+ <div class="step-row">
+ <button class="nav" onclick={() => s1.stepMonth(-1)} aria-label="Previous month" title="Previous month">
+ <Icon name="chevronLeft" size={13} />
+ </button>
+ <span class="current">{monthLabel(s1.month)}</span>
+ <button class="nav" onclick={() => s1.stepMonth(1)} aria-label="Next month" title="Next month">
+ <Icon name="chevronRight" size={13} />
+ </button>
+ </div>
+
+ <button class="row" class:on={!shown} onclick={() => s1.pick(null)}>
+ <span>Most recent pass</span>
+ </button>
+
+ {#if s1.busy}
+ <div class="menu-hint waiting"><span class="spinner" aria-hidden="true"></span> Reading passes…</div>
+ {:else if s1.note}
+ <div class="menu-hint" class:warn={s1.note.startsWith('Could not')}>{s1.note}</div>
+ {:else if s1.stale}
+ <div class="menu-hint">
+ <span class="warn">The map moved off this list.</span>
+ <button class="linkish" onclick={() => s1.loadPasses()}>Read here</button>
+ </div>
+ {/if}
+
+ {#if s1.passes.length}
+ <ul class="passes" aria-label="Sentinel-1 passes">
+ {#each s1.passes as entry (`${entry.date}T${entry.time}`)}
+ {@const on = shown?.date === entry.date && shown?.time === entry.time}
+ <li>
+ <button class="row mono" class:on onclick={() => s1.pick(entry)}
+ title={entry.orbit ? `Flying ${entry.orbit === 'descending' ? 'south' : 'north'}` : undefined}>
+ <span>{entry.date} · {entry.time.slice(0, 5)} UTC</span>
+ <span class="side">
+ {#if peer && sameTrack(entry.time, peer.time)}<span class="track">same track</span>{/if}
+ {orbitMark(entry.orbit)}
+ </span>
+ </button>
+ </li>
+ {/each}
+ </ul>
+ {/if}
+ <div class="menu-hint">One lookup a month, billed as one Copernicus request.</div>
+ </div>
+ {/if}
+</div>
+
+<style>
+ .s1-wrap {
+ position: relative;
+ display: flex;
+ }
+ .chip {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ height: 30px;
+ padding: 0 8px;
+ border-radius: var(--radius-1);
+ font-size: var(--fs-xs);
+ color: var(--text-1);
+ background: rgba(24, 24, 24, 0.88);
+ backdrop-filter: blur(6px);
+ box-shadow: 0 0 0 1px var(--border);
+ cursor: pointer;
+ }
+ .chip:hover,
+ .chip.on {
+ color: var(--accent);
+ }
+ .mark {
+ color: var(--text-3);
+ }
+ .spinner {
+ width: 11px;
+ height: 11px;
+ border: 2px solid currentColor;
+ border-top-color: transparent;
+ border-radius: 50%;
+ animation: spin 0.7s linear infinite;
+ }
+ @keyframes spin {
+ to { transform: rotate(360deg); }
+ }
+ .s1-menu {
+ position: absolute;
+ top: calc(100% + 8px);
+ right: 0;
+ width: 260px;
+ max-height: 70vh;
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ padding: 10px;
+ background: rgba(24, 24, 24, 0.96);
+ backdrop-filter: blur(6px);
+ box-shadow: var(--shadow-2);
+ z-index: 700;
+ }
+ .step-row {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 8px;
+ }
+ .current {
+ font-size: var(--fs-sm);
+ color: var(--text-1);
+ }
+ .nav {
+ display: flex;
+ padding: 2px 4px;
+ border: 1px solid var(--border);
+ border-radius: var(--r-sm);
+ background: var(--bg-2);
+ color: var(--text-2);
+ cursor: pointer;
+ }
+ .nav:hover {
+ color: var(--text-1);
+ border-color: var(--text-3);
+ }
+ .passes {
+ margin: 0;
+ padding: 0;
+ list-style: none;
+ max-height: 240px;
+ overflow-y: auto;
+ }
+ .row {
+ display: flex;
+ justify-content: space-between;
+ gap: 8px;
+ width: 100%;
+ padding: 3px 8px;
+ border-radius: var(--r-sm);
+ font-size: var(--fs-xs);
+ color: var(--text-2);
+ text-align: left;
+ cursor: pointer;
+ }
+ .row:hover {
+ background: var(--bg-3);
+ color: var(--text-1);
+ }
+ .row.on {
+ color: var(--accent);
+ background: var(--accent-soft);
+ }
+ .side {
+ display: inline-flex;
+ gap: 6px;
+ color: var(--text-3);
+ }
+ .track {
+ color: var(--ok, #46a758);
+ }
+ .menu-hint {
+ font-size: 10px;
+ line-height: 1.35;
+ color: var(--text-3);
+ }
+ .menu-hint.waiting {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ }
+ .menu-hint .warn,
+ .menu-hint.warn {
+ color: var(--warn, #e2a03f);
+ }
+ .linkish {
+ background: none;
+ border: 0;
+ padding: 0;
+ color: var(--accent);
+ font-size: 10px;
+ cursor: pointer;
+ text-decoration: underline;
+ }
+</style>
diff --git a/frontend/src/tools/satellite/RadarPicker.test.js b/frontend/src/tools/satellite/RadarPicker.test.js
new file mode 100644
index 0000000..147eef7
--- /dev/null
+++ b/frontend/src/tools/satellite/RadarPicker.test.js
@@ -0,0 +1,49 @@
+import { describe, expect, it, vi } from 'vitest';
+import { render } from 'svelte/server';
+import RadarPicker from './RadarPicker.svelte';
+
+function props(s1 = {}) {
+ return {
+ s1: {
+ menuOpen: true,
+ month: '2026-05',
+ pass: { date: '2026-05-14', time: '05:42:10', orbit: 'descending' },
+ passes: [
+ { date: '2026-05-14', time: '17:33:02', orbit: 'ascending' },
+ { date: '2026-05-14', time: '05:42:10', orbit: 'descending' },
+ ],
+ busy: false,
+ note: '',
+ stale: false,
+ peer: null,
+ toggleMenu: vi.fn(),
+ stepMonth: vi.fn(),
+ loadPasses: vi.fn(),
+ pick: vi.fn(),
+ ...s1,
+ },
+ };
+}
+
+describe('the radar pass picker', () => {
+ it('names a pass by its day, its UTC time and the way it flew', () => {
+ const { body } = render(RadarPicker, { props: props() });
+ expect(body).toContain('2026-05-14 · 05:42 UTC');
+ expect(body).toContain('17:33 UTC');
+ expect(body).toContain('↓');
+ expect(body).toContain('Most recent pass');
+ expect(body).toContain('billed as one Copernicus request');
+ });
+
+ it('marks the passes on the other side’s track', () => {
+ const { body } = render(RadarPicker, { props: props({ peer: { date: '2026-05-02', time: '05:42:40' } }) });
+ expect(body.match(/same track/g)).toHaveLength(1);
+ });
+
+ it('says a failed read failed', () => {
+ const { body } = render(RadarPicker, {
+ props: props({ passes: [], note: 'Could not read this month’s passes: offline' }),
+ });
+ expect(body).toContain('Could not read');
+ });
+});
diff --git a/frontend/src/tools/satellite/WaybackPicker.svelte b/frontend/src/tools/satellite/WaybackPicker.svelte
index 566bfd8..94c0d06 100644
--- a/frontend/src/tools/satellite/WaybackPicker.svelte
+++ b/frontend/src/tools/satellite/WaybackPicker.svelte
@@ -28,9 +28,9 @@
<div class="wb-wrap" bind:this={menuEl}>
<!-- The wait is on the chip, not only inside the menu: reading a point's
- history is a walk through Esri's tiles that takes seconds, it runs with
- the picker shut once it is following the map, and a basemap that answers
- nothing for that long without saying so reads as a broken one. -->
+ history is a walk through Esri's tiles that takes seconds, the picker
+ can be shut while it runs, and a basemap that answers nothing for that
+ long without saying so reads as a broken one. -->
<button
class="chip"
class:on={wb.menuOpen}
@@ -91,17 +91,17 @@
{/if}
<div class="chips">
- <button
- class="chip-opt"
- class:on={wb.changesOnly}
- onclick={() => wb.setChangesOnly(true)}
- title="Only releases showing a different picture at the crosshair"
- >Changes here</button>
<button
class="chip-opt"
class:on={!wb.changesOnly}
onclick={() => wb.setChangesOnly(false)}
>Every release</button>
+ <button
+ class="chip-opt"
+ class:on={wb.changesOnly}
+ onclick={() => wb.setChangesOnly(true)}
+ title="Read which releases show a different picture at the crosshair"
+ >Changes here</button>
</div>
{#if wb.changesOnly}
@@ -115,7 +115,7 @@
{:else if wb.stale}
<div class="menu-hint">
<span class="warn">The map moved off this history.</span>
- <button class="linkish" onclick={() => wb.loadChanges()}>Refresh</button>
+ <button class="linkish" onclick={() => wb.loadChanges()}>Read here</button>
</div>
{:else if wb.changes}
<div class="menu-hint dim">
@@ -143,7 +143,7 @@
</ul>
<div class="menu-hint dim">
- Release dates are Esri's; “taken” and the pill under the chip date the pixels.
+ Release dates are Esri's; the pill under the chip dates the pixels on screen.
</div>
{/if}
{/if}
diff --git a/frontend/src/tools/satellite/WaybackPicker.test.js b/frontend/src/tools/satellite/WaybackPicker.test.js
index 346388b..0359a95 100644
--- a/frontend/src/tools/satellite/WaybackPicker.test.js
+++ b/frontend/src/tools/satellite/WaybackPicker.test.js
@@ -48,8 +48,8 @@ describe('the Wayback chip', () => {
});
it('says it is waiting while Esri is being read, picker open or shut', () => {
- // the walk takes seconds and runs with the menu closed once the history
- // follows the map, so the chip is where the wait has to show
+ // the walk takes seconds and the menu can be shut while it runs, so the
+ // chip is where the wait has to show
const { body } = render(WaybackPicker, {
props: props({ menuOpen: false, releases: [], date: '', busy: true }),
});
@@ -103,16 +103,27 @@ describe('the picker', () => {
expect(
render(WaybackPicker, { props: props({ changesNote: 'Could not read it' }) }).body
).toContain('Could not read it');
- expect(render(WaybackPicker, { props: props({ stale: true }) }).body).toContain(
- 'The map moved off this history.'
- );
+ const stale = render(WaybackPicker, { props: props({ stale: true }) }).body;
+ expect(stale).toContain('The map moved off this history.');
+ // …and reading the new place is the analyst's call, not the map's
+ expect(stale).toContain('>Read here</button>');
+ });
+
+ it('offers every release first, and the history as a choice after it', () => {
+ const { body } = render(WaybackPicker, {
+ props: props({ changesOnly: false, changes: null, visible: RELEASES, position: 1 }),
+ });
+ expect(body.indexOf('Every release')).toBeLessThan(body.indexOf('Changes here'));
+ expect(body).toMatch(/class="chip-opt[^"]* on"[^>]*>Every release</);
+ expect(body).toContain('>2026-08-05<');
+ expect(body).not.toMatch(/changes? at the crosshair/);
});
it('keeps release dates apart from when the pixels were taken', () => {
const { body } = render(WaybackPicker, { props: props() });
expect(body).toContain('taken 2022-03-31');
expect(body).toContain('Taken by Maxar WV03');
- expect(body).toContain('the pill under the chip date the pixels');
+ expect(body).toContain('the pill under the chip dates the pixels on screen');
});
it('says so when the release list cannot be read', () => {
diff --git a/frontend/src/tools/satellite/state/imagery.svelte.js b/frontend/src/tools/satellite/state/imagery.svelte.js
index bae6904..9467279 100644
--- a/frontend/src/tools/satellite/state/imagery.svelte.js
+++ b/frontend/src/tools/satellite/state/imagery.svelte.js
@@ -33,6 +33,7 @@ import {
} from '../../../lib/usage.js';
import { variantId } from '../../../lib/sentinel.js';
import { WAYBACK_ID, waybackId } from '../../../lib/wayback.js';
+import { RADAR_ID, radarId } from '../../../lib/radar.js';
export const FALLBACK_PROVIDER = FREE_IMAGERY;
@@ -142,8 +143,8 @@ export function createImageryState({ api }) {
*
* @param {string} chosenId the provider the surface's selector is on
* @param {number} zoom that surface's view zoom
- * @param {object} [variant] Sentinel-2's layer/window/ceiling, or the
- * Wayback `release`, whichever the shown basemap reads
+ * @param {object} [variant] Sentinel-2's layer/window/ceiling, the Wayback
+ * `release` or the Sentinel-1 `pass`, whichever the shown basemap reads
*/
displayed(chosenId, zoom, variant) {
const chosen = this.find(chosenId);
@@ -160,7 +161,9 @@ export function createImageryState({ api }) {
// what every downstream consumer asks for: the tile URL, the capture,
// the disk cache — never the bare provider id
id:
- baseId === WAYBACK_ID ? waybackId(baseId, variant?.release) : variantId(baseId, variant),
+ baseId === WAYBACK_ID ? waybackId(baseId, variant?.release)
+ : baseId === RADAR_ID ? radarId(baseId, variant?.pass)
+ : variantId(baseId, variant),
// memoized by the caller so the layer is only rebuilt when the cell
// actually changes, i.e. crossing the z17 boost bracket
cell: provider ? layerCell(provider, zoom) : 256,
diff --git a/frontend/src/tools/satellite/state/radar.svelte.js b/frontend/src/tools/satellite/state/radar.svelte.js
new file mode 100644
index 0000000..de3bb03
--- /dev/null
+++ b/frontend/src/tools/satellite/state/radar.svelte.js
@@ -0,0 +1,129 @@
+/**
+ * Which Sentinel-1 pass a map shows, and which passes the point has.
+ *
+ * Like Sentinel-2's store, every question costs a metered request, so it is
+ * about *when* it asks:
+ *
+ * - **Passes are read by the month, when the picker is open**, and kept per
+ * month and place: paging back to a month already seen spends nothing.
+ * - **An empty month and a failed read are different facts.** A read that
+ * failed says so rather than offering a list that claims there was no pass.
+ * - **A pass is a day and a time.** The radar sees a place at dawn flying south
+ * and at dusk flying north, and those are two looks from opposite sides.
+ *
+ * The arithmetic is `lib/radar.js`; this holds what was asked and what came back.
+ *
+ * @param {object} deps
+ * @param {object} deps.api the app's fetch wrapper
+ * @param {() => {lat: number, lon: number}} deps.place where the map points
+ * @param {() => void} [deps.onBilled] a metered request went out
+ * @param {() => ({date: string, time: string}|null)} [deps.peer] the pass on the
+ * other side of a comparison, whose track the list marks
+ */
+import { validPass } from '../../../lib/radar.js';
+import { addMonths, isoDay, monthBounds, monthOf, sentinelPlaceKey } from '../../../lib/sentinel.js';
+
+export function createRadarState({ api, place, onBilled = () => {}, peer = () => null }) {
+ let pass = $state(null); // null = the most recent pass, the layer's default
+ let menuOpen = $state(false);
+ let month = $state(monthOf(''));
+ let passes = $state([]);
+ let passesFor = $state('');
+ let busy = $state(false);
+ let note = $state('');
+ let requestId = 0;
+ const cache = new Map();
+
+ const hereKey = () => `${month}@${sentinelPlaceKey(place().lat, place().lon)}`;
+
+ async function loadPasses(force = false) {
+ const key = hereKey();
+ if (!force && cache.has(key)) {
+ passes = cache.get(key);
+ passesFor = key;
+ note = passes.length ? '' : 'No Sentinel-1 pass here this month.';
+ return passes;
+ }
+ const mine = ++requestId;
+ const { lat, lon } = place();
+ const { from, to } = monthBounds(month);
+ busy = true;
+ note = '';
+ try {
+ const answer = await api.get(
+ `/api/satellite/sentinel/dates?collection=sentinel1&lat=${lat}&lon=${lon}&start=${from}&end=${to}`
+ );
+ onBilled();
+ if (mine !== requestId) return passes;
+ const list = (answer.dates ?? []).filter((entry) => entry.time);
+ cache.set(key, list);
+ passes = list;
+ passesFor = key;
+ if (!list.length) note = 'No Sentinel-1 pass here this month.';
+ } catch (error) {
+ if (mine !== requestId) return passes;
+ passes = [];
+ passesFor = '';
+ note = `Could not read this month’s passes: ${error.message}`;
+ } finally {
+ if (mine === requestId) busy = false;
+ }
+ return passes;
+ }
+
+ return {
+ get pass() {
+ return pass;
+ },
+ get menuOpen() {
+ return menuOpen;
+ },
+ set menuOpen(value) {
+ menuOpen = value;
+ },
+ get month() {
+ return month;
+ },
+ get passes() {
+ return passes;
+ },
+ get busy() {
+ return busy;
+ },
+ get note() {
+ return note;
+ },
+ /** The list on screen describes another place or month than the map's. */
+ get stale() {
+ return Boolean(passesFor) && passesFor !== hereKey();
+ },
+ /** The other side's pass, whose track the list marks. */
+ get peer() {
+ return peer();
+ },
+ /** What the provider id carries (`lib/radar.js` `radarId`). */
+ get variant() {
+ return { pass };
+ },
+ toggleMenu() {
+ menuOpen = !menuOpen;
+ if (menuOpen && (!passesFor || this.stale)) void loadPasses();
+ },
+ stepMonth(delta) {
+ const next = addMonths(month, delta);
+ if (next > monthOf(isoDay(new Date()))) return;
+ month = next;
+ void loadPasses();
+ },
+ loadPasses,
+ /** Show one pass, or the most recent with null. The pass already shown
+ * is left alone: a fresh object would read as a change to everything
+ * that follows it, the tiles included. */
+ pick(next) {
+ const chosen = validPass(next) ? { date: next.date, time: next.time, orbit: next.orbit ?? '' } : null;
+ if (chosen?.date === pass?.date && chosen?.time === pass?.time) return;
+ pass = chosen;
+ if (pass) month = monthOf(pass.date);
+ },
+ };
+}
diff --git a/frontend/src/tools/satellite/state/radar.svelte.test.js b/frontend/src/tools/satellite/state/radar.svelte.test.js
new file mode 100644
index 0000000..112733a
--- /dev/null
+++ b/frontend/src/tools/satellite/state/radar.svelte.test.js
@@ -0,0 +1,86 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { createRadarState } from './radar.svelte.js';
+
+/** Every read is a metered request, so what this store must get right is when it asks. */
+
+let at;
+let get;
+const PASSES = [
+ { date: '2026-05-14', time: '17:33:02', orbit: 'ascending', cloud: null, granules: 1 },
+ { date: '2026-05-14', time: '05:42:10', orbit: 'descending', cloud: null, granules: 2 },
+];
+
+function store(peer = () => null) {
+ return createRadarState({ api: { get }, place: () => at, onBilled: vi.fn(), peer });
+}
+
+beforeEach(() => {
+ at = { lat: 51.95, lon: 4.05 };
+ get = vi.fn(async () => ({ dates: PASSES }));
+});
+
+describe('radar passes', () => {
+ it('asks nothing until its picker opens, then asks for the month', async () => {
+ const s1 = store();
+ expect(get).not.toHaveBeenCalled();
+ s1.toggleMenu();
+ await vi.waitFor(() => expect(s1.passes).toHaveLength(2));
+ expect(get.mock.calls[0][0]).toContain('collection=sentinel1');
+ expect(get.mock.calls[0][0]).toMatch(/start=\d{4}-\d{2}-01&end=/);
+ });
+
+ it('keeps a month it has read, for the place it read it for', async () => {
+ const s1 = store();
+ await s1.loadPasses();
+ await s1.loadPasses();
+ expect(get).toHaveBeenCalledOnce();
+ at = { lat: 52.5, lon: 4.05 };
+ expect(s1.stale).toBe(true);
+ await s1.loadPasses();
+ expect(get).toHaveBeenCalledTimes(2);
+ });
+
+ it('says a read failed rather than that there was no pass', async () => {
+ get = vi.fn(async () => { throw new Error('offline'); });
+ const s1 = store();
+ await s1.loadPasses();
+ expect(s1.passes).toEqual([]);
+ expect(s1.note).toContain('Could not read');
+ get = vi.fn(async () => ({ dates: [] }));
+ const empty = store();
+ await empty.loadPasses();
+ expect(empty.note).toBe('No Sentinel-1 pass here this month.');
+ });
+
+ it('shows one pass, and goes back to the most recent', () => {
+ const s1 = store();
+ s1.pick(PASSES[1]);
+ expect(s1.variant).toEqual({ pass: { date: '2026-05-14', time: '05:42:10', orbit: 'descending' } });
+ expect(s1.month).toBe('2026-05');
+ s1.pick(null);
+ expect(s1.pass).toBe(null);
+ });
+
+ it('never pages past the current month', () => {
+ const s1 = store();
+ const now = s1.month;
+ s1.stepMonth(1);
+ expect(s1.month).toBe(now);
+ });
+
+ it('leaves the pass already shown alone, so asking twice changes nothing', () => {
+ const s1 = store();
+ s1.pick(PASSES[1]);
+ const shown = s1.pass;
+ // a fresh object for the same pass once read as a change, and fed a loop
+ s1.pick({ ...PASSES[1] });
+ expect(s1.pass).toBe(shown);
+ s1.pick(PASSES[0]);
+ expect(s1.pass.time).toBe('17:33:02');
+ });
+
+ it('knows the other side’s pass, to mark its track', () => {
+ const s1 = store(() => ({ date: '2026-05-02', time: '05:42:40' }));
+ expect(s1.peer.time).toBe('05:42:40');
+ });
+});
diff --git a/frontend/src/tools/satellite/state/wayback.svelte.js b/frontend/src/tools/satellite/state/wayback.svelte.js
index 8f7ffab..8257ca8 100644
--- a/frontend/src/tools/satellite/state/wayback.svelte.js
+++ b/frontend/src/tools/satellite/state/wayback.svelte.js
@@ -4,14 +4,13 @@
* Both questions reach Esri, so the store is about *when* it asks:
*
* - **The release list is read once**, the first time the basemap is shown or
- * its picker opened, never on mount.
- * - **The change list follows the map from the first time the picker is
- * opened**, and not before: opening it is the analyst saying they are reading
- * this place through time, and from then on a view that settles over another
- * tile reads that tile's history, picker open or not. Gating it on the picker
- * *staying* open was the bug: the map moved, the picker was shut, and it
- * re-opened on the history of wherever the analyst had been before. A pan
- * inside the same tile has the same history and asks nothing.
+ * its picker opened, never on mount. It costs one request and dates every
+ * release by publication.
+ * - **A point's history is read only when the analyst asks for it**: pressing
+ * *Changes here*, or *Imagery history here* on the map's menu. It walks
+ * Esri's tiles and metadata, dozens of requests, so it never follows the
+ * map. A history that no longer describes the tile under the crosshair says
+ * so and waits for the analyst to ask again.
* - **A failed read is said, not hidden.** An empty change list means the point
* never changed; a failed one means we do not know, and the picker falls back
* to every release rather than claiming there is nothing to see.
@@ -37,15 +36,13 @@ export function createWaybackState({ api, place }) {
let listBusy = $state(false); // …as the chip shows it
let release = $state(null); // null = the newest
let menuOpen = $state(false);
- let watching = $state(false); // the picker has been opened: the history follows the map
- let changesOnly = $state(true);
+ let changesOnly = $state(false);
let changes = $state(null); // [release] for `changesFor`, null when unknown
let pictures = $state({}); // release → { acquired, source } for those changes
let changesFor = $state('');
let changesBusy = $state(false);
let changesNote = $state('');
let changesRequest = 0;
- let asked = ''; // the tile whose history was last read, answered or refused
const changesCache = new Map();
const hereKey = () => {
@@ -78,9 +75,10 @@ export function createWaybackState({ api, place }) {
pictures = Object.fromEntries(list.map((entry) => [entry.release, entry]));
}
- async function loadChanges() {
- const key = hereKey();
- asked = key;
+ /** Read the history of the tile at `at`, the map's centre unless given. */
+ async function loadChanges(at = place()) {
+ const { lat, lon, zoom } = at;
+ const key = changesKey(lat, lon, zoom);
if (changesCache.has(key)) {
keep(changesCache.get(key));
changesFor = key;
@@ -88,7 +86,6 @@ export function createWaybackState({ api, place }) {
return changes;
}
const requestId = ++changesRequest;
- const { lat, lon, zoom } = place();
changesBusy = true;
changesNote = '';
try {
@@ -139,11 +136,10 @@ export function createWaybackState({ api, place }) {
/**
* Esri is being asked something, list or history.
*
- * Both walks take their time — the history reads a tile per release and
- * compares the pixels — and both can be running with the picker shut, since
- * the history follows the map once it has been opened. So the chip carries
- * the wait: a basemap that answers nothing for ten seconds and says nothing
- * about it reads as one that is broken.
+ * Both walks take their time, the history above all: it reads a tile per
+ * candidate release and compares the pixels. The picker can be shut while
+ * one runs, so the chip carries the wait: a basemap that answers nothing
+ * for ten seconds and says nothing about it reads as one that is broken.
*/
get busy() {
return listBusy || changesBusy;
@@ -151,14 +147,6 @@ export function createWaybackState({ api, place }) {
get changesNote() {
return changesNote;
},
- /** The analyst opened the history once, so it follows the map from here. */
- get watching() {
- return watching;
- },
- /** The tile the map is over. What a tool watches to keep the history here. */
- get here() {
- return hereKey();
- },
/** The point moved out of the tile the change list describes. */
get stale() {
return Boolean(changesFor) && changesFor !== hereKey();
@@ -212,24 +200,9 @@ export function createWaybackState({ api, place }) {
loadReleases,
loadChanges,
- /**
- * The map settled: read this tile's history unless it is the one we hold.
- *
- * A tile already answered costs nothing — the answer is kept for the
- * session — and a tile Esri refused is not asked again until the analyst
- * presses Refresh, so a service that is down is not hammered by panning.
- */
- follow() {
- if (!watching || hereKey() === asked) return undefined;
- return loadChanges();
- },
-
toggleMenu() {
menuOpen = !menuOpen;
- if (!menuOpen) return;
- watching = true;
- loadReleases();
- loadChanges();
+ if (menuOpen) loadReleases();
},
setChangesOnly(value) {
@@ -239,6 +212,19 @@ export function createWaybackState({ api, place }) {
if (changesOnly && (!changes || this.stale)) loadChanges();
},
+ /**
+ * Open the picker on the changes at `at`, a point the analyst named.
+ *
+ * The point is passed rather than read from the map, since a map sent
+ * there has not settled yet when this is asked.
+ */
+ historyAt(at) {
+ changesOnly = true;
+ menuOpen = true;
+ loadReleases();
+ return loadChanges(at);
+ },
+
/** Show one release. The newest is stored as null so the id stays plain. */
pick(next) {
release = next == null || next === releases[0]?.release ? null : next;
diff --git a/frontend/src/tools/satellite/state/wayback.svelte.test.js b/frontend/src/tools/satellite/state/wayback.svelte.test.js
index b296dac..7be2082 100644
--- a/frontend/src/tools/satellite/state/wayback.svelte.test.js
+++ b/frontend/src/tools/satellite/state/wayback.svelte.test.js
@@ -66,12 +66,13 @@ describe('asking Esri', () => {
expect(wb.busy).toBe(false);
});
- it('opening the picker reads the list and this point’s history', async () => {
+ it('opening the picker reads the list alone, and offers every release', async () => {
const wb = store();
wb.toggleMenu();
- await vi.waitFor(() => expect(wb.changes).toEqual([64776, 10]));
- expect(get).toHaveBeenCalledWith('/api/satellite/wayback/changes?lat=50.45&lon=30.51&zoom=15');
- expect(wb.visible.map((entry) => entry.release)).toEqual([64776, 10]);
+ await vi.waitFor(() => expect(wb.releases).toHaveLength(4));
+ expect(get.mock.calls.some(([path]) => path.includes('/changes'))).toBe(false);
+ expect(wb.changesOnly).toBe(false);
+ expect(wb.visible).toHaveLength(4);
});
it('answers a nudge inside the same tile from memory', async () => {
@@ -86,7 +87,7 @@ describe('asking Esri', () => {
it('marks the history stale once the map leaves its tile, and keeps the changes meanwhile', async () => {
const wb = store();
await wb.loadReleases();
- await wb.loadChanges();
+ await wb.historyAt(at);
at = { lat: 48.85, lon: 2.29, zoom: 15 };
expect(wb.stale).toBe(true);
// the walk takes seconds: the bar stays a bar of changes rather than
@@ -105,51 +106,50 @@ describe('asking Esri', () => {
});
});
-describe('following the map', () => {
- it('asks nothing until the picker has been opened once', async () => {
+describe('reading a history on request', () => {
+ it('never reads one because the map moved', async () => {
+ // the walk is dozens of requests to Esri: panning with the picker open
+ // or shut must not start one
const wb = store();
+ wb.toggleMenu();
+ await wb.loadReleases();
at = { lat: 48.85, lon: 2.29, zoom: 15 };
- expect(wb.follow()).toBeUndefined();
- expect(get).not.toHaveBeenCalled();
+ wb.toggleMenu();
+ wb.toggleMenu();
+ await wb.loadReleases();
+ expect(get.mock.calls.some(([path]) => path.includes('/changes'))).toBe(false);
});
- it('reads the new tile’s history once the picker has been opened, shut or not', async () => {
+ it('reads where the map is when Changes here is pressed', async () => {
const wb = store();
wb.toggleMenu();
+ wb.setChangesOnly(true);
await vi.waitFor(() => expect(wb.changes).toEqual([64776, 10]));
- wb.toggleMenu(); // shut again: the history still follows the map
- expect(wb.menuOpen).toBe(false);
- at = { lat: 48.85, lon: 2.29, zoom: 15 };
- await wb.follow();
- expect(get).toHaveBeenLastCalledWith(
- '/api/satellite/wayback/changes?lat=48.85&lon=2.29&zoom=15'
- );
- expect(wb.stale).toBe(false);
+ expect(get).toHaveBeenCalledWith('/api/satellite/wayback/changes?lat=50.45&lon=30.51&zoom=15');
+ expect(wb.visible.map((entry) => entry.release)).toEqual([64776, 10]);
});
- it('asks once per tile, however often the map settles over it', async () => {
+ it('reads a named point, not the map it is sending there', async () => {
+ // the map has not settled on the point yet when the menu asks
const wb = store();
- wb.toggleMenu();
- await vi.waitFor(() => expect(wb.changes).toEqual([64776, 10]));
- const asked = get.mock.calls.filter(([path]) => path.includes('/changes')).length;
- at = { lat: 50.4501, lon: 30.5101, zoom: 15 }; // a nudge inside the same tile
- await wb.follow();
- await wb.follow();
- expect(get.mock.calls.filter(([path]) => path.includes('/changes'))).toHaveLength(asked);
+ await wb.historyAt({ lat: 48.85, lon: 2.29, zoom: 16 });
+ expect(get).toHaveBeenCalledWith('/api/satellite/wayback/changes?lat=48.85&lon=2.29&zoom=16');
+ expect(wb.menuOpen).toBe(true);
+ expect(wb.changesOnly).toBe(true);
+ at = { lat: 48.85, lon: 2.29, zoom: 16 }; // …and once it has, the history is this place's
+ expect(wb.stale).toBe(false);
});
- it('leaves a tile Esri refused alone until Refresh is pressed', async () => {
+ it('asks again for a tile Esri refused only when the analyst does', async () => {
get = vi.fn(async (path) => {
if (path.includes('/releases')) return { releases: RELEASES };
throw new Error('offline');
});
const wb = store();
- wb.toggleMenu();
+ wb.setChangesOnly(true);
await vi.waitFor(() => expect(wb.changesNote).toContain('offline'));
const refused = get.mock.calls.filter(([path]) => path.includes('/changes')).length;
- await wb.follow(); // panning must not hammer a service that is down
- expect(get.mock.calls.filter(([path]) => path.includes('/changes'))).toHaveLength(refused);
- await wb.loadChanges(); // …but the analyst can ask again
+ await wb.loadChanges();
expect(get.mock.calls.filter(([path]) => path.includes('/changes'))).toHaveLength(refused + 1);
});
@@ -157,7 +157,7 @@ describe('following the map', () => {
const wb = store();
await wb.loadReleases();
expect(wb.reading).toBe(false);
- const coming = wb.loadChanges();
+ const coming = wb.historyAt(at);
expect(wb.reading).toBe(true);
await coming;
expect(wb.reading).toBe(false);
@@ -204,7 +204,7 @@ describe('naming what is on screen', () => {
const wb = store();
await wb.loadReleases();
expect(wb.date).toBe('2026-08-05');
- await wb.loadChanges();
+ await wb.historyAt(at);
expect(wb.date).toBe('2023-08-31');
wb.setChangesOnly(false);
expect(wb.date).toBe('2026-08-05');
@@ -225,7 +225,7 @@ describe('choosing a release', () => {
it('steps through what the picker offers', async () => {
const wb = store();
await wb.loadReleases();
- await wb.loadChanges();
+ await wb.historyAt(at);
// the newest release shows the latest change's pixels here, so one step
// older is the change before it
expect(wb.step(1)).toBe(10);
diff --git a/frontend/src/tools/settings/ImageryTab.svelte b/frontend/src/tools/settings/ImageryTab.svelte
index d473810..98295b1 100644
--- a/frontend/src/tools/settings/ImageryTab.svelte
+++ b/frontend/src/tools/settings/ImageryTab.svelte
@@ -12,7 +12,9 @@
* before it matters, and past `BLOCK_SHARE` the app falls back to free imagery
* unless the analyst says otherwise.
*/
+ import { tick } from 'svelte';
import Icon from '../../components/Icon.svelte';
+ import RadarLayer from './RadarLayer.svelte';
import {
monthCount,
tilesOfFree,
@@ -43,6 +45,10 @@
saveFreeTier,
eco = $bindable(),
ecoMaxZoom = $bindable(),
+ /** The Sentinel-1 layer radar reads, inside the Copernicus card. */
+ radarLayer = $bindable(''),
+ /** A card asked for from another tool, opened once and scrolled to. */
+ focusCard = $bindable(''),
} = $props();
const perProvider = (value) => Object.fromEntries(KEYED.map((k) => [k.id, value(k)]));
@@ -52,6 +58,14 @@
let open = $state(perProvider(() => false));
let shown = $state(perProvider(() => false));
let termsOpen = $state(false);
+
+ $effect(() => {
+ const id = focusCard;
+ if (!id || !(id in open)) return;
+ open[id] = true;
+ focusCard = '';
+ void tick().then(() => document.getElementById(`card-${id}`)?.scrollIntoView({ block: 'start', behavior: 'smooth' }));
+ });
</script>
<section class="group">
@@ -74,7 +88,7 @@
overrides,
tiers,
})}
- <div class="card" class:open={open[k.id]}>
+ <div class="card" class:open={open[k.id]} id="card-{k.id}">
<div class="card-head">
<button
class="card-toggle"
@@ -175,6 +189,10 @@
</p>
{/if}
+ {#if k.id === 'sentinelhub' && keys[k.id]}
+ <RadarLayer bind:layer={radarLayer} onchanged={load} />
+ {/if}
+
<p class="overage">{k.cost}. {k.overage}</p>
{#if k.metered !== false && (keys[k.id] || count)}
diff --git a/frontend/src/tools/settings/RadarLayer.render.test.js b/frontend/src/tools/settings/RadarLayer.render.test.js
new file mode 100644
index 0000000..c0aacf0
--- /dev/null
+++ b/frontend/src/tools/settings/RadarLayer.render.test.js
@@ -0,0 +1,50 @@
+// @vitest-environment happy-dom
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { flushSync, mount, unmount } from 'svelte';
+
+const post = vi.fn();
+const put = vi.fn();
+vi.mock('../../lib/api.js', () => ({ api: { post, put } }));
+vi.mock('../../lib/state.svelte.js', () => ({ toast: vi.fn() }));
+const { default: RadarLayer } = await import('./RadarLayer.svelte');
+
+let live;
+let target;
+const settle = async () => { for (let i = 0; i < 20; i++) await Promise.resolve(); flushSync(); };
+const button = (text) => [...target.querySelectorAll('button')].find((node) => node.textContent.trim().startsWith(text));
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ target = document.createElement('div');
+ document.body.append(target);
+});
+afterEach(() => {
+ if (live) unmount(live);
+ live = null;
+ target.remove();
+});
+
+it('asks nothing until Find is pressed, then keeps the layer that answered', async () => {
+ const onchanged = vi.fn();
+ post.mockResolvedValue({ ok: true, layer: 'SAR_IW', detail: 'reads Sentinel-1 VV and VH', tried: [] });
+ live = mount(RadarLayer, { target, props: { layer: '', onchanged } });
+ flushSync();
+ expect(post).not.toHaveBeenCalled();
+ expect(target.querySelector('[aria-label="Sentinel-1 layer form"]').textContent).toContain('Sentinel-1 GRD');
+ expect(target.textContent).toContain('Any predefined product');
+ button('Find the radar layer').click(); await settle();
+ expect(post).toHaveBeenCalledWith('/api/satellite/sentinel1/layer', {});
+ expect(target.textContent).toContain('Radar reads SAR_IW');
+ expect(onchanged).toHaveBeenCalled();
+});
+
+it('says why a named layer is not a radar one', async () => {
+ post.mockResolvedValue({ ok: false, layer: 'TRUE_COLOR', detail: 'Band VV not found', tried: [] });
+ live = mount(RadarLayer, { target, props: { layer: '' } });
+ flushSync();
+ const field = target.querySelector('[aria-label="Sentinel-1 layer name"]');
+ field.value = 'TRUE_COLOR'; field.dispatchEvent(new Event('input', { bubbles: true })); flushSync();
+ button('Check').click(); await settle();
+ expect(post).toHaveBeenCalledWith('/api/satellite/sentinel1/layer', { layer: 'TRUE_COLOR' });
+ expect(target.textContent).toContain('Band VV not found');
+});
diff --git a/frontend/src/tools/settings/RadarLayer.svelte b/frontend/src/tools/settings/RadarLayer.svelte
new file mode 100644
index 0000000..0c4317e
--- /dev/null
+++ b/frontend/src/tools/settings/RadarLayer.svelte
@@ -0,0 +1,127 @@
+<script>
+ /**
+ * The Sentinel-1 layer, inside the Copernicus card.
+ *
+ * Radar comes through the same account and the same configuration, but only
+ * once a layer reading Sentinel-1 is added to it: Copernicus serves no radar
+ * otherwise. Nothing in the configuration says which layer reads what, so
+ * Find asks each new layer once with a tiny render only a radar layer can
+ * answer, and keeps the first that does. It never runs on its own.
+ */
+ import { api } from '../../lib/api.js';
+ import { toast } from '../../lib/state.svelte.js';
+ import Icon from '../../components/Icon.svelte';
+ import RadarForm from '../../components/RadarForm.svelte';
+ import { RADAR_STEPS } from '../../lib/copernicusSetup.js';
+
+ let { layer = $bindable(''), onchanged = () => {} } = $props();
+
+ let busy = $state(false);
+ let answer = $state(null);
+ let typed = $state('');
+
+ async function find(named = '') {
+ if (busy) return;
+ busy = true;
+ answer = null;
+ try {
+ answer = await api.post('/api/satellite/sentinel1/layer', named ? { layer: named } : {});
+ if (answer.ok) {
+ layer = answer.layer;
+ typed = '';
+ toast(`Radar reads ${answer.layer}`, 'ok');
+ onchanged();
+ }
+ } catch (error) {
+ answer = { ok: false, detail: error.message };
+ } finally {
+ busy = false;
+ }
+ }
+
+ async function forget() {
+ await api.put('/api/settings/prefs', { sentinel1_layer: '' });
+ layer = '';
+ answer = null;
+ onchanged();
+ }
+</script>
+
+<div class="radar">
+ <p class="head"><strong>Sentinel-1 radar</strong> <span>sees through cloud and at night</span></p>
+ {#if layer}
+ <p class="set"><Icon name="check" size={12} /> Radar reads <code>{layer}</code>.
+ <button class="linkish" onclick={forget}>Forget it</button></p>
+ {:else}
+ <ol class="key-steps">
+ {#each RADAR_STEPS as step (step)}<li>{step}</li>{/each}
+ </ol>
+ <RadarForm />
+ <div class="line">
+ <button class="btn btn-sm" disabled={busy} onclick={() => find()}>{busy ? 'Looking…' : 'Find the radar layer'}</button>
+ <input class="input mono" placeholder="or its name, e.g. RADAR" bind:value={typed} spellcheck="false"
+ aria-label="Sentinel-1 layer name" onkeydown={(event) => event.key === 'Enter' && typed.trim() && find(typed.trim())} />
+ <button class="btn btn-sm" disabled={busy || !typed.trim()} onclick={() => find(typed.trim())}>Check</button>
+ </div>
+ {/if}
+ {#if answer && !answer.ok}
+ <p class="verdict bad"><Icon name="alert" size={12} /> {answer.detail}</p>
+ {/if}
+</div>
+
+<style>
+ .radar {
+ display: grid;
+ gap: 6px;
+ margin-top: 10px;
+ padding-top: 10px;
+ border-top: 1px solid var(--border);
+ }
+ .head {
+ margin: 0;
+ font-size: var(--fs-xs);
+ }
+ .head span {
+ color: var(--text-3);
+ }
+ .set {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ margin: 0;
+ color: var(--ok, #46a758);
+ font-size: var(--fs-xs);
+ }
+ .line {
+ display: flex;
+ gap: 6px;
+ align-items: center;
+ }
+ .line .input {
+ flex: 1;
+ min-width: 0;
+ }
+ .key-steps {
+ margin: 0;
+ padding-left: 18px;
+ color: var(--text-2);
+ font-size: var(--fs-xs);
+ line-height: 1.5;
+ }
+ .verdict.bad {
+ display: flex;
+ gap: 6px;
+ margin: 0;
+ color: var(--danger, #e5484d);
+ font-size: var(--fs-xs);
+ }
+ .linkish {
+ background: none;
+ border: 0;
+ padding: 0;
+ color: var(--accent);
+ font-size: var(--fs-xs);
+ cursor: pointer;
+ text-decoration: underline;
+ }
+</style>
diff --git a/src/azimut/__init__.py b/src/azimut/__init__.py
index a3d63de..9140976 100644
--- a/src/azimut/__init__.py
+++ b/src/azimut/__init__.py
@@ -13,7 +13,7 @@ from PIL import Image as _Image
# The capture extension is versioned separately, on purpose — it carries the
# release that last changed it (tests/test_updates.py). Don't move the two
# together.
-__version__ = "0.3.0"
+__version__ = "0.3.1"
# Cap the pixels Pillow will decode from a file, process-wide. A tiny,
# highly-compressed image can otherwise expand to gigabytes in memory and take
diff --git a/src/azimut/api/analyzers.py b/src/azimut/api/analyzers.py
index 802638b..05183f9 100644
--- a/src/azimut/api/analyzers.py
+++ b/src/azimut/api/analyzers.py
@@ -3,18 +3,22 @@
from __future__ import annotations
import io
+import math
import secrets
from typing import Any, Literal
from fastapi import APIRouter, HTTPException
from fastapi.responses import Response
from PIL import Image, ImageDraw, ImageFont
-from pydantic import Field
+from pydantic import Field, ValidationError
from .. import config
from ..engine import analyzers as engine
-from ..engine import media, workqueue
-from ..engine.analysis_models import BUILTINS, METHODS, Model, Recipe, RunInput, ZoneSet
+from ..engine import analysis_export, analysis_geometry, media, workqueue
+from ..engine.analysis_models import (
+ BUILTINS, GROUPS, METHODS, RELIABILITY, SINGLE_METHODS, Area, AreaDates, AreaGeometry, Model, Recipe,
+ RunInput, ShortId, Source, Zone, ZoneSet,
+)
from .cases import delete_by_path, delete_entity_deep, get_case
router = APIRouter(prefix="/api", tags=["analyzers"])
@@ -22,15 +26,23 @@ router = APIRouter(prefix="/api", tags=["analyzers"])
@router.get("/compare/analyzers")
def recipes() -> dict[str, Any]:
+ settings = config.load_settings()
custom = []
- for raw in config.load_settings().get("analyzers", []):
+ for raw in settings.get("analyzers", []):
try:
custom.append(Recipe.model_validate(raw).model_dump())
except ValueError:
continue
return {"builtins": [r.model_dump() for r in BUILTINS], "custom": custom, "methods": METHODS,
"max_tiles": engine.MAX_TILES, "max_results": engine.MAX_RESULTS,
- "grid": list(engine.GRID)}
+ "grid": list(engine.GRID),
+ # what is locked: every analyzer without a Copernicus key, the
+ # radar ones until Settings has found their layer
+ "copernicus_key": bool((settings.get("api_keys") or {}).get("sentinelhub")),
+ "radar_layer": str(settings.get("sentinel1_layer") or ""),
+ "groups": [{"id": ident, "label": label, "recipes": members}
+ for ident, label, members in GROUPS],
+ "reliability": RELIABILITY}
@router.post("/compare/analyzers")
@@ -56,7 +68,7 @@ def delete_recipe(ident: str) -> dict[str, bool]:
return {"deleted": True}
-Kind = Literal["zones", "followups", "runs"]
+Kind = Literal["areas", "zones", "followups", "runs"]
def read(case: Any, kind: str, ident: str) -> dict[str, Any]:
@@ -78,6 +90,18 @@ def load_item(case_id: str, kind: Kind, ident: str) -> dict[str, Any]:
return read(get_case(case_id), kind, ident)
[email protected]("/cases/{case_id}/analysis/areas")
+def save_area(case_id: str, body: Area) -> dict[str, Any]:
+ return engine.save(get_case(case_id), "areas", body.model_dump())
+
+
[email protected]("/cases/{case_id}/analysis/areas/{ident}")
+def update_area(case_id: str, ident: str, body: Area) -> dict[str, Any]:
+ case = get_case(case_id)
+ read(case, "areas", ident)
+ return engine.save(case, "areas", body.model_dump(), ident)
+
+
@router.post("/cases/{case_id}/analysis/zones")
def save_zones(case_id: str, body: ZoneSet) -> dict[str, Any]:
return engine.save(get_case(case_id), "zones", body.model_dump())
@@ -104,25 +128,101 @@ def update_followup(case_id: str, ident: str, body: RunInput) -> dict[str, Any]:
return engine.save(case, "followups", body.model_dump(), ident)
[email protected]("/cases/{case_id}/analysis/runs")
-def start_run(case_id: str, body: RunInput) -> dict[str, Any]:
- case = get_case(case_id)
+def start(case: Any, body: RunInput) -> dict[str, Any]:
+ """Queue one run. Runs of a case wait their turn behind each other, so a
+ whole list of saved detections can be started at once; only the same
+ detection twice is refused, since the second would sweep what the first
+ is already sweeping."""
with engine.LOCK, case._lock:
- if any(row.get("status") in engine.ACTIVE for row in engine.listing(case, "runs")):
- raise HTTPException(409, "an analysis is already queued or running in this case")
+ body = engine.hydrate(case, body)
if body.followup_id:
read(case, "followups", body.followup_id)
+ if any(row.get("status") in engine.ACTIVE and row.get("followup_id") == body.followup_id
+ for row in engine.listing(case, "runs")):
+ raise HTTPException(409, "this detection is already queued or running")
try:
- planned = engine.plan(body)
+ plans = [engine.plan(engine.for_area(body, zone)) for zone in body.zones]
+ if sum(map(len, plans)) > engine.MAX_TILES:
+ raise ValueError("areas exceed the tile limit; split them into smaller runs")
except ValueError as exc:
raise HTTPException(422, str(exc)) from exc
- saved = engine.save(case, "runs", {"title": body.title, "input": body.model_dump(),
- "status": "queued", "progress": 0, "total": len(planned),
+ prepared, area_runs = engine.prepare_areas(case, body)
+ duplicates = engine.duplicates(case, prepared, area_runs)
+ if duplicates and not body.run_anyway:
+ return {"duplicates": duplicates, "input": prepared.model_dump()}
+ # Store the resolved pairs, not the launch request or its confirmation flag.
+ prepared = prepared.model_copy(update={"run_anyway": False})
+ saved = engine.save(case, "runs", {"title": body.title, "input": prepared.model_dump(),
+ "area_runs": area_runs,
+ "status": "queued", "progress": 0, "total": sum(map(len, plans)),
"results": [], "frames": {}, "count": 0, "message": ""})
workqueue.enqueue(case, engine.JOB, key=saved["id"], payload={"run_id": saved["id"]})
return saved
[email protected]("/cases/{case_id}/analysis/runs")
+def start_run(case_id: str, body: RunInput) -> dict[str, Any]:
+ return start(get_case(case_id), body)
+
+
+class RunAgain(Model):
+ """Which pass this run of a routine reads, when the analyst picked one.
+
+ A routine is relaunched against a day, not a rule: leaving this empty falls
+ back to the rule it was saved with, which looks the newest pass up itself.
+ """
+ date: str = Field(default="", max_length=10)
+ reference: str = Field(default="", max_length=10)
+ area_dates: list[AreaDates] | None = Field(default=None, max_length=32)
+ run_anyway: bool = False
+
+
[email protected]("/cases/{case_id}/analysis/followups/{ident}/run")
+def run_followup(case_id: str, ident: str, body: RunAgain | None = None) -> dict[str, Any]:
+ """Run a saved detection, on the pass asked for or on the rule it carries."""
+ case = get_case(case_id)
+ saved = read(case, "followups", ident)
+ fields = {key: saved[key] for key in RunInput.model_fields if key in saved}
+ chosen = body or RunAgain()
+ try:
+ run = RunInput.model_validate({**fields, "followup_id": ident})
+ if chosen.area_dates is not None:
+ run = RunInput.model_validate({**run.model_dump(), "area_dates": chosen.area_dates})
+ if chosen.date:
+ # A pass named here is this run's pass, so the rule has nothing left
+ # to look up: the reference it would have found is settled now, and
+ # the run records two fixed dates.
+ run = RunInput.model_validate({**run.model_dump(),
+ "b": {**run.b.model_dump(), "date": chosen.date},
+ "area_dates": [{**pair.model_dump(),
+ "date_rule": "manual" if chosen.reference or pair.date_rule != "latest_previous" else "latest_previous",
+ "a": {**pair.a.model_dump(), "date": chosen.reference or pair.a.date},
+ "b": {**pair.b.model_dump(), "date": chosen.date}}
+ for pair in run.area_dates]})
+ except ValidationError as exc:
+ reason = str(exc.errors()[0].get("msg", "")).removeprefix("Value error, ")
+ raise HTTPException(422, reason or "this detection needs editing before it can run") from exc
+ return start(case, run.model_copy(update={"run_anyway": chosen.run_anyway}))
+
+
[email protected]("/cases/{case_id}/analysis/followups/{ident}/findings")
+def followup_findings(case_id: str, ident: str) -> list[dict[str, Any]]:
+ """Everything this routine has found and nobody has dismissed."""
+ case = get_case(case_id)
+ read(case, "followups", ident)
+ return engine.findings(case, ident)
+
+
[email protected]("/cases/{case_id}/analysis/{kind}/{ident}/export")
+def export_layer(case_id: str, kind: Literal["runs", "followups"], ident: str) -> dict[str, Any]:
+ case = get_case(case_id)
+ read(case, kind, ident)
+ try:
+ return analysis_export.export(case, kind, ident)
+ except ValueError as exc:
+ raise HTTPException(422, str(exc)) from exc
+
+
@router.post("/cases/{case_id}/analysis/runs/{ident}/cancel")
def cancel_run(case_id: str, ident: str) -> dict[str, Any]:
case = get_case(case_id)
@@ -139,16 +239,21 @@ def delete_item(case_id: str, kind: Kind, ident: str) -> dict[str, Any]:
case = get_case(case_id)
with engine.LOCK, case._lock:
saved = read(case, kind, ident)
+ if kind == "areas":
+ used = [row["title"] for row in engine.listing(case, "followups")
+ if any(zone["id"] == ident for zone in row.get("zones", []))]
+ if used:
+ raise HTTPException(409, "Remove this area from these routines first: " + ", ".join(used))
if saved.get("status") in engine.ACTIVE:
raise HTTPException(409, "cancel the analysis before deleting it")
return delete_by_path(case, engine.relpath(kind, ident))
class Review(Model):
- # A candidate is "new" until an analyst looks at it. "kept" is set by
- # promotion, which is the act of keeping: nothing reaches the case without
- # it, so the two cannot drift apart.
- review: Literal["dismissed", "new"]
+ # A candidate is "new" until an analyst looks at it. "noted" keeps it in the
+ # detection's own findings and writes nothing to the case; "kept" is set by
+ # promotion, which is the act of keeping, so the two cannot drift apart.
+ review: Literal["dismissed", "new", "noted"]
def result_of(saved: dict[str, Any], result_id: str) -> dict[str, Any]:
@@ -169,10 +274,76 @@ def review_result(case_id: str, ident: str, result_id: str, body: Review) -> dic
if kept_entity(case, result):
raise HTTPException(409, "this candidate is a pin in the case; remove the pin first")
result.update(review=body.review, reviewed_at=engine.now(), entity_id=None)
+ if body.review == "dismissed":
+ saved["results"] = [row for row in saved["results"] if row["id"] != result_id]
+ saved["count"] = len(saved["results"])
engine.persist_run(case, saved)
return result
+class ManualPoint(Model):
+ type: Literal["Point"]
+ coordinates: tuple[float, float]
+
+
+class ManualCandidate(Model):
+ area_id: ShortId
+ geometry: ManualPoint | AreaGeometry
+
+
[email protected]("/cases/{case_id}/analysis/runs/{ident}/results")
+def add_manual(case_id: str, ident: str, body: ManualCandidate) -> dict[str, Any]:
+ case = get_case(case_id)
+ with engine.LOCK, case._lock:
+ saved = read(case, "runs", ident)
+ if saved.get("status") != "ready":
+ raise HTTPException(409, "finish the run before adding a candidate")
+ if len(saved["results"]) >= engine.MAX_RESULTS:
+ raise HTTPException(409, "this run has reached the candidate limit")
+ zone = next((Zone.model_validate(z) for z in saved["input"]["zones"] if z["id"] == body.area_id), None)
+ outcome = next((p for p in saved.get("area_runs", []) if p["area_id"] == body.area_id), None)
+ if zone is None or (outcome and outcome["status"] != "ready"):
+ raise HTTPException(422, "choose an area successfully read by this run")
+ shape = body.geometry.model_dump()
+ points = [shape["coordinates"]] if shape["type"] == "Point" else shape["coordinates"][0]
+ if not all(analysis_geometry.contains(zone.ring(), point) for point in points):
+ raise HTTPException(422, "the candidate must be inside its run area")
+ z, size = engine.GRID
+ grid = [engine.mercator(*point) for point in points]
+ left = math.floor(min(p[0] for p in grid) * (1 << z) * size)
+ top = math.floor(min(p[1] for p in grid) * (1 << z) * size)
+ right = max(left + 1, math.ceil(max(p[0] for p in grid) * (1 << z) * size))
+ bottom = max(top + 1, math.ceil(max(p[1] for p in grid) * (1 << z) * size))
+ source = outcome or saved["input"]
+ sources = [source["b"]] if saved["input"]["recipe"]["method"] in SINGLE_METHODS else [source["a"], source["b"]]
+ parts = []
+ for ty in range(top // size, (bottom - 1) // size + 1):
+ for tx in range(left // size, (right - 1) // size + 1):
+ keys = [engine._key(Source.model_validate(s), z, tx, ty, None) 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)
+ parts.append({"frames": keys, "box": [px - tx * size, py - ty * size,
+ min(right, (tx + 1) * size) - px, min(bottom, (ty + 1) * size) - py]})
+ if not parts:
+ raise HTTPException(422, "this run has no retained image at that location")
+ west, north = engine.geographic(left / ((1 << z) * size), top / ((1 << z) * size))
+ east, south = engine.geographic(right / ((1 << z) * size), bottom / ((1 << z) * size))
+ centre = list(points[0]) if shape["type"] == "Point" else [(west + east) / 2, (south + north) / 2]
+ mpp = engine.WORLD * math.cos(math.radians(centre[1])) / ((1 << z) * size)
+ row = {"id": f"manual-{secrets.token_hex(6)}", "origin": "manual", "area_id": zone.id,
+ "area_name": zone.name, "geometry": shape, "coordinates": centre,
+ "bbox": [west, south, east, north], "parts": parts, "review": "new",
+ "phenomenon": "Manual candidate", "margin": 0, "measure": {},
+ "area": (right - left) * (bottom - top) * mpp ** 2,
+ "width": (right - left) * mpp, "height": (bottom - top) * mpp,
+ "sources": {"a": source["a"], "b": source["b"]}}
+ saved["results"].append(row)
+ saved["count"] = len(saved["results"])
+ engine.persist_run(case, saved)
+ return row
+
+
# A candidate is a handful of pixels: a 30 m vessel is three of them. Blowing
# the crop up on the server, by a whole number and with no interpolation, is
# what makes it legible — the browser would otherwise stretch a 40 px thumbnail
@@ -180,6 +351,8 @@ def review_result(case_id: str, ident: str, result_id: str, body: Review) -> dic
# invents nothing, so what is on screen is still the sensor's own reading.
PREVIEW_EDGE = 320
PREVIEW_MARGIN = 20
+#: The two lines under the pictures: the point, then whose imagery it is.
+PREVIEW_FOOT = 40
# The most of the sweep one preview shows, in source pixels. A burn scar can be
# kilometres across; past this the crop is centred on the candidate.
PREVIEW_SPAN = 1024
@@ -188,6 +361,9 @@ PREVIEW_SPAN = 1024
def source_label(source: dict[str, Any]) -> str:
if source.get("provider") == "esri-wayback":
return f"Release {source.get('release')}"
+ if source.get("provider") == "sentinel1":
+ moment = f"{source.get('date') or ''} {str(source.get('time') or '')[:5]}".strip()
+ return f"{moment} UTC · radar" if source.get("time") else f"{moment or 'Sentinel-1'} · radar"
return str(source.get("date") or "Sentinel-2")
@@ -211,7 +387,24 @@ def _tile_image(case: Any, saved: dict[str, Any], source: dict[str, Any],
return None
-def preview_bytes(case: Any, saved: dict[str, Any], result: dict[str, Any]) -> bytes:
+def preview_captions(saved: dict[str, Any], result: dict[str, Any],
+ sources: list[dict[str, Any]]) -> tuple[list[str], list[str]]:
+ """What a candidate's picture says on its face: one label per image, and the foot.
+
+ A pinned crop is evidence and outlives the run that made it, so it carries
+ when each image was taken and where. A pair is lettered the way the maps
+ are; a single image names its own pass. The foot is the point, then whose
+ imagery it is.
+ """
+ labels = ([f"{letter} · {source_label(source)}" for letter, source in zip("AB", sources)]
+ if len(sources) > 1 else [source_label(sources[-1])])
+ lon, lat = result["coordinates"]
+ attribution = ("Esri World Imagery Wayback" if saved["input"]["b"].get("provider") == "esri-wayback"
+ else "Copernicus Sentinel data / Sentinel Hub")
+ return labels, [f"{lat:.5f}, {lon:.5f}", attribution]
+
+
+def preview_bytes(case: Any, saved: dict[str, Any], result: dict[str, Any], *, after_only: bool = False) -> bytes:
"""One picture per date, stitched across every tile the candidate touches.
A candidate that crosses a tile edge is still one thing, so it is shown as
@@ -226,6 +419,8 @@ def preview_bytes(case: Any, saved: dict[str, Any], result: dict[str, Any]) -> b
with Image.open(case.resolve_inside(first["path"])) as image:
size = image.width
sources = [saved["frames"][key]["source"] for key in result["parts"][0]["frames"]]
+ if after_only:
+ sources = sources[-1:]
boxes = []
for part in result["parts"]:
record = saved["frames"].get(part["frames"][0])
@@ -269,21 +464,19 @@ def preview_bytes(case: Any, saved: dict[str, Any], result: dict[str, Any]) -> b
band = 24
font = ImageFont.load_default(size=15)
small = ImageFont.load_default(size=12)
- # A pair is labelled the way the maps are; a single image has no other half
- # to tell it apart from, so it says which image it is instead.
- labels = ["A", "B"] if len(crops) > 1 else [source_label(saved["input"]["b"])]
+ labels, foot = preview_captions(saved, result, sources)
+ panels = [max(crop.width, math.ceil(font.getlength(label)) + 8) for label, crop in zip(labels, crops)]
body = max(crop.height for crop in crops)
- preview = Image.new("RGB", (sum(c.width for c in crops) + gap * (len(crops) - 1),
- body + band * 2), (20, 24, 32))
+ width = max(sum(panels) + gap * (len(crops) - 1), max(math.ceil(small.getlength(line)) for line in foot) + 8)
+ preview = Image.new("RGB", (width, band + body + PREVIEW_FOOT), (20, 24, 32))
drawing = ImageDraw.Draw(preview)
offset = 0
- for label, crop in zip(labels, crops):
- preview.paste(crop, (offset, band))
+ for label, crop, panel in zip(labels, crops, panels):
+ preview.paste(crop, (offset + (panel - crop.width) // 2, band))
drawing.text((offset + 4, 4), label, fill="white", font=font)
- offset += crop.width + gap
- attribution = ("Esri World Imagery Wayback" if saved["input"]["b"].get("provider") ==
- "esri-wayback" else "Copernicus Sentinel data / Sentinel Hub")
- drawing.text((4, band + body + 5), attribution, fill="#c8ced6", font=small)
+ offset += panel + gap
+ for row, line in enumerate(foot):
+ drawing.text((4, band + body + 5 + row * 16), line, fill="white" if row == 0 else "#c8ced6", font=small)
output = io.BytesIO()
preview.save(output, "PNG")
return output.getvalue()
@@ -299,6 +492,9 @@ def preview(case_id: str, ident: str, result_id: str) -> Response:
class Promotion(Model):
title: str = Field(min_length=1, max_length=120)
+ description: str = Field(default="", max_length=4000)
+ after_only: bool | None = None
+ shape: Literal["point", "area"] | None = None
@router.post("/cases/{case_id}/analysis/runs/{ident}/results/{result_id}/promote")
@@ -320,14 +516,25 @@ def promote(case_id: str, ident: str, result_id: str, body: Promotion) -> dict[s
# deleting the working run cannot remove evidence used by the case.
source = {"type": "compare", "analysis_run": ident, "candidate_id": result_id,
"input": saved["input"], "candidate": result, "engine_version": saved["engine_version"]}
- filed = media.import_rendered_bytes(case, preview_bytes(case, saved, result),
+ single = saved["input"]["recipe"]["method"] in SINGLE_METHODS
+ as_area = body.shape == "area" or (body.shape is None and not single)
+ geometry = result["geometry"] if as_area else {"type": "Point", "coordinates": result["coordinates"]}
+ if as_area and geometry["type"] == "Point":
+ raise HTTPException(422, "this candidate is a point; pin it as a point")
+ filed = media.import_rendered_bytes(case, preview_bytes(case, saved, result,
+ after_only=single if body.after_only is None else body.after_only),
body.title, ".png", source, by="compare")
lon, lat = result["coordinates"]
+ if as_area:
+ lon, lat = analysis_geometry.interior(geometry, (lon, lat))
entity = case.add_entity("place", body.title, attrs={"lat": lat, "lon": lon,
"zoom": 16, "analysis_run": ident, "candidate_id": result_id,
- "geometry": result["geometry"], "evidence": filed["item"]["path"],
+ "geometry": geometry, "description": body.description,
+ **({"footprint": geometry} if as_area else {}),
+ "evidence": filed["item"]["path"],
"analysis_provenance": source}, by="compare")
- result.update(entity_id=entity["id"], review="kept", reviewed_at=engine.now())
+ result.update(entity_id=entity["id"], review="kept", reviewed_at=engine.now(),
+ title=body.title, description=body.description, pinned_geometry=geometry)
engine.persist_run(case, saved)
return {"entity": entity, "image": filed["item"]["path"], "result": result}
diff --git a/src/azimut/api/cases/common.py b/src/azimut/api/cases/common.py
index 199df87..898949a 100644
--- a/src/azimut/api/cases/common.py
+++ b/src/azimut/api/cases/common.py
@@ -12,6 +12,7 @@ re-derived per surface.
from __future__ import annotations
+import json
from typing import Any
from fastapi import HTTPException
@@ -65,6 +66,29 @@ def delete_entities_deep(case: Case, entity_ids: list[str]) -> dict[str, Any]:
tombstoned.update(entity["id"] for entity in plan["tombstone"])
going = list(going_by_id.values())
+ # Shared Detect areas must not leave surviving routines with broken references.
+ # Read their stored references under the case lock, without taking the
+ # analyzer worker lock in the opposite order.
+ area_ids = {str(e.get("attrs", {}).get("spec", "")).removesuffix(".json").rsplit("-", 1)[-1]
+ for e in going if e.get("type") == "analysis-area"}
+ if area_ids:
+ removed_specs = {e.get("attrs", {}).get("spec") for e in going}
+ users = []
+ for routine in case.list_entities():
+ if routine.get("type") != "analysis-follow-up":
+ continue
+ spec = routine.get("attrs", {}).get("spec")
+ if not spec or spec in removed_specs:
+ continue
+ try:
+ saved = json.loads(case.resolve_inside(spec).read_text(encoding="utf-8"))
+ except (OSError, ValueError):
+ continue
+ if any(pair.get("area_id") in area_ids for pair in saved.get("area_dates", [])):
+ users.append(routine["label"])
+ if users:
+ raise HTTPException(409, "Remove this area from these routines first: " + ", ".join(users))
+
scars: list[dict[str, str]] = []
losses = link_engine.losses(case, {e["id"] for e in going})
for survivor_id, lost_sources in losses.items():
diff --git a/src/azimut/api/compare.py b/src/azimut/api/compare.py
index a23f99f..65cb3a2 100644
--- a/src/azimut/api/compare.py
+++ b/src/azimut/api/compare.py
@@ -26,7 +26,7 @@ from typing import Any, Literal
from fastapi import APIRouter, File, Form, HTTPException, UploadFile
from fastapi.responses import Response
from PIL import Image
-from pydantic import BaseModel, Field, model_validator
+from pydantic import BaseModel, Field, field_validator, model_validator
from .. import config, layout
from ..engine import artifacts as artifact_engine
@@ -67,6 +67,13 @@ class CompareSentinel(BaseModel):
maxcc: int = Field(default=100, ge=0, le=100)
+class CompareRadar(BaseModel):
+ """A Sentinel-1 pass: its day and its UTC time, which says which look."""
+
+ date: str = Field(default="", pattern=_DAY)
+ time: str = Field(default="", pattern=r"^$|^([01]\d|2[0-3]):[0-5]\d:[0-5]\d$")
+
+
class CompareFirms(BaseModel):
sensor: str = Field(default="viirs", min_length=1, max_length=50)
window: str = Field(default="24h", min_length=1, max_length=20)
@@ -85,6 +92,7 @@ class CompareSide(BaseModel):
overlays: list[str] = Field(default_factory=list, max_length=len(OVERLAYS))
sentinel: CompareSentinel = Field(default_factory=CompareSentinel)
wayback_release: int | None = Field(default=None, ge=1)
+ radar: CompareRadar = Field(default_factory=CompareRadar)
firms: CompareFirms = Field(default_factory=CompareFirms)
nightlights: CompareNightlights = Field(default_factory=CompareNightlights)
@@ -121,9 +129,8 @@ class CompareChangeAssist(BaseModel):
palette: Literal["directional", "colourblind", "thermal"] = "directional"
zones: bool = True
opacity: int = Field(default=70, ge=0, le=100)
- # "side" lays the same reading over both images instead of one of them.
- base: Literal["a", "b", "side"] = "b"
- visible: bool = True
+ # Which images carry the highlights, in whatever view mode the pair is read.
+ base: Literal["a", "b", "both"] = "both"
# Flashing the overlay on and off, which is easier to catch than a still one.
blink: bool = False
@@ -170,6 +177,14 @@ class CompareAnnotation(BaseModel):
#: that set lives in the browser and grows there, and a name this build does
#: not know is drawn as the first symbol rather than refused on the way in.
glyph: str = Field(default="", max_length=40)
+ #: The compass direction that was up on the screen a box or an ellipse was
+ #: drawn on, in degrees: its sides run along that screen, not along north.
+ angle: float = Field(default=0, allow_inf_nan=False)
+
+ @field_validator("angle")
+ @classmethod
+ def _fold(cls, value: float) -> float:
+ return value % 360
@model_validator(mode="after")
def _shape(self) -> "CompareAnnotation":
@@ -197,6 +212,14 @@ class CompareFrame(BaseModel):
#: ``[lon, lat]`` pairs, in the order they were drawn.
points: list[tuple[float, float]] = Field(min_length=2, max_length=2)
+ #: The compass direction that was up when the frame was drawn, which is
+ #: the way up it is exported at.
+ angle: float = Field(default=0, allow_inf_nan=False)
+
+ @field_validator("angle")
+ @classmethod
+ def _fold(cls, value: float) -> float:
+ return value % 360
@model_validator(mode="after")
def _ground(self) -> "CompareFrame":
@@ -211,7 +234,9 @@ class CompareFrame(BaseModel):
class CompareSpec(BaseModel):
version: Literal[2] = 2
camera: CompareCamera
- mode: Literal["side", "swipe", "opacity", "blink", "change"] = "side"
+ mode: Literal["side", "swipe", "opacity", "blink"] = "side"
+ #: Highlights laid over the view mode, not a mode of their own.
+ difference: bool = False
divider: int = Field(default=50, ge=0, le=100)
opacity: int = Field(default=50, ge=0, le=100)
blink: CompareBlink = Field(default_factory=CompareBlink)
@@ -256,7 +281,7 @@ def _validated_spec(spec: CompareSpec) -> dict[str, Any]:
mark["points"] = [list(point) for point in mark["points"]]
if cleaned["frame"]:
cleaned["frame"]["points"] = [list(point) for point in cleaned["frame"]["points"]]
- if cleaned["mode"] == "change":
+ if cleaned["difference"]:
reason = change_refusal(cleaned["a"], cleaned["b"], assist["method"])
if reason:
raise HTTPException(status_code=422, detail=reason)
@@ -308,6 +333,17 @@ def change_refusal(a: dict[str, Any], b: dict[str, Any], method: str = "colour")
if not _same_layers(a, b):
return "Match the reference layers on A and B"
return None
+ if a["provider"] == b["provider"] == sentinel.RADAR_ID:
+ radar_a, radar_b = a.get("radar") or {}, b.get("radar") or {}
+ if not radar_a.get("date") or not radar_b.get("date"):
+ return "Choose a dated Sentinel-1 pass on both sides"
+ if (radar_a["date"], radar_a.get("time")) == (radar_b["date"], radar_b.get("time")):
+ return "Choose two different Sentinel-1 passes"
+ if not sentinel.same_track(radar_a.get("time", ""), radar_b.get("time", "")):
+ return "Radar compares two passes of one track, at the same time of day"
+ if not _same_layers(a, b):
+ return "Match the reference layers on A and B"
+ return None
if {a["provider"], b["provider"]} <= _ESRI_CHAIN:
same_picture = (
a["provider"] == b["provider"]
@@ -341,7 +377,8 @@ def change_refusal(a: dict[str, Any], b: dict[str, Any], method: str = "colour")
if not _same_layers(a, b, skip="nightlights"):
return "Match every other layer on A and B"
return None
- return "Difference reads Sentinel-2, Esri imagery releases or VIIRS night-light pairs"
+ return ("Difference reads Sentinel-2, Sentinel-1 on one track, Esri imagery releases or "
+ "VIIRS night-light pairs")
def _read_session(case: Case, name: str) -> dict[str, Any] | None:
diff --git a/src/azimut/api/satellite.py b/src/azimut/api/satellite.py
index 693cd33..165abdc 100644
--- a/src/azimut/api/satellite.py
+++ b/src/azimut/api/satellite.py
@@ -11,7 +11,7 @@ import tempfile
# 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 pathlib import Path
-from typing import Any
+from typing import Any, Literal
import httpx
from fastapi import APIRouter, Form, HTTPException, Query, UploadFile
@@ -45,6 +45,9 @@ from .. import layout
router = APIRouter(prefix="/api", tags=["satellite"])
+# How many layers a search for the Sentinel-1 one may ask about, each a request.
+MAX_RADAR_PROBES = 6
+
# A live map pans through dozens of tiles at once, all proxied through here. A
# fresh connection per tile means a TCP + TLS handshake per tile — the dominant
@@ -257,8 +260,11 @@ def sentinel_layers(check: bool = False) -> dict[str, Any]:
@router.get("/satellite/sentinel/dates")
-def sentinel_dates(lat: float, lon: float, start: str, end: str) -> dict[str, Any]:
- """Sentinel-2 acquisition dates over a point, newest first.
+def sentinel_dates(
+ lat: float, lon: float, start: str, end: str,
+ collection: Literal["sentinel2", "sentinel1"] = "sentinel2",
+) -> dict[str, Any]:
+ """Sentinel-2 acquisition dates over a point, newest first, or Sentinel-1 passes.
User-triggered only (a date picker being opened/moved) — never on mount.
Billed as one request on the sentinelhub meter: a WFS query is ~0.01 PU
@@ -273,7 +279,10 @@ def sentinel_dates(lat: float, lon: float, start: str, end: str) -> dict[str, An
"free tier is used; enable the override in Settings to keep going",
)
try:
- found = sentinel.dates(instance, lat, lon, start, end)
+ found = sentinel.dates(instance, lat, lon, start, end, collection=collection)
+ 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: {exc}") from exc
config.record_usage("sentinelhub", 1)
@@ -286,6 +295,8 @@ class AcquisitionQuery(BaseModel):
zones: list[Zone] = Field(min_length=1, max_length=32)
start: str = Field(pattern=r"^\d{4}-\d{2}-\d{2}$")
end: str = Field(pattern=r"^\d{4}-\d{2}-\d{2}$")
+ # Radar methods sweep Sentinel-1 passes, which come with a time and a direction.
+ collection: Literal["sentinel2", "sentinel1"] = "sentinel2"
@router.post("/satellite/sentinel/acquisitions")
@@ -309,7 +320,8 @@ 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
+ instance, [list(zone.ring()) for zone in body.zones], body.start, body.end,
+ collection=body.collection,
)
except ValueError as exc:
raise HTTPException(status_code=422, detail=str(exc)) from exc
@@ -319,6 +331,58 @@ def sentinel_acquisitions(body: AcquisitionQuery) -> dict[str, Any]:
return {**found, "start": body.start, "end": body.end}
+class RadarLayerQuery(BaseModel):
+ """A layer to check, or none to look for one."""
+
+ layer: str = Field(default="", pattern=r"^$|^[A-Z0-9_]{1,40}$")
+
+
[email protected]("/satellite/sentinel1/layer")
+def sentinel1_layer(body: RadarLayerQuery) -> dict[str, Any]:
+ """Find or check the Sentinel-1 layer Detect's radar methods read, and keep it.
+
+ Copernicus says which collections an instance's layers read (WFS, free) but
+ not which layer reads which, so each candidate is asked with one tiny render
+ that only a Sentinel-1 layer with VV and VH can answer. Looking skips the
+ layers the Sentinel-2 templates ship and stops at the first that answers.
+ User-triggered only; every probe is one request on the meter.
+ """
+ instance = _sentinel_instance()
+ if config.usage_blocked("sentinelhub"):
+ raise HTTPException(
+ status_code=429,
+ detail=f"Sentinel Hub is paused: {int(config.BLOCK_SHARE * 100)}% of the monthly "
+ "free tier is used; enable the override in Settings to keep going",
+ )
+ try:
+ if body.layer:
+ candidates = [body.layer]
+ else:
+ if not sentinel.serves_sentinel1(instance):
+ return {"ok": False, "layer": "", "serves": False, "tried": [],
+ "detail": "this instance has no Sentinel-1 layer yet"}
+ candidates = [entry["id"] for entry in sentinel.capabilities_layers(instance)
+ if entry["id"] not in sentinel.TEMPLATE_LAYERS][:MAX_RADAR_PROBES]
+ tried: list[dict[str, Any]] = []
+ for layer in candidates:
+ try:
+ answer = sentinel.probe_sar_layer(instance, layer)
+ finally:
+ config.record_usage("sentinelhub", 1)
+ tried.append(answer)
+ if answer["ok"]:
+ config.update_settings(lambda settings: settings.update(sentinel1_layer=layer))
+ return {**answer, "serves": True, "tried": tried}
+ except HTTPException:
+ raise
+ except Exception as exc:
+ raise HTTPException(status_code=502, detail=f"layer check failed: {exc}") from exc
+ detail = (tried[-1]["detail"] if body.layer and tried else
+ "no layer of this instance reads Sentinel-1 VV and VH")
+ return {"ok": False, "layer": body.layer, "serves": None if body.layer else True,
+ "tried": tried, "detail": detail}
+
+
@router.get("/satellite/sentinel/coverage")
def sentinel_coverage(
lat: float, lon: float, layer: str, date: str, maxcc: int = sentinel.DEFAULT_MAXCC
@@ -369,8 +433,9 @@ def wayback_changes(
"""The distinct pictures of a point, newest first, each with the release
that first published it and when it was taken.
- A few small requests per picture found, so it is asked while the picker is
- open and answered from memory for the same tile afterwards.
+ A few small requests per picture found, so it is asked only when the
+ analyst asks for the changes, and answered from memory for the same tile
+ afterwards.
"""
try:
found = wayback.local_changes(lat, lon, zoom)
diff --git a/src/azimut/api/settings.py b/src/azimut/api/settings.py
index 9b71728..8be7670 100644
--- a/src/azimut/api/settings.py
+++ b/src/azimut/api/settings.py
@@ -33,7 +33,7 @@ from ..engine import (
workspacemove,
)
from .templates import MAX_PER_KIND as MAX_TEMPLATES_PER_KIND
-from ..engine.analysis_models import Recipe
+from ..engine.analysis_models import DetectPrefs, Recipe
# A backup carries the signature logo as base64: 4 characters per 3 bytes, plus
# slack for padding and any line breaks a hand-edited file picked up.
@@ -102,6 +102,9 @@ class PrefsIn(BaseModel):
coord_format: str | None = None # one of config.COORD_FORMATS
units: str | None = None # one of config.UNIT_SYSTEMS
home_view: HomeView | None = None # where the Satellite tab opens
+ detect_view: DetectPrefs | None = None
+ # the Sentinel-1 layer radar detections read; "" forgets it
+ sentinel1_layer: str | None = Field(default=None, pattern=r"^$|^[A-Z0-9_]{1,40}$")
# burn a scale bar and a north arrow into captures (the capture menu's tick)
capture_scale_north: bool | None = None
# whether saving a proof files its point as a place, or asks first
@@ -134,6 +137,8 @@ def _prefs(settings: dict[str, Any]) -> dict[str, Any]:
"coord_format": settings.get("coord_format", "dd"),
"units": settings.get("units", "metric"),
"home_view": settings.get("home_view", DEFAULT_HOME_VIEW),
+ "detect_view": settings.get("detect_view", config.DEFAULT_SETTINGS["detect_view"]),
+ "sentinel1_layer": settings.get("sentinel1_layer", ""),
"capture_scale_north": bool(settings.get("capture_scale_north", False)),
"proof_place_auto": bool(settings.get("proof_place_auto", True)),
"post_mention": settings.get("post_mention", DEFAULT_POST_MENTION),
@@ -263,6 +268,10 @@ def _apply_prefs(settings: dict[str, Any], body: PrefsIn) -> None:
settings["units"] = body.units
if body.home_view is not None:
settings["home_view"] = body.home_view.model_dump()
+ if body.detect_view is not None:
+ settings["detect_view"] = body.detect_view.model_dump()
+ if body.sentinel1_layer is not None:
+ settings["sentinel1_layer"] = body.sentinel1_layer
if body.capture_scale_north is not None:
settings["capture_scale_north"] = bool(body.capture_scale_north)
if body.proof_place_auto is not None:
@@ -313,6 +322,9 @@ def put_keys(body: KeysIn) -> dict[str, Any]:
# about the old key, and a stale failure would keep the basemap
# benched (tiles.key_for) with no way back but a manual re-test
status.pop(name, None)
+ if name == "sentinelhub":
+ # the radar layer was one of the old instance's layers
+ settings["sentinel1_layer"] = ""
if value:
keys[name] = value
else:
@@ -615,6 +627,8 @@ class ImportedSettings(BaseModel):
model_config = ConfigDict(extra="ignore", strict=True, populate_by_name=True)
analyzers: list[Recipe] = Field(default_factory=list, max_length=100)
+ detect_view: DetectPrefs = Field(default_factory=DetectPrefs)
+ sentinel1_layer: str = Field(default="", pattern=r"^$|^[A-Z0-9_]{1,40}$")
schema_version: int = Field(
default=config.SETTINGS_SCHEMA,
diff --git a/src/azimut/config.py b/src/azimut/config.py
index 2bc067c..d4d89ad 100644
--- a/src/azimut/config.py
+++ b/src/azimut/config.py
@@ -48,6 +48,10 @@ SETTINGS_SCHEMA = 1
DEFAULT_SETTINGS: dict[str, Any] = {
"analyzers": [], # portable custom recipes shared by all cases
+ # 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},
# 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_export.py b/src/azimut/engine/analysis_export.py
new file mode 100644
index 0000000..af177e1
--- /dev/null
+++ b/src/azimut/engine/analysis_export.py
@@ -0,0 +1,57 @@
+"""On-demand snapshots of reviewed detections into a case's map layers."""
+
+from __future__ import annotations
+
+import colorsys
+import json
+from typing import Any
+
+from .. import layout
+from ..workspace import Case
+from . import analyzers, maplayers
+from .analysis_models import SINGLE_METHODS
+
+
+def export(case: Case, kind: str, ident: str) -> dict[str, Any]:
+ with analyzers.LOCK, case._lock:
+ item = analyzers.read(case, kind, ident)
+ routine = ident if kind == "followups" else item["input"].get("followup_id")
+ key = f"followups-{routine}" if routine else f"runs-{ident}"
+ existing = next((row for row in maplayers.listing(case)
+ if row["source"].get("detection_key") == key), None)
+ document: dict[str, Any] = {"type": "FeatureCollection", "azimut_detect_layer": 1,
+ "name": item["title"], "features": []}
+ if existing:
+ document = json.loads(case.resolve_inside(layout.layer_snapshot_rel(existing["name"])).read_bytes())
+ if kind == "followups":
+ runs = [analyzers.read(case, "runs", row["id"]) for row in reversed(analyzers.listing(case, "runs"))
+ if row.get("followup_id") == ident and row.get("status") == "ready"]
+ else:
+ if item.get("status") != "ready":
+ raise ValueError("finish the run before exporting it")
+ runs = [item]
+ for run in runs:
+ pairs = run.get("area_runs") or [{"status": "ready", "b": run["input"]["b"]}]
+ dates = {p["b"]["date"] for p in pairs if p["status"] == "ready"}
+ document["features"] = [f for f in document["features"] if f["properties"]["pass_date"] not in dates]
+ recipe = run["input"]["recipe"]
+ for row in run["results"]:
+ if row["review"] not in analyzers.KEPT:
+ continue
+ day = row.get("sources", run["input"])["b"]["date"]
+ geometry = row.get("pinned_geometry") or (row["geometry"] if row.get("origin") == "manual" else (
+ {"type": "Point", "coordinates": row["coordinates"]}
+ if recipe["method"] in SINGLE_METHODS else row["geometry"]))
+ document["features"].append({"type": "Feature", "geometry": geometry, "properties": {
+ "name": row.get("title") or row["phenomenon"], "description": row.get("description", ""),
+ "category": day, "pass_date": day, "detector": recipe["name"],
+ "area_name": row.get("area_name", ""), "run_id": run["id"],
+ }})
+ days = sorted({f["properties"]["pass_date"] for f in document["features"]})
+ for feature in document["features"]:
+ rank = days.index(feature["properties"]["pass_date"])
+ lightness = .78 - .48 * rank / max(1, len(days) - 1)
+ rgb = colorsys.hls_to_rgb(210 / 360, lightness, .70)
+ colour = "#" + "".join(f"{round(channel * 255):02x}" for channel in rgb)
+ feature["properties"].update({"marker-color": colour, "stroke": colour, "fill": colour})
+ return maplayers.save_detection_snapshot(case, key, document["name"], document)
diff --git a/src/azimut/engine/analysis_geometry.py b/src/azimut/engine/analysis_geometry.py
new file mode 100644
index 0000000..0c10f7b
--- /dev/null
+++ b/src/azimut/engine/analysis_geometry.py
@@ -0,0 +1,113 @@
+"""Pixel-edge footprints. Only post-processing; the detector mask stays intact."""
+
+from __future__ import annotations
+
+from collections import defaultdict
+from typing import Any
+
+
+def contains(ring: list, point: tuple[float, float]) -> bool:
+ x, y = point
+ inside = False
+ for a, b in zip(ring, ring[1:] + ring[:1]):
+ cross = (x - a[0]) * (b[1] - a[1]) - (y - a[1]) * (b[0] - a[0])
+ if abs(cross) < 1e-12 and min(a[0], b[0]) <= x <= max(a[0], b[0]) and min(a[1], b[1]) <= y <= max(a[1], b[1]):
+ return True
+ if (a[1] > y) != (b[1] > y) and x < (b[0] - a[0]) * (y - a[1]) / (b[1] - a[1]) + a[0]:
+ inside = not inside
+ return inside
+
+
+def outlines(mask: Any) -> list[list[list[tuple[int, int]]]]:
+ """Trace cell boundaries, preserving holes and diagonal-only components.
+
+ Collinear vertices are removed without moving any edge or closing a gap.
+ At a corner shared by two pixels the right turn keeps their rings separate.
+ """
+ import numpy as np
+
+ cells = np.pad(np.asarray(mask, dtype=bool), 1)
+ core = cells[1:-1, 1:-1]
+ edges: dict[tuple[int, int], set[tuple[int, int]]] = defaultdict(set)
+ for exposed, start, end in (
+ (core & ~cells[:-2, 1:-1], (0, 0), (1, 0)),
+ (core & ~cells[1:-1, 2:], (1, 0), (1, 1)),
+ (core & ~cells[2:, 1:-1], (1, 1), (0, 1)),
+ (core & ~cells[1:-1, :-2], (0, 1), (0, 0)),
+ ):
+ ys, xs = np.nonzero(exposed)
+ for x, y in zip(xs.tolist(), ys.tolist()):
+ edges[(x + start[0], y + start[1])].add((x + end[0], y + end[1]))
+ directions = {(1, 0): 0, (0, 1): 1, (-1, 0): 2, (0, -1): 3}
+ rings = []
+ while edges:
+ start = next(iter(edges))
+ ring = [start]
+ current = start
+ direction = None
+ while True:
+ options = edges[current]
+ def priority(end: tuple[int, int]) -> int:
+ heading = directions[(end[0] - current[0], end[1] - current[1])]
+ return {1: 0, 0: 1, 3: 2, 2: 3}[(heading - direction) % 4] if direction is not None else heading
+ following = min(options, key=priority)
+ options.remove(following)
+ if not options:
+ del edges[current]
+ direction = directions[(following[0] - current[0], following[1] - current[1])]
+ current = following
+ if current == start:
+ break
+ ring.append(current)
+ simplified = []
+ for i, point in enumerate(ring):
+ a, b = ring[i - 1], ring[(i + 1) % len(ring)]
+ if (point[0] - a[0]) * (b[1] - point[1]) != (point[1] - a[1]) * (b[0] - point[0]):
+ simplified.append(point)
+ if simplified:
+ simplified.append(simplified[0])
+ rings.append(simplified)
+ def signed(ring: list) -> float:
+ return sum(a[0] * b[1] - b[0] * a[1] for a, b in zip(ring, ring[1:]))
+ polygons = [[ring] for ring in rings if signed(ring) > 0]
+ for hole in (ring for ring in rings if signed(ring) < 0):
+ owners = [polygon for polygon in polygons if contains(polygon[0], hole[0])]
+ if owners:
+ min(owners, key=lambda polygon: abs(signed(polygon[0]))).append(hole)
+ return polygons
+
+
+def footprint(mask: Any, x: int, y: int, z: int, size: int, offset=(0, 0)) -> dict[str, Any]:
+ from .analyzers import geographic
+
+ polygons = [[[
+ list(geographic((x + (px + offset[0]) / size) / (1 << z),
+ (y + (py + offset[1]) / size) / (1 << z)))
+ for px, py in reversed(ring)] for ring in polygon] for polygon in outlines(mask)]
+ return {"type": "Polygon", "coordinates": polygons[0]} if len(polygons) == 1 else {
+ "type": "MultiPolygon", "coordinates": polygons}
+
+
+def joined(a: dict[str, Any], b: dict[str, Any]) -> dict[str, Any]:
+ def parts(shape: dict[str, Any]) -> list:
+ return [shape["coordinates"]] if shape["type"] == "Polygon" else shape["coordinates"]
+ return {"type": "MultiPolygon", "coordinates": parts(a) + parts(b)}
+
+
+def interior(geometry: dict[str, Any], preferred: tuple[float, float]) -> tuple[float, float]:
+ """Choose a point inside a footprint, including a concave or merged one."""
+ polygons = [geometry["coordinates"]] if geometry["type"] == "Polygon" else geometry["coordinates"]
+ for polygon in polygons:
+ if contains(polygon[0], preferred) and not any(contains(hole, preferred) for hole in polygon[1:]):
+ return preferred
+ for polygon in polygons:
+ ys = sorted({p[1] for ring in polygon for p in ring})
+ for low, high in zip(ys, ys[1:]):
+ y = (low + high) / 2
+ xs = sorted(a[0] + (y - a[1]) * (b[0] - a[0]) / (b[1] - a[1])
+ for ring in polygon for a, b in zip(ring, ring[1:])
+ if (a[1] > y) != (b[1] > y))
+ for left, right in zip(xs[::2], xs[1::2]):
+ if right > left:
+ return ((left + right) / 2, y)
+ raise ValueError("the footprint has no interior")
diff --git a/src/azimut/engine/analysis_models.py b/src/azimut/engine/analysis_models.py
index e020d97..6650a30 100644
--- a/src/azimut/engine/analysis_models.py
+++ b/src/azimut/engine/analysis_models.py
@@ -1,6 +1,7 @@
"""Portable recipes and geographic inputs for Compare's Detect mode.
-Detect reads Copernicus Sentinel-2 only. Every method measures reflectance,
+Detect reads Copernicus only: Sentinel-2's reflectance for the optical methods
+and Sentinel-1's radar backscatter for the radar ones. Both are measurements,
which a rendered picture has already stretched away, so a source that serves
pictures has nothing to offer it. Models describe capabilities by stable ids,
and a saved run keeps meaning what it meant when it ran.
@@ -12,22 +13,36 @@ import math
from datetime import date
from typing import Annotated, Any, Literal
-from pydantic import BaseModel, ConfigDict, Field, FiniteFloat, model_validator
-
-Method = Literal["vessels", "hotspots", "structure", "spots", "surface", "index"]
+from pydantic import (
+ BaseModel,
+ ConfigDict,
+ Field,
+ FiniteFloat,
+ SerializerFunctionWrapHandler,
+ model_serializer,
+ model_validator,
+)
+
+Method = Literal["vessels", "hotspots", "structure", "spots", "surface", "index",
+ "sar-vessels", "sar-change"]
Index = Literal["ndvi", "ndwi", "mndwi", "nbr", "ndbi", "bsi"]
ShortId = Annotated[str, Field(pattern=r"^[a-zA-Z0-9_-]{1,48}$")]
Colour = Annotated[str, Field(pattern=r"^#[0-9a-fA-F]{6}$")]
# Methods that read one image instead of a pair. A vessel or a fire is a thing
# present on a date, not a difference between two of them.
-SINGLE_METHODS = frozenset({"vessels", "hotspots"})
+SINGLE_METHODS = frozenset({"vessels", "hotspots", "sar-vessels"})
+
+# Methods that read Sentinel-1's radar rather than Sentinel-2. Radar sees
+# through cloud and at night, which is why they exist beside the optical ones.
+RADAR_METHODS = frozenset({"sar-vessels", "sar-change"})
# The band product each method measures, fetched beside the picture the analyst
# reviews. `index` reads the one its parameters name.
PRODUCT_METHODS: dict[str, str] = {
"vessels": "vessel", "hotspots": "fire",
"structure": "surface", "spots": "surface", "surface": "surface",
+ "sar-vessels": "sar", "sar-change": "sar",
}
# Where the cloud and shadow switches mean something. The fire test rejects
@@ -47,10 +62,23 @@ def product_for(method: str, index: str) -> str:
return f"index-{index}" if method == "index" else PRODUCT_METHODS[method]
+def sensor_for(method: str) -> str:
+ """The Copernicus collection a method reads."""
+ return "sentinel1" if method in RADAR_METHODS else "sentinel2"
+
+
class Model(BaseModel):
model_config = ConfigDict(extra="forbid", allow_inf_nan=False)
+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", "labels", "roads", "railway", "power", "seamarks", "gpstraces"]] = Field(
+ default=["boundaries"], max_length=7)
+ saved: bool = True
+
+
class Parameters(Model):
# Moves each method's threshold inside the range it was calibrated over
# (engine/analyzers.py), so the same number means "about as picky" everywhere.
@@ -63,6 +91,9 @@ class Parameters(Model):
smoothing: int = Field(default=0, ge=0, le=3)
index: Index = "ndvi"
direction: Literal["both", "gain", "loss"] = "both"
+ # Where a radar change counts: anywhere, on ground bright enough to be
+ # built-up or metal on the side that has it, or where open water came or went.
+ sar_ground: Literal["any", "bright", "water"] = "any"
ignore_clouds: bool = True
ignore_shadows: bool = True
# Metres are what a reader thinks in, but the mask is grown on the grid, and
@@ -103,6 +134,10 @@ SIZES: dict[str, dict[str, dict[str, float]]] = {
"spots": _sizes((0, 800, 0, 0, 0), (100, 2500, 0, 0, 0), (400, 8000, 0, 0, 20)),
"surface": _CHANGE_SIZES,
"index": _CHANGE_SIZES,
+ # Radar pixels are 10 m like Sentinel-2's, and speckle is what smoothing
+ # works against: a small target keeps the finest window.
+ "sar-vessels": _sizes((0, 150_000, 0, 0, 30), (250, 150_000, 0, 0, 50), (2500, 400_000, 0, 0, 100)),
+ "sar-change": _sizes((300, 0, 0, 1, 0), (2000, 0, 1, 2, 30), (20000, 0, 1, 3, 100)),
}
@@ -153,24 +188,28 @@ class Recipe(Model):
parameters: Parameters = Field(default_factory=Parameters)
colour: Colour = "#f6a81a"
style: Literal["pins", "outlines", "both"] = "both"
- zones: list[Zone] = Field(default_factory=list, max_length=32)
@model_validator(mode="before")
@classmethod
def legacy(cls, data: Any) -> Any:
if not isinstance(data, dict):
return data
- data = {key: value for key, value in data.items() if key != "providers"}
+ # Areas belong to a saved detection, not to what it looks for. An
+ # analyzer saved with areas of its own still loads, without them.
+ data = {key: value for key, value in data.items() if key not in ("providers", "zones")}
if data.get("method") in LEGACY_METHODS:
data["method"] = LEGACY_METHODS[data["method"]]
return data
class Source(Model):
- provider: Literal["sentinel2"] = "sentinel2"
+ provider: Literal["sentinel2", "sentinel1"] = "sentinel2"
date: str = Field(default="", max_length=10)
layer: str = Field(default="TRUE_COLOR", pattern=r"^[A-Z0-9_]{1,40}$")
maxcc: int = Field(default=30, ge=0, le=100)
+ #: A Sentinel-1 pass's UTC time of day. The radar can see a place twice on
+ #: one day, from opposite directions, and only the time says which look.
+ time: str = Field(default="", pattern=r"^$|^([01]\d|2[0-3]):[0-5]\d:[0-5]\d$")
@model_validator(mode="before")
@classmethod
@@ -187,20 +226,62 @@ class Source(Model):
try:
date.fromisoformat(self.date)
except ValueError as exc:
- raise ValueError("choose a dated Sentinel-2 acquisition") from exc
+ raise ValueError("choose a dated Copernicus acquisition") from exc
return self
+ @model_serializer(mode="wrap")
+ def compact(self, handler: SerializerFunctionWrapHandler) -> dict[str, Any]:
+ # An optical source says what it always said, so the frame keys, the
+ # repeat check and every run saved before radar keep matching.
+ data: dict[str, Any] = handler(self)
+ if not data.get("time"):
+ data.pop("time", None)
+ return data
+
class ZoneSet(Model):
title: str = Field(min_length=1, max_length=120)
zones: list[Zone] = Field(min_length=1, max_length=32)
-class RunInput(ZoneSet):
+class AreaGeometry(Model):
+ type: Literal["Polygon"] = "Polygon"
+ coordinates: list[list[tuple[FiniteFloat, FiniteFloat]]] = Field(min_length=1, max_length=1)
+
+ @model_validator(mode="after")
+ def polygon(self) -> AreaGeometry:
+ ring = self.coordinates[0]
+ if len(ring) < 4 or ring[0] != ring[-1]:
+ raise ValueError("a polygon must have a closed ring")
+ Zone(id="area", kind="polygon", points=ring[:-1])
+ return self
+
+
+class Area(Model):
+ name: str = Field(min_length=1, max_length=120)
+ colour: Colour = "#38bdf8"
+ geometry: AreaGeometry
+
+
+class AreaDates(Model):
+ area_id: ShortId
+ a: Source = Field(default_factory=Source)
+ b: Source = Field(default_factory=Source)
+ date_rule: Literal["manual", "latest_reference", "latest_previous"] = "latest_reference"
+
+
+class RunInput(Model):
+ title: str = Field(min_length=1, max_length=120)
+ zones: list[Zone] = Field(default_factory=list, max_length=32)
+ area_dates: list[AreaDates] = Field(default_factory=list, max_length=32)
+ #: What this detection is for, in the analyst's own words. It travels with
+ #: the run, so a sweep opened months later still says why it was made.
+ note: str = Field(default="", max_length=500)
recipe: Recipe
- a: Source
- b: Source
+ a: Source = Field(default_factory=Source)
+ b: Source = Field(default_factory=Source)
offline: bool = False
+ run_anyway: bool = False
followup_id: ShortId | None = None
date_rule: Literal["manual", "latest_reference", "latest_previous"] = "manual"
@@ -208,6 +289,22 @@ class RunInput(ZoneSet):
def pair(self) -> RunInput:
if len({zone.id for zone in self.zones}) != len(self.zones):
raise ValueError("area ids must be unique")
+ if self.area_dates:
+ ids = [pair.area_id for pair in self.area_dates]
+ if len(set(ids)) != len(ids):
+ raise ValueError("area ids must be unique")
+ if self.zones and set(ids) != {zone.id for zone in self.zones}:
+ raise ValueError("each area needs its own dates")
+ for pair in self.area_dates:
+ if pair.date_rule == "manual" and not pair.b.date:
+ raise ValueError("choose a pass date for each area")
+ if self.recipe.method not in SINGLE_METHODS and not pair.a.date and not (
+ pair.date_rule == "latest_previous" and self.followup_id
+ ):
+ raise ValueError("choose a reference date for each area")
+ return self
+ if not self.zones:
+ raise ValueError("choose at least one area")
required = []
if self.date_rule == "manual":
required.append(self.b)
@@ -216,7 +313,7 @@ class RunInput(ZoneSet):
):
required.append(self.a)
if any(not source.date for source in required):
- raise ValueError("choose a dated Sentinel-2 acquisition")
+ raise ValueError("choose a dated Copernicus acquisition")
return self
@@ -269,15 +366,80 @@ BUILTINS = [
description="Ground that now reads as open water in the modified water index.",
parameters={"sensitivity": 56, "index": "mndwi", "direction": "gain"},
colour="#0ea5e9"),
+ # Sentinel-1. The radar sees through cloud and at night, and a metal hull
+ # or a standing wall answers it far louder than water or open ground.
+ _recipe(id="radar-vessels", name="Vessels by radar", method="sar-vessels",
+ phenomenon="Vessel candidate (radar)",
+ description="A strong radar return from open water, through cloud and at night. "
+ "Platforms, turbines, bridges and harbour walls answer too.",
+ parameters={"sensitivity": 60}, colour="#22d3ee"),
+ _recipe(id="radar-change", name="Radar change", method="sar-change",
+ phenomenon="Radar change",
+ description="Backscatter that moved between two passes of the same track, whatever "
+ "moved it. Fields change weekly in the growing season, so expect them.",
+ parameters={"sensitivity": 50}, colour="#c084fc"),
+ _recipe(id="radar-razed", name="Damaged or razed buildings (radar)", method="sar-change",
+ phenomenon="Loss of built-up return",
+ description="Ground that answered the radar like standing walls and went quiet. "
+ "Two passes only flag where to look; confirm on imagery before calling it damage.",
+ parameters={"sensitivity": 60, "direction": "loss", "sar_ground": "bright"},
+ colour="#f43f5e"),
+ _recipe(id="radar-new-objects", name="New structures and vehicles (radar)",
+ method="sar-change", phenomenon="New strong return",
+ description="Ground that now answers like metal or walls: new buildings, parked "
+ "vehicles, containers, moored ships.",
+ parameters={"sensitivity": 60, "direction": "gain", "sar_ground": "bright"},
+ colour="#eab308"),
+ _recipe("large", id="radar-flood", name="Flooding by radar", method="sar-change",
+ phenomenon="New open water (radar)",
+ description="Ground that went as radar-dark as calm water, under the cloud a flood "
+ "usually comes with. Wind on the water and flooded streets can hide it.",
+ parameters={"sensitivity": 60, "direction": "loss", "sar_ground": "water"},
+ colour="#3b82f6"),
]
+# How the built-ins are offered: by what an analyst is looking for, radar
+# first where it reads the same thing better. Every built-in is in one group.
+GROUPS: list[tuple[str, str, list[str]]] = [
+ ("vessels", "Vessels", ["radar-vessels", "boats"]),
+ ("fire", "Fires and burns", ["anomaly", "burn-scars"]),
+ ("water", "Water and floods", ["radar-flood", "new-water"]),
+ ("built", "Buildings and earthworks", ["structures", "radar-new-objects", "radar-razed"]),
+ ("ground", "Vegetation and small marks", ["vegetation-loss", "impacts"]),
+ ("any", "Any change", ["radar-change", "large-change"]),
+]
+
+# How far a built-in's reading can be trusted, from what calibration showed.
+# Reliable: the published test or a contrast few false hits survive. Approximate:
+# right more often than not, with known look-alikes. Rough: a lead to check.
+# Radar vessels beat optical ones because a hull answers the radar through cloud
+# and glint alike; two radar passes read damage roughly, where a year of them
+# would not (docs/SPEC.md §7).
+RELIABILITY: dict[str, Literal["reliable", "approximate", "rough"]] = {
+ "radar-vessels": "reliable", "boats": "approximate",
+ "anomaly": "reliable", "burn-scars": "reliable",
+ "radar-flood": "reliable", "new-water": "approximate",
+ "structures": "approximate", "radar-new-objects": "approximate", "radar-razed": "rough",
+ "vegetation-loss": "reliable", "impacts": "rough",
+ "radar-change": "rough", "large-change": "rough",
+}
+
+
+def frames_per_tile(method: str) -> int:
+ """Requests one tile costs: the picture and the product for each date, and
+ for radar vessels the Sentinel-2 water classification beside them."""
+ return (2 if method in SINGLE_METHODS else 4) + (1 if method == "sar-vessels" else 0)
+
+
# What the panel reads so it never has to know a method by name: `single` stops
# it asking for a reference image, `clouds` says whether the cloud switch means
-# anything, `sizes` fills Small/Medium/Large and `measure` words a candidate's
+# anything, `sensor` which collection its passes come from, `frames` what a
+# tile costs, `sizes` fills Small/Medium/Large and `measure` words a candidate's
# reading ({value}, {signed}, {before}, {after} and {index} are filled in).
METHODS = [
{"id": method, "label": label, "single": method in SINGLE_METHODS,
- "clouds": method in CLOUD_METHODS, "sizes": SIZES[method], "measure": measure}
+ "clouds": method in CLOUD_METHODS, "sensor": sensor_for(method),
+ "frames": frames_per_tile(method), "sizes": SIZES[method], "measure": measure}
for method, label, measure in [
("vessels", "Vessels: infrared contrast over water",
"{value}× brighter than the water around it"),
@@ -287,5 +449,8 @@ METHODS = [
("spots", "Isolated small change", "Reflectance {signed}% against its surroundings"),
("surface", "Any reflectance change", "Reflectance moved by {value}%"),
("index", "Spectral index change", "{index} {before} → {after}"),
+ ("sar-vessels", "Radar: strong return over water",
+ "{value} dB brighter than the sea around it"),
+ ("sar-change", "Radar: backscatter change", "Backscatter {signed} dB, {before} → {after} dB"),
]
]
diff --git a/src/azimut/engine/analyzers.py b/src/azimut/engine/analyzers.py
index db1edb9..ac6fe8b 100644
--- a/src/azimut/engine/analyzers.py
+++ b/src/azimut/engine/analyzers.py
@@ -3,14 +3,15 @@
Source frames are owned evidence, not an expiring map cache. Completed runs
never change when their recipe, area, camera or provider catalogue changes.
-Every detector here reads Copernicus Sentinel-2 band products. Their thresholds
-were set against real scenes, not synthetic ones: sea under glint and in rough
-weather (Bab-el-Mandeb), a dense anchorage under cumulus (Singapore Strait),
-wakes (Gibraltar), empty calm sea (Dover Strait), flares and an oil fire
+Every optical detector here reads Copernicus Sentinel-2 band products. Their
+thresholds were set against real scenes, not synthetic ones: sea under glint and
+in rough weather (Bab-el-Mandeb), a dense anchorage under cumulus (Singapore
+Strait), wakes (Gibraltar), empty calm sea (Dover Strait), flares and an oil fire
(Rumaila), active wildfires (California, Cerrado), bright industrial roofs
(Jebel Ali), a construction site across seven months (Egypt's new capital),
-dry-season clearing (Rondônia) and irrigated desert. The numbers below say what
-each of them taught.
+dry-season clearing (Rondônia) and irrigated desert. The radar detectors read
+Sentinel-1 backscatter, and the scenes behind their numbers are listed with
+them. The numbers below say what each of them taught.
"""
from __future__ import annotations
@@ -30,15 +31,20 @@ from PIL import Image
from .. import config, layout
from ..workspace import Case
-from . import media, sentinel, tilecache, tiles, workqueue
+from . import analysis_geometry, media, sentinel, tilecache, tiles, workqueue
from .analysis_models import (
CLOUD_METHODS,
+ RADAR_METHODS,
SINGLE_METHODS,
+ Area,
+ AreaDates,
+ AreaGeometry,
Parameters,
RunInput,
Source,
Zone,
product_for,
+ sensor_for,
)
# What one run may sweep. The ceiling is not memory — tiles are read one at a
@@ -65,7 +71,7 @@ PAD = 32
PRODUCT_VERSION = 2
ENGINE_VERSION = 2
LOCK = threading.RLock()
-KINDS = {"zones": "analysis-zones", "followups": "analysis-follow-up", "runs": "analysis-run"}
+KINDS = {"areas": "analysis-area", "zones": "analysis-zones", "followups": "analysis-follow-up", "runs": "analysis-run"}
ACTIVE = {"queued", "running"}
JOB = "compare-analyzer"
WORLD = 40_075_016.68557849
@@ -160,6 +166,45 @@ GROW = 0.7
DARK_ABSENT = frozenset({"nbr"})
+# --- Radar -------------------------------------------------------------------
+# Sentinel-1 speckle: every pixel of a single look is the sum of many random
+# echoes, so a lone pixel can read several decibels off its neighbours. Levels
+# are therefore averaged as power, never as decibels, whose mean is biased low.
+# The numbers below were read off real scenes: the Singapore Strait anchorage,
+# the Dover Strait and its harbour, the North Sea in the October 2023 storms,
+# the Belgian offshore wind farms, the Bosphorus, Port Sudan's desert coast,
+# the May 2023 Emilia-Romagna floods, and Gaza City before and after late 2023.
+#
+# What is sea. Windy sea rose to -11 dB in VV in the North Sea storm, above
+# farmland's -10, so VV alone called it land; cross-pol stayed near -24 dB on
+# every sea and between -12 and -18 on vegetated land. Dry desert is as dark as
+# calm sea in both, and at Port Sudan the radar alone put 72 candidates on the
+# town and the sand around it. So the sea is first what Sentinel-2's own scene
+# classification calls water on the clearest pass of the past year, and only
+# where that pass saw cloud is the radar asked.
+SEA_WINDOW = 31 # a median over 300 m ignores a hull and its sidelobes
+SEA_VV_DB = -9.0
+SEA_VH_DB = -21.0
+# A hull answers in both polarisations; the ghosts a strong target leaves in
+# azimuth, the streaks turning blades smear, and sea spikes answer in VV alone.
+# In the Singapore anchorage every hull cleared VH by 8 dB, those ghosts 4 to 7.
+VH_GAP = 2.0
+# A weak return within 400 m of one 6 dB stronger is that one's sidelobe or
+# ghost: it cut the Belgian wind farms from 1,043 candidates to about one a
+# turbine, and cost the anchorage no hull.
+GHOST_DB = 6.0
+GHOST_M = 400.0
+# Ground that answers like walls or metal, measured on the side that has it. At
+# -4 dB in VV a drop picked ten times more of Gaza's built-up area after late
+# 2023 than across the same fortnight before, and growing crops rarely reach it.
+BRIGHT_DB = -4.0
+# Radar-dark like calm water: the usual threshold for flood mapping in VV.
+WATER_DB = -18.0
+# The largest overall shift between two passes of one track still read as the
+# sensor rather than the ground; calibration holds a pair within a few tenths.
+MAX_SAR_SHIFT = 1.0
+
+
def now() -> str:
return datetime.now(timezone.utc).isoformat(timespec="seconds")
@@ -176,29 +221,140 @@ def read(case: Case, kind: str, ident: str) -> dict[str, Any]:
path = case.resolve_inside(relpath(kind, ident))
if path.stat().st_size > 16_000_000:
raise ValueError("analysis record is too large")
- return json.loads(path.read_text(encoding="utf-8"))
+ saved = json.loads(path.read_text(encoding="utf-8"))
+ if kind == "followups":
+ with LOCK, case._lock:
+ if not saved.get("area_dates"):
+ saved = share_areas(case, saved, ident)
+ media.write_json_atomic(path, saved)
+ saved["zones"] = [area_zone(read(case, "areas", pair["area_id"])).model_dump()
+ for pair in saved["area_dates"]]
+ return saved
+
+
+def area_zone(area: dict[str, Any]) -> Zone:
+ return Zone(id=area["id"], name=area["name"], kind="polygon",
+ points=area["geometry"]["coordinates"][0][:-1])
+
+
+def share_areas(case: Case, data: dict[str, Any], ident: str) -> dict[str, Any]:
+ """Promote routine zones once; stable ids make interrupted migration resumable."""
+ result = dict(data)
+ pairs = {pair["area_id"]: pair for pair in data.get("area_dates", [])}
+ linked = []
+ zones = data.get("zones") or data.get("recipe", {}).get("zones") or []
+ for raw in zones:
+ zone = Zone.model_validate(raw)
+ try:
+ read(case, "areas", zone.id)
+ area_id = zone.id
+ except (ValueError, FileNotFoundError):
+ area_id = hashlib.sha256(f"{ident}:{zone.id}".encode()).hexdigest()[:12]
+ ring = zone.ring()
+ area = Area(name=zone.name, colour=data.get("recipe", {}).get("colour", "#38bdf8"),
+ geometry=AreaGeometry(coordinates=[ring + [ring[0]]]))
+ if not case.resolve_inside(relpath("areas", area_id)).exists():
+ save(case, "areas", area.model_dump(), new_id=area_id)
+ pair = pairs.get(zone.id) or {"a": data.get("a", {}),
+ "b": {**data.get("b", {}), **({"date": ""} if data.get("date_rule", "manual") != "manual" else {})},
+ "date_rule": data.get("date_rule", "manual")}
+ linked.append({**pair, "area_id": area_id})
+ result["area_dates"] = linked or list(pairs.values())
+ result.pop("zones", None)
+ if "zones" in result.get("recipe", {}):
+ result["recipe"] = {k: v for k, v in result["recipe"].items() if k != "zones"}
+ return result
+
+
+def hydrate(case: Case, body: RunInput) -> RunInput:
+ """Freeze shared geometry into a run; its dates remain owned by that run."""
+ if body.zones:
+ return body
+ return body.model_copy(update={"zones": [area_zone(read(case, "areas", p.area_id))
+ for p in body.area_dates]})
+
+
+def summary(kind: str, saved: dict[str, Any]) -> dict[str, Any]:
+ """What a list shows of one saved item, without the item itself.
+
+ Detect's home list is a row per saved detection with its latest run under
+ it, so a run says which detection it belongs to and how much of it is still
+ waiting for a verdict, and both say what they look for.
+ """
+ if kind == "areas":
+ return dict(saved)
+ row: dict[str, Any] = {key: saved[key] for key in
+ ("id", "title", "created_at", "updated_at", "status", "progress",
+ "total", "count", "message", "completed_at") if key in saved}
+ body = saved.get("input", saved)
+ row["areas"] = len(body.get("zones") or [])
+ if kind == "zones":
+ return row
+ recipe = body.get("recipe") or {}
+ row.update(analyzer=recipe.get("name", ""), colour=recipe.get("colour", ""),
+ method=recipe.get("method", ""), date_rule=body.get("date_rule", "manual"))
+ row["note"] = body.get("note", "")
+ if kind == "followups":
+ # The list draws every watched area on the map, so the shapes travel
+ # with the row rather than costing one read per routine.
+ row["zones"] = body.get("zones") or []
+ if kind == "runs":
+ results = saved.get("results") or []
+ row.update(followup_id=body.get("followup_id"),
+ dates=[(body.get(side) or {}).get("date", "") for side in ("a", "b")],
+ to_review=sum(1 for r in results if r.get("review") == "new"),
+ marked=sum(1 for r in results if r.get("review") in KEPT))
+ row["area_runs"] = saved.get("area_runs", [])
+ return row
def listing(case: Case, kind: str) -> list[dict[str, Any]]:
+ if kind == "areas":
+ listing(case, "followups") # migrate embedded areas before exposing the shared list
rows: list[dict[str, Any]] = []
for path in case.subdir(layout.ANALYSIS_DIR).glob(f"{kind}-*.json"):
try:
- saved = read(case, kind, path.stem.split("-", 1)[1])
- rows.append({key: saved[key] for key in
- ("id", "title", "created_at", "updated_at", "status", "progress", "count")
- if key in saved})
+ rows.append(summary(kind, read(case, kind, path.stem.split("-", 1)[1])))
except (OSError, ValueError, KeyError):
continue
return sorted(rows, key=lambda row: row["created_at"], reverse=True)
-def save(case: Case, kind: str, data: dict[str, Any], ident: str | None = None) -> dict[str, Any]:
+#: Verdicts that keep a candidate. "kept" is a pin in the case, written by
+#: promotion; "noted" keeps it in the detection's own view and nowhere else.
+KEPT = ("kept", "noted")
+
+
+def findings(case: Case, followup_id: str) -> list[dict[str, Any]]:
+ """What a routine has found and nobody has dismissed, newest run first.
+
+ A routine is worth coming back to only if it remembers: its runs are
+ separate sweeps, but what they found is one growing list, and this is it.
+ """
+ rows: list[dict[str, Any]] = []
+ for summary in listing(case, "runs"):
+ if summary.get("followup_id") != followup_id or summary.get("status") != "ready":
+ continue
+ run = read(case, "runs", summary["id"])
+ day = (run["input"].get("b") or {}).get("date", "")
+ for result in run.get("results", []):
+ if result.get("review") not in KEPT:
+ continue
+ rows.append({**result, "run_id": run["id"], "run_title": run["title"],
+ "date": result.get("sources", {}).get("b", {}).get("date", day)})
+ return rows
+
+
+def save(case: Case, kind: str, data: dict[str, Any], ident: str | None = None,
+ *, new_id: str | None = None) -> dict[str, Any]:
with LOCK, case._lock:
if ident:
old = read(case, kind, ident)
else:
- ident = secrets.token_hex(6)
+ ident = new_id or secrets.token_hex(6)
old = {}
+ if kind == "followups":
+ data = share_areas(case, data, ident)
rel = relpath(kind, ident)
saved = {**data, "id": ident, "created_at": old.get("created_at", now()),
"updated_at": now(), "version": 1}
@@ -206,10 +362,11 @@ def save(case: Case, kind: str, data: dict[str, Any], ident: str | None = None)
path.parent.mkdir(parents=True, exist_ok=True)
media.write_json_atomic(path, saved)
entity = case.find_entity(attr="spec", value=rel)
+ title = saved.get("title", saved.get("name", "Area"))
if entity:
- case.update_entity(entity["id"], {"label": saved["title"]})
+ case.update_entity(entity["id"], {"label": title})
else:
- case.add_entity(KINDS[kind], saved["title"], attrs={"spec": rel}, by="compare")
+ case.add_entity(KINDS[kind], title, attrs={"spec": rel}, by="compare")
return saved
@@ -284,8 +441,24 @@ def _key(source: Source, z: int, x: int, y: int, product: str | None) -> str:
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.
+ """
+ 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)
+
+
def product_cache_id(source: Source, product: str) -> str:
"""The tile-cache folder a band product lives in, beside its picture's."""
+ 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)
return f"{variant}~{product}~v{PRODUCT_VERSION}"
@@ -308,6 +481,34 @@ def _instance() -> str:
return str(instance)
+def radar_layer() -> str:
+ """The Sentinel-1 layer the user added to their Copernicus configuration."""
+ layer = str(config.load_settings().get("sentinel1_layer") or "")
+ if not layer:
+ raise ValueError("choose the Sentinel-1 layer in Settings → Imagery before a radar run")
+ return layer
+
+
+def water_source(source: Source) -> Source:
+ """The Sentinel-2 source a radar pass's water classification is read from.
+
+ It is named by the first day of the pass's month, so every pass of a month
+ shares one classification and one cache entry.
+ """
+ return Source(provider="sentinel2", date=f"{source.date[:7]}-01",
+ layer=sentinel.DEFAULT_LAYER, maxcc=100)
+
+
+def _box(z: int, x: int, y: int, pad: int) -> tuple[float, float, float, float]:
+ """One grid tile in Web Mercator metres, grown by `pad` pixels on every side."""
+ _, size = GRID
+ pixel = WORLD / ((1 << z) * size)
+ return (x / (1 << z) * WORLD - WORLD / 2 - pad * pixel,
+ WORLD / 2 - (y + 1) / (1 << z) * WORLD - pad * pixel,
+ (x + 1) / (1 << z) * WORLD - WORLD / 2 + pad * pixel,
+ WORLD / 2 - y / (1 << z) * WORLD + pad * pixel)
+
+
def frame(case: Case, run: dict[str, Any], source: Source, x: int, y: int,
product: str | None = None) -> Any:
"""One tile's picture, or its band product with PAD pixels of context."""
@@ -324,9 +525,7 @@ def frame(case: Case, run: dict[str, Any], source: Source, x: int, y: int,
if cached.is_file() and cached.stat().st_size <= MAX_FRAME_BYTES:
raw = cached.read_bytes()
break
- cache_id = (product_cache_id(source, product) if product else
- sentinel.variant_id("sentinel2", source.layer, source.date, source.date,
- source.maxcc))
+ cache_id = product_cache_id(source, product) if product else picture_cache_id(source)
if raw is None:
cached_tile = tilecache.get(cache_id, z, x, y)
if cached_tile:
@@ -338,15 +537,15 @@ def frame(case: Case, run: dict[str, Any], source: Source, x: int, y: int,
if config.usage_blocked("sentinelhub"):
raise ValueError("Sentinel Hub usage limit reached; review Settings")
instance = _instance()
- if product:
- pixel = WORLD / ((1 << z) * size)
- box = (x / (1 << z) * WORLD - WORLD / 2 - PAD * pixel,
- WORLD / 2 - (y + 1) / (1 << z) * WORLD - PAD * pixel,
- (x + 1) / (1 << z) * WORLD - WORLD / 2 + PAD * pixel,
- WORLD / 2 - y / (1 << z) * WORLD + PAD * pixel)
+ radar = source.provider == "sentinel1"
+ 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, edge, edge, source.date, product,
- source.maxcc, layer=source.layer)
+ 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,
+ time=source.time)
finally:
config.record_usage("sentinelhub", 1)
else:
@@ -719,9 +918,130 @@ def _spots(before: Any, after: Any, valid: Any, metres: float, threshold: float,
return np.sqrt((spot ** 2).mean(-1)), spot.mean(-1), share < SPOT_SHARE
+def _power_mean(level: Any, valid: Any, window: int) -> Any:
+ """Backscatter averaged as power over a square window, back in decibels.
+
+ Only pixels the radar measured count, so an area's edge or a swath's end
+ does not pull its neighbours down.
+ """
+ import cv2
+ import numpy as np
+
+ power = np.where(valid, 10.0 ** (sentinel.sar_decibels(level.astype(np.float64)) / 10.0), 0.0)
+ total = cv2.boxFilter(power, cv2.CV_64F, (window, window), normalize=False,
+ borderType=cv2.BORDER_REFLECT)
+ count = cv2.boxFilter(valid.astype(np.float64), cv2.CV_64F, (window, window),
+ normalize=False, borderType=cv2.BORDER_REFLECT)
+ return 10.0 * np.log10(np.maximum(total / np.maximum(count, 1e-9), 1e-6))
+
+
+def _sar_vessels(product: Any, water: Any, inside: Any, metres: float,
+ options: Parameters) -> tuple[Any, Any, float, dict[str, tuple[Any, str]]]:
+ """Hulls: a strong return standing out of the sea around it.
+
+ Each pixel is measured against a ring of sea with a hole in the middle, the
+ ring the optical detector uses, in decibels above the ring's mean power. It
+ has to clear the line in VV and come close in VH, and not sit in the
+ shadow of a much stronger return. `water` is Sentinel-2's classification,
+ or None where the sweep could not read it.
+ """
+ import cv2
+ import numpy as np
+
+ data = product[:, :, 0] > 0
+ median_vv = sentinel.sar_decibels(cv2.medianBlur(product[:, :, 0], SEA_WINDOW).astype(np.float64))
+ median_vh = sentinel.sar_decibels(cv2.medianBlur(product[:, :, 1], SEA_WINDOW).astype(np.float64))
+ radar_sea = (median_vv < SEA_VV_DB) & (median_vh < SEA_VH_DB)
+ classed = (water[:, :, 0] if water is not None else
+ np.full(data.shape, sentinel.WATER_UNKNOWN, np.uint8))
+ sea = data & np.where(classed == sentinel.WATER_WATER, True,
+ np.where(classed == sentinel.WATER_LAND, False, radar_sea))
+ land = components_over(data & ~sea, metres * metres, LAND_M2)
+ land = cv2.dilate(land.astype(np.uint8), np.ones((5, 5), np.uint8)).astype(bool)
+
+ def contrast(level: Any) -> tuple[Any, Any]:
+ decibels = sentinel.sar_decibels(level.astype(np.float64))
+ power = np.where(data, 10.0 ** (decibels / 10.0), 0.0)
+ mean, _, share = ring_statistics(power, sea, VESSEL_RING, VESSEL_GUARD)
+ return np.where(share > 0, decibels - 10.0 * np.log10(np.maximum(mean, 1e-9)), 0.0), share
+
+ vv, share = contrast(product[:, :, 0])
+ vh, _ = contrast(product[:, :, 1])
+ ok = inside & data & ~land & (share > VESSEL_WATER_SHARE)
+ threshold = _scale(options.sensitivity, 6.0, 14.0)
+ seed = ok & (vv >= threshold) & (vh >= threshold - VH_GAP)
+ binary = hysteresis(seed, ok & (vv >= threshold / 2))
+ return _without_ghosts(binary, vv, metres), vv, threshold, {"value": (vv, "max")}
+
+
+def _without_ghosts(binary: Any, strength: Any, metres: float) -> Any:
+ """Drop a return within GHOST_M of one GHOST_DB stronger."""
+ import cv2
+ import numpy as np
+
+ count, labels, stats, _ = cv2.connectedComponentsWithStats(binary.astype(np.uint8), connectivity=8)
+ if count <= 2:
+ return binary
+ peaks = np.full(count, -np.inf)
+ np.maximum.at(peaks, labels.ravel(), strength.ravel())
+ reach = GHOST_M / metres
+ left, top = stats[:, cv2.CC_STAT_LEFT].astype(float), stats[:, cv2.CC_STAT_TOP].astype(float)
+ right = left + stats[:, cv2.CC_STAT_WIDTH]
+ bottom = top + stats[:, cv2.CC_STAT_HEIGHT]
+ keep = np.ones(count, bool)
+ keep[0] = False
+ for label in range(1, count):
+ stronger = peaks >= peaks[label] + GHOST_DB
+ stronger[0] = False
+ if not stronger.any():
+ continue
+ gap_x = np.maximum(0, np.maximum(left - right[label], left[label] - right))
+ gap_y = np.maximum(0, np.maximum(top - bottom[label], top[label] - bottom))
+ if (stronger & (np.hypot(gap_x, gap_y) <= reach)).any():
+ keep[label] = False
+ return keep[labels]
+
+
+def _sar_change(before: Any, after: Any, valid: Any,
+ options: Parameters) -> tuple[Any, Any, Any, float, dict[str, tuple[Any, str]]]:
+ """Backscatter that moved between two passes of one track, in decibels.
+
+ Both passes are averaged as power over the same window before they are
+ compared, so speckle does not read as change. What the recipe's ground
+ setting asks for then gates it: bright ground on the side that has it, or
+ water coming or going.
+ """
+ import numpy as np
+
+ window = 2 * max(1, options.smoothing) + 1
+ old = _power_mean(before[:, :, 0], valid, window)
+ new = _power_mean(after[:, :, 0], valid, window)
+ # Both polarisations vote: a building that falls or a field that floods
+ # darkens in each, while speckle in one is not speckle in the other.
+ delta = (new - old + _power_mean(after[:, :, 1], valid, window)
+ - _power_mean(before[:, :, 1], valid, window)) / 2
+ shift = float(np.median(delta[valid])) if valid.any() else 0.0
+ delta = delta - max(-MAX_SAR_SHIFT, min(MAX_SAR_SHIFT, shift))
+ ground = options.sar_ground
+ if ground == "bright":
+ state = np.where(delta < 0, old >= BRIGHT_DB, new >= BRIGHT_DB)
+ elif ground == "water":
+ state = np.where(delta < 0, (new < WATER_DB) & (old >= WATER_DB),
+ (old < WATER_DB) & (new >= WATER_DB))
+ else:
+ state = np.ones(valid.shape, bool)
+ threshold = _scale(options.sensitivity, 1.0, 5.0)
+ measures = {"signed": (delta, "mean"), "before": (old, "mean"), "after": (new, "mean")}
+ return np.abs(delta), delta, state, threshold, measures
+
+
def detect(pictures: tuple[Any, Any], products: tuple[Any, Any], mask: Any, body: RunInput,
- lat: float) -> Reading:
- """One deterministic tile. Products carry PAD pixels of context on every side."""
+ lat: float, water: Any = None) -> Reading:
+ """One deterministic tile. Products carry PAD pixels of context on every side.
+
+ `water` is Sentinel-2's water classification over the same padded tile,
+ which only the radar vessel method reads.
+ """
import cv2
import numpy as np
@@ -748,10 +1068,15 @@ def detect(pictures: tuple[Any, Any], products: tuple[Any, Any], mask: Any, body
binary, stat, threshold, measures = _vessels(products[1], inside, blocked, metres, options)
elif method == "hotspots":
binary, stat, threshold, measures = _hotspots(products[1], inside, options)
+ elif method == "sar-vessels":
+ binary, stat, threshold, measures = _sar_vessels(products[1], water, inside, metres, options)
else:
before, after = products
valid = inside & ~blocked
- if method == "index":
+ if method == "sar-change":
+ valid &= (before[:, :, 0] > 0) & (after[:, :, 0] > 0)
+ stat, signed, state, threshold, measures = _sar_change(before, after, valid, options)
+ elif method == "index":
old = before[:, :, 0].astype(np.float32) / 127.5 - 1
new = after[:, :, 0].astype(np.float32) / 127.5 - 1
valid &= (before[:, :, 0] > 0) & (after[:, :, 0] > 0)
@@ -793,7 +1118,8 @@ def detect(pictures: tuple[Any, Any], products: tuple[Any, Any], mask: Any, body
if options.direction != "both":
valid &= signed > 0 if options.direction == "gain" else signed < 0
stat = np.clip(stat, -10, 10).astype(np.float32)
- if options.smoothing:
+ # Radar change was already averaged as power over this window.
+ if options.smoothing and method not in RADAR_METHODS:
stat = cv2.GaussianBlur(stat, (options.smoothing * 2 + 1,) * 2, 0)
grow = valid & (np.abs(signed if method == "structure" else stat) >= threshold * GROW)
binary = hysteresis(valid & state & (stat >= threshold), grow & state)
@@ -847,6 +1173,8 @@ def _candidates(reading: Reading, body: RunInput, x: int, y: int,
(y + (py + height) / size) / (1 << z))
margin = float(peaks[label]) / reading.threshold if reading.threshold else 0.0
rows.append({"id": f"{part}-{label}", "bbox": [west, south, east, north],
+ "geometry": analysis_geometry.footprint(
+ labels[py:py + height, px:px + width] == label, x, y, z, size, (px, py)),
"coordinates": [lon, lat], "area": pixels * mpp * mpp,
"width": width * mpp, "height": height * mpp,
"margin": round(margin, 3), "strength": strength(margin),
@@ -881,6 +1209,8 @@ def merge(rows: list[dict[str, Any]], distance: float) -> list[dict[str, Any]]:
row["area"] += other["area"]
row["bbox"] = [min(a[0], b[0]), min(a[1], b[1]), max(a[2], b[2]), max(a[3], b[3])]
row["parts"].extend(other["parts"])
+ if "geometry" in row and "geometry" in other:
+ row["geometry"] = analysis_geometry.joined(row["geometry"], other["geometry"])
a = row["bbox"]
row["coordinates"] = [(a[0] + a[2]) / 2, (a[1] + a[3]) / 2]
row["width"] = (a[2] - a[0]) * 111_320 * math.cos(math.radians(lat))
@@ -911,56 +1241,245 @@ def prune_frames(case: Case, run: dict[str, Any]) -> None:
tiles = {tuple(run["frames"][key]["tile"]) for key in shown if key in run["frames"]}
with LOCK, case._lock:
for key, record in list(run["frames"].items()):
- if tuple(record["tile"]) in tiles:
+ if record.get("index") is None or tuple(record["tile"]) in tiles:
continue
case.resolve_inside(record["path"]).unlink(missing_ok=True)
del run["frames"][key]
-def resolve_dates(case: Case, body: RunInput) -> RunInput:
- if body.date_rule == "manual":
- return body
+def previous_pass(case: Case, body: RunInput) -> Source:
+ """The pass this routine's last finished run swept, which the next one
+ compares against. Falls back to the reference the routine was saved with."""
+ if not body.followup_id:
+ return body.a
+ best: tuple[tuple[str, str], Source] | None = None
+ for summary in listing(case, "runs"):
+ if summary.get("followup_id") != body.followup_id or summary.get("status") != "ready":
+ continue
+ previous = read(case, "runs", summary["id"])
+ area_id = body.zones[0].id
+ if previous.get("area_runs"):
+ area = next((p for p in previous["area_runs"] if p["area_id"] == area_id
+ and p["status"] == "ready"), None)
+ if not area:
+ continue
+ candidate = Source.model_validate(area["b"])
+ else:
+ if not any(z["id"] == area_id or hashlib.sha256(
+ f"{body.followup_id}:{z['id']}".encode()).hexdigest()[:12] == area_id
+ for z in previous["input"].get("zones", [])):
+ continue
+ candidate = Source.model_validate(previous["input"]["b"])
+ if candidate.layer != body.b.layer or not candidate.date:
+ continue
+ if body.b.date and candidate.date >= body.b.date:
+ continue
+ # Radar compares like with like: a pass from another track sees the
+ # same ground at another angle, and that difference is not change.
+ if candidate.provider == "sentinel1" and body.b.time and not sentinel.same_track(
+ candidate.time, body.b.time):
+ continue
+ # Runs of one routine can share a timestamp, which is only seconds deep,
+ # so the pass they swept settles the order between them.
+ key = (str(summary.get("created_at", "")), candidate.date)
+ if best is None or key > best[0]:
+ best = (key, candidate)
+ return best[1] if best else body.a
+
+
+def _lookup(body: RunInput, start: str, end: str) -> list[dict[str, Any]]:
+ """The passes over every area of `body` in a window, newest first.
+
+ One lookup over every area at once, answering about the areas rather than
+ about their centres: a pass can reach a centre and miss most of the shape
+ around it, and picking that date sweeps mostly nodata.
+ """
if body.offline:
raise ValueError("latest-date lookup needs network; select explicit dates for offline runs")
- source = body.b.model_copy(deep=True)
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")
- # One lookup over every area at once, answering about the areas rather
- # than about their centres: a pass can reach a centre and miss most of
- # the shape around it, and picking that date sweeps mostly nodata.
try:
- found = sentinel.acquisitions(
- instance, [list(zone.ring()) for zone in body.zones],
- (date.today() - timedelta(days=LOOKBACK_DAYS)).isoformat(),
- date.today().isoformat(),
- )
+ found = sentinel.acquisitions(instance, [list(zone.ring()) for zone in body.zones],
+ start, end, collection=sensor_for(body.recipe.method))
finally:
config.record_usage("sentinelhub", 1)
- allowed = [entry for entry in found["dates"]
- if entry.get("cloud") is not None and entry["cloud"] <= source.maxcc]
+ return list(found["dates"])
+
+
+def _sensed_by(body: RunInput) -> RunInput:
+ """Sources that name the collection the method reads.
+
+ The panel builds Sentinel-2 sources; a radar method reads the user's
+ Sentinel-1 layer, whatever the source was saved with, and has no clouds to
+ set a ceiling on. An optical source never carries a pass time.
+ """
+ if body.recipe.method in RADAR_METHODS:
+ radar: dict[str, Any] = {"provider": "sentinel1", "layer": radar_layer(), "maxcc": 100}
+ return body.model_copy(update={"a": body.a.model_copy(update=radar),
+ "b": body.b.model_copy(update=radar)})
+
+ def optical(source: Source) -> Source:
+ # A pass time left over from a radar analyzer would narrow the day to
+ # forty minutes around a radar pass, and Sentinel-2 flies at another hour.
+ if source.provider == "sentinel2" and not source.time:
+ return source
+ patch: dict[str, Any] = {"provider": "sentinel2", "time": ""}
+ if source.provider != "sentinel2":
+ patch["layer"] = sentinel.DEFAULT_LAYER
+ return source.model_copy(update=patch)
+
+ return body.model_copy(update={"a": optical(body.a), "b": optical(body.b)})
+
+
+def _pass_time(body: RunInput, side: Source, track: str,
+ found: list[dict[str, Any]] | None = None) -> Source:
+ """A dated radar source pinned to one pass of its day.
+
+ A date typed by hand names a day, and Sentinel-1 can pass twice in one,
+ from opposite directions. The pass on `track` wins, then the one that
+ covers the areas best. Offline there is nothing to ask, and the day is read
+ whole from whatever the cache holds.
+ """
+ if not side.date or side.time or body.offline:
+ return side
+ passes = [entry for entry in (found if found is not None else _lookup(body, side.date, side.date))
+ if entry["date"] == side.date]
+ if not passes:
+ raise ValueError(f"no Sentinel-1 pass reaches this area on {side.date}")
+ passes.sort(key=lambda entry: (not sentinel.same_track(entry["time"], track),
+ -entry["coverage"], entry["time"]))
+ return side.model_copy(update={"time": passes[0]["time"]})
+
+
+def _timed(body: RunInput) -> RunInput:
+ """Radar sources pinned to their passes, and a pair held to one track.
+
+ A pass from another track sees the ground at another angle, and that
+ difference is not change. One lookup settles both sides.
+ """
+ if body.recipe.method not in RADAR_METHODS:
+ return body
+ single = body.recipe.method in SINGLE_METHODS
+ sides = [body.b] if single else [body.a, body.b]
+ missing = sorted(side.date for side in sides if side.date and not side.time)
+ found = _lookup(body, missing[0], missing[-1]) if missing and not body.offline else None
+ b = _pass_time(body, body.b, "" if single else body.a.time, found)
+ if single:
+ return body.model_copy(update={"a": b, "b": b})
+ a = _pass_time(body, body.a, b.time, found)
+ if a.time and b.time and not sentinel.same_track(a.time, b.time):
+ raise ValueError("the reference and the pass were seen from different tracks; choose "
+ "two passes at the same time of day, which the pass list groups")
+ return body.model_copy(update={"a": a, "b": b})
+
+
+def resolve_dates(case: Case, body: RunInput, *, selected: bool = False) -> RunInput:
+ body = _sensed_by(body)
+ single = body.recipe.method in SINGLE_METHODS
+ radar = body.recipe.method in RADAR_METHODS
+ if single:
+ body = body.model_copy(update={"a": body.b})
+ if body.date_rule == "manual":
+ return _timed(body)
+ if selected and body.b.date:
+ if radar:
+ body = body.model_copy(update={"b": _pass_time(body, body.b, body.a.time)})
+ reference = (body.b if single else
+ previous_pass(case, body) if body.date_rule == "latest_previous" else body.a)
+ if not single and not reference.date:
+ raise ValueError("choose a reference image for the first execution of this follow-up")
+ return _timed(body.model_copy(update={"a": reference}))
+ track = ""
+ if radar and not single:
+ # The newest pass is looked for on one track: the reference's, or for a
+ # routine that compares with its previous pass, the track it has run on.
+ anchor = body.a if body.date_rule != "latest_previous" else previous_pass(case, body)
+ anchor = _pass_time(body, anchor, "")
+ if body.date_rule != "latest_previous":
+ body = body.model_copy(update={"a": anchor})
+ track = anchor.time
+ source = body.b.model_copy(deep=True)
+ found = _lookup(body, (date.today() - timedelta(days=LOOKBACK_DAYS)).isoformat(),
+ date.today().isoformat())
+ allowed = [entry for entry in found if radar or (
+ entry.get("cloud") is not None and entry["cloud"] <= source.maxcc)]
+ if track:
+ allowed = [entry for entry in allowed if sentinel.same_track(entry["time"], track)]
whole = [entry for entry in allowed if entry["coverage"] >= FULL_COVER]
if not whole:
best = max((entry["coverage"] for entry in allowed), default=0)
raise ValueError(
- "no recent pass covers the whole area under the cloud limit"
+ (f"no recent Sentinel-1 pass{' on this track' if track else ''} covers the whole area"
+ if radar else "no recent pass covers the whole area under the cloud limit")
+ (f"; the best reaches {round(best * 100)}% of it, so choose the dates by hand"
if best else "")
)
source.date = whole[0]["date"] # newest first
- reference = body.a
- if body.date_rule == "latest_previous" and body.followup_id:
- for summary in listing(case, "runs"):
- previous = read(case, "runs", summary["id"])
- if previous.get("status") == "ready" and \
- previous["input"].get("followup_id") == body.followup_id:
- candidate = Source.model_validate(previous["input"]["b"])
- if candidate.layer == source.layer and candidate.date:
- reference = candidate
- break
- if body.recipe.method not in SINGLE_METHODS and not reference.date:
+ if radar:
+ source.time = whole[0]["time"]
+ reference = (source if single else
+ body.a if body.date_rule != "latest_previous" else
+ previous_pass(case, body.model_copy(update={"b": source})))
+ if not single and not reference.date:
raise ValueError("choose a reference image for the first execution of this follow-up")
- return body.model_copy(update={"a": reference, "b": source})
+ return _timed(body.model_copy(update={"a": reference, "b": source}))
+
+
+def for_area(body: RunInput, zone: Zone) -> RunInput:
+ pair = next((pair for pair in body.area_dates if pair.area_id == zone.id), None)
+ changes: dict[str, Any] = {"zones": [zone], "area_dates": []}
+ if pair:
+ changes.update(a=pair.a, b=pair.b, date_rule=pair.date_rule)
+ return body.model_copy(update=changes)
+
+
+def prepare_areas(case: Case, body: RunInput) -> tuple[RunInput, list[dict[str, Any]]]:
+ """Resolve each area independently, only as part of an explicit launch."""
+ outcomes = []
+ pairs = []
+ for zone in body.zones:
+ local = for_area(body, zone)
+ outcome: dict[str, Any] = {"area_id": zone.id, "name": zone.name}
+ try:
+ local = resolve_dates(case, local, selected=bool(body.area_dates))
+ outcome.update(status="pending", a=local.a.model_dump(), b=local.b.model_dump(), message="")
+ pairs.append(AreaDates(area_id=zone.id, a=local.a, b=local.b, date_rule="manual"))
+ except Exception as exc:
+ message = str(exc) if isinstance(exc, ValueError) else "Imagery could not be read"
+ outcome.update(status="failed", message=f"{zone.name}: {message}",
+ a=local.a.model_dump(), b=local.b.model_dump())
+ pairs.append(AreaDates(area_id=zone.id, a=local.a, b=local.b, date_rule=local.date_rule))
+ outcomes.append(outcome)
+ return body.model_copy(update={"area_dates": pairs}), outcomes
+
+
+def duplicates(case: Case, body: RunInput, outcomes: list[dict[str, Any]]) -> list[dict[str, Any]]:
+ """Exact geometry, recipe and source pairs only; overlapping dates do not match."""
+ found = []
+ for summary in listing(case, "runs"):
+ if summary.get("status") != "ready":
+ continue
+ run = read(case, "runs", summary["id"])
+ old = RunInput.model_validate(run["input"])
+ if old.recipe.model_dump() != body.recipe.model_dump():
+ continue
+ for outcome in outcomes:
+ if outcome["status"] != "pending":
+ continue
+ zone = next(z for z in body.zones if z.id == outcome["area_id"])
+ old_zone = next((z for z in old.zones if z.id == zone.id), None)
+ if old_zone is None or old_zone.ring() != zone.ring():
+ continue
+ records = run.get("area_runs") or [{"area_id": zone.id, "status": "ready",
+ "a": old.a.model_dump(), "b": old.b.model_dump()}]
+ match = next((r for r in records if r["area_id"] == zone.id and r["status"] == "ready"
+ and r["b"] == outcome["b"] and
+ (body.recipe.method in SINGLE_METHODS or r["a"] == outcome["a"])), None)
+ if match:
+ found.append({"run_id": run["id"], "title": run["title"], "area_id": zone.id,
+ "area_name": zone.name, "a": outcome["a"], "b": outcome["b"]})
+ return found
def execute(case: Case, job: dict[str, Any]) -> None:
@@ -968,67 +1487,59 @@ def execute(case: Case, job: dict[str, Any]) -> None:
check_active(case, ident)
run = read(case, "runs", ident)
try:
- body = resolve_dates(case, RunInput.model_validate(run["input"]))
- single = body.recipe.method in SINGLE_METHODS
- if single:
- body = body.model_copy(update={"a": body.b})
- run["input"] = body.model_dump()
- if not single and body.a.model_dump() == body.b.model_dump():
- run.update(status="no_new_imagery", message="No different dated imagery is available")
- persist_run(case, run)
- return
- planned = plan(body)
+ original = hydrate(case, RunInput.model_validate(run["input"]))
+ outcomes = run.get("area_runs")
+ if outcomes is None:
+ _, outcomes = prepare_areas(case, original)
+ single = original.recipe.method in SINGLE_METHODS
z, size = GRID
- run.update(status="running", total=len(planned), resolution={"grid_zoom": z,
+ run.update(status="running", area_runs=outcomes, resolution={"grid_zoom": z,
"tile_size": size, "pad": PAD}, engine_version=ENGINE_VERSION)
persist_run(case, run)
-
- product = product_for(body.recipe.method, body.recipe.parameters.index)
- results: list[dict[str, Any]] = []
- # What the sweep actually read, against what was asked for. A date the
- # granules only half reach comes back half nodata, and without this the
- # run reports "nothing found" over ground it never saw.
asked = imaged = 0
- for part, (x, y) in enumerate(planned):
+ kept: list[dict[str, Any]] = []
+ resolved = []
+ for outcome in outcomes:
check_active(case, ident)
- picture_b = frame(case, run, body.b, x, y)
- picture_a = picture_b if single else frame(case, run, body.a, x, y)
- # Two frames for one date: the picture the analyst reviews, and the
- # bands the detector measures. Both are metered.
- product_b = frame(case, run, body.b, x, y, product)
- product_a = product_b if single else frame(case, run, body.a, x, y, product)
- mask = mask_for(body.zones, z, size, x, y)
- inside = mask.astype(bool)
- asked += int(inside.sum())
- imaged += int((inside & (picture_a[:, :, 3] > 0) & (picture_b[:, :, 3] > 0)).sum())
- _, lat = geographic((x + .5) / (1 << z), (y + .5) / (1 << z))
- reading = detect((picture_a, picture_b), (product_a, product_b), mask, body, lat)
- # One image analyzed, one frame of evidence: a vessel's "before" and
- # "after" would be the same picture twice.
- sources = [body.b] if single else [body.a, body.b]
- keys = [_key(source, z, x, y, None) for source in sources]
- results.extend(_candidates(reading, body, x, y, part, keys))
- if len(results) > MAX_RESULTS * 4:
- raise ValueError("too many fragments; lower the sensitivity or use smaller areas")
- run["progress"] = part + 1
+ if outcome["status"] == "failed":
+ continue
+ zone = next(zone for zone in original.zones if zone.id == outcome["area_id"])
+ body = for_area(original, zone).model_copy(update={
+ "a": Source.model_validate(outcome["b"] if single else outcome["a"]),
+ "b": Source.model_validate(outcome["b"]), "date_rule": "manual"})
+ resolved.append(AreaDates(area_id=zone.id, a=body.a, b=body.b, date_rule="manual"))
+ if not single and body.a == body.b:
+ outcome.update(status="no_new_imagery", message=f"{zone.name}: No different dated imagery is available")
+ continue
+ try:
+ rows, area_asked, area_imaged = sweep_area(case, run, body)
+ kept.extend(rows)
+ asked += area_asked
+ imaged += area_imaged
+ outcome.update(status="ready", count=len(rows))
+ except (workqueue.JobCancelled, workqueue.JobRemoved):
+ raise
+ except Exception as exc:
+ message = str(exc) if isinstance(exc, ValueError) else "Imagery could not be read"
+ outcome.update(status="failed", message=f"{zone.name}: {message}")
persist_run(case, run)
- options = body.recipe.parameters
- joined = merge(results, options.merge_metres)
- kept = [r for r in joined if r["area"] >= options.min_area and
- (not options.max_area or r["area"] <= options.max_area)]
if len(kept) > MAX_RESULTS:
raise ValueError("too many results; raise the minimum area or lower the sensitivity")
kept.sort(key=lambda row: row["margin"], reverse=True)
- for row in kept:
- w, s, e, n = row["bbox"]
- row["geometry"] = {"type": "Polygon", "coordinates": [[[w, s], [e, s], [e, n],
- [w, n], [w, s]]]}
+ if resolved:
+ # Keep the original envelope readable by older clients; each actual
+ # pair is recorded beside its area's outcome and on every result.
+ original = original.model_copy(update={"a": resolved[0].a, "b": resolved[0].b})
+ run["input"] = original.model_dump()
swept = round(imaged / asked, 3) if asked else 0.0
- run.update(results=kept, count=len(kept), status="ready", swept=swept, message="",
+ status = ("ready" if any(o["status"] == "ready" for o in outcomes) else
+ "failed" if any(o["status"] == "failed" for o in outcomes) else "no_new_imagery")
+ run.update(results=kept, count=len(kept), status=status, swept=swept,
+ message=" · ".join(o["message"] for o in outcomes if o.get("message")),
completed_at=now())
prune_frames(case, run)
persist_run(case, run)
- except workqueue.JobCancelled:
+ except (workqueue.JobCancelled, workqueue.JobRemoved):
raise
except Exception as exc:
# Never persist provider URLs or credentials from network exception text.
@@ -1037,4 +1548,50 @@ def execute(case: Case, job: dict[str, Any]) -> None:
persist_run(case, run)
+def sweep_area(case: Case, run: dict[str, Any], body: RunInput) -> tuple[list[dict[str, Any]], int, int]:
+ """Apply the unchanged detector to one area's own pair."""
+ single = body.recipe.method in SINGLE_METHODS
+ z, size = GRID
+ product = product_for(body.recipe.method, body.recipe.parameters.index)
+ results: list[dict[str, Any]] = []
+ asked = imaged = 0
+ for part, (x, y) in enumerate(plan(body)):
+ check_active(case, run["id"])
+ workqueue.let_others_through(case, JOB)
+ picture_b = frame(case, run, body.b, x, y)
+ picture_a = picture_b if single else frame(case, run, body.a, x, y)
+ product_b = frame(case, run, body.b, x, y, product)
+ product_a = product_b if single else frame(case, run, body.a, x, y, product)
+ water = None
+ if body.recipe.method == "sar-vessels":
+ # Without it the radar alone decides what is sea, which it does
+ # well enough offshore; a failed read is not a failed tile.
+ try:
+ water = frame(case, run, water_source(body.b), x, y, "water")
+ except (ValueError, sentinel.CoverageError, httpx.HTTPError):
+ water = None
+ mask = mask_for(body.zones, z, size, x, y)
+ inside = mask.astype(bool)
+ asked += int(inside.sum())
+ imaged += int((inside & (picture_a[:, :, 3] > 0) & (picture_b[:, :, 3] > 0)).sum())
+ _, lat = geographic((x + .5) / (1 << z), (y + .5) / (1 << z))
+ reading = detect((picture_a, picture_b), (product_a, product_b), mask, body, lat, water)
+ sources = [body.b] if single else [body.a, body.b]
+ keys = [_key(source, z, x, y, None) for source in sources]
+ results.extend(_candidates(reading, body, x, y, part, keys))
+ if len(results) > MAX_RESULTS * 4:
+ raise ValueError("too many fragments; lower the sensitivity or use smaller areas")
+ run["progress"] += 1
+ persist_run(case, run)
+ options = body.recipe.parameters
+ joined = merge(results, options.merge_metres)
+ kept = [r for r in joined if r["area"] >= options.min_area and
+ (not options.max_area or r["area"] <= options.max_area)]
+ for row in kept:
+ row.update(id=f"{body.zones[0].id}-{row['id']}", area_id=body.zones[0].id,
+ area_name=body.zones[0].name, origin="detector",
+ sources={"a": body.a.model_dump(), "b": body.b.model_dump()})
+ return kept, asked, imaged
+
+
workqueue.register(JOB, execute)
diff --git a/src/azimut/engine/artifacts.py b/src/azimut/engine/artifacts.py
index 01f4b6b..0fb2bbe 100644
--- a/src/azimut/engine/artifacts.py
+++ b/src/azimut/engine/artifacts.py
@@ -134,6 +134,7 @@ KINDS: dict[str, Kind] = {
# a proof may already be built on it, so it outlives the session.
"compare-session": Kind(path_attr="spec"),
"analysis-zones": Kind(path_attr="spec"),
+ "analysis-area": Kind(path_attr="spec"),
"analysis-follow-up": Kind(path_attr="spec"),
"analysis-run": Kind(path_attr="spec", companions=(Named(layout.analysis_assets_rel),)),
"note": Kind(path_attr="path"),
diff --git a/src/azimut/engine/entities.py b/src/azimut/engine/entities.py
index 36b23f8..c421b36 100644
--- a/src/azimut/engine/entities.py
+++ b/src/azimut/engine/entities.py
@@ -559,6 +559,8 @@ ENTITY_TYPES: tuple[EntityType, ...] = (
hint="two map sources, their layers and the shared camera"),
EntityType("analysis-zones", "Analysis areas", DOCUMENT, "polygon", ANNEX,
hint="saved geographic areas reusable by any Compare analyzer"),
+ EntityType("analysis-area", "Area", DOCUMENT, "mapArea", ANNEX,
+ hint="a named area shared by detections in this case"),
# Named "watch" everywhere a user reads it: the type id is storage, and
# renaming that would migrate files for a word nobody sees.
EntityType("analysis-follow-up", "Analysis watch", DOCUMENT, "clock", ANNEX,
diff --git a/src/azimut/engine/maplayers.py b/src/azimut/engine/maplayers.py
index b3f1672..f1558a5 100644
--- a/src/azimut/engine/maplayers.py
+++ b/src/azimut/engine/maplayers.py
@@ -609,7 +609,8 @@ def _from_geojson(data: bytes, filename: str) -> tuple[list[dict[str, Any]], str
"properties": _properties(
name=_first(source, _NAME_KEYS),
description=_first(source, _DESCRIPTION_KEYS),
- category=category,
+ category=_text(source.get("category"), MAX_NAME) if document.get("azimut_detect_layer") == 1 else category,
+ date=source.get("pass_date", "") if document.get("azimut_detect_layer") == 1 else "",
# simplestyle-spec, which is what every tool that writes a
# styled GeoJSON — geojson.io included — puts the colour in
colour=_hex(source.get("marker-color") or source.get("stroke")
@@ -617,6 +618,9 @@ def _from_geojson(data: bytes, filename: str) -> tuple[list[dict[str, Any]], str
),
}
)
+ if document.get("azimut_detect_layer") == 1:
+ features[-1]["properties"].update({key: _text(source.get(key), MAX_NAME)
+ for key in ("pass_date", "detector", "area_name", "run_id")})
return features, _text(document.get("name"), MAX_NAME)
@@ -1771,6 +1775,26 @@ def add_file(
return add_source(case, data, parsed, source=source, title=title, icons=icons)
+def save_detection_snapshot(case: "Case", key: str, title: str,
+ document: dict[str, Any]) -> dict[str, Any]:
+ """An explicit Detect export, kept independently of its working runs."""
+ data = json.dumps(document, ensure_ascii=False).encode()
+ parsed = parse(data, filename="detect.geojson", title=title)
+ existing = next((r for r in listing(case) if r["source"].get("detection_key") == key), None)
+ if existing is None:
+ return add_source(case, data, parsed, title=title, icons=False,
+ source={"kind": "file", "name": "detect.geojson", "format": "geojson", "detection_key": key})
+ name = existing["name"]
+ spec = _read_spec(case, name)
+ spec["snapshot"] = _store(case, name, data, parsed, icons=False)
+ spec["summary"] = parsed["summary"]
+ spec["updated_at"] = _now()
+ live = {row["name"] for row in parsed["summary"]["categories"]}
+ spec["hidden"] = [entry for entry in spec.get("hidden", []) if entry in live]
+ _write_spec(case, name, spec)
+ return row(name, spec)
+
+
def subscribe(
case: "Case",
url: str,
diff --git a/src/azimut/engine/sentinel.py b/src/azimut/engine/sentinel.py
index 059dc57..63657d6 100644
--- a/src/azimut/engine/sentinel.py
+++ b/src/azimut/engine/sentinel.py
@@ -24,8 +24,9 @@ import math
import re
import xml.etree.ElementTree as ET
from dataclasses import dataclass
-from datetime import date
+from datetime import date, datetime, timedelta
from typing import Any, Callable
+from urllib.parse import quote
import httpx
from PIL import Image, UnidentifiedImageError
@@ -37,6 +38,11 @@ USER_AGENT = "Azimut/0.1 (+local OSINT workbench; single-user)"
# The basemap renders L2A, so date discovery must ask about L2A: L1C passes the
# same orbit but a date list from the wrong collection would be a plausible lie.
WFS_TYPENAME = "DSS2"
+# Sentinel-1 GRD, which Detect's radar methods read. An instance only answers
+# for the collections its own layers use, so this type exists once the user has
+# added a Sentinel-1 layer to the configuration (docs/IMAGERY_PROVIDERS.md).
+S1_TYPENAME = "DSS3"
+COLLECTIONS = {"sentinel2": WFS_TYPENAME, "sentinel1": S1_TYPENAME}
@dataclass(frozen=True)
@@ -390,6 +396,69 @@ function evaluatePixel(p) {{
return base64.b64encode(script.encode("ascii")).decode("ascii")
+# Sentinel-1 backscatter, as Detect's radar methods measure it. The layer the
+# user added decides the processing (orthorectification, backscatter
+# coefficient); ours only decides how the power is rounded into bytes.
+#
+# Power is carried in decibels, a fifth of one per step from -35 dB: calm sea
+# sits near -25 dB in VV and -32 dB in VH, a ship or a roof above 0 dB, and a
+# byte that spans -35 to +16 dB keeps both ends. As with the optical products
+# the first channel is never zero where the radar saw something.
+SAR_DB_FLOOR = -35.0
+SAR_DB_STEP = 0.2
+# The review picture is the usual dual-polarisation composite: co-pol red,
+# cross-pol green, their difference blue. Water goes dark blue, vegetation
+# grey-green, built-up land and hulls white.
+_SAR_COMPOSITE = ((-22.0, 2.0), (-30.0, -6.0), (0.0, 15.0))
+
+
+def _sar_script(values: str) -> str:
+ script = f"""//VERSION=3
+function setup() {{
+ return {{ input: [{{ bands: ["VV", "VH", "dataMask"] }}], output: {{ bands: 4, sampleType: "UINT8" }} }};
+}}
+function db(v) {{ return v > 0 ? 10 * Math.log(v) / Math.LN10 : -99; }}
+function level(v) {{ return Math.max(1, Math.min(255, Math.round((db(v) - ({SAR_DB_FLOOR:g})) / {SAR_DB_STEP:g}))); }}
+function stretch(v, low, high) {{ return Math.max(0, Math.min(255, Math.round((v - low) / (high - low) * 255))); }}
+function evaluatePixel(p) {{
+ if (!p.dataMask) return [0, 0, 0, 0];
+ return {values};
+}}
+"""
+ return base64.b64encode(script.encode("ascii")).decode("ascii")
+
+
+def _sar_evalscript(product: str) -> str:
+ if product == "sar":
+ return _sar_script("[level(p.VV), level(p.VH), 0, 255]")
+ (r_low, r_high), (g_low, g_high), (b_low, b_high) = _SAR_COMPOSITE
+ return _sar_script(
+ f"[stretch(db(p.VV), {r_low:g}, {r_high:g}), stretch(db(p.VH), {g_low:g}, {g_high:g}), "
+ f"stretch(db(p.VV) - db(p.VH), {b_low:g}, {b_high:g}), 255]"
+ )
+
+
+# Where the water is, for the radar vessel method: Sentinel-2's own scene
+# classification, one byte a pixel, read from the clearest pass of the year
+# before (`band_frame` sets that window). Cloud, shadow, snow and defective
+# pixels say nothing either way, and the radar decides there.
+WATER_LAND, WATER_WATER, WATER_UNKNOWN = 1, 2, 3
+WATER_LOOKBACK_DAYS = 365
+_WATER_SCRIPT = base64.b64encode(
+ f"""//VERSION=3
+function setup() {{
+ return {{ input: [{{ bands: ["SCL", "dataMask"] }}], output: {{ bands: 4, sampleType: "UINT8" }} }};
+}}
+function evaluatePixel(p) {{
+ if (!p.dataMask) return [0, 0, 0, 0];
+ if (p.SCL === 6) return [{WATER_WATER}, 0, 0, 255];
+ if ([0, 1, 3, 8, 9, 10, 11].indexOf(p.SCL) >= 0) return [{WATER_UNKNOWN}, 0, 0, 255];
+ return [{WATER_LAND}, 0, 0, 255];
+}}
+""".encode("ascii")
+).decode("ascii")
+
+
# Everything a caller may ask `band_frame` for: Detect's products, measured on
# the server, and Difference's frames, decoded in the browser.
DETECT_PRODUCTS: frozenset[str] = frozenset(
@@ -398,15 +467,117 @@ DETECT_PRODUCTS: frozenset[str] = frozenset(
CHANGE_PRODUCTS: frozenset[str] = frozenset(
{"change-sky", *(f"change-{name}" for name in SPECTRAL_INDEX)}
)
-PRODUCTS: frozenset[str] = frozenset({*CHANGE_PRODUCTS, *DETECT_PRODUCTS})
+# Radar: the measured product, and the picture a candidate is reviewed on,
+# which for Sentinel-1 is rendered by us rather than by a layer's own style.
+SAR_PRODUCTS: frozenset[str] = frozenset({"sar", "sar-picture"})
+PRODUCTS: frozenset[str] = frozenset({*CHANGE_PRODUCTS, *DETECT_PRODUCTS, *SAR_PRODUCTS, "water"})
def _evalscript(product: str) -> str:
+ if product == "water":
+ return _WATER_SCRIPT
if product in CHANGE_PRODUCTS:
return _change_evalscript(product)
+ if product in SAR_PRODUCTS:
+ return _sar_evalscript(product)
return _detect_evalscript(product)
+# -- the Sentinel-1 basemap -------------------------------------------------------
+
+RADAR_ID = "sentinel1"
+_PASS_TIME_RE = re.compile(r"^([01]\d|2[0-3])([0-5]\d)([0-5]\d)$")
+
+
+def radar_variant_id(day: str | None = None, time: str = "") -> str:
+ """The radar basemap's id for one pass: ``sentinel1~2026-05-14~054210``.
+
+ A day alone mosaics every pass of that day, and no day at all is the most
+ recent pass, which is the layer's own default. The time rides without its
+ colons, because the id is also a folder name in the tile cache.
+ """
+ if not day:
+ return RADAR_ID
+ parts = [RADAR_ID, day]
+ if time:
+ parts.append(time.replace(":", ""))
+ return VARIANT_SEP.join(parts)
+
+
+def parse_radar_variant(spec: str) -> tuple[str, str]:
+ """``"2026-05-14~054210"`` → ``("2026-05-14", "05:42:10")``; the time may be absent."""
+ parts = spec.split(VARIANT_SEP)
+ if not 1 <= len(parts) <= 2:
+ raise ValueError(f"malformed Sentinel-1 variant '{spec}'")
+ day = parts[0]
+ _window(day, day)
+ if len(parts) == 1:
+ return day, ""
+ found = _PASS_TIME_RE.match(parts[1])
+ if not found:
+ raise ValueError(f"malformed pass time '{parts[1]}' (expected HHMMSS)")
+ return day, ":".join(found.groups())
+
+
+def radar_wmts_url(layer: str, day: str = "", time: str = "") -> str:
+ """The WMTS GetTile template for the radar basemap, drawn in our composite.
+
+ The layer is the user's Sentinel-1 layer; its own style is replaced by the
+ picture Detect reviews radar candidates on, so the map and the evidence
+ read alike. JPEG like the optical basemap: speckle costs PNG a fortune.
+ """
+ if not _LAYER_RE.match(layer or ""):
+ raise ValueError(f"malformed layer '{layer}'")
+ url = (
+ f"{BASE}/wmts/{{key}}"
+ "?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0"
+ f"&LAYER={layer}&TILEMATRIXSET=PopularWebMercator512"
+ "&TILEMATRIX={z}&TILECOL={x}&TILEROW={y}&FORMAT=image/jpeg"
+ f"&EVALSCRIPT={quote(_sar_evalscript('sar-picture'), safe='')}"
+ )
+ if day:
+ url += f"&TIME={pass_window(day, time)}"
+ return url
+
+
+def radar_label(day: str, time: str) -> str:
+ """How a radar variant reads: "2026-05-14 05:42 UTC", a day, or the latest."""
+ if not day:
+ return "most recent pass"
+ return f"{day} {time[:5]} UTC" if time else day
+
+
+def sar_decibels(level: Any) -> Any:
+ """The byte a radar product carries, back in decibels."""
+ return level * SAR_DB_STEP + SAR_DB_FLOOR
+
+
+# How far either side of a Sentinel-1 pass the request window reaches. A pass
+# crosses an area in seconds; the other direction comes twelve hours later and
+# the next orbit a hundred minutes later over ground 2,700 km away, so twenty
+# minutes holds one pass and nothing else.
+PASS_WINDOW_MINUTES = 20
+_TIME_RE = re.compile(r"^([01]\d|2[0-3]):[0-5]\d:[0-5]\d$")
+
+
+def pass_window(day: str, time: str = "") -> str:
+ """The ``TIME`` value for one pass: a day, or minutes around a known time.
+
+ A day is enough for Sentinel-2, which passes once. Sentinel-1 can pass the
+ same day twice, morning and evening in opposite directions, and a window of
+ the whole day would mosaic the two looks into one frame.
+ """
+ if not time:
+ return _window(day, day)
+ if not _TIME_RE.match(time):
+ raise ValueError(f"malformed pass time '{time}' (expected HH:MM:SS)")
+ _window(day, day)
+ moment = datetime.fromisoformat(f"{day}T{time}+00:00")
+ reach = timedelta(minutes=PASS_WINDOW_MINUTES)
+ stamp = "%Y-%m-%dT%H:%M:%SZ"
+ return f"{(moment - reach).strftime(stamp)}/{(moment + reach).strftime(stamp)}"
+
+
def band_frame(
instance: str,
bbox: tuple[float, float, float, float],
@@ -417,14 +588,17 @@ def band_frame(
maxcc: int = DEFAULT_MAXCC,
*,
layer: str = DEFAULT_LAYER,
+ time: str = "",
get: Callable[..., Any] | None = None,
) -> bytes:
"""One band product over a Web Mercator box, rendered for one day.
``layer`` only chooses the data collection the instance reads (its
evalscript is replaced by ours), so the true-colour layer every standard
- configuration has is the default. The image is validated before it is
- handed on: a PNG, the size asked for, within the byte budget.
+ configuration has is the default, and a radar product names the user's
+ Sentinel-1 layer. ``time`` narrows the day to one pass (``pass_window``).
+ The image is validated before it is handed on: a PNG, the size asked for,
+ within the byte budget.
"""
if product not in PRODUCTS:
raise ValueError(f"unknown band product '{product}'")
@@ -448,10 +622,15 @@ def band_frame(
"WIDTH": str(width),
"HEIGHT": str(height),
"FORMAT": "image/png",
- "TIME": f"{checked_day}/{checked_day}",
+ "TIME": pass_window(str(checked_day), time),
"MAXCC": str(checked_maxcc),
"EVALSCRIPT": _evalscript(product),
}
+ if product == "water":
+ # The year before the day, the least cloudy pass first wherever it has
+ # pixels: where the shore is does not change with the weather.
+ start = date.fromisoformat(str(checked_day)) - timedelta(days=WATER_LOOKBACK_DAYS)
+ params.update(TIME=f"{start.isoformat()}/{checked_day}", PRIORITY="leastCC")
fetch = get or httpx.get
response = fetch(
f"{BASE}/wms/{instance}", params=params,
@@ -583,6 +762,70 @@ def _window(start: str, end: str) -> str:
return f"{start}/{end}"
+# A product name carries its sensing start: ``S1A_IW_GRDH_1SDV_20260105T051824_…``.
+_SENSED_RE = re.compile(r"_(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})_")
+# Two looks at one place are the same track when they pass at the same time of
+# day. A track repeats to the second every twelve days, whichever Sentinel-1
+# flies it, while the neighbouring track that also sees the place passes about
+# eight minutes earlier or later, so four minutes tells them apart.
+SAME_TRACK_MINUTES = 4
+
+
+def _sensed(props: dict[str, Any]) -> str:
+ """The pass's UTC time of day, ``HH:MM:SS``, or '' when nothing says."""
+ value = str(props.get("time") or "")[:8]
+ if _TIME_RE.match(value):
+ return value
+ for name in ("id", "path"):
+ found = _SENSED_RE.search(str(props.get(name) or ""))
+ if found:
+ hour, minute, second = found.groups()[3:]
+ candidate = f"{hour}:{minute}:{second}"
+ if _TIME_RE.match(candidate):
+ return candidate
+ return ""
+
+
+def _minutes(time: str) -> int:
+ hour, minute, second = (int(part) for part in time.split(":"))
+ return hour * 60 + minute + (1 if second >= 30 else 0)
+
+
+def same_track(one: str, other: str) -> bool:
+ """Whether two pass times are one track: the same look, so comparable."""
+ if not (_TIME_RE.match(one or "") and _TIME_RE.match(other or "")):
+ return False
+ gap = abs(_minutes(one) - _minutes(other)) % 1440
+ return min(gap, 1440 - gap) <= SAME_TRACK_MINUTES
+
+
+def orbit_direction(time: str, lon: float) -> str:
+ """Which way Sentinel-1 was flying: descending at dawn, ascending at dusk.
+
+ Its orbit keeps the sun where it is, crossing every latitude near 06:00
+ local solar time southbound and 18:00 northbound, so the local hour of the
+ pass is enough to say which way it went.
+ """
+ if not _TIME_RE.match(time or ""):
+ return ""
+ local = (_minutes(time) / 60 + lon / 15) % 24
+ return "descending" if local < 12 else "ascending"
+
+
+def _pass_key(entries: dict[str, dict[str, Any]], day: str, time: str) -> str:
+ """The entry a granule belongs to: its day, and for radar its pass.
+
+ Slices of one pass are sensed seconds apart; a second pass the same day is
+ the other direction, hours away, and a separate image.
+ """
+ if not time:
+ return day
+ for key, entry in entries.items():
+ if entry["date"] == day and same_track(entry["time"], time):
+ return key
+ return f"{day}T{time}"
+
+
def _passes(
instance: str,
box: Box,
@@ -590,9 +833,13 @@ def _passes(
start: str,
end: str,
*,
+ collection: str = "sentinel2",
get: Callable[..., Any] | None = None,
) -> tuple[dict[str, dict[str, Any]], int]:
- """One WFS query, collapsed to per-day entries and the samples each covers.
+ """One WFS query, collapsed to per-pass entries and the samples each covers.
+
+ 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
@@ -601,13 +848,16 @@ def _passes(
Raises httpx.HTTPError / ValueError upward: a date list that failed must not
read as "no imagery here".
"""
+ if collection not in COLLECTIONS:
+ raise ValueError(f"unknown collection '{collection}'")
+ radar = collection == "sentinel1"
fetch = get or httpx.get
left, bottom, right, top = box
params = {
"SERVICE": "WFS",
"REQUEST": "GetFeature",
"VERSION": "2.0.0",
- "TYPENAMES": WFS_TYPENAME,
+ "TYPENAMES": COLLECTIONS[collection],
"OUTPUTFORMAT": "application/json",
# EPSG:4326 puts latitude first — the axis order the CRS declares, not
# the lon/lat habit. Swapped, the box lands in the ocean off Somalia.
@@ -624,10 +874,14 @@ def _passes(
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 []
- by_date: dict[str, dict[str, Any]] = {}
+ by_pass: dict[str, dict[str, Any]] = {}
for feature in features:
props = feature.get("properties") or {}
day = str(props.get("date") or "")[:10]
@@ -637,16 +891,28 @@ def _passes(
hit = _covered(feature, samples, box)
if not hit:
continue
- cloud = _cloud(props)
- entry = by_date.setdefault(
- day, {"date": day, "cloud": cloud, "granules": 0, "covered": set()}
+ cloud = None if radar else _cloud(props)
+ time = _sensed(props) if radar else ""
+ key = _pass_key(by_pass, day, time)
+ entry = by_pass.setdefault(
+ key, {"date": day, "time": time, "cloud": cloud, "granules": 0, "covered": set()}
)
entry["granules"] += 1
entry["covered"] |= hit
+ # a pass is named by the first of its slices to cross the area
+ if time and time < entry["time"] and same_track(time, entry["time"]):
+ entry["time"] = time
# 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_date, len(features)
+ return by_pass, len(features)
+
+
+def _listed(entry: dict[str, Any], lon: float, collection: str) -> dict[str, Any]:
+ row = {"date": entry["date"], "cloud": entry["cloud"], "granules": entry["granules"]}
+ if collection == "sentinel1":
+ row.update(time=entry["time"], orbit=orbit_direction(entry["time"], lon))
+ return row
def dates(
@@ -656,13 +922,15 @@ def dates(
start: str,
end: str,
*,
+ collection: str = "sentinel2",
get: Callable[..., Any] | None = None,
) -> list[dict[str, Any]]:
- """Sentinel-2 acquisition dates over a point, newest first.
+ """Acquisition dates over a point, newest first.
Each entry: ``{"date", "cloud", "granules"}`` — ``cloud`` is the least
cloudy granule covering the point that day (None when the service didn't
- say), ``granules`` how many covered it.
+ say), ``granules`` how many covered it. A Sentinel-1 entry is one pass and
+ adds its ``time`` and ``orbit`` direction.
This is what makes a date picker honest: without it the user guesses a date,
pays a tile, and finds out it was cloud or a gap. For a drawn area rather
@@ -670,11 +938,10 @@ 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, get=get)
+ found, _ = _passes(instance, box, [(lon, lat)], start, end, collection=collection, get=get)
return sorted(
- ({"date": e["date"], "cloud": e["cloud"], "granules": e["granules"]}
- for e in found.values()),
- key=lambda entry: entry["date"], reverse=True,
+ (_listed(e, lon, collection) for e in found.values()),
+ key=lambda entry: (entry["date"], entry.get("time", "")), reverse=True,
)
@@ -727,9 +994,10 @@ def acquisitions(
start: str,
end: str,
*,
+ collection: str = "sentinel2",
get: Callable[..., Any] | None = None,
) -> dict[str, Any]:
- """Sentinel-2 acquisitions over drawn areas, newest first.
+ """Acquisitions over drawn areas, newest first.
Each entry adds ``coverage`` to what ``dates`` reports: the share of the
areas that day's granules actually reach, 0…1. It is the number a point
@@ -750,12 +1018,13 @@ 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, get=get)
+ found, features = _passes(instance, box, samples, start, end, collection=collection, get=get)
+ middle = (box[0] + box[2]) / 2
listed = sorted(
- ({"date": entry["date"], "cloud": entry["cloud"], "granules": entry["granules"],
+ ({**_listed(entry, middle, collection),
"coverage": round(len(entry["covered"]) / len(samples), 3)}
for entry in found.values()),
- key=lambda entry: entry["date"], reverse=True,
+ key=lambda entry: (entry["date"], entry.get("time", "")), reverse=True,
)
return {"dates": listed, "truncated": features >= _MAX_FEATURES}
@@ -875,3 +1144,96 @@ def capabilities_layers(
}
)
return found
+
+
+# -- the Sentinel-1 layer --------------------------------------------------------
+
+# Layers the Sentinel-2 templates ship, which are therefore never the Sentinel-1
+# layer a user added: looking for theirs need not spend a request on these.
+TEMPLATE_LAYERS = frozenset({
+ *(entry.id for entry in LAYERS), *KNOWN_HINTS, "AGRICULTURE", "ATMOSPHERIC_PENETRATION",
+ "BATHYMETRIC", "COLOR_INFRARED", "COLOR_INFRARED__URBAN_", "GEOLOGY", "VEGETATION_INDEX",
+})
+# Where a probe looks: the North Sea off Rotterdam, which Sentinel-1 sees from
+# several tracks every few days, so a month back always holds a pass.
+_PROBE_POINT = (51.95, 4.05)
+_PROBE_DAYS = 30
+_PROBE_SCRIPT = base64.b64encode(
+ b"""//VERSION=3
+function setup() {
+ return { input: [{ bands: ["VV", "VH", "dataMask"] }], output: { bands: 1, sampleType: "UINT8" } };
+}
+function evaluatePixel(p) {
+ return [p.dataMask && (p.VV > 0 || p.VH > 0) ? 255 : 0];
+}
+"""
+).decode("ascii")
+_WFS_NS = {"wfs": "http://www.opengis.net/wfs/2.0"}
+
+
+def ogc_error(body: str) -> str:
+ """The human half of an OGC exception report, or the body itself."""
+ try:
+ root = ET.fromstring(body)
+ except ET.ParseError:
+ return body.strip()[:300]
+ texts = [node.text.strip() for node in root.iter() if node.text and node.text.strip()]
+ return " ".join(texts)[:300] or body.strip()[:300]
+
+
+def serves_sentinel1(instance: str, *, get: Callable[..., Any] | None = None) -> bool:
+ """Whether any layer of the instance reads Sentinel-1.
+
+ WFS lists a feature type per collection the instance's layers use, which
+ is the one place the configuration says what its layers read. Asking costs
+ no processing units.
+ """
+ fetch = get or httpx.get
+ response = fetch(
+ f"{BASE}/wfs/{instance}",
+ params={"SERVICE": "WFS", "REQUEST": "GetCapabilities", "VERSION": "2.0.0"},
+ headers={"User-Agent": USER_AGENT}, timeout=15,
+ )
+ response.raise_for_status()
+ root = ET.fromstring(response.text)
+ names = {(node.text or "").strip() for node in root.iterfind(".//wfs:FeatureType/wfs:Name", _WFS_NS)}
+ return S1_TYPENAME in names
+
+
+def probe_sar_layer(
+ instance: str, layer: str, today: date | None = None, *, get: Callable[..., Any] | None = None
+) -> dict[str, Any]:
+ """Whether ``layer`` reads Sentinel-1 VV and VH: one tiny render.
+
+ A Sentinel-2 layer refuses the script outright, as does a Sentinel-1 layer
+ set to the polar HH/HV polarisations, so a 400 is the answer "not this one"
+ and the service's own sentence says why. Billed as one request.
+ """
+ if not _LAYER_RE.match(layer or ""):
+ raise ValueError(f"malformed layer '{layer}'")
+ today = today or date.today()
+ lat, lon = _PROBE_POINT
+ earth_radius = 6_378_137.0
+ x = earth_radius * math.radians(lon)
+ y = earth_radius * math.log(math.tan(math.pi / 4 + math.radians(lat) / 2))
+ half = 2_000.0
+ params = {
+ "SERVICE": "WMS", "REQUEST": "GetMap", "VERSION": "1.3.0", "LAYERS": layer,
+ "CRS": "EPSG:3857", "BBOX": f"{x - half},{y - half},{x + half},{y + half}",
+ "WIDTH": str(_COVERAGE_SIZE), "HEIGHT": str(_COVERAGE_SIZE), "FORMAT": "image/png",
+ "TIME": f"{(today - timedelta(days=_PROBE_DAYS)).isoformat()}/{today.isoformat()}",
+ "EVALSCRIPT": _PROBE_SCRIPT,
+ }
+ fetch = get or httpx.get
+ response = fetch(f"{BASE}/wms/{instance}", params=params,
+ headers={"User-Agent": USER_AGENT}, timeout=20)
+ if response.status_code == 400:
+ return {"ok": False, "layer": layer, "detail": ogc_error(response.text)}
+ response.raise_for_status()
+ try:
+ with Image.open(io.BytesIO(response.content)) as source:
+ seen = any(source.convert("L").tobytes())
+ except (OSError, UnidentifiedImageError) as exc:
+ raise CoverageError("the probe returned no readable image") from exc
+ return {"ok": True, "layer": layer, "detail": "reads Sentinel-1 VV and VH" if seen else
+ "reads Sentinel-1, though it saw nothing at the probe point this month"}
diff --git a/src/azimut/engine/tiles.py b/src/azimut/engine/tiles.py
index c94071e..e5915dd 100644
--- a/src/azimut/engine/tiles.py
+++ b/src/azimut/engine/tiles.py
@@ -257,6 +257,28 @@ def all_providers() -> list[Provider]:
)
)
+ # Sentinel-1: the same account and quota, through the radar layer the user
+ # added to the same configuration. Offered once that layer is known.
+ radar_layer = str(settings.get("sentinel1_layer") or "")
+ if sentinelhub_key and radar_layer:
+ providers.append(
+ Provider(
+ id=sentinel.RADAR_ID,
+ label="Sentinel-1 radar (Copernicus)",
+ url=sentinel.radar_wmts_url(radar_layer).replace("{key}", sentinelhub_key),
+ attribution="© Copernicus Sentinel data / Sentinel Hub",
+ max_zoom=18,
+ max_native_zoom=14,
+ imagery=True,
+ capturable=True,
+ cacheable=True,
+ meter="sentinelhub",
+ tile_size=512,
+ zoom_offset=1,
+ eco_max_zoom=11,
+ )
+ )
+
for entry in settings.get("tile_providers", []):
try:
url = entry["url"]
@@ -302,6 +324,8 @@ def get_provider(provider_id: str) -> Provider:
if provider.id == base_id:
if not sep:
return provider
+ if provider.id == sentinel.RADAR_ID:
+ return _radar_provider(provider, provider_id, spec)
if provider.id != "sentinel2":
raise KeyError(f"provider '{base_id}' has no variants")
try:
@@ -319,6 +343,25 @@ def get_provider(provider_id: str) -> Provider:
raise KeyError(f"unknown tile provider '{provider_id}'")
+def _radar_provider(provider: Provider, provider_id: str, spec: str) -> Provider:
+ """One Sentinel-1 pass (or day) of the radar basemap."""
+ try:
+ day, time = sentinel.parse_radar_variant(spec)
+ except ValueError as exc:
+ raise KeyError(str(exc)) from exc
+ layer = re.search(r"[?&]LAYER=([A-Z0-9_]+)", provider.url)
+ if not layer:
+ raise KeyError("Sentinel-1 provider URL carries no layer")
+ return replace(
+ provider,
+ id=provider_id,
+ label=f"{provider.label} · {sentinel.radar_label(day, time)}",
+ url=sentinel.radar_wmts_url(layer.group(1), day, time).replace(
+ "{key}", _sentinel_key_from(provider.url)
+ ),
+ )
+
+
def _wayback_provider(spec: str | None) -> Provider:
"""One Wayback release as a provider, the newest when none is named.
diff --git a/src/azimut/engine/wayback.py b/src/azimut/engine/wayback.py
index 7e3ec2d..22ae069 100644
--- a/src/azimut/engine/wayback.py
+++ b/src/azimut/engine/wayback.py
@@ -3,16 +3,17 @@
Esri republishes World Imagery a few times a month and keeps each release
online under its own number. That archive is what answers "what did this place
look like before", key-less, from the same imagery the default basemap already
-shows. Three services make it up, and all three are asked only once the analyst
-picks the basemap or opens its picker (local-first):
+shows. Three services make it up, and none is asked before the analyst picks
+the basemap (local-first):
- **The release list** (`CONFIG_URL`), one JSON document naming every release,
- its publication date and its metadata service.
+ its publication date and its metadata service. Read once the basemap shows.
- **The tilemap**, which answers for one tile and one release which release
that tile's pixels were actually published in. Walking it backwards shortlists
the releases that touched a point without reading every release, the same walk
Esri's own Wayback app makes. It answers in bytes, not in ground, so the
shortlist is then settled on the pixels: one tile per candidate, compared.
+ Walked only when the analyst asks for a point's changes.
- **The metadata service** of each release, which says when the pixels under a
point were acquired and by which sensor. A release date is when Esri
published the mosaic, which can be years after the picture was taken.
diff --git a/src/azimut/engine/workqueue.py b/src/azimut/engine/workqueue.py
index fd1e163..f716653 100644
--- a/src/azimut/engine/workqueue.py
+++ b/src/azimut/engine/workqueue.py
@@ -95,6 +95,23 @@ def _settle(case: "CaseType", job: dict[str, Any]) -> bool:
return False
+def let_others_through(case: "CaseType", kind: str) -> None:
+ """Settle the case's queued jobs of every *other* kind, from inside a long
+ ``kind`` job, on the calling thread.
+
+ A handler that works in steps calls this between them, holding no lock. It
+ keeps the one-worker rule, because nothing runs beside anything else: the
+ long job simply pauses while the short ones go through. Jobs of ``kind``
+ itself keep their place in the queue.
+ """
+ others = [name for name in HANDLERS if name != kind]
+ if not others:
+ return
+ while (job := case.claim_job(kinds=others)) is not None:
+ if _settle(case, job):
+ raise JobRemoved()
+
+
def drain(case: "CaseType") -> int:
"""Process every queued job for one case, one at a time, in the calling
thread. Returns how many jobs were handled. Synchronous and deterministic —
diff --git a/tests/fullcase.py b/tests/fullcase.py
index e26154b..a5da0e7 100644
--- a/tests/fullcase.py
+++ b/tests/fullcase.py
@@ -78,6 +78,7 @@ class FullCase:
compare_session: str = ""
compare_image: str = "" # the session's render, a media working file
analyzer_zones: str = ""
+ analyzer_area: str = ""
analyzer_followup: str = ""
analyzer_run: str = ""
proof: str = ""
@@ -537,7 +538,11 @@ def build_full_case(client, name: str = "Full case") -> FullCase:
from analyzerfixture import sample_input, seed_images
analysis = sample_input()
seed_images(analysis)
+ from azimut.engine.analysis_models import Zone
+ ring = Zone.model_validate(analysis["zones"][0]).ring()
for kind, body, attr in (
+ ("areas", {"name": "Port", "colour": "#38bdf8", "geometry": {
+ "type": "Polygon", "coordinates": [ring + [ring[0]]]}}, "analyzer_area"),
("zones", {"title": "Port areas", "zones": analysis["zones"]}, "analyzer_zones"),
("followups", analysis, "analyzer_followup"),
("runs", analysis, "analyzer_run"),
diff --git a/tests/test_analyzers.py b/tests/test_analyzers.py
index 9f8b7d5..85daa9c 100644
--- a/tests/test_analyzers.py
+++ b/tests/test_analyzers.py
@@ -8,6 +8,7 @@ import pytest
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.analysis_models import (
BUILTINS,
@@ -67,6 +68,9 @@ def scenario(client, monkeypatch):
def run(client, case, body):
result = client.post(f"/api/cases/{case.id}/analysis/runs", json=body)
assert result.status_code == 200, result.text
+ if result.json().get("duplicates"):
+ result = client.post(f"/api/cases/{case.id}/analysis/runs", json={**result.json()["input"], "run_anyway": True})
+ assert result.status_code == 200, result.text
workqueue.drain(case)
return client.get(f"/api/cases/{case.id}/analysis/runs/{result.json()['id']}").json()
@@ -120,8 +124,8 @@ def test_keeping_a_candidate_is_the_only_thing_that_reaches_the_case(client, sce
assert places == [] # candidates are not places until one is kept
endpoint = f"/api/cases/{case.id}/analysis/runs/{saved['id']}/results/{row['id']}"
- # Dismissing says so and leaves nothing behind.
- assert client.patch(endpoint, json={"review": "dismissed"}).json()["review"] == "dismissed"
+ # Keeping within a run leaves the case's entities alone.
+ assert client.patch(endpoint, json={"review": "noted"}).json()["review"] == "noted"
assert [e for e in case.list_entities() if e["type"] == "place"] == []
# Keeping is one act: it records the verdict and files the pin together.
@@ -136,6 +140,7 @@ def test_keeping_a_candidate_is_the_only_thing_that_reaches_the_case(client, sce
assert client.delete(endpoint + "/promote").json()["result"]["review"] == "new"
assert case.get_entity(kept["entity"]["id"]) is None
assert client.patch(endpoint, json={"review": "dismissed"}).status_code == 200
+ assert client.get(endpoint + "/preview").status_code == 404
def test_a_candidate_preview_is_enlarged_so_its_pixels_can_be_read(client, scenario):
@@ -150,7 +155,46 @@ def test_a_candidate_preview_is_enlarged_so_its_pixels_can_be_read(client, scena
zoom = round(320 / crop)
assert zoom > 1
assert preview.width == 2 * (box[2] + 2 * 20) * zoom + 8
- assert preview.height == (box[3] + 2 * 20) * zoom + 48
+ # a band of labels above, and two lines of point and attribution below
+ assert preview.height == (box[3] + 2 * 20) * zoom + 24 + 40
+
+
+def test_a_candidate_picture_says_when_and_where_it_was_taken(client, scenario):
+ """A pinned crop outlives the run that made it, so its face carries the
+ date of each image and the point, not only the letters."""
+ case, body = scenario
+ saved = run(client, case, body)
+ row = saved["results"][0]
+ sources = [saved["frames"][key]["source"] for key in row["parts"][0]["frames"]]
+ labels, foot = analyzers_api.preview_captions(saved, row, sources)
+ lon, lat = row["coordinates"]
+ assert labels == [f"A · {saved['input']['a']['date']}", f"B · {saved['input']['b']['date']}"]
+ assert foot == [f"{lat:.5f}, {lon:.5f}", "Copernicus Sentinel data / Sentinel Hub"]
+ assert analyzers_api.preview_captions(saved, row, sources[-1:])[0] == [saved["input"]["b"]["date"]]
+ endpoint = f"/api/cases/{case.id}/analysis/runs/{saved['id']}/results/{row['id']}"
+ pinned = client.post(endpoint + "/promote", json={"title": "Checked"}).json()
+ with Image.open(case.resolve_inside(pinned["image"])) as image:
+ # the lines are drawn, not only composed: the foot holds ink
+ foot_band = image.convert("RGB").crop((0, image.height - 40, image.width, image.height))
+ assert (np.asarray(foot_band) != (20, 24, 32)).any()
+
+
+def test_a_narrow_candidate_picture_still_has_room_for_its_label(client, scenario):
+ """A radar pass names its time too, which is wider than a thin crop."""
+ case, body = scenario
+ saved = run(client, case, body)
+ row = saved["results"][0]
+ for key in row["parts"][0]["frames"]:
+ saved["frames"][key]["source"] = {**saved["frames"][key]["source"], "provider": "sentinel1",
+ "time": "16:32:10"}
+ labels, _ = analyzers_api.preview_captions(saved, row, [saved["frames"][key]["source"]
+ for key in row["parts"][0]["frames"]])
+ assert labels[0].endswith("16:32 UTC · radar")
+ row["parts"][0]["box"] = [0, 0, 2, 40]
+ with Image.open(io.BytesIO(analyzers_api.preview_bytes(case, saved, row))) as preview:
+ crop = 2 + 2 * 20
+ zoom = round(320 / (40 + 2 * 20))
+ assert preview.width > 2 * crop * zoom + 8
def test_a_candidate_across_a_tile_edge_is_one_candidate_with_one_picture(client, scenario):
@@ -216,7 +260,6 @@ def test_recipe_backup_and_duplicate_preserve_builtin(client):
def test_cancelled_run_never_fetches_and_does_not_reappear(client, scenario):
case, body = scenario
saved = client.post(f"/api/cases/{case.id}/analysis/runs", json=body).json()
- assert client.post(f"/api/cases/{case.id}/analysis/runs", json=body).status_code == 409
url = f"/api/cases/{case.id}/analysis/runs/{saved['id']}"
assert client.delete(url).status_code == 409
assert client.post(url + "/cancel").json()["status"] == "cancelled"
@@ -226,6 +269,147 @@ def test_cancelled_run_never_fetches_and_does_not_reappear(client, scenario):
assert client.get(url).status_code == 404
+def test_runs_wait_their_turn_and_one_detection_is_never_swept_twice_at_once(client, scenario):
+ case, body = scenario
+ base = f"/api/cases/{case.id}/analysis"
+ first = client.post(f"{base}/runs", json=body).json()
+ second = client.post(f"{base}/runs", json={**body, "title": "Another pass"}).json()
+ assert [first["status"], second["status"]] == ["queued", "queued"]
+ watch = client.post(f"{base}/followups", json={**body, "title": "Harbour"}).json()
+ queued = client.post(f"{base}/followups/{watch['id']}/run")
+ assert queued.status_code == 200, queued.text
+ again = client.post(f"{base}/followups/{watch['id']}/run")
+ assert again.status_code == 409
+ assert "already queued or running" in again.json()["detail"]
+ workqueue.drain(case)
+ statuses = {row["id"]: row["status"] for row in client.get(f"{base}/runs").json()}
+ assert statuses == {first["id"]: "ready", second["id"]: "ready", queued.json()["id"]: "ready"}
+ # finished, the same detection can go again
+ assert client.post(f"{base}/followups/{watch['id']}/run").status_code == 200
+
+
+def test_a_saved_detection_runs_as_it_was_saved(client, scenario):
+ case, body = scenario
+ base = f"/api/cases/{case.id}/analysis"
+ watch = client.post(f"{base}/followups", json={**body, "title": "Harbour weekly"}).json()
+ started = client.post(f"{base}/followups/{watch['id']}/run").json()
+ assert started["title"] == "Harbour weekly"
+ assert started["input"]["followup_id"] == watch["id"]
+ assert Zone.model_validate(started["input"]["zones"][0]).ring() == Zone.model_validate(body["zones"][0]).ring()
+ assert started["input"]["zones"][0]["id"] == watch["area_dates"][0]["area_id"]
+ assert client.post(f"{base}/followups/abcdefabcdef/run").status_code == 404
+ # A watch saved against Wayback reopens undated, and says so rather than failing later.
+ analyzers.save(case, "followups", {**deepcopy(body), "title": "Old", "followup_id": None,
+ "a": {"provider": "esri-wayback", "release": 3}})
+ old = next(row for row in client.get(f"{base}/followups").json() if row["title"] == "Old")
+ refused = client.post(f"{base}/followups/{old['id']}/run")
+ assert refused.status_code == 422
+ assert refused.json()["detail"] == "choose a reference date for each area"
+
+
+def test_lists_say_what_each_item_looks_for_and_what_is_left_to_review(client, scenario):
+ case, body = scenario
+ base = f"/api/cases/{case.id}/analysis"
+ watch = client.post(f"{base}/followups", json={**body, "title": "Harbour"}).json()
+ client.post(f"{base}/followups/{watch['id']}/run")
+ workqueue.drain(case)
+ [listed] = client.get(f"{base}/followups").json()
+ assert listed["analyzer"] == body["recipe"]["name"] and listed["areas"] == 1
+ # the shapes travel with the row, so the map can draw every watched area
+ assert Zone.model_validate(listed["zones"][0]).ring() == Zone.model_validate(body["zones"][0]).ring()
+ assert listed["date_rule"] == "manual" and listed["colour"] == body["recipe"]["colour"]
+ [ran] = client.get(f"{base}/runs").json()
+ assert ran["followup_id"] == watch["id"]
+ assert ran["dates"] == [body["a"]["date"], body["b"]["date"]]
+ assert ran["count"] == 1 and ran["to_review"] == 1 and ran["total"] == 1
+ result = client.get(f"{base}/runs/{ran['id']}").json()["results"][0]
+ client.patch(f"{base}/runs/{ran['id']}/results/{result['id']}", json={"review": "dismissed"})
+ assert client.get(f"{base}/runs").json()[0]["to_review"] == 0
+
+
+def test_a_sweep_lets_other_queued_work_through_between_its_tiles(client, scenario, monkeypatch):
+ case, body = scenario
+ monkeypatch.setattr(workqueue, "HANDLERS", dict(workqueue.HANDLERS))
+ seen = []
+ workqueue.register("probe", lambda c, job: seen.append(
+ [row["status"] for row in analyzers.listing(c, "runs")]))
+ client.post(f"/api/cases/{case.id}/analysis/runs", json=body)
+ workqueue.enqueue(case, "probe", payload={})
+ workqueue.drain(case)
+ # queued after the sweep, settled while it was still running
+ assert seen == [["running"]]
+ assert analyzers.listing(case, "runs")[0]["status"] == "ready"
+
+
+def test_a_candidate_can_be_kept_in_the_detections_view_without_touching_the_case(client, scenario):
+ case, body = scenario
+ base = f"/api/cases/{case.id}/analysis"
+ watch = client.post(f"{base}/followups", json={**body, "title": "Harbour", "note": "Weekly look"}).json()
+ saved = run(client, case, {**body, "followup_id": watch["id"]})
+ row = saved["results"][0]
+ endpoint = f"{base}/runs/{saved['id']}/results/{row['id']}"
+ before = len(case.list_entities())
+ noted = client.patch(endpoint, json={"review": "noted"}).json()
+ assert noted["review"] == "noted" and noted["entity_id"] is None
+ # nothing reaches the case: no pin, no evidence file
+ assert len(case.list_entities()) == before
+ [found] = client.get(f"{base}/followups/{watch['id']}/findings").json()
+ assert found["id"] == row["id"] and found["run_id"] == saved["id"]
+ assert found["date"] == body["b"]["date"] and found["run_title"] == saved["title"]
+ # a dismissal takes it back out of the findings
+ client.patch(endpoint, json={"review": "dismissed"})
+ assert client.get(f"{base}/followups/{watch['id']}/findings").json() == []
+ assert client.post(endpoint + "/promote", json={"title": "Gone"}).status_code == 404
+ # A later sweep can find the dismissed candidate again.
+ saved = run(client, case, {**body, "followup_id": watch["id"]})
+ endpoint = f"{base}/runs/{saved['id']}/results/{saved['results'][0]['id']}"
+ client.post(endpoint + "/promote", json={"title": "Kept change"})
+ [pinned] = client.get(f"{base}/followups/{watch['id']}/findings").json()
+ assert pinned["review"] == "kept" and pinned["entity_id"]
+ assert next(r for r in client.get(f"{base}/runs").json() if r["id"] == saved["id"])["marked"] == 1
+
+
+def test_a_routine_relaunched_on_a_chosen_pass_asks_the_catalogue_nothing(client, scenario):
+ case, body = scenario
+ base = f"/api/cases/{case.id}/analysis"
+ routine = {**deepcopy(body), "title": "Harbour", "date_rule": "latest_previous"}
+ watch = client.post(f"{base}/followups", json=routine).json()
+ # `scenario` makes any network call an error, so a lookup here would fail the run
+ started = client.post(f"{base}/followups/{watch['id']}/run", json={"date": body["b"]["date"]}).json()
+ workqueue.drain(case)
+ saved = client.get(f"{base}/runs/{started['id']}").json()
+ assert saved["status"] == "ready", saved["message"]
+ assert saved["input"]["b"]["date"] == body["b"]["date"]
+ # the first run of a routine compares against the reference it was saved with
+ assert saved["input"]["a"]["date"] == body["a"]["date"]
+
+
+def test_a_second_pass_of_a_routine_compares_against_the_pass_before_it(client, scenario, monkeypatch):
+ case, body = scenario
+ base = f"/api/cases/{case.id}/analysis"
+ routine = {**deepcopy(body), "title": "Harbour", "date_rule": "latest_previous"}
+ watch = client.post(f"{base}/followups", json=routine).json()
+ client.post(f"{base}/followups/{watch['id']}/run", json={"date": body["b"]["date"]})
+ workqueue.drain(case)
+ later = "2026-05-18"
+ seed_images({**body, "a": body["b"], "b": {**body["b"], "date": later}})
+ second = client.post(f"{base}/followups/{watch['id']}/run", json={"date": later}).json()
+ workqueue.drain(case)
+ saved = client.get(f"{base}/runs/{second['id']}").json()
+ assert saved["status"] == "ready", saved["message"]
+ assert [saved["input"]["a"]["date"], saved["input"]["b"]["date"]] == [body["b"]["date"], later]
+
+
+def test_a_detection_carries_what_it_is_for(client, scenario):
+ case, body = scenario
+ base = f"/api/cases/{case.id}/analysis"
+ watch = client.post(f"{base}/followups", json={**body, "title": "Harbour", "note": "Vessels weekly"}).json()
+ assert client.get(f"{base}/followups").json()[0]["note"] == "Vessels weekly"
+ started = client.post(f"{base}/followups/{watch['id']}/run").json()
+ assert started["input"]["note"] == "Vessels weekly"
+ assert client.get(f"{base}/runs").json()[0]["note"] == "Vessels weekly"
+
+
def test_reexecution_uses_preserved_frames_after_tile_cache_loss(client, scenario, monkeypatch):
case, body = scenario
first = run(client, case, body)
@@ -269,21 +453,22 @@ def test_detect_reads_copernicus_only_and_a_wayback_watch_asks_for_a_date(client
old["b"] = {"provider": "esri-wayback", "release": 2}
response = client.post(f"/api/cases/{case.id}/analysis/runs", json=old)
assert response.status_code == 422
- assert "dated Sentinel-2" in response.text
+ assert "dated Copernicus" in response.text
assert case.list_jobs() == []
-def test_zone_union_does_not_duplicate_detections(client, scenario):
+def test_overlapping_areas_keep_their_own_candidates(client, scenario):
case, body = scenario
first = run(client, case, body)
body["zones"].append({**body["zones"][0], "id": "overlap"})
second = run(client, case, body)
- assert second["results"] == first["results"]
- assert second["total"] == first["total"]
+ assert second["count"] == 2 * first["count"]
+ assert {r["area_id"] for r in second["results"]} == {"patch", "overlap"}
+ assert second["total"] == 2 * first["total"]
-def test_a_sweep_keeps_only_the_tiles_that_found_something(client, scenario):
- """What a case stores follows what was found, not how much was swept."""
+def test_a_sweep_keeps_review_images_for_manual_candidates_and_prunes_unused_bands(client, scenario):
+ """A missed detection can still be marked and cropped without fetching again."""
case, body = scenario
z, x, y = SENTINEL_TILE
body["zones"] = [zone(0.1, 0.1, 1.9, 0.9)]
@@ -292,8 +477,8 @@ def test_a_sweep_keeps_only_the_tiles_that_found_something(client, scenario):
assert saved["status"] == "ready", saved
assert saved["total"] == 2
assert saved["count"] == 1
- assert len(saved["frames"]) == 4
- assert {tuple(record["tile"]) for record in saved["frames"].values()} == {(z, x, y)}
+ assert len(saved["frames"]) == 6
+ assert {tuple(record["tile"]) for record in saved["frames"].values() if record["index"] is not None} == {(z, x, y)}
folder = case.resolve_inside(layout.analysis_assets_rel(f"runs-{saved['id']}"))
assert {path.name for path in folder.iterdir()} == {
record["path"].rsplit("/", 1)[1] for record in saved["frames"].values()
@@ -337,11 +522,15 @@ def test_a_recipe_saved_before_detect_went_copernicus_only_still_loads():
assert recipe.parameters.sensitivity == 40 and recipe.parameters.cloud_margin == 2
assert Recipe.model_validate({**old, "method": "water_objects"}).method == "vessels"
assert "providers" not in recipe.model_dump()
+ # areas once kept with an analyzer belong to a saved detection now
+ kept = Recipe.model_validate({**old, "zones": [zone()]})
+ assert "zones" not in kept.model_dump()
def test_every_method_publishes_sizes_and_words_for_its_reading():
methods = {entry["id"]: entry for entry in METHODS}
- assert set(methods) == {"vessels", "hotspots", "structure", "spots", "surface", "index"}
+ assert set(methods) == {"vessels", "hotspots", "structure", "spots", "surface", "index",
+ "sar-vessels", "sar-change"}
for entry in METHODS:
assert set(entry["sizes"]) == {"small", "medium", "large", "all"}
for size in entry["sizes"].values():
@@ -353,9 +542,14 @@ def test_every_method_publishes_sizes_and_words_for_its_reading():
assert entry["sizes"]["all"]["min_area"] == 0
assert entry["sizes"]["all"]["max_area"] == 0
assert "{" in entry["measure"]
- # the fire test rejects cloud itself; everything else can use the mask
- assert [m for m, entry in methods.items() if not entry["clouds"]] == ["hotspots"]
+ # the fire test rejects cloud itself and radar sees through it; every other
+ # method can use the mask
+ assert [m for m, entry in methods.items() if not entry["clouds"]] == [
+ "hotspots", "sar-vessels", "sar-change"]
assert methods["vessels"]["single"] and methods["hotspots"]["single"]
+ assert methods["sar-vessels"]["single"] and not methods["sar-change"]["single"]
+ assert {m for m, entry in methods.items() if entry["sensor"] == "sentinel1"} == {
+ "sar-vessels", "sar-change"}
# a small target is never morphologically cleaned away
assert all(entry["sizes"]["small"]["cleanup"] == 0 for entry in METHODS)
@@ -364,9 +558,12 @@ def test_builtins_cover_big_and_small_things_and_start_at_medium():
ids = {recipe.id for recipe in BUILTINS}
assert {"boats", "anomaly", "structures", "impacts", "large-change", "burn-scars",
"vegetation-loss", "new-water"} <= ids
+ # A flood is fields wide: at Medium the May 2023 Emilia-Romagna floods came
+ # out in some 280 pieces, so the radar flood detector starts at Large.
+ starts = {"radar-flood": "large"}
for recipe in BUILTINS:
- medium = SIZES[recipe.method]["medium"]
- assert {key: getattr(recipe.parameters, key) for key in medium} == medium, recipe.id
+ size = SIZES[recipe.method][starts.get(recipe.id, "medium")]
+ assert {key: getattr(recipe.parameters, key) for key in size} == size, recipe.id
assert len(recipe.description) < 200, recipe.id
@@ -826,7 +1023,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):
+ def acquisitions(instance, rings, start, end, collection="sentinel2"):
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 3ca5c0a..ca776fd 100644
--- a/tests/test_compare_api.py
+++ b/tests/test_compare_api.py
@@ -107,8 +107,7 @@ def test_compare_session_roundtrip_rename_and_sidebar_delete(client):
"palette": "colourblind",
"zones": False,
"opacity": 71,
- "base": "side",
- "visible": True,
+ "base": "a",
"blink": True,
}
spec["blink"] = {"interval": 1200}
@@ -121,6 +120,9 @@ def test_compare_session_roundtrip_rename_and_sidebar_delete(client):
"points": [[2.2946, 48.8585]], "number": 2, "font_size": 20},
{"id": "truck", "kind": "icon", "colour": "#38bdf8",
"points": [[2.2947, 48.8586]], "glyph": "vehicle"},
+ # drawn on a camera turned 30° anticlockwise, so its sides run along that screen
+ {"id": "roof", "kind": "rect", "colour": "#f6a81a",
+ "points": [[2.2945, 48.8584], [2.2950, 48.8580]], "angle": -30},
]
saved = _save(client, cid, "Harbour change", spec)
assert saved.status_code == 200, saved.text
@@ -149,12 +151,16 @@ def test_compare_session_roundtrip_rename_and_sidebar_delete(client):
# The overlay's own blink, and a mask margin in ground metres because the
# reading follows the camera.
assert (assist["blink"], assist["cloud_margin"]) == (True, 80)
+ assert assist["base"] == "a"
+ assert loaded["spec"]["difference"] is False
assert loaded["spec"]["blink"] == {"interval": 1200}
assert loaded["spec"]["annotations"][0]["side"] == "a"
assert loaded["spec"]["annotations"][1]["points"][2] == [2.30, 48.86]
# the two stamps: one press, one point, and what each one carries
assert loaded["spec"]["annotations"][2]["number"] == 2
assert loaded["spec"]["annotations"][3]["glyph"] == "vehicle"
+ assert loaded["spec"]["annotations"][4]["angle"] == 330
+ assert loaded["spec"]["annotations"][0]["angle"] == 0
entity = _entities(cid, "compare-session")[0]
renamed = _save(client, cid, "Harbour after", rename_from="Harbour change")
@@ -187,7 +193,11 @@ def test_compare_session_roundtrip_rename_and_sidebar_delete(client):
lambda spec: spec.update(frame={"points": [[2, 48]]}),
lambda spec: spec.update(frame={"points": [[2, 48], [2, 48]]}),
lambda spec: spec.update(frame={"points": [[2, 48], [200, 48]]}),
+ lambda spec: spec.update(frame={"points": [[2, 48], [3, 47]], "angle": "north"}),
lambda spec: spec.update(change_assist={"method": "ratio"}),
+ # Difference is a switch over the view now, not a mode
+ lambda spec: spec.update(mode="change"),
+ lambda spec: spec.update(change_assist={"base": "side"}),
# a stamp is one point, and its number is a count rather than a label
lambda spec: spec.update(annotations=[{
"id": "x", "kind": "number", "colour": "#ffffff", "points": [[2, 48], [3, 48]],
@@ -218,19 +228,20 @@ def test_compare_session_keeps_google_maps_js_as_a_reopenable_source(client):
def test_compare_session_keeps_an_optional_export_frame_on_the_ground(client):
cid = _case(client, "Compare frame")
spec = _spec()
- spec["frame"] = {"points": [[2.2945, 48.8584], [2.2961, 48.8572]]}
+ spec["frame"] = {"points": [[2.2945, 48.8584], [2.2961, 48.8572]], "angle": 405}
assert _save(client, cid, "Framed reading", spec).status_code == 200
loaded = client.get(f"/api/cases/{cid}/compare/sessions/Framed reading").json()
- assert loaded["spec"]["frame"] == spec["frame"]
+ # The bearing it was drawn at comes back with it, folded into one turn.
+ assert loaded["spec"]["frame"] == {**spec["frame"], "angle": 45}
# -- which pairs a pixel reading is fair on --------------------------------------
-def _pair(a: dict, b: dict, mode: str = "change", method: str = "colour") -> dict:
+def _pair(a: dict, b: dict, difference: bool = True, method: str = "colour") -> dict:
spec = _spec()
- spec.update(mode=mode, a=a, b=b, change_assist={"method": method})
+ spec.update(difference=difference, a=a, b=b, change_assist={"method": method})
return spec
@@ -296,8 +307,8 @@ def test_change_assist_refuses_misleading_pairs(client, a, b, method, reason):
refused = _save(client, cid, "Unfair pair", _pair(a, b, method=method))
assert refused.status_code == 422
assert reason in refused.json()["detail"]
- # the same pair is still a perfectly good side-by-side reading
- assert _save(client, cid, "Plain pair", _pair(a, b, mode="side", method=method)).status_code == 200
+ # the same pair is still a perfectly good reading without the highlights
+ assert _save(client, cid, "Plain pair", _pair(a, b, difference=False, method=method)).status_code == 200
def test_change_refusal_needs_both_sides():
diff --git a/tests/test_detect_rework.py b/tests/test_detect_rework.py
new file mode 100644
index 0000000..7df8788
--- /dev/null
+++ b/tests/test_detect_rework.py
@@ -0,0 +1,310 @@
+"""Detect orchestration, shared areas, review and snapshot boundaries."""
+
+import io
+import json
+from copy import deepcopy
+
+import numpy as np
+import pytest
+from PIL import Image
+
+from azimut import config, layout
+from azimut.engine import analysis_geometry, analyzers, bundles, maplayers, media, workqueue
+from azimut.engine.analysis_models import RunInput, Zone
+from azimut.workspace import Case
+from analyzerfixture import SENTINEL_TILE, fire_frame, flame, hull, sea, seed, seed_images, sentinel_input, zone
+from test_analyzers import run, scenario as analyzer_scenario
+
+
+def scenario(client, monkeypatch):
+ return analyzer_scenario.__wrapped__(client, monkeypatch)
+
+
+def area_body(raw):
+ parsed = Zone.model_validate(raw)
+ ring = parsed.ring()
+ return {"name": parsed.name, "colour": "#123456", "geometry": {"type": "Polygon", "coordinates": [ring + [ring[0]]]}}
+
+
+def test_shared_area_is_reusable_and_delete_names_its_routines(client, scenario):
+ case, body = scenario
+ base = f"/api/cases/{case.id}/analysis"
+ area = client.post(base + "/areas", json=area_body(body["zones"][0])).json()
+ shared = {**body, "zones": [], "area_dates": [{"area_id": area["id"], "a": body["a"], "b": body["b"], "date_rule": "manual"}]}
+ watches = [client.post(base + "/followups", json={**shared, "title": title}).json() for title in ("Port weekly", "Port baseline")]
+ assert len(client.get(base + "/areas").json()) == 1
+ for watch in watches:
+ stored = json.loads(case.resolve_inside(analyzers.relpath("followups", watch["id"])).read_text())
+ assert "zones" not in stored
+ assert stored["area_dates"][0]["area_id"] == area["id"]
+ saved = run(client, case, shared)
+ assert saved["status"] == "ready"
+ assert saved["results"][0]["area_id"] == area["id"]
+ refused = client.delete(base + "/areas/" + area["id"])
+ assert refused.status_code == 409
+ assert "Port weekly" in refused.text and "Port baseline" in refused.text
+ entity = case.find_entity(attr="spec", value=analyzers.relpath("areas", area["id"]))
+ refused = client.delete(f"/api/cases/{case.id}/entities/{entity['id']}")
+ assert refused.status_code == 409 and "Port weekly" in refused.text
+ changed = {**area_body(body["zones"][0]), "name": "Renamed", "colour": "#abcdef"}
+ assert client.put(base + "/areas/" + area["id"], json=changed).status_code == 200
+ assert client.get(base + "/followups/" + watches[0]["id"]).json()["zones"][0]["name"] == "Renamed"
+ assert analyzers.read(case, "runs", saved["id"])["input"]["zones"][0]["name"] == "Patch"
+ for watch in watches:
+ assert client.delete(base + "/followups/" + watch["id"]).status_code == 200
+ removed = client.delete(base + "/areas/" + area["id"]).json()
+ assert not case.resolve_inside(analyzers.relpath("areas", area["id"])).exists()
+ assert client.post(f"/api/cases/{case.id}/trash/{removed['trash']}/restore").status_code == 200
+ assert client.get(base + "/areas/" + area["id"]).json()["name"] == "Renamed"
+
+
+def test_embedded_routine_migration_is_lossless_and_idempotent(client, scenario):
+ case, body = scenario
+ saved = analyzers.save(case, "followups", body)
+ # Simulate an older record, including a zone carried by its recipe.
+ old = {**saved, "zones": body["zones"], "recipe": {**body["recipe"], "zones": body["zones"]}}
+ old.pop("area_dates")
+ media.write_json_atomic(case.resolve_inside(analyzers.relpath("followups", saved["id"])), old)
+ first = analyzers.read(case, "followups", saved["id"])
+ second = analyzers.read(case, "followups", saved["id"])
+ assert first == second
+ assert first["created_at"] == old["created_at"]
+ assert first["a"] == body["a"] and first["b"] == body["b"]
+ assert Zone.model_validate(first["zones"][0]).ring() == Zone.model_validate(body["zones"][0]).ring()
+ assert len(analyzers.listing(case, "areas")) == 1
+
+
+def tracks(body):
+ z, x, y = SENTINEL_TILE
+ other = (z, x + 40, y + 30)
+ body = deepcopy(body)
+ body["zones"].append({**zone(tile=other, ident="other"), "name": "Other track"})
+ body["offline"] = False
+ body["area_dates"] = [{"area_id": area["id"], "a": body["a"], "b": {**body["b"], "date": ""},
+ "date_rule": "latest_reference"} for area in body["zones"]]
+ return body, other
+
+
[email protected]("partial", [False, True])
+def test_each_track_resolves_its_own_pass_and_only_the_missing_area_fails(client, scenario, monkeypatch, partial):
+ case, body = scenario
+ body, other = tracks(body)
+ seed_images({**body, "b": {**body["b"], "date": "2026-05-13"}}, other)
+ 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"):
+ calls.append(rings)
+ 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",
+ "cloud": 5, "coverage": 1}]}
+ monkeypatch.setattr(analyzers.sentinel, "acquisitions", lookup)
+ saved = run(client, case, body)
+ assert saved["status"] == "ready", saved
+ assert len(calls) == 2
+ assert config.month_usage("sentinelhub") == 2
+ if partial:
+ assert "Other track" in saved["message"]
+ assert {r["area_id"] for r in saved["results"]} == {"patch"}
+ assert saved["area_runs"][1]["status"] == "failed"
+ else:
+ assert [p["b"]["date"] for p in saved["area_runs"]] == ["2026-05-11", "2026-05-13"]
+ assert {r["area_id"] for r in saved["results"]} == {"patch", "other"}
+
+
+def test_previous_pass_is_per_area_and_explicit_launch_never_looks_up(client, scenario):
+ case, body = scenario
+ body, other = tracks(body)
+ body["offline"] = True
+ for i, pair in enumerate(body["area_dates"]):
+ pair["date_rule"] = "manual"
+ pair["b"]["date"] = "2026-05-11" if i == 0 else "2026-05-13"
+ seed_images({**body, "b": body["area_dates"][1]["b"]}, other)
+ base = f"/api/cases/{case.id}/analysis"
+ watch = client.post(base + "/followups", json=body).json()
+ started = client.post(base + f"/followups/{watch['id']}/run").json()
+ workqueue.drain(case)
+ initial = analyzers.read(case, "runs", started["id"])
+ pairs = []
+ for i, pair in enumerate(initial["area_runs"]):
+ nxt = {**pair["b"], "date": "2026-05-20"}
+ seed_images({**body, "a": pair["b"], "b": nxt}, SENTINEL_TILE if i == 0 else other)
+ pairs.append({"area_id": pair["area_id"], "a": body["a"], "b": nxt, "date_rule": "latest_previous"})
+ started = client.post(base + f"/followups/{watch['id']}/run", json={"area_dates": pairs}).json()
+ workqueue.drain(case)
+ second = analyzers.read(case, "runs", started["id"])
+ assert second["status"] == "ready", second
+ assert [p["a"]["date"] for p in second["area_runs"]] == ["2026-05-11", "2026-05-13"]
+
+
+def test_dismiss_removes_and_keep_creates_no_entity_or_media(client, scenario):
+ case, body = scenario
+ saved = run(client, case, body)
+ endpoint = f"/api/cases/{case.id}/analysis/runs/{saved['id']}/results/{saved['results'][0]['id']}"
+ before = case.list_entities()
+ assert client.patch(endpoint, json={"review": "noted"}).status_code == 200
+ assert case.list_entities() == before
+ assert client.patch(endpoint, json={"review": "dismissed"}).status_code == 200
+ assert analyzers.read(case, "runs", saved["id"])["results"] == []
+ assert client.get(endpoint + "/preview").status_code == 404
+ assert run(client, case, body)["count"] == 1
+
+
[email protected]("shape", ["point", "area"])
+def test_pin_options_choose_image_and_geometry(client, scenario, shape):
+ case, body = scenario
+ saved = run(client, case, body)
+ endpoint = f"/api/cases/{case.id}/analysis/runs/{saved['id']}/results/{saved['results'][0]['id']}"
+ with Image.open(io.BytesIO(client.get(endpoint + "/preview").content)) as image:
+ paired_width = image.width
+ response = client.post(endpoint + "/promote", json={"title": "Checked", "description": "Observed change",
+ "after_only": True, "shape": shape})
+ assert response.status_code == 200, response.text
+ pinned = response.json()
+ with Image.open(case.resolve_inside(pinned["image"])) as image:
+ assert image.format == "PNG" and image.width == (paired_width - 8) // 2
+ attrs = pinned["entity"]["attrs"]
+ assert attrs["description"] == "Observed change"
+ assert attrs["geometry"]["type"] == ("Polygon" if shape == "area" else "Point")
+ assert ("footprint" in attrs) == (shape == "area")
+
+
+def test_mask_outlines_preserve_an_l_hole_and_diagonal_parts():
+ mask = np.zeros((8, 8), bool)
+ mask[1:7, 1:3] = True
+ mask[5:7, 1:7] = True
+ shape = analysis_geometry.footprint(mask, 0, 0, 1, 8)
+ assert shape["type"] == "Polygon" and len(shape["coordinates"][0]) == 7
+ assert np.count_nonzero(mask) == 20 # tracing did not change the detector output
+ hole = np.ones((5, 5), bool)
+ hole[2, 2] = False
+ assert len(analysis_geometry.outlines(hole)[0]) == 2
+ diagonal = analysis_geometry.footprint(np.eye(3, dtype=bool), 0, 0, 1, 8)
+ assert diagonal["type"] == "MultiPolygon" and len(diagonal["coordinates"]) == 3
+
+
+def test_merge_keeps_the_parts_footprints():
+ shape = {"type": "Polygon", "coordinates": [[[0, 0], [1, 0], [1, 1], [0, 0]]]}
+ rows = [{"id": str(i), "bbox": [i, 0, i + 1, 1], "geometry": shape, "margin": 1,
+ "area": 1, "parts": [], "measure": {}, "strength": "clear"} for i in range(2)]
+ [merged] = analyzers.merge(rows, 0)
+ assert merged["geometry"] == {"type": "MultiPolygon", "coordinates": [shape["coordinates"], shape["coordinates"]]}
+
+
+def test_manual_candidate_survives_reload_and_has_the_same_preview_and_verdicts(client, scenario):
+ case, body = scenario
+ saved = run(client, case, body)
+ base = f"/api/cases/{case.id}/analysis/runs/{saved['id']}"
+ point = saved["results"][0]["coordinates"]
+ response = client.post(base + "/results", json={"area_id": "patch", "geometry": {"type": "Point", "coordinates": point}})
+ assert response.status_code == 200, response.text
+ manual = response.json()
+ assert manual["origin"] == "manual" and manual["sources"]["b"] == body["b"]
+ assert client.get(base + f"/results/{manual['id']}/preview").content.startswith(b"\x89PNG")
+ assert client.get(base).json()["results"][-1] == manual
+ assert client.patch(base + f"/results/{manual['id']}", json={"review": "noted"}).status_code == 200
+ assert client.delete(base).status_code == 200
+
+
+def test_exact_repeat_warns_before_queueing_but_overlap_does_not(client, scenario):
+ case, body = scenario
+ first = run(client, case, body)
+ base = f"/api/cases/{case.id}/analysis/runs"
+ repeat = client.post(base, json=body).json()
+ assert repeat["duplicates"][0]["run_id"] == first["id"]
+ assert len(analyzers.listing(case, "runs")) == 1
+ overlap = {**body, "a": {**body["a"], "date": "2026-05-03"}}
+ seed_images(overlap)
+ assert "id" in client.post(base, json=overlap).json()
+ assert "id" in client.post(base, json={**repeat["input"], "run_anyway": True}).json()
+
+
+def test_export_snapshots_kept_candidates_with_pass_categories_and_replaces_a_pass(client, scenario):
+ case, body = scenario
+ base = f"/api/cases/{case.id}/analysis"
+ watch = client.post(base + "/followups", json=body).json()
+ first = run(client, case, {**body, "followup_id": watch["id"]})
+ first_url = base + f"/runs/{first['id']}"
+ client.patch(first_url + f"/results/{first['results'][0]['id']}", json={"review": "noted"})
+ exported = client.post(first_url + "/export").json()
+ later = {**body, "followup_id": watch["id"], "b": {**body["b"], "date": "2026-05-18"}}
+ seed_images(later)
+ second = run(client, case, later)
+ second_url = base + f"/runs/{second['id']}"
+ # New candidates are excluded.
+ assert client.post(second_url + "/export").json()["features"] == 1
+ client.post(second_url + f"/results/{second['results'][0]['id']}/promote", json={"title": "Pinned"})
+ updated = client.post(second_url + "/export").json()
+ assert updated["name"] == exported["name"] and updated["features"] == 2
+ assert {c["name"] for c in updated["categories"]} == {"2026-05-11", "2026-05-18"}
+ assert client.post(second_url + "/export").json()["features"] == 2
+ drawing = json.loads(maplayers.drawing(case, updated["name"]).read_text())
+ features = sorted(drawing["features"], key=lambda f: f["properties"]["date"])
+ assert int(features[0]["properties"]["colour"][1:3], 16) > int(features[1]["properties"]["colour"][1:3], 16)
+ assert all(f["properties"]["run_id"] and f["properties"]["area_name"] for f in features)
+ assert client.delete(first_url).status_code == 200
+ assert client.delete(second_url).status_code == 200
+ # Rebuild from the portable snapshot, without a run or the derived cache.
+ case.resolve_inside(layout.layer_cache_rel(updated["name"])).unlink()
+ assert len(json.loads(maplayers.drawing(case, updated["name"]).read_text())["features"]) == 2
+
+
+def test_detect_preferences_round_trip_through_settings_backup(client):
+ choice = {"collapsed": True, "basemap": "osm", "overlays": ["roads"], "saved": False}
+ assert client.put("/api/settings/prefs", json={"detect_view": choice}).status_code == 200
+ backup = client.get("/api/settings/export").json()
+ client.put("/api/settings/prefs", json={"detect_view": {}})
+ assert client.post("/api/settings/import", json=backup).status_code == 200
+ assert client.get("/api/settings").json()["detect_view"] == choice
+
+
+def test_shared_areas_and_routine_references_survive_a_bundle(client, scenario):
+ case, body = scenario
+ watch = analyzers.save(case, "followups", body)
+ original = analyzers.read(case, "followups", watch["id"])
+ area = analyzers.read(case, "areas", watch["area_dates"][0]["area_id"])
+ destination = Case.create("Imported areas")
+ bundles.import_into(destination, bundles.export_case(case))
+ imported = Case.open(destination.id)
+ assert analyzers.read(imported, "followups", watch["id"]) == original
+ assert analyzers.read(imported, "areas", area["id"]) == area
+ assert imported.find_entity(attr="spec", value=analyzers.relpath("areas", area["id"]))
+
+
+def test_previous_pass_finds_a_run_made_before_shared_area_migration(client, scenario):
+ case, body = scenario
+ watch = analyzers.save(case, "followups", body)
+ earlier = run(client, case, {**body, "followup_id": watch["id"]})
+ earlier.pop("area_runs")
+ media.write_json_atomic(case.resolve_inside(analyzers.relpath("runs", earlier["id"])), earlier)
+ shared = analyzers.read(case, "followups", watch["id"])
+ later = RunInput.model_validate({**body, "zones": shared["zones"], "followup_id": watch["id"],
+ "b": {**body["b"], "date": "2026-05-20"}})
+ assert analyzers.previous_pass(case, later).date == body["b"]["date"]
+
+
[email protected]("recipe_id", ["boats", "anomaly"])
+def test_single_image_methods_need_no_reference_and_pin_after_only(client, scenario, recipe_id):
+ case, _ = scenario
+ body = sentinel_input(recipe_id, min_area=0, merge_metres=0)
+ body["a"]["date"] = ""
+ pixels = sea() if recipe_id == "boats" else fire_frame()
+ if recipe_id == "boats":
+ hull(pixels, 120, 140, 6, 3)
+ else:
+ flame(pixels, 120, 140, 6, 3)
+ seed(body, after=pixels)
+ body["area_dates"] = [{"area_id": "patch", "b": body["b"], "date_rule": "manual"}]
+ saved = run(client, case, body)
+ assert saved["status"] == "ready" and saved["count"] == 1, saved
+ assert saved["area_runs"][0]["a"] == saved["area_runs"][0]["b"]
+ result = saved["results"][0]
+ assert len(result["parts"][0]["frames"]) == 1
+ endpoint = f"/api/cases/{case.id}/analysis/runs/{saved['id']}/results/{result['id']}"
+ pinned = client.post(endpoint + "/promote", json={"title": "Observed"})
+ assert pinned.status_code == 200, pinned.text
+ assert pinned.json()["entity"]["attrs"]["geometry"]["type"] == "Point"
+ with Image.open(case.resolve_inside(pinned.json()["image"])) as image:
+ assert image.format == "PNG" and image.width <= 400
diff --git a/tests/test_graph.py b/tests/test_graph.py
index f6f2046..ef426bf 100644
--- a/tests/test_graph.py
+++ b/tests/test_graph.py
@@ -169,7 +169,7 @@ def test_a_reading_of_the_case_leaves_out_what_the_analyst_wrote():
readings with no edit here."""
filing = entity_engine.types_with_role(entity_engine.ANNEX, entity_engine.DELIVERABLE)
assert filing == {"note", "sheet", "inspect-session", "compare-session", "post",
- "analysis-zones", "analysis-follow-up", "analysis-run", "map-layer"}
+ "analysis-zones", "analysis-area", "analysis-follow-up", "analysis-run", "map-layer"}
for lens_id in ("all", "subjects", "ground", "claims"):
assert set(graph_engine.lens(lens_id).hides) == filing, lens_id
diff --git a/tests/test_radar_detect.py b/tests/test_radar_detect.py
new file mode 100644
index 0000000..6611a40
--- /dev/null
+++ b/tests/test_radar_detect.py
@@ -0,0 +1,599 @@
+"""Detect's radar methods: Sentinel-1 products, passes, tracks and detectors.
+
+Products are built in the byte layout the radar evalscript returns
+(engine/sentinel.py): decibels in fifths from -35 dB, VV first, VH second.
+"""
+
+import base64
+import io
+from copy import deepcopy
+
+import numpy as np
+import pytest
+from PIL import Image
+
+from azimut import config
+from azimut.engine import analyzers, sentinel, tilecache, workqueue
+from azimut.engine.analysis_models import BUILTINS, RunInput, Source
+from azimut.workspace import Case
+from analyzerfixture import EDGE, PAD, SENTINEL_TILE, zone
+
+LAYER = "SAR_IW"
+DAY_A, DAY_B = "2026-05-02", "2026-05-14"
+TIME = "05:42:10"
+
+
+def level(db):
+ return np.clip(np.round((np.asarray(db, float) - sentinel.SAR_DB_FLOOR) / sentinel.SAR_DB_STEP),
+ 1, 255).astype(np.uint8)
+
+
+def speckled(mean_db, seed, size=EDGE, looks=4.4):
+ """Sea or ground as the radar reads it: gamma-distributed power."""
+ rng = np.random.default_rng(seed)
+ power = rng.gamma(looks, 1 / looks, (size, size)) * 10 ** (mean_db / 10)
+ return 10 * np.log10(power)
+
+
+def water(value, size=EDGE):
+ frame = np.zeros((size, size, 4), np.uint8)
+ frame[..., 0] = value
+ frame[..., 3] = 255
+ return frame
+
+
+def recipe(rid, **parameters):
+ found = next(r for r in BUILTINS if r.id == rid).model_copy(deep=True)
+ return found.model_copy(update={"parameters": found.parameters.model_copy(update=parameters)})
+
+
+def body(rid, **parameters):
+ return RunInput.model_validate({
+ "title": rid, "zones": [zone()], "recipe": recipe(rid, **parameters).model_dump(),
+ "a": {"provider": "sentinel1", "date": DAY_A, "layer": LAYER, "maxcc": 100, "time": TIME},
+ "b": {"provider": "sentinel1", "date": DAY_B, "layer": LAYER, "maxcc": 100, "time": TIME},
+ "offline": True,
+ })
+
+
+def reading(rid, before, after, mask=None, water_frame=None, **parameters):
+ picture = np.full((512, 512, 4), 255, np.uint8)
+ mask = np.ones((512, 512), np.uint8) if mask is None else mask
+ return analyzers.detect((picture, picture), (before, after), mask, body(rid, **parameters),
+ 1.0, water_frame)
+
+
+def found(result):
+ import cv2
+ count, _ = cv2.connectedComponents(result.binary, connectivity=8)
+ return count - 1
+
+
+# -- products, windows and passes -------------------------------------------------------
+
+
+def test_radar_products_carry_decibels_in_fifths_and_are_never_zero_where_seen():
+ script = base64.b64decode(sentinel._evalscript("sar")).decode("ascii")
+ assert 'bands: ["VV", "VH", "dataMask"]' in script
+ assert "return [level(p.VV), level(p.VH), 0, 255]" in script
+ assert "Math.max(1," in script
+ picture = base64.b64decode(sentinel._evalscript("sar-picture")).decode("ascii")
+ assert "stretch(db(p.VV) - db(p.VH)" in picture
+ # the byte goes back to decibels exactly on the grid it was rounded to
+ assert sentinel.sar_decibels(level(-22.0).astype(float)) == pytest.approx(-22.0)
+ assert sentinel.sar_decibels(level(3.4).astype(float)) == pytest.approx(3.4)
+
+
+def test_a_pass_window_holds_one_pass_and_crosses_midnight():
+ assert sentinel.pass_window("2026-05-14") == "2026-05-14/2026-05-14"
+ assert sentinel.pass_window("2026-05-14", "05:42:10") == \
+ "2026-05-14T05:22:10Z/2026-05-14T06:02:10Z"
+ assert sentinel.pass_window("2026-05-14", "23:50:00") == \
+ "2026-05-14T23:30:00Z/2026-05-15T00:10:00Z"
+ for bad in ("5:42", "25:00:00", "05:42:10Z"):
+ with pytest.raises(ValueError):
+ sentinel.pass_window("2026-05-14", bad)
+
+
+def test_band_frame_reads_the_pass_and_the_water_reads_the_clearest_year(monkeypatch):
+ sent = []
+
+ class Answer:
+ status_code = 200
+ text = ""
+
+ def __init__(self, size):
+ out = io.BytesIO()
+ Image.new("RGBA", size).save(out, "PNG")
+ self.content = out.getvalue()
+
+ def raise_for_status(self):
+ return None
+
+ def get(url, params, **kwargs):
+ sent.append(params)
+ return Answer((int(params["WIDTH"]), int(params["HEIGHT"])))
+
+ box = (0.0, 0.0, 1000.0, 1000.0)
+ sentinel.band_frame("inst", box, 8, 8, "2026-05-14", "sar", 100, layer=LAYER, time=TIME, get=get)
+ sentinel.band_frame("inst", box, 8, 8, "2026-05-01", "water", 100, get=get)
+ radar_request, water_request = sent
+ assert radar_request["LAYERS"] == LAYER
+ assert radar_request["TIME"] == "2026-05-14T05:22:10Z/2026-05-14T06:02:10Z"
+ assert water_request["LAYERS"] == "TRUE_COLOR"
+ assert water_request["TIME"] == "2025-05-01/2026-05-01"
+ assert water_request["PRIORITY"] == "leastCC"
+ script = base64.b64decode(water_request["EVALSCRIPT"]).decode("ascii")
+ assert "p.SCL === 6" in script
+
+
+def _feature(day, time, *, ident=None, ring=None):
+ ring = ring or [[3.0, 51.0], [5.0, 51.0], [5.0, 53.0], [3.0, 53.0], [3.0, 51.0]]
+ props = {"date": day}
+ if time:
+ props["time"] = time
+ if ident:
+ props["id"] = ident
+ return {"properties": props, "geometry": {"type": "Polygon", "coordinates": [ring]}}
+
+
+def test_radar_passes_are_one_entry_per_pass_with_time_and_direction():
+ """Sentinel-1 can see a place twice on one day, from opposite directions;
+ those are two images, not one day. Slices of one pass are one."""
+ asked = {}
+
+ class Answer:
+ status_code = 200
+ text = ""
+
+ def raise_for_status(self):
+ return None
+
+ def json(self):
+ return {"features": [
+ _feature("2026-05-14", "05:42:10"),
+ _feature("2026-05-14", "05:42:35"), # the next slice of the same pass
+ _feature("2026-05-14", "17:33:02"), # the evening pass, ascending
+ # no time field: read from the product name instead
+ _feature("2026-05-02", "", ident="S1A_IW_GRDH_1SDV_20260502T054212_20260502T054237_064000_07AB12_1F2E"),
+ ]}
+
+ def get(url, params, **kwargs):
+ asked.update(params)
+ return Answer()
+
+ found = sentinel.dates("inst", 52.0, 4.0, "2026-05-01", "2026-05-31", collection="sentinel1", get=get)
+ assert asked["TYPENAMES"] == sentinel.S1_TYPENAME
+ assert [(row["date"], row["time"], row["orbit"], row["granules"]) for row in found] == [
+ ("2026-05-14", "17:33:02", "ascending", 1),
+ ("2026-05-14", "05:42:10", "descending", 2),
+ ("2026-05-02", "05:42:12", "descending", 1),
+ ]
+ assert all(row["cloud"] is None for row in found)
+
+
+def test_a_radar_lookup_on_an_instance_without_sentinel1_says_so():
+ class Answer:
+ status_code = 400
+ text = "<ServiceExceptionReport>TYPENAME=DSS3 not found!</ServiceExceptionReport>"
+
+ with pytest.raises(ValueError, match="no Sentinel-1 layer"):
+ sentinel.dates("inst", 52.0, 4.0, "2026-05-01", "2026-05-31", collection="sentinel1",
+ get=lambda *a, **k: Answer())
+
+
+def test_a_track_repeats_to_the_minute_and_its_neighbour_is_eight_minutes_off():
+ # Over Dover in 2025: relative orbits 132 and 59 pass at 17:49 and 17:41.
+ assert sentinel.same_track("17:49:10", "17:48:40")
+ assert not sentinel.same_track("17:49:10", "17:41:05")
+ assert sentinel.same_track("23:59:30", "00:01:10") # across midnight
+ assert not sentinel.same_track("", "17:49:10")
+ # Singapore: 11:25 UTC is dusk there, 22:48 UTC is dawn
+ assert sentinel.orbit_direction("11:25:46", 104.0) == "ascending"
+ assert sentinel.orbit_direction("22:48:24", 104.0) == "descending"
+ assert sentinel.orbit_direction("", 104.0) == ""
+
+
+def test_the_sentinel1_probe_tells_a_radar_layer_from_an_optical_one():
+ class Refused:
+ status_code = 400
+ text = ("<ServiceExceptionReport><ServiceException>Failed to evaluate script! "
+ "Band VV not found</ServiceException></ServiceExceptionReport>")
+
+ answer = sentinel.probe_sar_layer("inst", "TRUE_COLOR", get=lambda *a, **k: Refused())
+ assert answer == {"ok": False, "layer": "TRUE_COLOR",
+ "detail": "Failed to evaluate script! Band VV not found"}
+
+ class Rendered:
+ status_code = 200
+ text = ""
+
+ def __init__(self):
+ out = io.BytesIO()
+ Image.new("L", (8, 8), 255).save(out, "PNG")
+ self.content = out.getvalue()
+
+ def raise_for_status(self):
+ return None
+
+ assert sentinel.probe_sar_layer("inst", LAYER, get=lambda *a, **k: Rendered())["ok"]
+ with pytest.raises(ValueError):
+ sentinel.probe_sar_layer("inst", "../etc", get=lambda *a, **k: Rendered())
+
+
+# -- detectors ---------------------------------------------------------------------------
+
+
+def _sea_with(targets, seed=1, sea_vv=-22.0, sea_vh=-28.0):
+ vv, vh = speckled(sea_vv, seed), speckled(sea_vh, seed + 1)
+ for (x, y, w, h), (target_vv, target_vh) in targets:
+ vv[y:y + h, x:x + w] = target_vv
+ vh[y:y + h, x:x + w] = target_vh
+ product = np.zeros((EDGE, EDGE, 4), np.uint8)
+ product[..., 0], product[..., 1], product[..., 3] = level(vv), level(vh), 255
+ return product
+
+
+def test_radar_finds_a_hull_and_not_a_ghost_or_a_sea_spike():
+ """A hull answers in both polarisations. A ghost of it, or a spike of sea,
+ answers in VV alone: in the Singapore anchorage every hull cleared VH by
+ 8 dB and those ghosts by 4 to 7."""
+ hull = ((300, 300, 8, 3), (5.0, -8.0))
+ ghost = ((150, 150, 3, 6), (-8.0, -27.0))
+ result = reading("radar-vessels", *(2 * [_sea_with([hull, ghost])]))
+ assert found(result) == 1
+ ys, xs = np.nonzero(result.binary)
+ assert 300 - PAD <= xs.min() and xs.max() < 308 - PAD + 2
+
+
+def test_a_weak_return_beside_a_much_stronger_one_is_its_ghost():
+ strong = ((300, 300, 8, 3), (12.0, 0.0))
+ beside = ((300, 330, 3, 3), (0.0, -12.0)) # 200 m off, 12 dB weaker
+ far = ((100, 100, 3, 3), (0.0, -12.0))
+ result = reading("radar-vessels", *(2 * [_sea_with([strong, beside, far])]))
+ assert found(result) == 2
+
+
+def test_the_sentinel2_water_keeps_dark_desert_from_being_sea():
+ """Dry sand is as radar-dark as calm sea in both polarisations. At Port
+ Sudan the radar alone put candidates on the town and the desert; Sentinel-2's
+ classification says where the water is."""
+ desert = _sea_with([((300, 300, 4, 4), (6.0, -6.0))], sea_vv=-19.0, sea_vh=-24.0)
+ assert found(reading("radar-vessels", desert, desert)) == 1
+ land = water(sentinel.WATER_LAND)
+ assert found(reading("radar-vessels", desert, desert, water_frame=land)) == 0
+ sea = water(sentinel.WATER_WATER)
+ assert found(reading("radar-vessels", desert, desert, water_frame=sea)) == 1
+
+
+def test_a_storm_sea_is_still_sea():
+ """In the October 2023 North Sea storm the sea rose to -11 dB in VV, above
+ farmland; cross-pol stayed near -24 dB, which is what still calls it sea."""
+ storm = _sea_with([((300, 300, 8, 3), (8.0, -4.0))], sea_vv=-11.0, sea_vh=-24.0)
+ assert found(reading("radar-vessels", storm, storm)) == 1
+
+
+def test_radar_change_gates_bright_loss_bright_gain_and_new_water():
+ ground = speckled(-10.0, 5), speckled(-16.0, 6)
+ town = (slice(200, 240), slice(200, 240))
+ field = (slice(350, 400), slice(350, 400))
+
+ def scene(town_db=None, field_db=None):
+ vv, vh = ground[0].copy(), ground[1].copy()
+ if town_db is not None:
+ vv[town] += town_db[0] + 10
+ vh[town] += town_db[1] + 16
+ if field_db is not None:
+ vv[field] += field_db[0] + 10
+ vh[field] += field_db[1] + 16
+ product = np.zeros((EDGE, EDGE, 4), np.uint8)
+ product[..., 0], product[..., 1], product[..., 3] = level(vv), level(vh), 255
+ return product
+
+ standing = scene(town_db=(0.0, -8.0))
+ razed = scene(town_db=(-10.0, -16.0))
+ flooded = scene(town_db=(0.0, -8.0), field_db=(-23.0, -27.0))
+ assert found(reading("radar-razed", standing, standing)) == 0
+ assert found(reading("radar-razed", standing, razed)) == 1
+ assert found(reading("radar-new-objects", razed, standing)) == 1
+ assert found(reading("radar-new-objects", standing, razed)) == 0
+ assert found(reading("radar-flood", standing, flooded)) == 1
+ assert found(reading("radar-flood", standing, razed)) == 0
+ result = reading("radar-razed", standing, razed)
+ assert result.measures["before"][0].max() > analyzers.BRIGHT_DB
+
+
+def test_every_radar_built_in_names_its_method_and_the_old_ones_stay():
+ ids = [r.id for r in BUILTINS]
+ assert ids[:8] == ["boats", "anomaly", "structures", "impacts", "large-change",
+ "burn-scars", "vegetation-loss", "new-water"]
+ assert {r.id: r.method for r in BUILTINS if r.method.startswith("sar")} == {
+ "radar-vessels": "sar-vessels", "radar-change": "sar-change", "radar-razed": "sar-change",
+ "radar-new-objects": "sar-change", "radar-flood": "sar-change"}
+
+
+# -- runs ------------------------------------------------------------------------------
+
+
+def radar_case(client, monkeypatch):
+ monkeypatch.setattr(workqueue, "start_workers", False)
+ ident = client.post("/api/cases", json={"name": "Radar tests"}).json()["id"]
+ client.put("/api/settings/prefs", json={"sentinel1_layer": LAYER})
+
+ def forbidden(*args, **kwargs):
+ raise AssertionError("unexpected network")
+
+ monkeypatch.setattr(analyzers.httpx, "stream", forbidden)
+ monkeypatch.setattr(analyzers.sentinel, "band_frame", forbidden)
+ monkeypatch.setattr(analyzers.sentinel, "acquisitions", forbidden)
+ return Case.open(ident)
+
+
+def _png(pixels):
+ out = io.BytesIO()
+ Image.fromarray(pixels).save(out, "PNG")
+ return out.getvalue()
+
+
+def _seed(source, product, water_frame=None, tile=SENTINEL_TILE):
+ z, x, y = tile
+ parsed = Source.model_validate(source)
+ picture = np.full((512, 512, 4), 90, np.uint8)
+ picture[..., 3] = 255
+ tilecache.put(analyzers.picture_cache_id(parsed), z, x, y, _png(picture), "image/png")
+ tilecache.put(analyzers.product_cache_id(parsed, "sar"), z, x, y, _png(product), "image/png")
+ if water_frame is not None:
+ tilecache.put(analyzers.product_cache_id(analyzers.water_source(parsed), "water"),
+ z, x, y, _png(water_frame), "image/png")
+
+
+def _run(client, case, payload):
+ answer = client.post(f"/api/cases/{case.id}/analysis/runs", json=payload)
+ assert answer.status_code == 200, answer.text
+ workqueue.drain(case)
+ return client.get(f"/api/cases/{case.id}/analysis/runs/{answer.json()['id']}").json()
+
+
+def test_an_offline_radar_sweep_reads_the_pass_it_names_and_keeps_its_water(client, radar_case):
+ case = radar_case
+ payload = body("radar-vessels").model_dump()
+ # the panel builds optical sources; the engine makes them radar ones
+ for letter in "ab":
+ payload[letter] = {**payload[letter], "provider": "sentinel2", "layer": "TRUE_COLOR", "maxcc": 30}
+ sea = _sea_with([((300, 300, 8, 3), (5.0, -8.0))])
+ _seed({"provider": "sentinel1", "date": DAY_B, "layer": LAYER, "maxcc": 100, "time": TIME},
+ sea, water(sentinel.WATER_WATER))
+ saved = _run(client, case, payload)
+ assert saved["status"] == "ready", saved
+ assert saved["count"] == 1
+ row = saved["results"][0]
+ assert row["sources"]["b"] == {"provider": "sentinel1", "date": DAY_B, "layer": LAYER,
+ "maxcc": 100, "time": TIME}
+ assert "dB" not in row["measure"] and row["measure"]["value"] > 9
+ # the water it was judged against is kept beside the picture and the product
+ assert sorted(frame["index"] or "picture" for frame in saved["frames"].values()) == [
+ "picture", "sar", "water"]
+ preview = client.get(f"/api/cases/{case.id}/analysis/runs/{saved['id']}/results/{row['id']}/preview")
+ assert preview.content.startswith(b"\x89PNG")
+
+
+def test_a_radar_run_without_its_layer_says_where_to_set_it(client, radar_case):
+ client.put("/api/settings/prefs", json={"sentinel1_layer": ""})
+ saved = _run(client, radar_case, body("radar-vessels").model_dump())
+ assert saved["status"] == "failed"
+ assert "Sentinel-1 layer in Settings" in saved["message"]
+
+
+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"):
+ asked.append((start, end, collection))
+ return {"dates": [
+ {"date": DAY_B, "time": "17:33:02", "cloud": None, "coverage": 1.0},
+ {"date": DAY_B, "time": "05:42:40", "cloud": None, "coverage": 0.6},
+ {"date": DAY_A, "time": "05:42:10", "cloud": None, "coverage": 1.0},
+ ]}
+
+ monkeypatch.setattr(analyzers.sentinel, "acquisitions", acquisitions)
+ client.put("/api/settings/keys", json={"sentinelhub": "test-instance"})
+ client.put("/api/settings/prefs", json={"sentinel1_layer": LAYER})
+ typed = body("radar-change").model_copy(update={"offline": False})
+ typed = typed.model_copy(update={"b": typed.b.model_copy(update={"time": ""})})
+ settled = analyzers.resolve_dates(radar_case, typed)
+ # the morning pass, though the evening one covers more: it is A's track
+ assert settled.b.time == "05:42:40"
+ assert asked == [(DAY_B, DAY_B, "sentinel1")]
+ with pytest.raises(ValueError, match="different tracks"):
+ analyzers.resolve_dates(radar_case, typed.model_copy(
+ update={"b": typed.b.model_copy(update={"time": "17:33:02"})}))
+
+
+def test_an_automatic_radar_pass_stays_on_the_reference_track(client, radar_case, monkeypatch):
+ monkeypatch.setattr(analyzers.sentinel, "acquisitions", lambda *a, **k: {"dates": [
+ {"date": "2026-06-01", "time": "17:41:00", "cloud": None, "coverage": 1.0},
+ {"date": "2026-05-30", "time": "05:42:30", "cloud": None, "coverage": 1.0},
+ ]})
+ client.put("/api/settings/keys", json={"sentinelhub": "test-instance"})
+ client.put("/api/settings/prefs", json={"sentinel1_layer": LAYER})
+ routine = body("radar-razed").model_copy(update={"offline": False, "date_rule": "latest_reference"})
+ routine = routine.model_copy(update={"b": routine.b.model_copy(update={"date": "", "time": ""})})
+ settled = analyzers.resolve_dates(radar_case, routine)
+ assert (settled.b.date, settled.b.time) == ("2026-05-30", "05:42:30")
+ assert settled.a.time == TIME
+
+
+def test_optical_sources_dump_as_they_always_did():
+ """Frame keys and the repeat notice compare dumps: an optical source must
+ not grow a field because radar sources carry a time."""
+ optical = Source(date=DAY_B)
+ assert "time" not in optical.model_dump()
+ assert Source(provider="sentinel1", date=DAY_B, layer=LAYER, time=TIME).model_dump()["time"] == TIME
+ old = deepcopy(optical.model_dump())
+ assert analyzers._key(Source.model_validate(old), 13, 1, 2, None) == \
+ analyzers._key(optical, 13, 1, 2, None)
+
+
+# -- finding the layer ----------------------------------------------------------------------
+
+
+def test_finding_the_radar_layer_skips_template_layers_and_keeps_the_first_that_answers(client, monkeypatch):
+ from azimut.api import satellite
+
+ client.put("/api/settings/keys", json={"sentinelhub": "test-instance"})
+ probed = []
+ monkeypatch.setattr(satellite.sentinel, "serves_sentinel1", lambda instance: True)
+ monkeypatch.setattr(satellite.sentinel, "capabilities_layers", lambda instance: [
+ {"id": "TRUE_COLOR"}, {"id": "SWIR"}, {"id": "MY_NOTES"}, {"id": LAYER}, {"id": "LATER"}])
+
+ def probe(instance, layer):
+ probed.append(layer)
+ return {"ok": layer == LAYER, "layer": layer, "detail": "reads Sentinel-1 VV and VH"}
+
+ monkeypatch.setattr(satellite.sentinel, "probe_sar_layer", probe)
+ before = config.month_usage("sentinelhub")
+ answer = client.post("/api/satellite/sentinel1/layer", json={}).json()
+ assert answer["ok"] and answer["layer"] == LAYER
+ assert probed == ["MY_NOTES", LAYER]
+ assert config.month_usage("sentinelhub") == before + 2
+ assert client.get("/api/settings").json()["sentinel1_layer"] == LAYER
+ # a new instance is another configuration: its radar layer is found again
+ client.put("/api/settings/keys", json={"sentinelhub": "other-instance"})
+ assert client.get("/api/settings").json()["sentinel1_layer"] == ""
+
+
+def test_an_instance_without_sentinel1_is_told_before_any_probe(client, monkeypatch):
+ from azimut.api import satellite
+
+ client.put("/api/settings/keys", json={"sentinelhub": "test-instance"})
+ monkeypatch.setattr(satellite.sentinel, "serves_sentinel1", lambda instance: False)
+ monkeypatch.setattr(satellite.sentinel, "probe_sar_layer",
+ lambda *a: pytest.fail("no probe for an instance without Sentinel-1"))
+ answer = client.post("/api/satellite/sentinel1/layer", json={}).json()
+ assert answer == {"ok": False, "layer": "", "serves": False, "tried": [],
+ "detail": "this instance has no Sentinel-1 layer yet"}
+ assert client.post("/api/satellite/sentinel1/layer", json={"layer": "../x"}).status_code == 422
+
+
+# -- the radar basemap ----------------------------------------------------------------------
+
+
+def _radar_settings(monkeypatch, tmp_path, layer=LAYER):
+ from azimut.engine import tiles
+
+ monkeypatch.setenv("AZIMUT_HOME", str(tmp_path))
+ config.save_settings({**config.DEFAULT_SETTINGS, "api_keys": {"sentinelhub": "inst-uuid"},
+ "sentinel1_layer": layer})
+ return tiles
+
+
+def test_the_radar_basemap_is_offered_once_its_layer_is_known(monkeypatch, tmp_path):
+ tiles = _radar_settings(monkeypatch, tmp_path, layer="")
+ assert "sentinel1" not in {p.id for p in tiles.all_providers()}
+ tiles = _radar_settings(monkeypatch, tmp_path)
+ radar_map = next(p for p in tiles.all_providers() if p.id == "sentinel1")
+ assert f"LAYER={LAYER}" in radar_map.url and "inst-uuid" in radar_map.url
+ assert "EVALSCRIPT=" in radar_map.url and "TIME=" not in radar_map.url
+ # the same quota and the same native ceiling as the optical basemap
+ assert (radar_map.meter, radar_map.tile_size, radar_map.max_native_zoom) == ("sentinelhub", 512, 14)
+
+
+def test_a_radar_variant_draws_one_pass_and_names_it(monkeypatch, tmp_path):
+ tiles = _radar_settings(monkeypatch, tmp_path)
+ one = tiles.get_provider("sentinel1~2026-05-14~054210")
+ assert one.id == "sentinel1~2026-05-14~054210"
+ assert "TIME=2026-05-14T05:22:10Z/2026-05-14T06:02:10Z" in one.url
+ assert "05:42 UTC" in one.label
+ day = tiles.get_provider("sentinel1~2026-05-14")
+ assert "TIME=2026-05-14/2026-05-14" in day.url
+ for bad in ("sentinel1~2026-05-14~5421", "sentinel1~2026-13-01", "sentinel1~2026-05-14~054210~x",
+ "sentinel1~../etc"):
+ with pytest.raises(KeyError):
+ tiles.get_provider(bad)
+ assert sentinel.radar_variant_id("2026-05-14", "05:42:10") == "sentinel1~2026-05-14~054210"
+ assert sentinel.radar_variant_id() == "sentinel1"
+
+
+def test_radar_difference_needs_two_passes_of_one_track(client):
+ from azimut.api.compare import change_refusal
+
+ def side(day, time):
+ return {"present": True, "provider": "sentinel1", "overlays": [], "radar": {"date": day, "time": time},
+ "sentinel": {"layer": "TRUE_COLOR", "date": "", "maxcc": 100}, "wayback_release": None}
+
+ assert change_refusal(side("2026-05-02", "05:42:10"), side("2026-05-14", "05:42:40")) is None
+ assert "one track" in change_refusal(side("2026-05-02", "05:42:10"), side("2026-05-14", "17:33:02"))
+ assert "two different" in change_refusal(side("2026-05-14", "05:42:10"), side("2026-05-14", "05:42:10"))
+ assert "dated" in change_refusal(side("", ""), side("2026-05-14", "05:42:10"))
+
+
+def test_a_radar_comparison_saves_its_passes(client):
+ client.put("/api/settings/keys", json={"sentinelhub": "inst-uuid"})
+ client.put("/api/settings/prefs", json={"sentinel1_layer": LAYER})
+ cid = client.post("/api/cases", json={"name": "Radar compare"}).json()["id"]
+ side = {"present": True, "provider": "sentinel1", "overlays": [],
+ "sentinel": {"layer": "TRUE_COLOR", "date": "", "maxcc": 100}, "wayback_release": None}
+ spec = {"version": 2, "camera": {"lat": 51.9, "lon": 4.0, "zoom": 13}, "mode": "side",
+ "a": {**side, "radar": {"date": DAY_A, "time": TIME}},
+ "b": {**side, "radar": {"date": DAY_B, "time": TIME}}}
+ saved = client.post(f"/api/cases/{cid}/compare/sessions", json={"title": "Radar pair", "spec": spec})
+ assert saved.status_code == 200, saved.text
+ reopened = client.get(f"/api/cases/{cid}/compare/sessions/{saved.json()['name']}").json()
+ assert (reopened.get("spec") or reopened)["b"]["radar"] == {"date": DAY_B, "time": TIME}
+
+
+def test_the_radar_layer_travels_with_the_backup(client):
+ client.put("/api/settings/prefs", json={"sentinel1_layer": LAYER})
+ bundle = client.get("/api/settings/export").json()
+ assert bundle["settings"]["sentinel1_layer"] == LAYER
+ client.put("/api/settings/prefs", json={"sentinel1_layer": ""})
+ assert client.post("/api/settings/import", json=bundle).status_code == 200
+ assert client.get("/api/settings").json()["sentinel1_layer"] == LAYER
+ bad = {**bundle, "settings": {**bundle["settings"], "sentinel1_layer": "../x"}}
+ assert client.post("/api/settings/import", json=bad).status_code == 422
+
+
+def test_a_radar_routine_stays_on_the_track_it_has_run_on(client, radar_case, monkeypatch):
+ """A place is seen from several tracks. A routine that compares each pass
+ with the one before must keep to its own, or every run would jump tracks
+ and read the change in angle as change on the ground."""
+ case = radar_case
+ client.put("/api/settings/keys", json={"sentinelhub": "test-instance"})
+ client.put("/api/settings/prefs", json={"sentinel1_layer": LAYER})
+ monkeypatch.setattr(analyzers, "previous_pass", lambda case, body: Source(
+ provider="sentinel1", date=DAY_B, layer=LAYER, maxcc=100, time="05:42:10"))
+ monkeypatch.setattr(analyzers.sentinel, "acquisitions", lambda *a, **k: {"dates": [
+ {"date": "2026-05-28", "time": "17:33:02", "cloud": None, "coverage": 1.0},
+ {"date": "2026-05-26", "time": "05:42:30", "cloud": None, "coverage": 1.0},
+ ]})
+ routine = body("radar-razed").model_copy(update={
+ "offline": False, "date_rule": "latest_previous", "followup_id": "abcdef123456"})
+ routine = routine.model_copy(update={"b": routine.b.model_copy(update={"date": "", "time": ""})})
+ settled = analyzers.resolve_dates(case, routine)
+ assert (settled.b.date, settled.b.time) == ("2026-05-26", "05:42:30")
+ assert settled.a.date == DAY_B
+
+
+def test_an_optical_run_drops_a_pass_time_left_by_a_radar_analyzer(radar_case):
+ leftover = body("radar-change").model_dump()
+ leftover["recipe"] = next(r for r in BUILTINS if r.id == "large-change").model_dump()
+ leftover["a"] = {**leftover["a"], "provider": "sentinel2", "layer": "TRUE_COLOR"}
+ settled = analyzers.resolve_dates(radar_case, RunInput.model_validate(leftover))
+ assert settled.a.time == "" and settled.b.provider == "sentinel2"
+ assert settled.b.layer == "TRUE_COLOR"
+
+
+def test_every_built_in_sits_in_one_group_with_a_stated_reliability(client):
+ from azimut.engine.analysis_models import GROUPS, RELIABILITY
+
+ grouped = [ident for _, _, members in GROUPS for ident in members]
+ assert sorted(grouped) == sorted(r.id for r in BUILTINS)
+ assert set(RELIABILITY) == {r.id for r in BUILTINS}
+ # a hull answers the radar through cloud and glint alike
+ assert (RELIABILITY["radar-vessels"], RELIABILITY["boats"]) == ("reliable", "approximate")
+ catalogue = client.get("/api/compare/analyzers").json()
+ assert catalogue["copernicus_key"] is False and catalogue["radar_layer"] == ""
+ assert catalogue["groups"][0] == {"id": "vessels", "label": "Vessels", "recipes": ["radar-vessels", "boats"]}
+ client.put("/api/settings/keys", json={"sentinelhub": "inst"})
+ assert client.get("/api/compare/analyzers").json()["copernicus_key"] is True
diff --git a/tests/test_sentinel.py b/tests/test_sentinel.py
index 0b7e2e3..8690ca1 100644
--- a/tests/test_sentinel.py
+++ b/tests/test_sentinel.py
@@ -669,7 +669,7 @@ def test_band_frame_refuses_a_product_it_has_no_evalscript_for():
with pytest.raises(ValueError):
sentinel.band_frame("inst-uuid", BOX, 64, 64, "2026-05-11", "thermal", get=get)
assert sentinel.PRODUCTS == {
- "vessel", "fire", "surface", "change-sky",
+ "vessel", "fire", "surface", "change-sky", "sar", "sar-picture", "water",
*(f"index-{name}" for name in ("ndvi", "ndwi", "mndwi", "nbr", "ndbi", "bsi")),
*(f"change-{name}" for name in ("ndvi", "ndwi", "mndwi", "nbr", "ndbi", "bsi")),
}
diff --git a/tests/test_updates.py b/tests/test_updates.py
index 94cc5ad..808505e 100644
--- a/tests/test_updates.py
+++ b/tests/test_updates.py
@@ -138,7 +138,7 @@ def test_update_endpoint_with_check_queries_github(client, monkeypatch):
# The pair below is the contract, and it moves in one direction only: when a
# shipped file really changes, set the manifest to the current __version__ and
# record the new digest here (the failing test prints it).
-EXTENSION_VERSION = "0.3.0"
+EXTENSION_VERSION = "0.3.1"
EXTENSION_PAYLOAD = "207f769e50979032a6052386396ece5972de7ce0f267c60e39e25e78806d5dca"
# The digest itself lives in engine/extinstall.py, because the update button
diff --git a/tests/test_workqueue.py b/tests/test_workqueue.py
index dc4b891..eae7d20 100644
--- a/tests/test_workqueue.py
+++ b/tests/test_workqueue.py
@@ -159,3 +159,44 @@ def test_a_worker_that_dies_hands_the_queue_back(case, monkeypatch):
assert workqueue._worker_running is False
# and the case it never got to is still queued, for the worker after it
assert workqueue.wait_until_idle(timeout=0) is True
+
+
+def test_a_long_job_lets_other_kinds_through_between_its_steps(case):
+ order: list[str] = []
+
+ def sweep(c, job):
+ for step in range(2):
+ order.append(f"sweep {job['payload']['n']}.{step}")
+ if step == 0:
+ workqueue.enqueue(c, "thumb", payload={})
+ workqueue.let_others_through(c, "sweep")
+
+ workqueue.register("sweep", sweep)
+ workqueue.register("thumb", lambda c, job: order.append("thumb"))
+ workqueue.enqueue(case, "sweep", payload={"n": "1"})
+ workqueue.enqueue(case, "sweep", payload={"n": "2"})
+
+ assert workqueue.drain(case) == 2
+ # the thumbnail never waits out a sweep, and the second sweep keeps its turn
+ assert order == ["sweep 1.0", "thumb", "sweep 1.1", "sweep 2.0", "thumb", "sweep 2.1"]
+ assert {j["state"] for j in case.list_jobs()} == {"ready"}
+
+
+def test_letting_others_through_with_nothing_else_registered_claims_nothing(case):
+ workqueue.HANDLERS.clear()
+ nested: list[bool] = []
+ busy = [False]
+
+ def sweep(c, job):
+ nested.append(busy[0])
+ busy[0] = True
+ workqueue.let_others_through(c, "sweep")
+ busy[0] = False
+
+ workqueue.register("sweep", sweep)
+ workqueue.enqueue(case, "sweep", payload={})
+ workqueue.enqueue(case, "sweep", payload={})
+ # an empty kind list must not turn into "any kind", or the second sweep
+ # would run inside the first
+ assert workqueue.drain(case) == 2
+ assert nested == [False, False]