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

Sweep drawn areas for changes, vessels and shortwave hotspots (#80)

OsintMeThatcfe066c4111c
diff --git a/README.md b/README.md
index 330a068..05970ab 100644
--- a/README.md
+++ b/README.md
@@ -61,6 +61,7 @@ to fix a point on the map.*
| **Reverse Search** | Prepare an image or a video frame for keyless reverse-image services. With the capture extension, pressing an engine opens it with the picture already in it. Nothing leaves the machine until you press one. |
| **Inspect** | 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. |
| **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 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. |
@@ -245,10 +246,11 @@ once and paste the pairing token. Because the app owns the folder, later updates
are one button — it rewrites the files and the extension restarts itself.
Firefox refuses an unsigned extension and forgets an unpacked one on exit, so it
-installs the signed `azimut-capture-<version>.xpi` from the
-[latest release](https://github.com/OsintMeThat/azimut/releases/latest) instead.
-That copy is sealed, so the update button does not apply to it: Firefox reads
-Azimut's own update manifest and replaces the add-on itself. Full instructions in
+installs the signed `azimut-capture-<version>.xpi` instead. **Settings → Capture
+extension** links that exact file, which rides on the release that last changed
+the extension rather than on the newest one. That copy is sealed, so the update
+button does not apply to it: Firefox reads Azimut's own update manifest and
+replaces the add-on itself. Full instructions in
[extension/README.md](extension/README.md).
## Building & releasing
diff --git a/docs/ASSIST_HANDOVER.md b/docs/ASSIST_HANDOVER.md
new file mode 100644
index 0000000..a34411d
--- /dev/null
+++ b/docs/ASSIST_HANDOVER.md
@@ -0,0 +1,109 @@
+# Compare Detect — working notes
+
+Scratch notes for whoever picks this up next, not a project doc. Delete it when
+the work lands in a release. What is *done* is described in
+[UI.md](UI.md) and [SPEC.md](SPEC.md); only what is open or surprising is here.
+
+## Decisions taken
+
+- **Two computing modes, one column.** `Difference` (the old Change assist) reads
+ the pixels on screen; `Detect` sweeps a drawn area at native resolution. They
+ sit right of a rule in the mode dock, and share one docked column beside the
+ stage. There is no "Assist" button and no cross-link between panels: the dock
+ is the only switch. `lib/map/compare.js` carries the grouping.
+- **No machine-learning model, and not as a fallback.** At Sentinel-2's 10 m a
+ pixel a 30 m vessel is three pixels: there is no shape to recognise, and a
+ detector trained on shapes would do worse than the physics. So the two new
+ Copernicus methods read reflectance:
+ - `vessels` — CFAR on B08. Water absorbs near-infrared almost completely, so a
+ hull is an outlier against the sea *around it*; the background comes from a
+ ring with its middle punched out (`analyzers.local_contrast`), which is what
+ makes one threshold work on a calm lagoon and a sunlit swell alike.
+ - `hotspots` — the published short-wave test: B12 above an absolute floor and
+ high against B11 and B08. Cloud is bright in B12 too but bright in its
+ neighbours as well, so its ratios sit at one, and that is what rejects it.
+ Both ride on `sentinel.band_frame`, which already existed for spectral
+ indices. No new dependency: numpy and opencv-python-headless were already in.
+- **Preset names state what is measured, never what it means.** "Vessels on
+ water" is a claim about infrared contrast; "Boats" would have claimed
+ recognition. `signal_score` is signal strength and `confidence` stays null.
+- **Disk follows findings, not area.** `prune_frames` drops the frames of tiles
+ that produced no candidate, which is what let `MAX_TILES` go from 256 to 4096
+ (313 km a side on Sentinel, 4.9 km on Wayback). The trade is stated in the
+ panel and in UI.md: an offline rerun now covers what the tile cache still
+ holds, not the whole of a past sweep.
+- **Detect leads the maps.** Inside the mode the A/B source cards are hidden and
+ step 2 pushes its imagery onto the stage, so what is on screen is what a run
+ would sweep. One analyzer that reads one date shows one map, and its evidence
+ is one crop rather than the same picture twice.
+- **Keeping is the review.** The triage is `new → kept | dismissed`, and `kept`
+ is set by `promote` itself: one act files the pin, its evidence copy and the
+ verdict together, so a candidate cannot be marked kept without being in the
+ case or the reverse. `PATCH` refuses to re-triage a candidate whose pin still
+ exists; `DELETE …/promote` is the undo, and it sends the pin to Trash. The old
+ three-way relevant/ignored/to-review was two decisions where there is one.
+- **An area is grabbed by its edge.** The fill of a zone no longer takes pointer
+ events, so dragging inside one pans the map; a transparent wide stroke is the
+ move target, and a press under four pixels selects without moving anything.
+ Screen positions all go through `project()`, which reads the camera revision,
+ so handles and boxes cannot be left behind by a pan.
+- **Detect's drawing stays in Detect.** Areas and candidate layers render only
+ in the mode that explains them. A kept candidate is a pin and shows wherever
+ case work shows, which is the honest way for a result to outlive the mode.
+- **"Watch" is the UI word for a follow-up.** The entity type id stays
+ `analysis-follow-up`; renaming storage for a word nobody reads is not worth a
+ migration.
+
+## Still open
+
+1. **No tile halo.** `detect` runs per tile with no overlap; components crossing
+ a seam are merged afterwards by their boxes (`merge`), which can overmerge and
+ can split a target whose halves each fall under `min_area`. Needs boundary
+ tests before multi-tile results can be called robust.
+2. **Promotion saves one evidence part.** `promote` calls `preview_bytes(...)`
+ with the default `part=0`, so a candidate spanning several tiles promotes only
+ its first before/after. The promoted place also carries `evidence` as an
+ attribute rather than a formal link to the filed media.
+ `PREVIEW_EDGE`/`PREVIEW_MARGIN` decide how far the crop is enlarged; the zoom
+ is a whole number and nearest-neighbour on purpose, and that is worth keeping
+ whatever else changes there.
+3. **Preserved frames are trusted by filename.** `frame` reuses any
+ `runs-*.assets/<key>.png` it finds without checking the recorded `sha256`
+ against the bytes. The key is derived from the source and tile, not the
+ content, so an imported bundle could supply the file. Verify before reading.
+4. **Polygon validation** catches empty and zero-area geometry, not every
+ self-crossing.
+5. **Coverage is sampled, not clipped.** `sentinel.acquisitions` measures how
+ much of the drawn areas a pass reaches by testing a few hundred points inside
+ the rings against the granule footprints, so a share is accurate to about a
+ percent and `FULL_COVER = 0.98` is what counts as whole. It answers about the
+ granule footprints, which is where imagery exists — not about cloud inside
+ them, for which the scene's own figure is the only number on offer and it
+ covers a 110 km granule, not the area drawn. Wayback release dates are
+ publication dates, not acquisition dates. Both distinctions are in the UI
+ copy — keep them.
+6. **The picture cloud test is a guess and must stay opt-in.** Bright and
+ colourless is equally a cloud, a white roof, a gravel pad and fresh snow, and
+ nothing in a rendered image separates them. That is why it lives in its own
+ `guess_clouds` rather than riding on `ignore_clouds`, which means Sentinel-2's
+ scene classification and is on by default. Wiring the two together would
+ silently change what every saved colour recipe finds.
+7. **No measured benchmark.** Sequential bounded tiles are an argument about
+ memory, not a measurement, and no accuracy check against real imagery exists.
+ The detector tests use synthetic frames: they prove the method does what it
+ claims on a controlled input, not that it finds ships in the Bosphorus.
+
+## Verification at handover
+
+- Backend: `2813 passed` (`pytest -q tests/ -p no:randomly`, 17 min).
+ One caveat: under `pytest-randomly`'s default ordering a single unrelated test,
+ `test_updates.py::test_the_extension_version_moves_only_when_the_extension_does`,
+ failed once. It passes standalone, in its own file group, and in deterministic
+ order. Nothing in this work touches `extension/` or `extinstall`. Worth finding
+ the polluting test, separately.
+- Frontend: `262 files, 5036 tests`, no unhandled errors.
+- Browser: `e2e/compare.spec.js`, 8 passed on Chromium and Firefox.
+- `ruff check src/ tests/`, `mypy` on the changed modules, `svelte-check`: clean.
+- `npm run build`: clean, with the existing MapLibre chunk-size warning.
+
+No commit, PR, tag or wheel has been produced for this work.
diff --git a/docs/IMAGERY_PROVIDERS.md b/docs/IMAGERY_PROVIDERS.md
index ef2289a..54d3704 100644
--- a/docs/IMAGERY_PROVIDERS.md
+++ b/docs/IMAGERY_PROVIDERS.md
@@ -224,12 +224,33 @@ both quotas are 30k. The meter tracks requests exactly and slightly overstates P
so its unit is "request", not
"tile" (`meterUnit`).
-**Granule footprints are checked against the point** (`_covers`). A granule's
+**Granule footprints are checked against the query** (`_covered`). A granule's
bounding box is a square; its data is the slice of orbit swath inside it. WFS
answers on the box, so without the check a listed day can render black. The footprint is
tested under both axis orders: read backwards, every granule on Earth would be
rejected.
+### Over a drawn area, a date also has a coverage share
+
+`sentinel.acquisitions(rings, …)` runs the same WFS query over the union box of
+the areas a Detect sweep would cover, and keeps the footprints instead of
+reducing them to a yes/no. Each date comes back with `coverage`: the share of
+those areas that day's granules actually reach, measured by sampling a few
+hundred points inside the rings and testing each against the footprints — the
+geometry already in the module, so no polygon clipper joins the dependency list.
+Sampling puts the answer within a percent, which is what a "62% of the areas"
+badge can honestly claim; `FULL_COVER = 0.98` is what counts as whole, because a
+ring's own edge lands a point or two outside a granule that in truth reaches it.
+
+This is the question a crosshair lookup cannot answer. Sentinel-2 flies 290 km
+swaths, so an area wider than one has **no** single day covering it, and a date
+picked on its centre sweeps nodata over the rest. The automatic date rules
+(`resolve_dates`) take the newest pass that is both under the cloud ceiling and
+at full cover, and name the best partial share when there is none.
+
+Still one request for the whole set of areas, not one per area. `truncated` says
+the WFS hit its 100-feature ceiling, so older passes in the window are missing.
+
WFS dates are still candidates. Before changing the map, the picker sends an
8×8 WMS `dataMask` check for the selected layer and day. A failed check leaves
the current map in place and marks the date unavailable at that location. The
@@ -383,9 +404,10 @@ id and its cache always name one.
## Key-less overlays
Drawn over any basemap, fetched by the browser straight from their own servers
-(all answer cross-origin), never through the proxy, never cached on disk, never
-in a capture, and never asked for before their switch is on
-(`frontend/src/lib/map/basemap.js`). Checked 2026-09-13.
+(all answer cross-origin), never through the proxy, never cached on disk and
+never in a capture. Borders are the one layer the map opens with; every other is
+asked for only once its switch is on (`frontend/src/lib/map/basemap.js`).
+Checked 2026-09-13.
| Layer | Source | Licence / terms | Notes |
|---|---|---|---|
diff --git a/docs/ONTOLOGY.md b/docs/ONTOLOGY.md
index 1f8d840..e490765 100644
--- a/docs/ONTOLOGY.md
+++ b/docs/ONTOLOGY.md
@@ -46,9 +46,11 @@ index the ordering was already asking for.
Schema 15 adds the rebuildable temporal projection. Claims and media metadata remain
authoritative. Schema 16 lets Analysis Views own Timeline recipes and immutable
temporal snapshots. Schema 17 rebuilds temporal bounds at fixed microsecond width so
-SQLite text ordering stays chronological. A Timeline view stores presentation and
-track queries, never copies temporal rows into the graph and never creates a temporal
-relation.
+SQLite text ordering stays chronological. Schema 18 rebuilds the projection for the
+date a Proof states: a statement, because the analyst concluded it, beside the media
+rows that report what a file claims about itself. A Timeline view stores presentation
+and track queries, never copies temporal rows into the graph and never creates a
+temporal relation.
Legend: ✅ implemented in code · ⬜ proposed.
@@ -130,7 +132,7 @@ to one clause — no full stop, no em-dash, under a hundred characters.
| `class` | a model the case counts with, never one particular object | `equipment-type` |
| `identifier` | a handle on a system | `account`, `email`, `phone`, `domain`, `ip`, `network` |
| `collected` | bytes gathered into the case rather than written, so one may depict a place | `media`, `capture` |
-| `document` | it is read rather than gathered: made or consulted | `proof`, `post`, `note`, `sheet`, `inspect-session`, `bookmark` |
+| `document` | it is read rather than gathered: made or consulted | `proof`, `post`, `note`, `sheet`, `inspect-session`, `compare-session`, `bookmark` |
| `place` | a point, never a thing | `place` |
| `claim` | a statement about the graph, carrying its own reasoning | `claim` |
@@ -159,7 +161,7 @@ picture of the case is about it. The line that matters is between the first two
|---|---|---|---|
| `subject` | the case is about it | `person`, `organization`, `vehicle`, `vessel`, `aircraft`, `structure`, `equipment-type`, `account`, `email`, `phone`, `domain`, `ip`, `network`, `media`, `place`, `claim` | a node |
| `attestation` | a wrapper around something the case already holds | `bookmark`, `proof`, `capture` | folded into the edge that carries its provenance, drawn or not (below) |
-| `annex` | consulted rather than seen, hanging off one node | `note`, `sheet`, `inspect-session` | out of the case readings, drawn by **My work** |
+| `annex` | consulted rather than seen, hanging off one node | `note`, `sheet`, `inspect-session`, `compare-session` | out of the case readings, drawn by **My work** |
| `deliverable` | what the case produced | `post` | out of the case readings, drawn by **My work** |
A bookmark stays drawn because it is not a leaf: *this account posted it, this
@@ -181,6 +183,7 @@ answer by omission (`tests/test_entities.py`).
| `proof` | document | attestation | ✅ | proof-composer | `spec` (json), `path` (png) | yes |
| `post` | document | deliverable | ✅ | post-composer | `draft` (json) | yes |
| `inspect-session` | document | annex | ✅ | inspect | `spec` (json) | yes |
+| `compare-session` | document | annex | ✅ | compare | `spec` (json) | yes |
| `note` | document | annex | ✅ | notebook | `path`, `folder?` | yes (Markdown) |
| `sheet` | document | annex | ✅ | sheet | `path` (csv) | yes (CSV + sidecar) |
| `bookmark` | document | attestation | ✅ | capture extension | `url`, `fetched_at?`, `archive_url?`, `reliability?` | no (a URL) |
@@ -217,7 +220,7 @@ to declare here when built:
| Type | Family | Shape | Note |
|---|---|---|---|
-| `grid` | document | a spec, like `inspect-session` | Grid Search already writes `.search/<name>.json`; it is **the only saved tool state outside the graph**, so today nothing can say "this sweep is how I found it" |
+| `grid` | document | a spec, like `inspect-session` | Grid Search writes `.search/<name>.json` outside the graph, so today nothing can say "this sweep is how I found it" |
| `sky-session` | document | a spec, like `inspect-session` | a sun or moon lookup: the point, the date and the time, **never the numbers**. Reopening recomputes; a proof that shows the reading is what freezes it, exactly as a `proof` pairs an editable `spec` with an exported `path` |
| `ground-image` | collected | file-backed | a provider and a position of its own, which an imported media has not |
| `report` | document | file-backed | a distinct artifact, like `proof` |
@@ -360,11 +363,22 @@ may form an exact interval. Local-time intervals, mixed date/time intervals, ope
intervals and the rest of EDTF Level 2 remain outside the announced profile.
Time reads a derived SQLite projection, never a second authority. Claim `when` and
-`time_role` remain on the Claim; capture/publication/imagery dates remain in the media
-sidecar; filing and collection dates remain provenance. The projection labels them
-`statement`, `media` or `case_activity`, and can be deleted and rebuilt from those
-records. A manually assessed media time is therefore a sourced Claim about the media,
-not a rewrite of `taken_at`.
+`time_role` remain on the Claim; a Proof's `when` remains on the Proof;
+capture/publication/imagery dates remain in the media sidecar; filing and collection
+dates remain provenance. The projection labels them `statement`, `media` or
+`case_activity`, and can be deleted and rebuilt from those records. A manually assessed
+media time is therefore a sourced Claim about the media, not a rewrite of `taken_at`.
+
+**A dated Proof states that date for the material it rests on.** The footage was shot
+when it was shot, whichever document argues about it, so saving the proof files one
+Claim — `about` every source it composes, `cites` the proof — rather than leaving the
+date visible only from the proof's side. Three rules keep it honest: the chain is
+walked to the *origin*, so the video is dated and not the frame cut out of it, and a
+capture is never dated at all, its imagery being the provider's flyover; the file's own
+clock is never written over, so both readings sit on its Time panel with the statement
+above them; and one proof owns one statement, restated on every save, withdrawn when
+the date is cleared — unless reasoning has been added to it since, which makes it the
+analyst's and not the composer's to delete.
**Counting Claims counts observations, not objects**: two
videos of the same destroyed tank are two statements. Azimut does not merge
@@ -482,10 +496,10 @@ A grade is read wherever its source appears, including on a relation row, where
sits on the line carrying the entity's name while the edge's own rating sits on the
line below (§3). Nothing needs one: most bookmarks are never graded.
-The file-backed pointers of `proof`, `post` and `inspect-session` (`spec`,
-`draft`, `path`) are not stable: the file's name follows the label, so renaming
-one in its tool rewrites the pointer on the same entity. Look these up by id, or
-re-read the pointer — never cache one across a save.
+The file-backed pointers of `proof`, `post`, `inspect-session` and
+`compare-session` are not stable: the file's name follows the label, so renaming
+one in its tool rewrites its `spec`, `draft` or `path` on the same entity. Look
+these up by id, or re-read the pointer — never cache one across a save.
## 3. Link
@@ -622,7 +636,7 @@ keeps its entities and loses its edges, with the reason.
Six rules hold across the modes, and they are the reason it is safe to press twice.
**Nothing that owns a file is born from a cell.** A `media`, a `capture`, a `proof`, a
-`post`, an `inspect-session` hold bytes; a cell holds an address. They exist only where the
+`post`, an `inspect-session` or a `compare-session` hold bytes; a cell holds an address. They exist only where the
app itself fetched the file — the proof import's road (`engine/proofimport.py`), and the
build a geolocation index presses (`engine/sheetproofs.py`), which is that same road driven
a row at a time. The rule is not about where the request came from but about who fetched
diff --git a/docs/SPEC.md b/docs/SPEC.md
index 6fd601b..5a893e7 100644
--- a/docs/SPEC.md
+++ b/docs/SPEC.md
@@ -54,10 +54,12 @@ azimut/ # everything Azimut owns; the rest of the folder is yours
sheets/ # case sheets as plain CSV; .meta/ holds the grid's own state
media/ # source + captured + extracted media; .meta/ holds the sidecars
proofs/ # exported PNGs; .meta/ holds the specs and pasted images
- exports/ # notes as PDF, analysis plates, and yours to fill
+ exports/ # finished exports and yours to fill
.data/ # case.db, the authoritative SQLite graph, and entity photos
.drafts/ # post drafts
.inspect/ # saved Inspect session specs
+ .compare/ # saved Compare session specs
+ .analysis/ # Detect areas, watches, runs and the frames behind their results
.search/ # saved Grid Search state
.trash/ # recoverable artifact payloads, in numbered slots
```
@@ -153,24 +155,32 @@ proof for publication.
| ✅ **Imported proofs** | Turns a published post into a composed proof: every picture a panel, its text read for a position, the addresses it points at fetched as material, and nothing filed before the preview is approved. |
| ✅ **Import origin** | States one origin for a whole import, offers it to a batch that landed without one, and corrects any file later from Details. |
| ✅ **Drawing on a proof** | Stamps a fixed set of marks, fills boxes and ellipses at a chosen opacity, keeps every shape tool in hand, and recolours, restyles, nudges, drags or deletes a picked family at once. |
-| ✅ **A proof of several points** | States every place a proof argues, each optionally named and one of them the camera's, files them as places under one title, and carries them into the tweet and onto the exported picture. |
+| ✅ **A proof of several points** | States every place a proof argues — each panel's own included, none of them overwritten — optionally named, one of them the camera's, any of them moved on a map rather than typed; files them as places under one title and carries them into the tweet and onto the exported picture. |
+| ✅ **What a proof says about itself** | Carries an optional sentence, which is its notes and what a post is written from, and an optional date for when its material was taken — never pre-filled, cleared in one press, and shown on the Timeline. |
+| ✅ **A date that reaches the footage** | A dated proof states that date for the sources it rests on — the original, never the frame cut from it or a capture — as one cited statement per proof, restated on every save and never written over the file's own clock. |
### v3 GEOINT expansion (shipped as GitHub `v0.3.0+`)
| Tool | What it does |
|------|--------------|
| ✅ **Map engine** | Draws the map on MapLibre GL behind the `lib/map` façade, with the same providers, captures and bearing. |
-| ✅ **Map chrome** | Puts modes in one rail, layers in the right panel, imagery in the map corner and position in a status line, each tool declared once. |
+| ✅ **Map chrome** | Puts modes in one rail, map layers in their tool panel or popup, imagery in the map corner and position in a status line, each tool declared once. |
| ✅ **Point menu** | Right-clicking the ground copies that point in every format, looks it up, saves, measures, reads the sky or opens its imagery history from it, and links it out. |
| ✅ **Map windows** | Opens the map in several tabs with the view in the URL, links map tabs and extension panels on other sites to one camera, and syncs saved points, grids and sweeps live to every tab and extension panel. |
| ✅ **Map layers** | Stacks key-less overlays (borders, roads, railways, power lines, sea marks, GPS traces), NASA FIRMS fires and VIIRS night lights for a chosen day, and filters drawn pins by kind and folder. |
+| ✅ **Media on the map** | Draws the case's located photos and videos where a relation, a GPS reading or a proof puts 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. |
+| ✅ **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 at native resolution for changes, vessels on water and short-wave hotspots; candidates are reviewed one at a time and only a kept one becomes a case pin, and a saved watch reruns on demand. |
+| ✅ **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, on Sentinel-2's scene classification where there is one and a stated guess from the picture where there is not, with a margin that takes the fringe both masks leave. |
| ✅ **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, media pins, sun and moon, search grids and case media over third-party maps, calibrated per site by a replayable command. |
| ✅ **Extension updates** | Updates the unpacked extension in one click, installs a signed self-updating Firefox add-on, and flags a copy out of step with the app. |
| ✅ **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. |
---
@@ -187,9 +197,11 @@ Each version delivers one complete daily workflow. Firm ideas move here from
| **3D map** | Pitch, public DEM terrain and extruded OSM buildings on the MapLibre map. An oblique capture records its pitch beside the bearing, so the view can be reproduced. |
| **Camera Resection (GCP)** | Marks matching points photo↔map, then solves camera position, viewing azimuth and rough FOV (OpenCV `solvePnP`) and saves the match as evidence. Its photo canvas and pixel↔angle camera frame are built for two callers: Sky Clock fills the same frame by hand. |
| **Capture graticule** | The rest of what a plate states about itself: a latitude/longitude grid over app and extension captures, beside the scale bar and north arrow that already ship. |
-| **Satellite Compare** | Same coords across providers (Esri / Sentinel-2 date slider / Bing / keyed), synced pan/zoom. Copernicus easy link. |
| **Image Compare** | Overlay two images with opacity, swipe and pixel diff. Assist satellite-to-screen alignment without presenting a verdict. |
| **Georeferenced overlay** | Pins an image to the ground by three or four matching points: a commercial satellite shot from a post, a drone frame, an old plan. It draws under the map's own marks with an opacity slider, reprojects as the map pans, and is saved in the case with its control points so the fit can be checked. |
+| **Subscribed map layers** | Follows a public My Maps, KML/KMZ or GeoJSON URL and refreshes it automatically only while enabled, while keeping the last snapshot available offline and never rewriting evidence already saved from it. Local KML/KMZ, GeoJSON and GPX files open as fixed case layers. |
+| **GeoConfirmed layer** | Queries GeoConfirmed for a chosen conflict, date or viewport only when enabled, opens each event's original sources and lets selected events enter the case. |
+| **Source directory** | Keeps the accounts, channels and pages worth following for this case, searchable by platform, area and topic, with notes and source reliability; monitoring remains a later opt-in workflow. |
| **Metadata follow-up** | Explains which common image/video fields were stripped and proposes events from capture times. |
| **Edit Provenance** | Reads a rendered video's own edit history: which source clips it was cut from, in what order, and the GPS, dates and cameras those clips still carry. |
| **Sky sessions** | Saves a sun or moon lookup as a case artifact: the point, the date and the time, never the numbers they produce. It reopens where it was left, a proof can show its reading, and a statement can cite it. |
@@ -233,7 +245,7 @@ supplies, since a ridge ends the day well before the flat horizon does.
| Tool | What it does |
|------|--------------|
| **Skyline Matching** | Traces a horizon in a photo and compares it against the DEM profile seen from candidate points, in the same azimuth and elevation frame Camera Resection and Sky Clock already use. Terrain-occluded sun times then split candidates a matching horizon leaves tied. |
-| **Map Board (MyMaps-style)** | Editable case map: custom pins + notes/links, shapes, layers; import/export KML/KMZ/GeoJSON; pins bind to `place`. |
+| **Map Board (MyMaps-style)** | Edits case-owned pins, notes, links and shapes, groups them into analyst-made layers, binds pins to `place` and exports the finished map as KML/KMZ/GeoJSON. |
| **Evidence Locker** | Track SHA-256, timestamps, source and notes; archive with Wayback; export `evidence.jsonl` under a hash-chained manifest, so any later edit to an exported file is detectable. |
| **Report Builder** | Assemble proofs/maps/timeline/entities/notes into PDF or one self-contained HTML file with its media embedded, readable offline. |
| **Case Sync (Git)** | Push a case to a private or public Git remote, pull it back, and diff two revisions, so two analysts can work the same case. |
diff --git a/docs/STORAGE_AND_PERFORMANCE.md b/docs/STORAGE_AND_PERFORMANCE.md
index 538bcdb..4b5f39a 100644
--- a/docs/STORAGE_AND_PERFORMANCE.md
+++ b/docs/STORAGE_AND_PERFORMANCE.md
@@ -5,7 +5,9 @@ cases responsive. The migration from a monolithic `case.json` graph to per-case
SQLite is complete.
Structured case data lives in SQLite. Images, videos, proof PNGs, drafts, saved
-Inspect sessions and note bodies remain ordinary files inside the case folder.
+Inspect and Compare sessions and note bodies remain ordinary files inside the case folder.
+Compare GIFs explicitly saved to the case are derived media under `media/`; an
+exported copy stays a finished file under `exports/` or the selected Views folder.
## The shape of the workspace
@@ -100,12 +102,14 @@ for a case to fit under it on Windows, and names it as a warning elsewhere.
.thumbs/ # disposable thumbnail cache
proofs/ # rendered PNGs
.meta/ # editable specs and pasted assets
- exports/ # what the analyst exports: notes as PDF, and their own files
+ exports/ # finished exports and the analyst's own files
.data/ # private structured and presentation state
case.db # entities, links, folders, catalog and jobs (SQLite)
entity-images/ # private, bounded entity photos and their thumbnails
.drafts/ # post drafts
.inspect/ # saved Inspect session specs
+ .compare/ # saved Compare session specs
+ .analysis/ # saved areas, watches, runs and the frames behind their results
.search/ # saved Grid Search state
.trash/ # deleted artifacts grouped by delete action, in numbered slots
```
@@ -132,7 +136,7 @@ new directory level or a raised cap breaks it.
schema fields. It no longer holds the graph, so the case switcher can identify a
case without opening its database. `case.db` is the source of truth for mutable
structured state (entities, links, folders, jobs). The files under `media/`,
-`proofs/`, `.drafts/`, `.inspect/` and `notes/` are the source of truth for their
+`proofs/`, `.drafts/`, `.inspect/`, `.compare/` and `notes/` are the source of truth for their
own content.
App-wide preferences stay outside cases under `<workspace>/.azimut/settings/`:
@@ -142,7 +146,7 @@ there with independent atomic renames, so a partial move resumes. If both
locations differ, the current hidden file wins and the legacy copy is retained
beside it under a `.legacy` name.
-For media, proof PNGs, notes, drafts and Inspect sessions, the human-readable
+For media, proof PNGs, notes, drafts, Inspect sessions and Compare sessions, the human-readable
filename stem is the name Azimut shows. Spaces, case and Unicode survive;
characters forbidden by Windows are replaced and the returned canonical stem
is written back to the UI. Renaming moves the file and its companions, rewrites
@@ -267,13 +271,15 @@ review.
## Database shape
-`case.db` is at SQLite schema 17: schema 8 adds nullable `links.confidence`,
+`case.db` is at SQLite schema 18: schema 8 adds nullable `links.confidence`,
schema 9 rebuilds every row's `search_text`, schema 10 stores graph pins per lens,
schema 11 adds `links.nature`, schema 12 adds entity photo galleries, schema 13
adds saved analysis views with their bounded-list count, and schema 14 indexes the
two columns the catalog orders the whole case by. Schema 15 adds the rebuildable
temporal projection, schema 16 extends saved analysis views to Timeline recipes
-and snapshots, and schema 17 rewrites temporal bounds to fixed microsecond width.
+and snapshots, schema 17 rewrites temporal bounds to fixed microsecond width, and
+schema 18 rebuilds the projection once more, now that a proof's stated date is
+projected beside the dates its files carry.
The schema counter is independent of the JSON `CASE_SCHEMA`: the
manifest's `azimut.storage` field selects the backend, and each format counts its own
shape upgrades.
diff --git a/docs/UI.md b/docs/UI.md
index 127f40e..4eb182c 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, Coords & Sky | **one map, many modes**: Compare, Imagery Wayback, Event layers, Ground Imagery, Measures, Viewshed, OSM Query, Map Board |
+| **Map** | Satellite, Compare, 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
@@ -45,6 +45,16 @@ worked in, and its whole subject is the case the sidebar would be listing again.
Two tabs, chosen by who is looking. **Overview** is for somebody who has been here
before; **Guide** is for somebody who has not.
+- **To-do** appears whenever a case is open, including an empty case. Each named
+ list has its own tab and completed/total count. The block occupies one grid
+ column, beside the start actions in an empty case, and stacks on narrow screens. Enter adds a task; click its
+ text to edit it, check it off, or delete it. The list menu renames or deletes
+ a list, with confirmation for a populated list. Changes save automatically.
+ Lists are case metadata in `case.json`, included in case bundles; they are not
+ graph entities and own no artifact files. Task and list deletions are permanent,
+ outside Trash. Concurrent edits from another browser tab require reloading the
+ lists before saving again.
+
- **With a case open, the page is a reading, laid out as a dashboard.** The case name
and when it was last touched, then a two-column grid: *what is waiting* and the
recent work on the left, the case's points and the case by family on the right. It
@@ -85,9 +95,10 @@ before; **Guide** is for somebody who has not.
- **The case by family is drawn in the Graph's own eight hues** (`--graph-<family>`),
each bar measured against the biggest family rather than against the total. One
reading of one case cannot be two palettes.
-- **It asks the case nothing new.** Five bounded reads against the open case only: the
+- **The dashboard reads only the open case.** Five bounded summary reads supply the
catalog summary, one timeline page, the newest rows, a count of the last seven days,
- and the compact saved index the Satellite panel already opens on. Nothing opens a
+ and the compact saved index the Satellite panel already opens on. A separate read
+ loads the case checklists. Nothing opens a
second case to count it, and the only thing that reaches the network is the map of
the case, fetching the imagery under its points.
- **Two notices, both of them answers the startup checks already gave.** A newer release
@@ -1172,6 +1183,144 @@ 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
+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. 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, separated by a rule. Left of it, how the
+pair is *read*: 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.
+Right of it, what gets *computed* over the pair: **Difference** and **Detect**.
+Keys 1–6 switch modes; 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.
+
+**Difference** checks that the sources can be compared before it runs.
+Colour, structure and brightness methods read captured pixels in a worker.
+Sentinel-2 also offers NDVI, NDWI, NBR and NDBI from the actual spectral bands.
+Index frames are fetched only by **Read this view**, one metered request per
+side; reopening a session or moving the camera does not fetch them. A changed
+view must be run again before export. Pixel methods refresh after movement when
+live updates are enabled; disabling them keeps the last mask anchored to the ground.
+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.
+**Clouds & shadows** sits beside it, one click, 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. It says which answer it is giving: Sentinel-2's own scene
+classification under a spectral index, and a guess from the picture — bright and
+colourless, or near-black — under the pixel methods. The Filters tab splits cloud
+from shadow and sets the mask margin, which grows the mask past the soft edge
+both tests leave behind.
+Detection, Display and Filters tabs separate the rest of the settings, with hover descriptions.
+The settings panel offers automatic/manual thresholds, tone matching, alignment,
+smoothing, cleanup, minimum area, class filters, palettes and heat/class/outline
+displays. Coverage, highlighted
+area and selectable change zones describe the result. These are candidate pixel
+changes for inspection, not confirmed changes to objects.
+
+**Detect** sweeps a drawn area at native resolution and keeps what it found, for
+Wayback and Copernicus Sentinel-2. 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, frames to fetch and roughly how long. 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 something this cannot read — 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. Four ship built in: large surface change, vessels on
+water, new structures or ground disturbance, and active fire or hotspot. The last
+two of those read Copernicus bands rather than the rendered picture — vessels from
+near-infrared contrast against the water around them, hotspots from the published
+short-wave infrared ratios — so they are Sentinel-2 only and fetch band frames
+beside the picture, all of them metered. The same **Clouds & shadows** switch sits
+under the analyzer, on for the methods that read Sentinel-2's classification and
+off for the ones that can only guess from the picture — a guess that cannot tell
+cloud from a white roof is never made on anyone's behalf. Methods whose subject
+is itself bright and colourless (smoke, bright shapes on water) or that already
+reject cloud by their band ratios (hotspots) offer no switch at all. Thresholds
+and the analyzer itself open from links rather than sitting in the way; any
+analyzer can be duplicated under a name of its own and is then 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, and nothing else reaches the case
+on its own. 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 and polygons can belong to A, B or both. Polygon drawing ends with a
+double-click or Enter; Escape cancels. Select a mark to move it or edit its style,
+double-click a note to edit its text, and use Undo/Redo for annotation changes.
+
+**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 and annotations; 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 shared Views destination; 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.
+
The search bar in the header proposes matches as you type, in the order they can
answer: the coordinates the text parses to, saved work in this case, cities from
a gazetteer shipped with the app (GeoNames, credited under the list), and last
@@ -1187,18 +1336,44 @@ Saved work — places, captures and screenshots filed by the extension — lives
one right-hand **Saved** panel, grouped by geography rather than by date. The
tree's depth follows the case: one country opens straight on its regions, a
worldwide case opens on continents. A filter and an
-`All / Places / Captures | Proofs` switch stay pinned above it; a screenshot
+`All / Places / Captures | Proofs · Media` switch stay pinned above it; a screenshot
counts as a capture. The first three positions filter, and `All` shows
everything: a proof usually stands on the capture it composes, so that capture
-wears a dot rather than carrying a second mark. **Proofs** past the rule is a
-mode — it swaps the panel to the proofs index (`GET /proofs/index`, read the first time
-that position is opened) and hides places and captures so the two never stack.
+wears a dot rather than carrying a second mark. The two past the rule are
+**modes** — each swaps the panel to its own index and hides the rest, so nothing
+stacks two marks on one spot. **Proofs** reads `GET /proofs/index`, and **Media**
+`GET /satellite/media`; both are read the first time that position is opened,
+never on case open. The panel opens on **Media**, which is what a map is read
+for: where the case's footage stands.
A proof is placed by the coordinates written in its own spec — the composer's
coordinate field first, then the point its panels gave it — and only failing
that by every capture it composes, which is why deleting a capture does not
unpin the proofs built on it. A proof is filed in My work like any other
artifact, so the folder grouping works there too; **Locate** does not appear,
since a proof states or borrows its point and the pass has nothing to look up.
+
+**Media** lists the case's located images and videos, one row per point. A file
+carries no coordinates of its own, so the position is read off the graph, by
+every road that states it: a `located-at` or `depicts` edge to a place, the point
+enrichment proposed from the file's own GPS, and the derivation chain, which puts
+a video where the proof that composed a frame of it stands. A file recorded on a
+roof and showing the street below is a row at each, and roads that agree on a
+point are one row that names them all (`Recorded here · Shows this place · Via
+Roofline`). A file nothing places is not listed, and neither is anything the case
+made out of its own material: a frame cut in Inspect, a capture or a rendered
+comparison stands where its source already stands, and the Media Library holds
+the same set back behind its own switch (`links.PRODUCED_HERE`). Locate has nothing to do here
+either, and the row's own actions are gone: a file is renamed, filed and deleted
+in Media.
+
+Pressing a media row, or its mark on the map, plays the file **in the panel, in
+place of the list**: the footage is read beside the imagery it is being matched
+against, and a window over the map would hide the half being compared. The marks
+stack like any other, so one press opens every file on that metre; `←`/`→` walk
+them, the count says where you are, and `Esc` brings the list back. A focused
+video keeps its own arrows for seeking. The card carries the file's name, its
+point, why it stands there, and the ways out: **Open in Media**, and one button
+per proof built on it. The mark being read stays lit on the map.
Items with
no country collect under **Unlocated**, where **Locate** looks them up a batch at
a time and can be stopped mid-pass. Its left edge resizes from 260 to 560 px,
@@ -1305,9 +1480,10 @@ squares instead of hiding the detections or asking NASA for invented detail.
**The reference layers** are key-less and each is simply on or off: Esri's
borders (country, region, district, with names) and roads, Open Infrastructure
Map's power lines, OpenSeaMap's buoys and harbours, and the raw GPS traces people
-uploaded to OSM, which show tracks nobody has mapped yet. None of them fetches a
-tile before its switch is pressed, and the roads follow the labels' rule: over a
-street map they are greyed, since it already draws them. Power lines are drawn
+uploaded to OSM, which show tracks nobody has mapped yet. Borders start on —
+reading imagery starts with which side of a line the ground is on — and none of
+the others fetches a tile before its switch is pressed. The roads follow the
+labels' rule: over a street map they are greyed, since it already draws them. Power lines are drawn
from vector tiles in the app's own small style, coloured by voltage on Open
Infrastructure Map's scale, dashed where the line is buried, with towers from
zoom 14, substations, plants, pipelines and telecom masts. No overlay reaches a
@@ -1340,14 +1516,18 @@ leaves the path alone. Coords & Sky opens the same mode with its own point, date
and time, and hands over no computed value.
The saved-work layer answers two questions under its own switch: **what kind**
-(all, places, captures, proofs) and **which folder**, offered only where the
+(all, places, captures, proofs, media) and **which folder**, offered only where the
case has more than one to choose between. They are the Saved panel's own
filter, so a map read here and the panel beside it can never disagree about
what the case holds, and the layer's count is what is drawn rather than what is
-filed. It is off by default and session-only: places draw as outlined
-pins, captures and screenshots as filled ones, items at the same spot collapse
-into one counted mark, and clicking any mark opens a card
-with its preview, provider, dates and note. A mark whose capture carries proofs
+filed. It is on from the start, on the Media
+position, and session-only: the tool stays mounted across tabs, so a switch
+pressed off stays off until the app reloads and nothing is written to the case.
+Places draw as outlined pins, captures and screenshots as filled ones, located
+files as white-ringed ones, items at the same spot collapse
+into one counted mark, and clicking a mark of saved work opens a card
+with its preview, provider, dates and note. A mark of files has no card: it plays
+them in the panel. A mark whose capture carries proofs
wears a dot up-left; its card names the count and offers **Show proofs**, which
switches the panel and the layer to the proofs view. In that view the card opens
the proof in Geo Proof and lists the saved posts written from it. Two post titles
@@ -1444,7 +1624,7 @@ link already on is dropped when the last of them goes. Pressing it hands the
other linked tabs this tab's view, and from then on a pan or a zoom in any of
them carries the rest. It is per tab and off by default: two maps are worth linking while they
are being compared and in the way of each other the rest of the time. Two
-linked tabs on two providers are a first version of Compare — and the camera
+linked tabs on two providers complement Compare on a second screen — and the camera
travels between tabs of the same browser, never over the network, because a
view is not case state. The extension's map tools join the same link from
Google, Bing, Earth and the other sites they draw on: an open panel counts as a
@@ -1471,7 +1651,7 @@ coming back hands the chord back to the system clipboard. It lands in the `Overl
sits above the panels and the legend, and is moved,
resized from its corners and framed like anything else on the canvas — you can
annotate it too. It claims no source: no media is filed, no entity, no
-`derived-from` edge. The file lives in `proofs/<name>.assets/` under its own
+`derived-from` edge. The file lives in `proofs/.meta/<name>.assets/` under its own
content hash, travels with a rename, and goes when the proof does. A proof needs
a panel first, since the panels are what give the document its size — moving an
overlay never resizes the export.
@@ -1487,6 +1667,12 @@ first row is the proof's point**: the map mark, the coordinate a post cites, the
one the export prints. An arrow moves a row up to make it the conclusion; the
marker never reorders anything, or ticking it would take a coordinate out of a
tweet without saying so. A single-point proof is the field it has always been.
+**A panel that carries a place adds it**, under the point already on screen rather
+than in place of it — two captures of one point stay one point, and the answer the
+panels gave is written down before the new one joins it. **The pin beside a row
+opens it on the map**: the basemaps and the reference layers of the Map tool, the
+mark on what the row says, and a click to move it. A row added with `+` opens on
+the point above it, which is the only thing that says which ground it belongs on.
The exported picture prints them only when asked (Advanced → Show coordinates):
unnamed points share one line, a named one takes its own, and the plate grows by
what it prints. **Show text** switches the credit line off beside it, so a plate
@@ -1515,6 +1701,39 @@ already in the case by construction.
Wherever a source is *read* rather than edited — the post it is handed to, the Markdown
report — it is one address per line, and a report renders one link each.
+**Description and date** sit under the source, both marked *optional* and neither
+printed on the plate. Everything above them carries a `!` when it is empty, so a
+panel of blanks otherwise reads as a form to finish.
+
+The **description** is one sentence about what the proof shows. It is the proof's
+notes — the graph shows it and case search finds it — and it is what a post is written
+from, in place of the filename a title usually is. Editing it from the Details panel
+and reopening the proof shows the edit, not the copy the file was written with.
+
+The **date** is when the material was taken, in the same profile a Claim's *When*
+uses — a day, a month, a year, a timestamp or a range, with `~` for approximate and
+`?` for uncertain — edited in the same editor, folded to fit the column.
+
+**Nothing ever fills it in**, unlike the coordinates and the sources beside it. The
+date a file carries is when it was uploaded, or what a camera clock said; neither is
+when the thing happened, and a date offered is a date accepted without being read. So
+it is typed on purpose or it stays unknown, and the bin beside it empties it back to
+unknown. Nothing marks it missing either: plenty of material carries no date anyone
+can defend. A dated proof is what the Timeline shows under **Taken**, beside the dates
+the files themselves carry.
+
+**A date states itself for the footage, not only for the proof.** Saving says so — *Dated
+the material: clip.mp4* — and the video's own Time tab then shows it above the dates read
+out of the file, which it never overwrites. The frame is not dated, the video it was cut
+from is; a satellite capture never is. Changing the date restates it, clearing it takes it
+back, and a statement someone has since added reasoning to is left alone.
+
+**The toolbar is two columns.** In one it stood taller than a laptop window, and the
+colour, width and layout controls sat under the fold behind a scrollbar nobody looks
+for. The separators still mark the groups: history, the drawing tools, then fit and
+layout together. The controls that come and go with a selection are last, so picking a
+shape never reshuffles the buttons above them.
+
**Frames.** Any panel or overlay takes a coloured border, its own colour and
thickness, drawn inset so the layout does not shift. A frame is decoration: it
stays out of the legend, which is still built from annotation colours alone.
diff --git a/extension/README.md b/extension/README.md
index 1a60ff4..c99cee8 100644
--- a/extension/README.md
+++ b/extension/README.md
@@ -157,11 +157,13 @@ over a map must never end up inside the evidence.
and ordered by the app rather than by this tab: what crosses is one page of a case,
never the case. A video plays in the window, with its own controls.
-Two limits worth knowing. A file has to be **under 48 MB** to be handed over, which
-is the same ceiling a published thread's attachments answer to. And a video is the
-one thing here a site can refuse: an image is decoded and painted on a canvas,
-which asks the page's content policy nothing, while a video needs a URL and some
-sites will not load one. When that happens the window says so.
+Two limits worth knowing. A reference has to be **under 512 MB**, and it crosses in
+pieces, so a long clip opens the way it does in the app's own Satellite tab — the
+window counts up while it arrives. A published thread's attachments answer to a
+lower ceiling, **48 MB**, since those are pushed into the composer's page whole.
+And a video is the one thing here a site can refuse: an image is decoded and
+painted on a canvas, which asks the page's content policy nothing, while a video
+needs a URL and some sites will not load one. When that happens the window says so.
Reference windows work where the geometric tools do not — Street View, a pitched
camera, a globe — since nothing about holding a reference up needs the ground to
diff --git a/extension/background.js b/extension/background.js
index de7171b..49c39b8 100644
--- a/extension/background.js
+++ b/extension/background.js
@@ -104,6 +104,16 @@ async function ingest(blob, meta) {
// would be two answers to one question, and the pair that disagrees is the one
// nobody can find.
+/** What a thread's attachment may weigh.
+ *
+ * Lower than the app's own ceiling, and the one place in this file that keeps a
+ * size of its own rather than repeating the app's. It is a different limit, not
+ * a second copy: a composer's files are *pushed* into the page whole, as one
+ * injected payload, so the base64 is held on both sides at once. A reference
+ * window pulls its file a chunk at a time and answers to the app's number
+ * alone. */
+const MAX_COMPOSER_BYTES = 48 * 1024 * 1024;
+
/** One handed-over file, fetched from the app and carried as base64: what
* crosses into the page is a string, and the page turns it back into a file.
* Base64 rather than a `data:` URL because the page rebuilds it with `atob` —
@@ -115,6 +125,7 @@ async function fetchAttachment(backendUrl, token, caseId, path) {
// in the case, and attaching it by hand is what the analyst did before.
if (!r.ok) return null;
const blob = await r.blob();
+ if (blob.size > MAX_COMPOSER_BYTES) return null;
return {
name: path.split("/").pop(),
type: blob.type || "application/octet-stream",
@@ -133,7 +144,11 @@ function fileUrl(backendUrl, caseId, path) {
/** A blob as base64. What crosses into a page is a string: a message carries no
* blob, and both sides rebuild the file from this. */
async function base64(blob) {
- const bytes = new Uint8Array(await blob.arrayBuffer());
+ return encode(new Uint8Array(await blob.arrayBuffer()));
+}
+
+/** The same, for bytes already in hand. */
+function encode(bytes) {
let binary = "";
const CHUNK = 0x8000; // fromCharCode takes an argument list: chunk it or blow the stack
for (let i = 0; i < bytes.length; i += CHUNK) {
@@ -517,27 +532,65 @@ async function mapImage(msg) {
return `data:${blob.type || "image/png"};base64,${await base64(blob)}`;
}
+/** How much of a file crosses in one message.
+ *
+ * The whole point of the number: base64 of *this* is the biggest string either
+ * side ever holds, whatever the file weighs. A phone's clip of a street is
+ * hundreds of megabytes and the window that holds it up against the imagery is
+ * the reason the panel is open, so the file cannot be the unit. */
+const FILE_CHUNK_BYTES = 4 * 1024 * 1024;
+
+/** The end and the total of a `Content-Range`, or null when the app answered with
+ * the whole file — an unranged 200, which is what a small file gets. */
+function ranged(header) {
+ const m = /^bytes (\d+)-(\d+)\/(\d+)$/.exec(String(header || ""));
+ return m ? { end: Number(m[2]), total: Number(m[3]) } : null;
+}
+
/**
- * One of the case's files, for a reference window (`extension/mapref.js`).
+ * One slice of one of the case's files, for a reference window (`mapref.js`).
*
* Not `mapApi`: that one parses what comes back as JSON, and this is bytes. The
* route is written in rather than allowlisted — the panel may ask for a file
* from the case it has open and for nothing else, and the app's own fence
* (`api/ingest.py`, ``handoff_file``) is what says which files those are.
+ *
+ * It answers a slice rather than a file because the panel is often holding a
+ * video up, and a video is not 48 MB. `Range` is what `FileResponse` already
+ * serves, so nothing over there had to be built for this: the page asks again
+ * from `next` until `next` is null and glues the pieces into one blob. A slice
+ * short of the chunk size is not the signal — a file whose length divides evenly
+ * would end on a 416 — so the total in `Content-Range` is.
*/
-async function mapFile(caseId, path) {
+async function mapFile(caseId, path, offset = 0) {
const { backendUrl, token } = await settings();
if (!token) throw new Error("not paired. Open the extension options and paste the token from Azimut Settings");
if (!caseId) throw new Error("no case open");
+ const start = Number(offset) || 0;
let r;
try {
- r = await fetch(fileUrl(backendUrl, caseId, path), { headers: { "X-Azimut-Token": token } });
+ r = await fetch(fileUrl(backendUrl, caseId, path), {
+ headers: {
+ "X-Azimut-Token": token,
+ Range: `bytes=${start}-${start + FILE_CHUNK_BYTES - 1}`,
+ },
+ });
} catch {
throw new Error("Azimut is not answering. Is the app running?");
}
if (!r.ok) throw new Error(await refusal(r));
const blob = await r.blob();
- return { type: blob.type || "application/octet-stream", data: await base64(blob) };
+ const bytes = new Uint8Array(await blob.arrayBuffer());
+ const read = start + bytes.length;
+ // No `Content-Range` means the app ignored the ask and sent everything, which
+ // is a whole file in one message rather than a broken one.
+ const total = ranged(r.headers?.get?.("Content-Range"))?.total ?? read;
+ return {
+ type: blob.type || "application/octet-stream",
+ data: encode(bytes),
+ next: read < total ? read : null,
+ total,
+ };
}
/** Why the app would not hand a file over, in its own words where it gave any —
@@ -1106,10 +1159,11 @@ async function handle(msg, sender) {
}
}
- // The panel, asking for one of the case's files — bytes rather than JSON.
+ // The panel, asking for a slice of one of the case's files — bytes rather than
+ // JSON, and one chunk per message so a long video is not one huge string.
if (msg.type === "map-file") {
try {
- return { ok: true, file: await mapFile(msg.caseId, msg.path) };
+ return { ok: true, file: await mapFile(msg.caseId, msg.path, msg.offset) };
} catch (e) {
return { ok: false, error: e.message };
}
diff --git a/extension/mapoverlay.js b/extension/mapoverlay.js
index f14b5ae..6595f83 100644
--- a/extension/mapoverlay.js
+++ b/extension/mapoverlay.js
@@ -115,14 +115,37 @@
* worker boundary as base64, since a message carries strings and never a
* blob, and is rebuilt into one here. What `mapref.js` then does with it —
* decode an image, or hand a video an object URL — is its business.
+ *
+ * It is asked for in pieces (`background.js`, `mapFile`), which is what lets a
+ * reference be a long video rather than a small one. Each piece becomes a blob
+ * of its own straight away: a blob is the browser's to hold and it may keep it
+ * on disk, while an array of half a gigabyte of `Uint8Array` is this tab's
+ * heap. `onprogress` is optional — a thumbnail arrives in one piece and has
+ * nothing to report.
*/
- async function fetchFile(path) {
- const answer = await api.runtime.sendMessage({ type: "map-file", caseId: state.caseId, path });
- if (!answer?.ok) throw new Error(answer?.error || "the app did not answer");
- const binary = atob(answer.file.data);
- const bytes = new Uint8Array(binary.length);
- for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i);
- return new Blob([bytes], { type: answer.file.type });
+ async function fetchFile(path, onprogress) {
+ const parts = [];
+ let type = "application/octet-stream";
+ let offset = 0;
+ for (;;) {
+ const answer = await api.runtime.sendMessage({
+ type: "map-file",
+ caseId: state.caseId,
+ path,
+ offset,
+ });
+ if (!answer?.ok) throw new Error(answer?.error || "the app did not answer");
+ const { file } = answer;
+ const binary = atob(file.data || "");
+ const bytes = new Uint8Array(binary.length);
+ for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i);
+ parts.push(new Blob([bytes]));
+ if (file.type) type = file.type;
+ offset = file.next ?? file.total ?? offset + bytes.length;
+ onprogress?.(offset, file.total ?? offset);
+ if (file.next === null || file.next === undefined) break;
+ }
+ return new Blob(parts, { type });
}
// --- the state the whole panel reads ---------------------------------------
@@ -2184,11 +2207,18 @@
paint();
}
- /** Google Earth is the site the tools keep up with worst: its camera and its
- * 3D globe drift from what the URL says, so the panel owns up to it. */
+ /** The tools that put a shape on the ground, which is the half of the panel
+ * still settling: each one works from what a site writes about its own camera,
+ * and every site writes it differently. Reference windows and the sky are not
+ * in here — neither measures anything. */
+ const BETA_TOOLS = new Set(["measure", "pins", "grid", "fires"]);
+
+ /** Owning up, on whichever map. It used to name Google Earth, where the drift
+ * is worst, but the caveat was never really about that site: it is about what
+ * these four draw, so it now follows the tool rather than the map. */
function betaBadge() {
- if (state.parsed?.site !== "google-earth") return "";
- return ` <span class="beta" title="Drawings drift more on Google Earth than on other maps">Beta</span>`;
+ if (!BETA_TOOLS.has(state.tool)) return "";
+ return ` <span class="beta" title="Still settling: check what this tool draws against the map">Beta</span>`;
}
/** The status line when geometry is on: where, what it is drawing in, and
diff --git a/extension/mapref.js b/extension/mapref.js
index 74fe954..071a1ea 100644
--- a/extension/mapref.js
+++ b/extension/mapref.js
@@ -161,7 +161,8 @@
* @param {object} deps
* @param {ShadowRoot} deps.root where the panel already lives
* @param {object} deps.refs the tool holding which windows are open (maptools)
- * @param {(path: string) => Promise<Blob>} deps.file one case file's bytes
+ * @param {(path: string, onprogress?: (done: number, total: number) => void)
+ * => Promise<Blob>} deps.file one case file's bytes, reported as they land
* @param {(params: object) => Promise<object>} deps.search what the case offers
* @param {() => void} deps.onchange the open list moved; the panel re-reads it
* @param {(message: string) => void} deps.onnote something to say in the panel
@@ -218,13 +219,26 @@
};
wire(pane);
- file(viewer.path).then(
+ file(viewer.path, (done, total) => waiting(pane, done, total)).then(
(blob) => (moving ? play(pane, blob) : show(pane, blob)),
(e) => refuse(pane, e.message)
);
return pane;
}
+ /**
+ * How far along the file is, while it is still coming.
+ *
+ * Only ever seen on a file worth waiting for: one that arrives in a single
+ * piece reports `done === total` and is left alone, so a photo never
+ * flickers a percentage on its way in. A long video otherwise sits on
+ * "Loading…" for a minute with nothing to say whether it is moving.
+ */
+ function waiting(pane, done, total) {
+ if (!pane.wait.isConnected || !total || done >= total) return;
+ pane.wait.textContent = `Loading… ${Math.floor((done / total) * 100)}%`;
+ }
+
/** An image: decoded once, then painted at whatever zoom the window holds. */
async function show(pane, blob) {
try {
diff --git a/frontend/e2e/app.fixture.js b/frontend/e2e/app.fixture.js
index b520231..0c44d7b 100644
--- a/frontend/e2e/app.fixture.js
+++ b/frontend/e2e/app.fixture.js
@@ -21,6 +21,14 @@ const TILE_PNG = Buffer.from(
'base64'
);
+// A reference overlay is transparent but for the lines it draws. The fixture
+// answers with nothing drawn at all, so a layer that is on never paints over
+// what a spec is looking at underneath it.
+const CLEAR_TILE_PNG = Buffer.from(
+ 'iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAEklEQVR4nGNgGAWjYBSMAggAAAQQAAFVN1rQAAAAAElFTkSuQmCC',
+ 'base64'
+);
+
const media = [{
path: PANEL_PATH,
filename: 'panel.svg',
@@ -679,17 +687,21 @@ function fixtureTemporalReading(raw) {
export async function installAppFixture(page, options = {}) {
const unexpected = [];
const labelTiles = [];
+ const referenceTiles = [];
const captures = [];
const placeWrites = [];
const proofSaves = [];
const fixtureSavedIndex = options.savedIndex ?? savedIndex;
const fixtureProofIndex = options.proofIndex ?? [];
+ // Located files as the Media position reads them (GET /satellite/media).
+ const fixtureMediaIndex = options.mediaIndex ?? [];
const fixtureMedia = (options.media ?? media).map((item) => ({ ...item }));
const fixtureCases = options.cases ?? [caseOverview];
const fixtureProviders = options.widget ? [...providers, WIDGET_PROVIDER] : providers;
const widgetLoads = [];
const fixtureSavedIndexes = options.savedIndexes ?? { [CASE_ID]: fixtureSavedIndex };
const fixtureProofIndexes = options.proofIndexes ?? { [CASE_ID]: fixtureProofIndex };
+ const fixtureMediaIndexes = options.mediaIndexes ?? { [CASE_ID]: fixtureMediaIndex };
const savedIndexDelays = options.savedIndexDelays ?? {};
const proofIndexDelays = options.proofIndexDelays ?? {};
const caseDelays = options.caseDelays ?? {};
@@ -944,6 +956,14 @@ export async function installAppFixture(page, options = {}) {
return route.fulfill({ contentType: 'image/png', body: TILE_PNG });
}
+ // Esri's reference layers are drawn straight from their host too, and
+ // Borders is the one layer the map opens with — so every map spec asks for
+ // these. Answered here, so no run touches the network to draw a border.
+ if (url.hostname === 'services.arcgisonline.com') {
+ referenceTiles.push(request.url());
+ return route.fulfill({ contentType: 'image/png', body: CLEAR_TILE_PNG });
+ }
+
if (url.hostname !== '127.0.0.1') {
unexpected.push(`${request.method()} ${request.url()}`);
return route.abort('blockedbyclient');
@@ -1311,6 +1331,9 @@ export async function installAppFixture(page, options = {}) {
}
return json(route, fixtureSavedIndexes[caseId] ?? []);
}
+ if (caseId && path === `/api/cases/${caseId}/satellite/media`) {
+ return json(route, fixtureMediaIndexes[caseId] ?? []);
+ }
if (caseId && path === `/api/cases/${caseId}/proofs/index`) {
if (proofIndexDelays[caseId]) {
await new Promise((resolve) => setTimeout(resolve, proofIndexDelays[caseId]));
@@ -1944,6 +1967,7 @@ export async function installAppFixture(page, options = {}) {
captures,
placeWrites,
labelTiles,
+ referenceTiles,
widgetLoads,
gridWrites,
skyQueries,
@@ -1979,14 +2003,29 @@ export async function installAppFixture(page, options = {}) {
};
}
+/**
+ * Put the Saved panel, and the layer drawing from it, on one position.
+ *
+ * The panel opens on **Media**, so a spec about places, captures or proofs asks
+ * for its own position rather than assuming the one it used to open on.
+ */
+export async function showSaved(page, kind = 'All') {
+ await page
+ .getByRole('group', { name: 'What this panel lists' })
+ .getByRole('button', { name: kind, exact: true })
+ .click();
+}
+
/**
* Wait for the map to be up.
*
* The signal is `lib/map`'s own ready flag, not a class the engine happens to
* put on its container: a suite that recognises the engine is a suite pinned to
* it, and swapping the engine (SPEC v3) would then rewrite every map spec.
+ *
+ * `maps` is how many the screen puts up — two, on Compare's linked pair.
*/
-export async function awaitMapReady(page) {
+export async function awaitMapReady(page, maps = 1) {
// The runner's Firefox has no WebGL and cannot be given any: it asks for a
// native driver, a box with no GPU has none, and the software path a patched
// build would take is not there — `tryNativeGL()`, then `EXHAUSTED_DRIVERS`,
@@ -2002,7 +2041,9 @@ export async function awaitMapReady(page) {
!!process.env.CI && test.info().project.name === 'firefox',
'the runner\'s Firefox has no WebGL; Chromium answers for the map there'
);
- await expect(page.locator('.map[data-map-ready="true"]')).toBeVisible();
+ const ready = page.locator('.map[data-map-ready="true"]');
+ await expect(ready).toHaveCount(maps);
+ await expect(ready.first()).toBeVisible();
}
/**
diff --git a/frontend/e2e/compare.spec.js b/frontend/e2e/compare.spec.js
new file mode 100644
index 0000000..eb1d3a1
--- /dev/null
+++ b/frontend/e2e/compare.spec.js
@@ -0,0 +1,226 @@
+import { test, expect } from '@playwright/test';
+import { awaitMapReady, installAppFixture } from './app.fixture.js';
+
+async function openCompare(page, providerB = 'Esri World Imagery') {
+ const fixture = await installAppFixture(page);
+ const errors = [];
+ const saved = [];
+ 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' },
+ ] }));
+ await page.route('**/api/satellite/wayback/releases', (route) => route.fulfill({ json: { releases: [{ release: 2, date: '2021-01-01' }, { release: 1, date: '2020-01-01' }] } }));
+ page.on('pageerror', (error) => errors.push(error.message));
+ await page.route('**/api/cases/*/compare/sessions', async (route) => {
+ if (route.request().method() === 'POST') {
+ saved.push(route.request().postDataJSON());
+ await route.fulfill({ json: { name: 'Comparison', title: 'Comparison' } });
+ } else await route.fulfill({ json: [] });
+ });
+ await page.route('**/compare/sessions/*/preview', (route) => route.fulfill({ json: { path: 'media/Comparison.png' } }));
+ await page.goto('/#compare');
+ 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();
+ await page.locator('.provider-card').filter({ hasText: letter === 'A' ? 'Esri World Imagery' : providerB }).click();
+ }
+ await awaitMapReady(page, 2);
+ return { fixture, errors, saved };
+}
+
+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 });
+ const box = await canvas.boundingBox();
+ await page.getByTitle('Arrow (A)', { exact: true }).click();
+ await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2);
+ await page.mouse.down();
+ await page.mouse.move(box.x + box.width / 2 + 60, box.y + box.height / 2 + 40, { steps: 5 });
+ await page.mouse.up();
+ await expect(page.locator('.annotation-canvas .mark')).toHaveCount(2);
+ const before = await canvas.locator('path').getAttribute('d');
+ await page.mouse.move(box.x + 100, box.y + 100);
+ await page.mouse.down();
+ await page.mouse.move(box.x + 180, box.y + 140, { steps: 8 });
+ await page.mouse.up();
+ await expect(canvas.locator('path')).not.toHaveAttribute('d', before);
+ await expect.poll(async () => {
+ const paths = await page.locator('.annotation-canvas .mark path').evaluateAll((nodes) => nodes.map((node) => node.getAttribute('d')));
+ const numbers = paths.map((path) => path.match(/-?\d+(?:\.\d+)?/g).map(Number));
+ return Math.max(...numbers[0].map((n, i) => Math.abs(n - numbers[1][i])));
+ }).toBeLessThan(1);
+ await page.getByRole('button', { name: 'Swipe', exact: true }).click();
+ await expect(page.getByRole('slider', { name: 'Swipe divider on imagery' })).toBeVisible();
+ await page.getByRole('button', { name: 'Fade', exact: true }).click();
+ await expect(page.getByRole('slider', { name: 'B opacity' })).toBeVisible();
+ await page.getByRole('button', { name: 'Blink', exact: true }).click();
+ await page.getByRole('button', { name: 'Slow', exact: true }).click();
+ await page.getByRole('button', { name: 'Save comparison', exact: true }).click();
+ await page.getByRole('dialog').getByRole('button', { name: 'Save comparison', exact: true }).click();
+ await expect.poll(() => saved.length).toBe(1);
+ expect(saved[0].spec.version).toBe(2);
+ expect(saved[0].spec.blink.interval).toBe(1600);
+ expect(saved[0].spec.annotations[0].points[0][0]).toBeCloseTo(2.2945, 2);
+ expect(saved[0].spec.annotations[0].points[0][1]).toBeCloseTo(48.8584, 2);
+ await expect(page.getByText('Comparison and animated preview saved to My work', { exact: true })).toBeVisible();
+ await page.screenshot({ path: test.info().outputPath('compare.png') });
+ expect(errors).toEqual([]);
+});
+
+test('spectral frames are requested only by Run, including after reopening and moving', async ({ page }) => {
+ await installAppFixture(page);
+ const errors = [];
+ const requests = [];
+ page.on('pageerror', (error) => errors.push(error.message));
+ await page.route('**/api/satellite/providers', (route) => route.fulfill({ json: [
+ { id: 'sentinel2', label: 'Sentinel-2', url: 'https://tiles.invalid/{z}/{x}/{y}.png',
+ imagery: true, max_zoom: 19, tile_size: 256, oversample: 1, attribution: 'Browser fixture' },
+ ] }));
+ await page.route('**/api/satellite/sentinel/**', (route) => route.fulfill({ json:
+ route.request().url().includes('/layers') ? { layers: [{ id: 'TRUE_COLOR', title: 'True colour' }] } : { days: [] },
+ }));
+ const side = (day) => ({ present: true, provider: 'sentinel2', overlays: [],
+ sentinel: { layer: 'TRUE_COLOR', date: day, maxcc: 100 } });
+ await page.route('**/api/cases/*/compare/sessions', (route) => route.fulfill({ json: [{ name: 'Spectral', title: 'Spectral', mode: 'change' }] }));
+ await page.route('**/api/cases/*/compare/sessions/Spectral', (route) => route.fulfill({ json: {
+ title: 'Spectral', spec: { version: 2, camera: { lat: 48.8584, lon: 2.2945, zoom: 16, bearing: 35 },
+ mode: 'change', change_assist: { method: 'index' }, a: side('2026-08-01'), b: side('2026-09-01') },
+ } }));
+ await page.route('**/api/compare/sentinel-index', async (route) => {
+ const body = route.request().postDataJSON();
+ requests.push(body);
+ const png = await page.evaluate(({ width, height }) => {
+ const canvas = document.createElement('canvas');
+ canvas.width = width; canvas.height = height;
+ const ctx = canvas.getContext('2d');
+ ctx.fillStyle = 'rgb(128,4,0)';
+ ctx.fillRect(0, 0, width, height);
+ return canvas.toDataURL().split(',')[1];
+ }, body);
+ await route.fulfill({ contentType: 'image/png', body: Buffer.from(png, 'base64') });
+ });
+ await page.goto('/#compare');
+ await page.getByRole('button', { name: 'Open', exact: true }).click();
+ await page.locator('.session-open').click();
+ await awaitMapReady(page, 2);
+ // Reopening in Difference mode brings its column 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 expect(page.getByLabel('Method', { exact: true })).toHaveValue('index');
+ expect(requests).toHaveLength(0);
+ await page.getByRole('button', { name: 'Read this view', exact: true }).click();
+ await expect(page.locator('.secondary .change-map')).toBeVisible({ timeout: 20000 });
+ 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();
+ await expect(page.locator('.secondary .change-map')).not.toHaveCSS('transform', 'none');
+ await expect(page.getByLabel('Difference', { exact: true })).toContainText('Run again to match it');
+ await expect(page.getByRole('button', { name: 'Read this view', exact: true })).toBeEnabled();
+ expect(requests).toHaveLength(2);
+ expect(errors).toEqual([]);
+});
+
+test('changes run in the worker and export a composed PNG', async ({ page }) => {
+ const { errors } = await openCompare(page, 'Esri Wayback');
+ 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: 'Difference', exact: true }).click();
+ await expect(page.locator('.secondary .change-map')).toBeVisible({ timeout: 20000 });
+ await expect(page.getByLabel('Difference', { exact: true })).toContainText('highlighted');
+ await page.getByLabel('Method', { exact: true }).selectOption('structure');
+ await expect(page.getByLabel('Difference', { exact: true })).toContainText('coverage');
+ 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);
+ expect(Buffer.from(exports[0].png, 'base64').subarray(1, 4).toString()).toBe('PNG');
+ 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 recipe = { id: 'large-change', name: 'Large surface change', description: 'Pixel changes to review',
+ phenomenon: 'Surface change', method: 'colour', providers: ['esri-wayback', 'sentinel2'], zones: [],
+ colour: '#f6a81a', style: 'both', parameters: { sensitivity: 55, min_area: 20, min_score: 0,
+ cleanup: 1, smoothing: 0, normalize: false, index: 'ndvi', direction: 'both',
+ ignore_clouds: true, ignore_shadows: true, merge_metres: 0 } };
+ await page.route('**/api/compare/analyzers', (route) => route.fulfill({ json: {
+ builtins: [recipe], custom: [], max_tiles: 256, max_results: 2000,
+ methods: [{ id: 'colour', label: 'Colour', single: false, sentinel_only: false, classes: false }],
+ grids: { sentinel2: [13, 512], 'esri-wayback': [19, 256] },
+ } }));
+ 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, signal_score: 0.8, confidence: null,
+ 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: 1, 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();
+ 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('tiles of 256px');
+ await page.getByRole('button', { name: 'Change imagery, dates or the rule…' }).click();
+ await page.getByLabel('Release A', { exact: true }).selectOption('1');
+ await page.getByLabel('Release B', { exact: true }).selectOption('2');
+ await page.getByLabel('Analysis name', { exact: true }).fill('Harbour sweep');
+ expect(requests).toHaveLength(0);
+ await page.getByRole('button', { name: 'Run on 1 area', exact: true }).click();
+ await expect(page.getByText('Signal score 80% · not a calibrated confidence', { 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('Signal score 80% · not a calibrated confidence', { exact: true })).toBeVisible();
+ expect(requests).toHaveLength(1);
+ await page.screenshot({ path: test.info().outputPath('analyzers.png') });
+ expect(errors).toEqual([]);
+});
diff --git a/frontend/e2e/place-precision.spec.js b/frontend/e2e/place-precision.spec.js
index f357db2..46e68a3 100644
--- a/frontend/e2e/place-precision.spec.js
+++ b/frontend/e2e/place-precision.spec.js
@@ -1,5 +1,5 @@
import { test, expect } from '@playwright/test';
-import { awaitMapReady, installAppFixture } from './app.fixture.js';
+import { awaitMapReady, installAppFixture, showSaved } from './app.fixture.js';
/**
* How tightly a place is pinned, driven in a real browser.
@@ -55,7 +55,7 @@ async function openCard(page) {
});
await page.goto('/#satellite');
await awaitMapReady(page);
- await page.getByRole('button', { name: 'Saved work' }).click();
+ await showSaved(page); // the layer is on, on the Media position
await page.locator('.saved-mark').click();
return fixture;
}
diff --git a/frontend/e2e/proof-canvas.spec.js b/frontend/e2e/proof-canvas.spec.js
index 2acb650..74a34ee 100644
--- a/frontend/e2e/proof-canvas.spec.js
+++ b/frontend/e2e/proof-canvas.spec.js
@@ -8,10 +8,13 @@ test('a real Konva panel remains interactive after click and drag', async ({ pag
const canvas = page.locator('.konva canvas').first();
const box = await canvas.boundingBox();
expect(box).not.toBeNull();
- // The stage fills the full tool height while the fitted 16:9 panel sits near
- // its top. Use a point well inside that image, away from its footer.
+ // The stage centres the fitted panel in whatever room the toolbar leaves it,
+ // so its own middle is the one point that stays well inside the image however
+ // wide the rail gets. Off the page a drag pans the view instead of drawing
+ // (ProofComposer.onPointerDown), which is what a gesture anchored near the
+ // panel's edge turns into the day the canvas loses a few pixels.
const x = box.x + box.width / 2;
- const y = box.y + Math.min(180, box.height / 3);
+ const y = box.y + box.height / 2;
await page.mouse.click(x, y);
await expect(page.locator('.panel-row')).toHaveClass(/selected/);
@@ -400,7 +403,7 @@ test('a stroke started inside a shape draws, and leaves that shape where it was'
const canvas = page.locator('.konva canvas').first();
const box = await canvas.boundingBox();
const cx = box.x + box.width / 2;
- const cy = box.y + Math.min(180, box.height / 3);
+ const cy = box.y + box.height / 2;
// A box wide enough that the next gesture starts well inside it.
await page.getByTitle('Box (r)').click();
@@ -438,7 +441,7 @@ test('a fill is opt-in, rides the shape colour and survives the save', async ({
const canvas = page.locator('.konva canvas').first();
const box = await canvas.boundingBox();
const cx = box.x + box.width / 2;
- const cy = box.y + Math.min(180, box.height / 3);
+ const cy = box.y + box.height / 2;
await page.getByTitle('Box (r)').click();
@@ -488,7 +491,7 @@ async function drawTwoBoxes(page) {
const canvas = page.locator('.konva canvas').first();
const box = await canvas.boundingBox();
const cx = box.x + box.width / 2;
- const cy = box.y + Math.min(180, box.height / 3);
+ const cy = box.y + box.height / 2;
await page.getByTitle('Box (r)').click();
await page.mouse.move(cx - 80, cy - 40);
@@ -627,7 +630,7 @@ test('stamps a symbol, keeps the tool in hand, and saves it', async ({ page }) =
const canvas = page.locator('.konva canvas').first();
const box = await canvas.boundingBox();
const cx = box.x + box.width / 2;
- const cy = box.y + Math.min(180, box.height / 3);
+ const cy = box.y + box.height / 2;
await page.getByTitle('Symbol (s)').click();
await page.getByRole('button', { name: 'Tank', exact: true }).click();
@@ -716,7 +719,7 @@ test('a stroke let go off the canvas lands, and stops following the pointer', as
const box = await canvas.boundingBox();
const side = await page.locator('aside.side').boundingBox();
const x = box.x + box.width / 2 - 40;
- const y = box.y + Math.min(180, box.height / 3);
+ const y = box.y + box.height / 2;
await page.getByTitle('Box (r)').click();
await page.mouse.move(x, y);
@@ -754,7 +757,7 @@ test('a marquee let go off the canvas selects what it caught and leaves nothing
const box = await canvas.boundingBox();
const side = await page.locator('aside.side').boundingBox();
const cx = box.x + box.width / 2;
- const cy = box.y + Math.min(180, box.height / 3);
+ const cy = box.y + box.height / 2;
await page.getByTitle('Box (r)').click();
await page.mouse.move(cx - 30, cy - 20);
@@ -799,7 +802,7 @@ test('a pan let go off the canvas stops there', async ({ page }) => {
const box = await canvas.boundingBox();
const side = await page.locator('aside.side').boundingBox();
const cx = box.x + box.width / 2;
- const cy = box.y + Math.min(180, box.height / 3);
+ const cy = box.y + box.height / 2;
await page.mouse.move(cx, cy);
await page.mouse.down({ button: 'middle' });
@@ -821,7 +824,7 @@ test('the right button neither draws nor drops what is picked', async ({ page })
const canvas = page.locator('.konva canvas').first();
const box = await canvas.boundingBox();
const cx = box.x + box.width / 2;
- const cy = box.y + Math.min(180, box.height / 3);
+ const cy = box.y + box.height / 2;
await page.getByTitle('Box (r)').click();
await page.mouse.move(cx - 30, cy - 20);
@@ -855,7 +858,7 @@ test('Escape unwinds one level per press', async ({ page }) => {
const canvas = page.locator('.konva canvas').first();
const box = await canvas.boundingBox();
const x = box.x + box.width / 2 - 40;
- const y = box.y + Math.min(180, box.height / 3);
+ const y = box.y + box.height / 2;
// Mid-draft: the stroke goes and the pen stays, because cancelling a stroke
// is no reason to put the pen down.
@@ -894,7 +897,7 @@ test('a row picked in the side column takes the hand back to Select', async ({ p
const canvas = page.locator('.konva canvas').first();
const box = await canvas.boundingBox();
const x = box.x + box.width / 2 - 40;
- const y = box.y + Math.min(180, box.height / 3);
+ const y = box.y + box.height / 2;
await page.getByTitle('Box (r)').click();
await page.mouse.move(x, y);
@@ -933,7 +936,7 @@ test('a placed label opens its editor on the spot, and holds two lines', async (
const canvas = page.locator('.konva canvas').first();
const box = await canvas.boundingBox();
const cx = box.x + box.width / 2;
- const cy = box.y + Math.min(180, box.height / 3);
+ const cy = box.y + box.height / 2;
await page.getByTitle('Text (t)').click();
await page.mouse.click(cx - 40, cy);
@@ -1009,7 +1012,7 @@ test('a freehand stroke resizes from its handles, and its samples take the chang
const canvas = page.locator('.konva canvas').first();
const box = await canvas.boundingBox();
const cx = box.x + box.width / 2;
- const cy = box.y + Math.min(180, box.height / 3);
+ const cy = box.y + box.height / 2;
await page.getByTitle('Freehand (d)').click();
await page.mouse.move(cx - 60, cy - 20);
@@ -1057,7 +1060,7 @@ test('a finished curve puts the pen down, like every shape but the stamp', async
const canvas = page.locator('.konva canvas').first();
const box = await canvas.boundingBox();
const cx = box.x + box.width / 2;
- const cy = box.y + Math.min(180, box.height / 3);
+ const cy = box.y + box.height / 2;
const curve = page.getByTitle(/^Curve/);
// Konva calls any two clicks inside its 400 ms window a double-click, whatever
diff --git a/frontend/e2e/proof-point-map.spec.js b/frontend/e2e/proof-point-map.spec.js
new file mode 100644
index 0000000..e8982ca
--- /dev/null
+++ b/frontend/e2e/proof-point-map.spec.js
@@ -0,0 +1,68 @@
+import { test, expect } from '@playwright/test';
+import { awaitMapReady, installAppFixture, openProofWithPanel } from './app.fixture.js';
+
+/**
+ * A proof's point, moved on the ground rather than typed.
+ *
+ * Driven in a real browser because that is the only place the map exists: the
+ * unit tests pin what the dialog asks the engine for, and nothing below the
+ * engine can say that a click on the imagery lands in the coordinate row.
+ */
+
+const row = (page) => page.locator('.point-row').first();
+
+test('a click on the map fills the coordinate row it was opened from', async ({ page }) => {
+ await installAppFixture(page);
+ await openProofWithPanel(page);
+
+ await expect(row(page).locator('.meta-input')).toHaveValue('');
+ await row(page).getByTitle('Move this point on the map').click();
+ await expect(page.getByRole('dialog', { name: 'Move the point' })).toBeVisible();
+ await awaitMapReady(page);
+ await expect(page.getByText('Click the map to move the pin.')).toBeVisible();
+
+ const box = await page.locator('.stage .map').boundingBox();
+ await page.mouse.click(box.x + box.width / 2 - 70, box.y + box.height / 2 - 40);
+ const picked = await page.locator('.reading').textContent();
+ // six decimals: the point is a claim about a tenth of a metre
+ expect(picked.trim()).toMatch(/^-?\d+\.\d{6}, -?\d+\.\d{6}$/);
+
+ await page.getByRole('button', { name: 'Use this point' }).click();
+ await expect(page.getByRole('dialog', { name: 'Move the point' })).toHaveCount(0);
+ await expect(row(page).locator('.meta-input')).toHaveValue(picked.trim());
+});
+
+test('cancelling leaves the row exactly as it was', async ({ page }) => {
+ await installAppFixture(page);
+ await openProofWithPanel(page);
+
+ const field = row(page).locator('.meta-input');
+ await field.fill('48.858400, 2.294500');
+ await row(page).getByTitle('Move this point on the map').click();
+ await awaitMapReady(page);
+
+ // opened on what the row already says, which is where the pin starts
+ await expect(page.locator('.reading')).toHaveText('48.858400, 2.294500');
+ const box = await page.locator('.stage .map').boundingBox();
+ await page.mouse.click(box.x + box.width / 2 + 60, box.y + box.height / 2);
+ await page.getByRole('button', { name: 'Cancel' }).click();
+
+ await expect(page.getByRole('dialog', { name: 'Move the point' })).toHaveCount(0);
+ await expect(field).toHaveValue('48.858400, 2.294500');
+});
+
+test('a row added under a point opens beside it, not on the empty ocean', async ({ page }) => {
+ await installAppFixture(page);
+ await openProofWithPanel(page);
+
+ await row(page).locator('.meta-input').fill('48.858400, 2.294500');
+ await page.getByTitle('Add a point').click();
+ const second = page.locator('.point-row').nth(1);
+ await expect(second.locator('.meta-input')).toHaveValue('');
+
+ await second.getByTitle('Move this point on the map').click();
+ await awaitMapReady(page);
+ // the pin starts on the point above, so the analyst places the new one from
+ // the same rooftop rather than from zoom 3 over the Atlantic
+ await expect(page.locator('.reading')).toHaveText('48.858400, 2.294500');
+});
diff --git a/frontend/e2e/saved-linked-posts.spec.js b/frontend/e2e/saved-linked-posts.spec.js
index 53deb9a..f08ee58 100644
--- a/frontend/e2e/saved-linked-posts.spec.js
+++ b/frontend/e2e/saved-linked-posts.spec.js
@@ -1,5 +1,5 @@
import { test, expect } from '@playwright/test';
-import { CASE_ID, awaitMapReady, installAppFixture } from './app.fixture.js';
+import { CASE_ID, awaitMapReady, installAppFixture, showSaved } from './app.fixture.js';
// The third one names a target this build dropped, which is what a draft saved
// before that looks like: it is listed, and it opens (on X, by normalizePostTarget).
@@ -52,10 +52,9 @@ test('shows every linked post from a proof popup and opens the selected draft',
await page.goto('/#satellite');
await awaitMapReady(page);
- await page.getByRole('button', { name: 'Proofs', exact: true }).click();
+ await showSaved(page, 'Proofs');
await expect(page.getByText('Panorama autostitch test')).toBeVisible();
- await page.getByRole('button', { name: 'Saved work', exact: true }).click();
await page.locator('.saved-mark-proof').click();
const popup = page.locator('.saved-popup');
@@ -90,8 +89,8 @@ test('clears capture rows before a different case index arrives', async ({ page
await page.goto('/#satellite');
await awaitMapReady(page); // the rows are read beside a map, and one mark is on it
const savedPanel = page.locator('.captures');
+ await showSaved(page);
await expect(savedPanel.getByText('Capture A', { exact: true })).toBeVisible();
- await page.getByRole('button', { name: 'Saved work', exact: true }).click();
await expect(page.locator('.saved-mark-capture')).toHaveCount(1);
await page.getByTitle('Switch case').click();
await page.locator('.menu .item').filter({ hasText: 'Case B' }).click();
@@ -118,7 +117,7 @@ test('clears proof rows before a different case proof index arrives', async ({ p
await page.goto('/#satellite');
await awaitMapReady(page); // the panel is the map tool's, and it opens with it
- await page.getByRole('button', { name: 'Proofs', exact: true }).click();
+ await showSaved(page, 'Proofs');
await expect(page.getByText('Proof A')).toBeVisible();
await page.getByTitle('Switch case').click();
await page.locator('.menu .item').filter({ hasText: 'Case B' }).click();
diff --git a/frontend/e2e/saved-media.spec.js b/frontend/e2e/saved-media.spec.js
new file mode 100644
index 0000000..fc2d214
--- /dev/null
+++ b/frontend/e2e/saved-media.spec.js
@@ -0,0 +1,115 @@
+import { test, expect } from '@playwright/test';
+import { PANEL_PATH, awaitMapReady, installAppFixture, showSaved } from './app.fixture.js';
+
+/**
+ * Located files on the map, and the player they open.
+ *
+ * The gesture is holding footage next to the imagery it is being matched
+ * against, so the file plays in the panel and the map stays whole. Whether a
+ * mark answers its own click, what the arrows walk and what Escape puts back are
+ * all browser facts, which is why they are proved here.
+ */
+
+const point = {
+ lat: 48.8584,
+ lon: 2.2945,
+ geo: { state: 'ok', country_code: 'fr', country: 'France' },
+ continent: 'Europe',
+ country_en: 'France',
+};
+
+/** Two files on one spot: the marks collapse, and the stack is what opens. */
+const mediaIndex = [
+ {
+ id: 'media-1',
+ key: '[email protected],2.2945',
+ kind: 'media',
+ media_kind: 'image',
+ title: 'roadside photo',
+ path: PANEL_PATH,
+ thumbnail: null,
+ fetched_at: '2026-07-24T09:00:00Z',
+ status: 'confirmed',
+ roads: [{ type: 'located-at', status: 'confirmed' }],
+ linked_proofs: [],
+ ...point,
+ },
+ {
+ id: 'media-2',
+ key: '[email protected],2.2945',
+ kind: 'media',
+ media_kind: 'image',
+ title: 'rooftop still',
+ path: PANEL_PATH,
+ thumbnail: null,
+ fetched_at: '2026-07-24T08:00:00Z',
+ status: 'suggested',
+ roads: [{ type: 'proof', id: 'proof-1', title: 'Roofline', status: 'confirmed' }],
+ linked_proofs: [{ id: 'proof-1', name: 'Roofline', title: 'Roofline' }],
+ ...point,
+ },
+];
+
+const panel = (page) => page.locator('.captures');
+
+test('opens on the case’s located files, with the layer already drawing them', async ({ page }) => {
+ const fixture = await installAppFixture(page, { mediaIndex });
+ await page.goto('/#satellite');
+ await awaitMapReady(page);
+
+ // no switch was pressed: the panel opens on Media and the layer is on
+ await expect(panel(page).getByText('roadside photo')).toBeVisible();
+ await expect(panel(page).getByText('Recorded here')).toBeVisible();
+ await expect(page.locator('.saved-mark')).toHaveCount(1);
+ fixture.expectNoUnexpectedRequests();
+});
+
+test('plays the whole stack under one mark, and puts the list back', async ({ page }) => {
+ await installAppFixture(page, { mediaIndex });
+ await page.goto('/#satellite');
+ await awaitMapReady(page);
+
+ await page.locator('.saved-mark').click();
+ // the file plays in the panel; the map is not covered by a window over it
+ await expect(page.locator('.saved-popup')).toHaveCount(0);
+ await expect(panel(page).locator('.viewer img')).toBeVisible();
+ await expect(panel(page).getByText('1 / 2')).toBeVisible();
+ await expect(panel(page).getByText('roadside photo')).toBeVisible();
+
+ // the arrows walk the stack without a click into the panel first
+ await page.keyboard.press('ArrowRight');
+ await expect(panel(page).getByText('2 / 2')).toBeVisible();
+ await expect(panel(page).getByText('rooftop still')).toBeVisible();
+ // why it stands here, and that only a tool has claimed it so far
+ await expect(panel(page).getByText('Via Roofline')).toBeVisible();
+ await expect(panel(page).getByText('suggested')).toBeVisible();
+
+ await page.keyboard.press('Escape');
+ await expect(panel(page).getByText('Layers')).toBeVisible();
+});
+
+test('opens the proof a file was placed by', async ({ page }) => {
+ await installAppFixture(page, { mediaIndex });
+ await page.goto('/#satellite');
+ await awaitMapReady(page);
+
+ await page.locator('.saved-mark').click();
+ await page.keyboard.press('ArrowRight');
+ await panel(page).getByRole('button', { name: 'Roofline' }).click();
+ await expect(page.getByRole('heading', { name: 'Geo Proof' })).toBeVisible();
+ await expect(page).toHaveURL(/#proof/);
+});
+
+test('keeps the card for saved work, which is read rather than watched', async ({ page }) => {
+ await installAppFixture(page, {
+ mediaIndex,
+ savedIndex: [{ id: 'place-1', key: 'place-1', kind: 'place', title: 'checkpoint north', ...point }],
+ });
+ await page.goto('/#satellite');
+ await awaitMapReady(page);
+ await showSaved(page, 'Places');
+
+ await page.locator('.saved-mark').click();
+ await expect(page.locator('.saved-popup')).toBeVisible();
+ await expect(panel(page).locator('.viewer')).toHaveCount(0);
+});
diff --git a/frontend/e2e/saved-relations.spec.js b/frontend/e2e/saved-relations.spec.js
index d678847..92692f1 100644
--- a/frontend/e2e/saved-relations.spec.js
+++ b/frontend/e2e/saved-relations.spec.js
@@ -1,5 +1,5 @@
import { test, expect } from '@playwright/test';
-import { CASE_ID, awaitMapReady, installAppFixture } from './app.fixture.js';
+import { CASE_ID, awaitMapReady, installAppFixture, showSaved } from './app.fixture.js';
/**
* Relations on the map, in a real card opened on a mark.
@@ -73,7 +73,7 @@ test('opens a stacked row’s relations without closing the card', async ({ page
await page.goto('/#satellite');
await awaitMapReady(page);
- await page.getByRole('button', { name: 'Saved work', exact: true }).click();
+ await showSaved(page); // the layer is on, on the Media position
await page.locator('.saved-mark').click();
const popup = page.locator('.saved-popup');
@@ -98,7 +98,7 @@ test('corrects the reading of a relation in place, and takes one back', async ({
await page.goto('/#satellite');
await awaitMapReady(page);
- await page.getByRole('button', { name: 'Saved work', exact: true }).click();
+ await showSaved(page); // the layer is on, on the Media position
await page.locator('.saved-mark').click();
const popup = page.locator('.saved-popup');
@@ -125,7 +125,7 @@ test('settles a suggested relation from the card, which survives the click', asy
await page.goto('/#satellite');
await awaitMapReady(page);
- await page.getByRole('button', { name: 'Saved work', exact: true }).click();
+ await showSaved(page); // the layer is on, on the Media position
await page.locator('.saved-mark').click();
const popup = page.locator('.saved-popup');
@@ -169,7 +169,7 @@ test('shows the findings on the card and leaves the pointers out', async ({ page
await page.goto('/#satellite');
await awaitMapReady(page);
- await page.getByRole('button', { name: 'Saved work', exact: true }).click();
+ await showSaved(page); // the layer is on, on the Media position
await page.locator('.saved-mark').click();
const popup = page.locator('.saved-popup');
diff --git a/frontend/e2e/todos.spec.js b/frontend/e2e/todos.spec.js
new file mode 100644
index 0000000..1405f95
--- /dev/null
+++ b/frontend/e2e/todos.spec.js
@@ -0,0 +1,40 @@
+import { test, expect } from '@playwright/test';
+import { CASE_ID, installAppFixture } from './app.fixture.js';
+
+for (const empty of [false, true]) {
+ test(`checklists fit the dashboard grid in a ${empty ? 'new' : 'populated'} case`, async ({ page }) => {
+ await page.setViewportSize({ width: 1440, height: 1000 });
+ // An empty catalog falls back to the drawn case, so a new case needs its summary.
+ await installAppFixture(page, empty
+ ? { summary: { total: 0, by_type: {}, by_status: {}, by_folder: {}, linked_to: {} } }
+ : { catalog: [{ id: 'source', type: 'place', label: 'Source', attrs: {}, provenance: {} }] });
+ let data = { revision: 0, lists: [{ id: 'default', name: 'Tasks', tasks: [] }] };
+ await page.route(`**/api/cases/${CASE_ID}/todos`, async (route) => {
+ if (route.request().method() === 'PUT') {
+ const body = route.request().postDataJSON();
+ data = { ...body, revision: body.revision + 1 };
+ }
+ await route.fulfill({ json: data });
+ });
+ await page.goto('/#overview');
+ const todos = page.getByRole('region', { name: 'To-do', exact: true });
+ await expect(todos.getByLabel('New task', { exact: true })).toBeVisible();
+ const grid = page.locator('.home .grid');
+ if (empty) await expect(grid).toHaveClass(/empty-case/);
+ else await expect(page.getByRole('heading', { name: 'What is waiting' })).toBeVisible();
+ const gridBox = await grid.boundingBox();
+ const todoBox = await todos.boundingBox();
+ expect(todoBox.width).toBeLessThan(gridBox.width * 0.6);
+ await todos.getByLabel('New task', { exact: true }).fill('Verify source');
+ await todos.getByLabel('New task', { exact: true }).press('Enter');
+ await expect(todos.getByLabel('Task text', { exact: true })).toHaveValue('Verify source');
+ await todos.getByRole('checkbox').check();
+ await expect(todos.getByRole('button', { name: 'Tasks 1/1' })).toBeVisible();
+ await page.reload();
+ await expect(todos.getByRole('checkbox')).toBeChecked();
+ await page.setViewportSize({ width: 700, height: 1000 });
+ const narrowGrid = await grid.boundingBox();
+ const narrowTodos = await todos.boundingBox();
+ expect(Math.abs(narrowGrid.width - narrowTodos.width)).toBeLessThan(2);
+ });
+}
diff --git a/frontend/src/App.svelte b/frontend/src/App.svelte
index e081240..5cc95b5 100644
--- a/frontend/src/App.svelte
+++ b/frontend/src/App.svelte
@@ -55,6 +55,7 @@
{ id: 'reverse', label: TOOL_LABELS.reverse, load: () => import('./tools/ReverseSearch.svelte') },
{ 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: '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') },
diff --git a/frontend/src/components/Compass.svelte b/frontend/src/components/Compass.svelte
new file mode 100644
index 0000000..e1ed83b
--- /dev/null
+++ b/frontend/src/components/Compass.svelte
@@ -0,0 +1,110 @@
+<script>
+ /**
+ * Which way is up, as one reading: the needle resets north, the number opens
+ * for an exact angle. Every map that can turn shows this same control, so a
+ * turned view is read and undone the same way wherever it is met.
+ */
+ let { bearing = 0, onbearing = () => {} } = $props();
+
+ let editing = $state(false);
+ let typed = $state('');
+ const shown = $derived(Math.round(bearing));
+
+ function startEdit() {
+ typed = String(shown);
+ editing = true;
+ }
+
+ function commit() {
+ const deg = parseFloat(typed);
+ if (Number.isFinite(deg)) onbearing(deg);
+ editing = false;
+ }
+</script>
+
+<div class="rotate-ctl" class:turned={shown !== 0}>
+ <button
+ class="compass"
+ onclick={() => onbearing(0)}
+ title={shown ? 'Reset to north' : 'North up · middle-drag the map to rotate'}
+ aria-label="Reset to north"
+ >
+ <svg width="15" height="15" viewBox="0 0 16 16" style="transform: rotate({shown}deg)">
+ <!-- A needle, not a rose: the outline is the whole instrument and the
+ filled half is north. Two colours and a disc read as decoration. -->
+ <path
+ d="M8 1.6 11.7 14 8 10.9 4.3 14Z"
+ fill="none"
+ stroke="currentColor"
+ stroke-width="1.3"
+ stroke-linejoin="round"
+ />
+ <path d="M8 1.6 11.7 14 8 10.9Z" fill="currentColor" />
+ </svg>
+ </button>
+ {#if editing}
+ <!-- svelte-ignore a11y_autofocus -->
+ <input
+ class="input deg-input mono"
+ type="number"
+ min="0"
+ max="359"
+ bind:value={typed}
+ autofocus
+ onblur={commit}
+ onkeydown={(e) => {
+ if (e.key === 'Enter') commit();
+ else if (e.key === 'Escape') editing = false;
+ }}
+ aria-label="Set bearing in degrees"
+ />
+ {:else}
+ <button class="deg mono" onclick={startEdit} title="Click to type an exact angle">
+ {shown}°
+ </button>
+ {/if}
+</div>
+
+<style>
+ .rotate-ctl {
+ display: flex;
+ align-items: stretch;
+ height: 30px;
+ border-radius: var(--radius-1);
+ background: rgba(24, 24, 24, 0.88);
+ backdrop-filter: blur(6px);
+ box-shadow: 0 0 0 1px var(--border);
+ }
+ .rotate-ctl.turned {
+ box-shadow: 0 0 0 1px color-mix(in srgb, var(--accent) 50%, transparent);
+ }
+ .compass {
+ display: grid;
+ place-items: center;
+ width: 30px;
+ color: var(--text-2);
+ cursor: pointer;
+ }
+ .compass:hover {
+ color: var(--accent);
+ }
+ .deg {
+ min-width: 42px;
+ padding: 0 7px 0 5px;
+ text-align: left;
+ font-size: var(--fs-xs);
+ color: var(--text-1);
+ cursor: text;
+ }
+ .deg:hover {
+ color: var(--accent);
+ }
+ .deg-input {
+ width: 52px;
+ padding: 0 4px;
+ border: none;
+ background: none;
+ text-align: left;
+ font-size: var(--fs-xs);
+ }
+</style>
diff --git a/frontend/src/components/Compass.test.js b/frontend/src/components/Compass.test.js
new file mode 100644
index 0000000..c7ac65a
--- /dev/null
+++ b/frontend/src/components/Compass.test.js
@@ -0,0 +1,62 @@
+// @vitest-environment happy-dom
+import { describe, expect, it, vi } from 'vitest';
+import { flushSync, mount, unmount } from 'svelte';
+import Compass from './Compass.svelte';
+
+function render(props) {
+ const target = document.createElement('div');
+ document.body.append(target);
+ const live = mount(Compass, { target, props });
+ flushSync();
+ return { target, done: () => { unmount(live); target.remove(); } };
+}
+
+describe('Compass', () => {
+ it('turns the needle by the bearing and rounds what it prints', () => {
+ const { target, done } = render({ bearing: 32.4 });
+ expect(target.querySelector('svg').getAttribute('style')).toContain('rotate(32deg)');
+ expect(target.querySelector('.deg').textContent.trim()).toBe('32°');
+ expect(target.querySelector('.rotate-ctl').classList.contains('turned')).toBe(true);
+ done();
+ });
+
+ it('says nothing special when the map is north up', () => {
+ const { target, done } = render({ bearing: 0 });
+ expect(target.querySelector('.rotate-ctl').classList.contains('turned')).toBe(false);
+ expect(target.querySelector('button[aria-label="Reset to north"]').title)
+ .toBe('North up · middle-drag the map to rotate');
+ done();
+ });
+
+ it('resets north from the needle and takes an exact angle from the number', () => {
+ const onbearing = vi.fn();
+ const { target, done } = render({ bearing: 40, onbearing });
+ target.querySelector('button[aria-label="Reset to north"]').click();
+ expect(onbearing).toHaveBeenCalledWith(0);
+
+ target.querySelector('.deg').click();
+ flushSync();
+ const input = target.querySelector('[aria-label="Set bearing in degrees"]');
+ input.value = '125';
+ input.dispatchEvent(new Event('input', { bubbles: true }));
+ input.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true }));
+ flushSync();
+ expect(onbearing).toHaveBeenLastCalledWith(125);
+ expect(target.querySelector('[aria-label="Set bearing in degrees"]')).toBeNull();
+ done();
+ });
+
+ it('leaves the bearing alone when the typed angle is not a number', () => {
+ const onbearing = vi.fn();
+ const { target, done } = render({ bearing: 40, onbearing });
+ target.querySelector('.deg').click();
+ flushSync();
+ const input = target.querySelector('[aria-label="Set bearing in degrees"]');
+ input.value = '';
+ input.dispatchEvent(new Event('input', { bubbles: true }));
+ input.dispatchEvent(new Event('blur', { bubbles: true }));
+ flushSync();
+ expect(onbearing).not.toHaveBeenCalled();
+ done();
+ });
+});
diff --git a/frontend/src/components/EntityTime.test.js b/frontend/src/components/EntityTime.test.js
index 0daa017..be6b266 100644
--- a/frontend/src/components/EntityTime.test.js
+++ b/frontend/src/components/EntityTime.test.js
@@ -52,3 +52,15 @@ describe('entity Time tab', () => {
expect(source).toContain('visibleUndated = $derived(undated.filter');
});
});
+
+describe('entity Time tab — which date reads first', () => {
+ it('puts what the analyst concluded above what the file reports', () => {
+ // A proof that dates its footage states it here, and a stated date is the
+ // answer: the file's own clock is what the analyst was correcting or filling
+ // in. Pinned, because the order is the whole of the priority.
+ const about = source.indexOf('Statements about this');
+ const media = source.indexOf('Media dates');
+ expect(about).toBeGreaterThan(-1);
+ expect(media).toBeGreaterThan(about);
+ });
+});
diff --git a/frontend/src/components/Icon.svelte b/frontend/src/components/Icon.svelte
index ed1e2d5..64d75c8 100644
--- a/frontend/src/components/Icon.svelte
+++ b/frontend/src/components/Icon.svelte
@@ -6,6 +6,7 @@
// navigation / tools
media: '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-1Zm0 11 4.5-4.5a1 1 0 0 1 1.4 0L14 15.5m-1.5-1.5 2.6-2.6a1 1 0 0 1 1.4 0L21 15M9 9.5h.01',
satellite: 'M9 4.2 3.6 6.4a1 1 0 0 0-.6.9v11.2a1 1 0 0 0 1.4.9L9 17.4l6 2.4 5.4-2.2a1 1 0 0 0 .6-.9V5.5a1 1 0 0 0-1.4-.9L15 6.6 9 4.2Zm0 0v13.2M15 6.6v13.2',
+ compare: '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 0v14M7 9h2m6 6h2',
proof: 'M4 4h7v7H4V4Zm9 0h7v7h-7V4ZM4 13h7v7H4v-7Zm11.5 0v7m-3.5-3.5h7',
// the case as its graph: one entity and what it holds onto. The three spokes
// sit on the rose's thirds — north, then 210° and 330° — so the case reads in
@@ -91,6 +92,8 @@
network: 'M12 3.5a2.25 2.25 0 1 1 0 4.5 2.25 2.25 0 0 1 0-4.5ZM5 16a2.25 2.25 0 1 1 0 4.5A2.25 2.25 0 0 1 5 16Zm14 0a2.25 2.25 0 1 1 0 4.5 2.25 2.25 0 0 1 0-4.5ZM12 8v4m0 0-7 4m7-4 7 4',
building: 'M5 21V4.5A1 1 0 0 1 6 3.5h7a1 1 0 0 1 1 1V21M14 10h4a1 1 0 0 1 1 1v10M3 21h18M8 7.5h.01M11 7.5h.01M8 11h.01M11 11h.01M8 14.5h3',
alert: 'M12 3 2.5 19.5h19L12 3Zm0 7v4m0 3.5h.01',
+ // A ghosted collage piece: an editing state, so it must stay distinct from an alert.
+ ghost: 'M12 3a8 8 0 0 0-8 8v10l4-2 4 2 4-2 4 2V11a8 8 0 0 0-8-8Zm-3 8h.01m5.99 0H15',
info: 'M12 22a10 10 0 1 0 0-20 10 10 0 0 0 0 20Zm0-11v6m0-10h.01',
clock: 'M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18Zm0 4v5l3.5 2',
play: 'm8 5 11 7-11 7V5Z',
@@ -128,6 +131,13 @@
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',
+ // 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',
+ fade: 'M9 6.5a5.5 5.5 0 1 1 0 11 5.5 5.5 0 0 1 0-11Zm6 0a5.5 5.5 0 1 1 0 11',
+ blink: 'M4 6h7v12H4a1 1 0 0 1-1-1V7a1 1 0 0 1 1-1Zm9 0h7a1 1 0 0 1 1 1v10a1 1 0 0 1-1 1h-7M16 9.5v5',
+ changes: '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-1Zm4 9.5 2.5-3 2.5 2 3-4',
+ swap: 'M7 4 3.5 7.5 7 11M3.5 7.5H18M17 13l3.5 3.5L17 20m3.5-3.5H6',
angle: 'M5 4v15h15M5 19 20 6',
sun: 'M12 7a5 5 0 1 0 0 10 5 5 0 0 0 0-10ZM12 1v3M12 20v3M4.2 4.2l2.1 2.1M17.7 17.7l2.1 2.1M1 12h3M20 12h3M4.2 19.8l2.1-2.1M17.7 6.3l2.1-2.1',
moon: 'M21 12.8A9 9 0 1 1 11.2 3a7 7 0 0 0 9.8 9.8Z',
diff --git a/frontend/src/components/Icon.test.js b/frontend/src/components/Icon.test.js
new file mode 100644
index 0000000..645fc4d
--- /dev/null
+++ b/frontend/src/components/Icon.test.js
@@ -0,0 +1,15 @@
+import { describe, expect, it } from 'vitest';
+import { render } from 'svelte/server';
+import Icon, { paths } from './Icon.svelte';
+
+describe('Icon', () => {
+ it('renders a dedicated ghost glyph instead of the alert fallback', () => {
+ expect(paths.ghost).toBeTruthy();
+ expect(paths.ghost).not.toBe(paths.alert);
+
+ const { body } = render(Icon, { props: { name: 'ghost', size: 15 } });
+
+ expect(body).toContain(`d="${paths.ghost}"`);
+ expect(body).not.toContain(`d="${paths.alert}"`);
+ });
+});
diff --git a/frontend/src/components/TemporalInput.svelte b/frontend/src/components/TemporalInput.svelte
index 270cf26..70407b1 100644
--- a/frontend/src/components/TemporalInput.svelte
+++ b/frontend/src/components/TemporalInput.svelte
@@ -8,7 +8,12 @@
} from '../lib/temporalInput.js';
import { formatTemporalValue } from '../lib/timeline.js';
- let { id, value = '', onchange, onvaliditychange } = $props();
+ // `compact` is for a narrow column — the proof composer's 300px side panel —
+ // where the three-part date row does not fit and overflows its own container.
+ // It stacks the parts instead, which is what the editor already does on a
+ // narrow window; the difference is that a media query reads the viewport and
+ // cannot see that a wide window holds a narrow column.
+ let { id, value = '', compact = false, onchange, onvaliditychange } = $props();
let state = $state(readTemporalInput(''));
let sent = $state('');
const rawValue = $derived(writeTemporalInput(state));
@@ -45,7 +50,7 @@
}
</script>
-<div class="temporal-editor">
+<div class="temporal-editor" class:compact>
<label class="field format-field">
<span>Format</span>
<select
@@ -280,7 +285,12 @@
<style>
.temporal-editor { display: grid; gap: 7px; }
.field { min-width: 0; display: grid; gap: 3px; }
- .field > span { color: var(--text-3); font-size: 10px; }
+ .field > span { color: var(--text-3); font-size: var(--fs-xs); }
+ /* The size this editor's controls always meant to be. `input-sm` was written
+ on every one of them, but it is defined in the callers' scoped styles, which
+ Svelte does not let through to a child component — so the class did nothing
+ and the controls rendered a step larger than the fields beside them. */
+ .input-sm { padding: 4px 7px; font-size: var(--fs-xs); }
.parts { display: grid; align-items: end; gap: 6px; }
.date-parts { grid-template-columns: auto minmax(150px, 1fr) minmax(170px, .8fr); }
.timestamp-parts { grid-template-columns: minmax(190px, 1fr) auto auto; }
@@ -320,6 +330,43 @@
.temporal-preview small { color: var(--text-3); }
.temporal-preview code { margin-left: auto; color: var(--text-3); overflow-wrap: anywhere; }
.temporal-preview.error { border-left-color: var(--danger); color: var(--danger); }
+ /* Compact: the parts pair up instead of stacking, and the controls carry their
+ own names. Four labelled rows made this one field taller than the coordinates
+ and the sources above it put together, for a value most proofs answer with a
+ single day. The selects say what they hold — Date, Day, Exact as stated — so
+ the label above each becomes a caption of the word underneath it; it stays
+ for a screen reader, which cannot see the option. */
+ .compact { gap: 5px; }
+ .compact .field > span {
+ position: absolute;
+ width: 1px;
+ height: 1px;
+ margin: -1px;
+ padding: 0;
+ border: 0;
+ overflow: hidden;
+ clip-path: inset(50%);
+ white-space: nowrap;
+ }
+ /* Precision sits beside the value it qualifies — "Day" is three characters and
+ had a row of its own. Reading order is left to right then down, and it is
+ also the order the controls are reached in: nothing here is moved out of the
+ sequence it is written in. */
+ .compact .date-parts { grid-template-columns: auto minmax(0, 1fr); }
+ .compact .timestamp-parts { grid-template-columns: repeat(2, minmax(0, 1fr)); }
+ /* Certainty is a sentence, not a word, and a timestamp needs its own width. */
+ .compact .certainty-field,
+ .compact .datetime-field { grid-column: 1 / -1; }
+ .compact .range-parts,
+ .compact .time-range-parts { grid-template-columns: 1fr; }
+ .compact .format-field { justify-self: stretch; }
+ .compact .format,
+ .compact .precision,
+ .compact .zone,
+ .compact .offset { width: 100%; }
+ /* The guide is a wide table, and the column it opens in clips what overflows
+ it. Held to the column, it scrolls inside itself instead of being cut off. */
+ .compact .advanced-guide { width: 100%; }
@media (max-width: 620px) {
.date-parts, .timestamp-parts, .range-parts, .time-range-parts { grid-template-columns: 1fr; }
.format-field { justify-self: stretch; }
diff --git a/frontend/src/components/TemporalInput.test.js b/frontend/src/components/TemporalInput.test.js
index 8375c98..87e9d6a 100644
--- a/frontend/src/components/TemporalInput.test.js
+++ b/frontend/src/components/TemporalInput.test.js
@@ -24,3 +24,26 @@ describe('temporal input', () => {
expect(source).toContain('max-height: min(360px, 55vh)');
});
});
+
+describe('temporal input in a narrow column', () => {
+ it('sizes its own controls, since a caller cannot style into a component', () => {
+ expect(source).toContain('.input-sm { padding: 4px 7px; font-size: var(--fs-xs); }');
+ });
+
+ it('pairs the parts and hides the captions rather than stacking four rows', () => {
+ expect(source).toContain('class:compact');
+ expect(source).toContain('.compact .date-parts { grid-template-columns: auto minmax(0, 1fr); }');
+ expect(source).toContain('clip-path: inset(50%)');
+ });
+
+ it('keeps the labels in the markup, where a screen reader still reads them', () => {
+ // The compact rule hides them visually. Removing them would take the
+ // accessible name of every wrapping label with it.
+ expect(source).toContain('<span>Precision</span>');
+ expect(source).toContain('<span>Certainty</span>');
+ });
+
+ it('holds the syntax guide to the column it opens in', () => {
+ expect(source).toContain('.compact .advanced-guide { width: 100%; }');
+ });
+});
diff --git a/frontend/src/lib/composer.js b/frontend/src/lib/composer.js
index e9aff7d..5f7b615 100644
--- a/frontend/src/lib/composer.js
+++ b/frontend/src/lib/composer.js
@@ -635,6 +635,47 @@ export function statePoints(spec, points) {
return spec;
}
+/**
+ * The rows a proof holds once a panel carrying a place has landed on it.
+ *
+ * A panel with coordinates used to be able to *replace* the proof's answer
+ * without saying so: the field reads the first geo panel (`autoCoords`) while no
+ * row is typed, and in free layout a new panel is prepended — so dropping a
+ * second capture onto the canvas quietly renamed the place the proof concluded
+ * on. In grid layout the same panel went the other way and was never heard at
+ * all: it lands behind the first, and its place was simply lost.
+ *
+ * So the place is added rather than swapped. The answer already on screen is
+ * written down first (`answered`, read before the panel landed), because an
+ * answer the panels happen to give is not one the analyst chose, and the new
+ * point joins the list under it. A proof that had no coordinates at all is left
+ * alone: that panel *is* the answer, and the field reads it off the panels as it
+ * always has.
+ *
+ * @param {Array} points the rows as edited, at least one
+ * @param {object} panel the panel that just landed
+ * @param {string} answered what the proof answered with before it did
+ * @param {string} format the reader's coordinate format
+ */
+export function statePanelPoint(points, panel, answered, format = 'dd') {
+ const { lat, lon } = panel?.meta ?? {};
+ if (lat == null || lon == null) return points;
+ const text = formatCoords({ lat: Number(lat), lon: Number(lon) }, format);
+ if (!text || !answered) return points;
+ const rows = points?.length ? points : [{ coords: '', label: '', pov: false }];
+ if (rows.length >= MAX_POINTS) return points;
+ const stated = rows.map((one) => String(one.coords ?? '').trim()).filter(Boolean);
+ // The same place twice is one place: two captures of one point, taken on two
+ // dates, are the proof's whole subject and must not read as two.
+ if ((stated.length ? stated : [answered]).includes(text)) return points;
+ return [
+ ...rows.map((one, at) =>
+ at === 0 && !String(one.coords ?? '').trim() ? { ...one, coords: answered } : one
+ ),
+ { coords: text, label: '', pov: false },
+ ];
+}
+
/** Effective coordinates text for a proof/spec: what it concludes on, else auto. */
export function proofCoordsText(p, format = 'dd') {
const stated = specPoints(p)[0]?.coords;
@@ -1046,6 +1087,13 @@ export function toSpec(proof) {
// per line, and the place filed on save takes its verb from that line
// (engine/satellite.restate_proof_point).
...statePoints({}, proof.points),
+ // What the proof says about itself, both optional and neither printed: the
+ // date the material was taken, and the sentence a post is written from. They
+ // are mirrored onto the entity on save — `when` is what the Timeline reads,
+ // the description is the proof's notes — so the graph and search see them
+ // without opening this file (`api/proofs.save_proof`).
+ when: proof.when?.trim() ? proof.when.trim() : null,
+ description: proof.description?.trim() ? proof.description.trim() : null,
// What the plate's footer prints. `footer` is the credit line itself;
// `footerText` is whether it prints at all, and `footerCoords` whether the
// proof's points print above it. Coordinates are off unless asked: they are
diff --git a/frontend/src/lib/composer.test.js b/frontend/src/lib/composer.test.js
index dad14b0..65b2472 100644
--- a/frontend/src/lib/composer.test.js
+++ b/frontend/src/lib/composer.test.js
@@ -21,7 +21,8 @@ import {
normalizeFrame, newFrame, FRAME_COLOR, FRAME_WIDTH, FRAME_WIDTH_MAX,
newPaste, pasteBoxes, pasteInsertScale, clampPasteScale, clampPaste,
surfaces, surfaceHitTest, PASTE_SCALE_MAX, PASTE_SHARE,
- specPoints, statePoints, proofCoordsLines, coordsPlateLines, coordsPostLines,
+ specPoints, statePoints, statePanelPoint, MAX_POINTS,
+ proofCoordsLines, coordsPlateLines, coordsPostLines,
footerLines, footerBand,
} from './composer.js';
@@ -1826,6 +1827,55 @@ describe('the points a proof states', () => {
});
});
+describe('a panel that carries a place', () => {
+ const blank = [{ coords: '', label: '', pov: false }];
+ const panel = (lat, lon) => ({ id: 'p2', src: 'b.png', meta: { kind: 'satellite', lat, lon } });
+
+ it('leaves a proof with no coordinates alone: that panel is the answer', () => {
+ expect(statePanelPoint(blank, panel(48.8584, 2.2945), '')).toEqual(blank);
+ });
+
+ it('adds its place under the one the proof already answers with', () => {
+ // the answer was the panels' own, never typed — it is written down first, or
+ // the next panel would take its place without saying so
+ expect(statePanelPoint(blank, panel(48.8738, 2.295), '48.858400, 2.294500')).toEqual([
+ { coords: '48.858400, 2.294500', label: '', pov: false },
+ { coords: '48.873800, 2.295000', label: '', pov: false },
+ ]);
+ });
+
+ it('leaves a stated conclusion where it is', () => {
+ const stated = [{ coords: 'the camera', label: 'pov', pov: true }];
+ expect(statePanelPoint(stated, panel(1, 2), 'the camera')).toEqual([
+ { coords: 'the camera', label: 'pov', pov: true },
+ { coords: '1.000000, 2.000000', label: '', pov: false },
+ ]);
+ });
+
+ it('says one place once: two captures of one point are one point', () => {
+ const rows = [{ coords: '1.000000, 2.000000', label: '', pov: false }];
+ expect(statePanelPoint(rows, panel(1, 2), '1.000000, 2.000000')).toBe(rows);
+ // …including while the field is still reading it off the panels
+ expect(statePanelPoint(blank, panel(1, 2), '1.000000, 2.000000')).toBe(blank);
+ });
+
+ it('adds nothing for a panel with no place, and nothing past the ceiling', () => {
+ const media = { id: 'p3', src: 'c.png', meta: { kind: 'media' } };
+ expect(statePanelPoint(blank, media, '1.000000, 2.000000')).toBe(blank);
+ const full = Array.from({ length: MAX_POINTS }, (_, i) => ({
+ coords: `${i}.000000, 0.000000`,
+ label: '',
+ pov: false,
+ }));
+ expect(statePanelPoint(full, panel(9, 9), '0.000000, 0.000000')).toBe(full);
+ });
+
+ it('states the place in the reader’s own format', () => {
+ const [, added] = statePanelPoint(blank, panel(48.8584, 2.2945), '48.873800, 2.295000', 'dms');
+ expect(added.coords).toBe('48°51\'30.24"N 2°17\'40.20"E');
+ });
+});
+
describe('the coordinates a plate prints', () => {
const lines = [
{ coords: '64.1466, -21.9426', label: '' },
@@ -1892,3 +1942,26 @@ describe('a house style and the footer switches', () => {
expect(footerLines({ panels: [], footerText: false })).toEqual([]);
});
});
+
+
+describe('the date a proof states for its material', () => {
+ it('never reads one off the panels: a file date is not when the thing happened', () => {
+ // The panel carries the address its media traces back to, and nothing else
+ // about time. An offered date is a date accepted without being read.
+ const panel = mediaPanelInput(
+ { path: 'media/clip.png', taken_at: '2024-03-11T18:40:00', source: { webpage_url: 'https://x.com/a/1' } },
+ [],
+ );
+ expect(Object.keys(panel.meta).sort()).toEqual(['kind', 'source_url', 'source_urls']);
+ });
+
+ it('writes the date and the description into the spec, trimmed, else null', () => {
+ const bare = { panels: [], pastes: [], shapes: [], points: [], notes: {} };
+ const stated = toSpec({ ...bare, when: ' 2024-03-11~ ', description: ' 13 helicopters ' });
+ expect(stated.when).toBe('2024-03-11~');
+ expect(stated.description).toBe('13 helicopters');
+ const blank = toSpec({ ...bare, when: ' ', description: '' });
+ expect(blank.when).toBe(null);
+ expect(blank.description).toBe(null);
+ });
+});
diff --git a/frontend/src/lib/extension.test.js b/frontend/src/lib/extension.test.js
index bfcbd0b..4aec873 100644
--- a/frontend/src/lib/extension.test.js
+++ b/frontend/src/lib/extension.test.js
@@ -244,12 +244,21 @@ describe('the map tools panel’s own scripts', () => {
});
});
-describe('handle: map-file (a picture for a reference window)', () => {
+describe('handle: map-file (a picture or a video for a reference window)', () => {
const png = () => ({
type: 'image/png',
arrayBuffer: async () => new Uint8Array([0xff, 0x00, 0x10]).buffer,
});
+ /** The app answering a `Range` the way `FileResponse` does: the slice, and how
+ * much file there is behind it. */
+ const slice = (bytes, start, total) => ({
+ ok: true,
+ status: 206,
+ headers: { get: (name) => (name === 'Content-Range' ? `bytes ${start}-${start + bytes.length - 1}/${total}` : null) },
+ blob: async () => ({ type: 'video/mp4', arrayBuffer: async () => new Uint8Array(bytes).buffer }),
+ });
+
it('reads one case file with the pairing token and carries it as base64', async () => {
// a message carries a string, never a blob: the panel decodes it back into a
// bitmap and paints it, which is what gets a picture past a map site's CSP
@@ -257,19 +266,50 @@ describe('handle: map-file (a picture for a reference window)', () => {
const { handle } = load({ fetchImpl });
const res = await handle({ type: 'map-file', caseId: 'case-1', path: 'media/roof.png' }, {});
- expect(res).toEqual({ ok: true, file: { type: 'image/png', data: btoa('\xff\x00\x10') } });
+ // no Content-Range: the app sent the whole thing, so there is nothing after it
+ expect(res).toEqual({
+ ok: true,
+ file: { type: 'image/png', data: btoa('\xff\x00\x10'), next: null, total: 3 },
+ });
expect(fetchImpl.mock.calls[0][0]).toBe(
'http://127.0.0.1:8477/api/ingest/file?case_id=case-1&path=media%2Froof.png'
);
expect(fetchImpl.mock.calls[0][1].headers['X-Azimut-Token']).toBe('tok-123');
});
+ it('asks for a slice, and says where the next one starts', async () => {
+ // what makes a reference window able to hold a video: the file is never the
+ // unit, so nothing here scales with how long the clip is
+ const fetchImpl = vi.fn(async () => slice([1, 2, 3], 0, 9));
+ const { handle } = load({ fetchImpl });
+
+ const res = await handle(
+ { type: 'map-file', caseId: 'case-1', path: 'media/walk.mp4', offset: 0 },
+ {}
+ );
+ expect(res.file.next).toBe(3);
+ expect(res.file.total).toBe(9);
+ expect(fetchImpl.mock.calls[0][1].headers.Range).toBe(`bytes=0-${4 * 1024 * 1024 - 1}`);
+ });
+
+ it('asks from the offset it was given, and ends on the last slice', async () => {
+ const fetchImpl = vi.fn(async () => slice([7, 8], 7, 9));
+ const { handle } = load({ fetchImpl });
+
+ const res = await handle(
+ { type: 'map-file', caseId: 'case-1', path: 'media/walk.mp4', offset: 7 },
+ {}
+ );
+ expect(fetchImpl.mock.calls[0][1].headers.Range).toBe(`bytes=7-${7 + 4 * 1024 * 1024 - 1}`);
+ expect(res.file).toEqual({ type: 'video/mp4', data: btoa('\x07\x08'), next: null, total: 9 });
+ });
+
it('says which refusal it was, rather than leaving an empty window', async () => {
// the app states the size ceiling itself, so its own sentence is passed
// through rather than a second copy of the number kept over here
for (const [status, body, message] of [
[401, '', /pairing token rejected/],
- [413, '{"detail":"a handed-over file must be under 48 MB"}', /under 48 MB/],
+ [413, '{"detail":"a handed-over file must be under 512 MB"}', /under 512 MB/],
[404, 'not json at all', /refused that file \(404\)/],
]) {
const fetchImpl = vi.fn(async () => ({ ok: false, status, text: async () => body }));
@@ -393,6 +433,35 @@ describe('handOff: filling a composer the app prepared', () => {
await settle(() => expect(chrome.notifications.create).toHaveBeenCalled());
});
+ it('skips an attachment too heavy to push into the page, where a window would take it', async () => {
+ // The app's ceiling is the one a reference window answers to, and that one
+ // pulls its file a chunk at a time. A thread's files go the other way — the
+ // whole payload is injected at once — so this side keeps a lower number.
+ const chrome = fillingChrome();
+ const fetchImpl = vi.fn(async () => ({
+ ok: true,
+ blob: async () => ({
+ type: 'video/mp4',
+ size: 64 * 1024 * 1024,
+ arrayBuffer: async () => new Uint8Array([1, 2, 3]).buffer,
+ }),
+ }));
+ const { handOff } = load({ chrome, fetchImpl });
+ chrome.scripting.executeScript = vi.fn(async () => [{ result: { filled: 2 } }]);
+
+ await handOff(payload);
+
+ await settle(() =>
+ expect(chrome.notifications.create).toHaveBeenCalledWith(
+ expect.objectContaining({ message: expect.stringContaining('could not be handed over') })
+ )
+ );
+ const [setter] = chrome.scripting.executeScript.mock.calls
+ .map(([one]) => one)
+ .filter((call) => call.world === 'MAIN');
+ expect(setter.args[0].posts[0].files).toEqual([]);
+ });
+
it('says what the fill could not do, since the app was answered long before', async () => {
const chrome = fillingChrome();
const { handOff } = load({ chrome, fetchImpl: vi.fn(async () => attachment()) });
diff --git a/frontend/src/lib/extensionMapFiles.test.js b/frontend/src/lib/extensionMapFiles.test.js
new file mode 100644
index 0000000..949778b
--- /dev/null
+++ b/frontend/src/lib/extensionMapFiles.test.js
@@ -0,0 +1,220 @@
+// @vitest-environment happy-dom
+/**
+ * Getting a case file into a reference window (extension/mapoverlay.js, `fetchFile`).
+ *
+ * The panel floats on someone else's map, so a file it wants has to cross the
+ * worker boundary as a string — and a message is no place for a video. The
+ * worker answers a slice at a time (`background.js`, `mapFile`; `extension.test.js`
+ * covers that end) and this side asks again from where the last one stopped.
+ *
+ * Which makes the loop the thing worth a test: it is the difference between a
+ * reference being a photo and a reference being the clip the geolocation is
+ * actually of. A loop that stops early hands the window half a file, and one
+ * that never stops asks the worker for the same byte for ever.
+ */
+import { describe, expect, it, vi, beforeAll, beforeEach, afterEach } from 'vitest';
+import { readFileSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+import { dirname, join } from 'node:path';
+
+const here = dirname(fileURLToPath(import.meta.url));
+const read = (name) => readFileSync(join(here, `../../../extension/${name}`), 'utf8');
+
+/** The files the panel is injected with, in the order the worker injects them. */
+const PARTS = ['mapmath.js', 'maptheme.js', 'maptools.js', 'mapdraw.js', 'mapref.js', 'maplink.js'];
+
+const CASE = 'case-1';
+/** How often the panel re-reads the address bar — the clock the init is wound
+ * past so its opening errands have all landed. */
+const POLL_MS = 300;
+
+const CLIP = {
+ path: 'media/walk.mp4',
+ filename: 'walk.mp4',
+ title: 'The walk',
+ kind: 'video',
+ thumbnail: '',
+};
+
+beforeAll(() => {
+ globalThis.Path2D = class {
+ constructor(d) {
+ this.d = d;
+ }
+ };
+ window.HTMLCanvasElement.prototype.getContext = () => {
+ const noop = () => {};
+ return new Proxy(
+ { measureText: () => ({ width: 20 }) },
+ { get: (target, name) => target[name] ?? noop }
+ );
+ };
+ globalThis.createImageBitmap = async () => ({ width: 1600, height: 1200, close: vi.fn() });
+});
+
+/**
+ * A panel on a map, with a case holding one video.
+ *
+ * `chunk` is how much of the file the worker says it is willing to answer with,
+ * which stands for `FILE_CHUNK_BYTES` over there.
+ */
+function open({ bytes, chunk }) {
+ window.happyDOM.setViewport({ width: 1400, height: 900 });
+ const location = {
+ href: 'https://www.openstreetmap.org/#map=17/50.45/30.52',
+ host: 'www.openstreetmap.org',
+ };
+ const app = {
+ '/api/ingest/ping': { units: 'metric' },
+ '/api/ingest/cases': [{ id: CASE, name: 'Case one' }],
+ '/api/ingest/parse': {
+ site: 'openstreetmap',
+ label: 'OpenStreetMap',
+ lat: 50.45,
+ lon: 30.52,
+ zoom: 17,
+ bearing: 0,
+ projection: 'webmercator',
+ view_kind: 'map',
+ geometry: true,
+ scale_source: 'zoom',
+ },
+ '/api/ingest/saved': [],
+ '/api/ingest/grids': [],
+ '/api/ingest/media': { items: [CLIP], total: 1 },
+ };
+
+ const asked = []; // every map-file message, in order
+ const blobs = []; // what the window was handed to play
+ globalThis.URL.createObjectURL = vi.fn((blob) => {
+ blobs.push(blob);
+ return `blob:azimut/${blobs.length}`;
+ });
+ globalThis.URL.revokeObjectURL = vi.fn();
+
+ const api = {
+ storage: { local: { get: vi.fn(async (d) => ({ ...d })), set: vi.fn() } },
+ runtime: {
+ onMessage: { addListener: vi.fn(), removeListener: vi.fn() },
+ sendMessage: vi.fn(async (message) => {
+ if (message.type === 'map-api') return { ok: true, data: app[message.path] ?? null };
+ if (message.type !== 'map-file') return { ok: true, data: {} };
+ asked.push(message);
+ const start = message.offset ?? 0;
+ const part = bytes.slice(start, start + chunk);
+ const read_ = start + part.length;
+ return {
+ ok: true,
+ file: {
+ type: 'video/mp4',
+ data: btoa(String.fromCharCode(...part)),
+ next: read_ < bytes.length ? read_ : null,
+ total: bytes.length,
+ },
+ };
+ }),
+ connect: vi.fn(() => ({
+ onMessage: { addListener: vi.fn() },
+ onDisconnect: { addListener: vi.fn() },
+ postMessage: vi.fn(),
+ disconnect: vi.fn(),
+ })),
+ },
+ };
+
+ for (const part of PARTS) new Function('window', read(part))(window);
+ new Function('window', 'document', 'location', 'chrome', 'browser', read('mapoverlay.js'))(
+ window,
+ document,
+ location,
+ api,
+ undefined
+ );
+ const panel = window.__AZIMUT_MAP_TOOLS__;
+ const root = () => document.getElementById('azimut-map-tools').shadowRoot;
+ return {
+ ...panel,
+ root,
+ offsets: () => asked.map((m) => m.offset),
+ paths: () => asked.map((m) => m.path),
+ blobs,
+ /** Open the picker and take the one file the case has, the way a press does. */
+ pick: async () => {
+ root().querySelector('[data-tab="refs"]').click();
+ root().querySelector('[data-act="ref-add"]').click();
+ await settle();
+ root().querySelector('.pick-item').click();
+ await settle();
+ },
+ wait: () => root().querySelector('.rw-wait')?.textContent ?? null,
+ };
+}
+
+/** Let the panel's errands land. */
+const settle = (ms = POLL_MS) => vi.advanceTimersByTimeAsync(ms);
+
+let panel = null;
+
+beforeEach(() => vi.useFakeTimers());
+
+afterEach(() => {
+ panel?.close();
+ panel = null;
+ vi.useRealTimers();
+ document.documentElement.querySelectorAll('#azimut-map-tools').forEach((node) => node.remove());
+});
+
+describe('pulling a reference across', () => {
+ it('asks again from where the last slice stopped, and glues them in order', async () => {
+ const bytes = [...Array(10).keys()]; // 0..9, so a mis-ordered join is visible
+ panel = open({ bytes, chunk: 4 });
+ await settle();
+ await panel.pick();
+
+ expect(panel.offsets()).toEqual([0, 4, 8]);
+ expect(panel.paths()).toEqual(Array(3).fill(CLIP.path));
+ // one blob, the whole file, wearing the type the app gave it — what the
+ // video element is handed an object URL for
+ expect(panel.blobs).toHaveLength(1);
+ expect(panel.blobs[0].size).toBe(bytes.length);
+ expect(panel.blobs[0].type).toBe('video/mp4');
+ expect([...new Uint8Array(await panel.blobs[0].arrayBuffer())]).toEqual(bytes);
+ });
+
+ it('stops after one ask when the whole file came in one', async () => {
+ // a photo, and every thumbnail in the picker: the loop must cost nothing
+ // extra for the files that were never the problem
+ panel = open({ bytes: [1, 2, 3], chunk: 64 });
+ await settle();
+ await panel.pick();
+
+ expect(panel.offsets()).toEqual([0]);
+ expect(panel.blobs[0].size).toBe(3);
+ });
+
+ it('counts a long file up while it arrives', async () => {
+ // "Loading…" for a minute with no sign of movement is the state that gets a
+ // window closed and the file attached by hand instead. (The line itself is
+ // taken away by the video element, which loads nothing in this environment.)
+ panel = open({ bytes: [...Array(10).keys()], chunk: 4 });
+ await settle();
+ panel.root().querySelector('[data-tab="refs"]').click();
+ panel.root().querySelector('[data-act="ref-add"]').click();
+ await settle();
+ panel.root().querySelector('.pick-item').click();
+ // partway in, before the rest of the slices land: a number, and never 100
+ await vi.advanceTimersByTimeAsync(0);
+ expect(panel.wait()).toMatch(/^Loading… [1-9]\d?%$/);
+ await settle();
+ expect(panel.wait()).not.toBe('Loading… 100%');
+ });
+
+ it('says nothing about a file that came in one piece', async () => {
+ // a percentage that appears and is immediately right is noise on a photo
+ panel = open({ bytes: [1, 2, 3], chunk: 64 });
+ await settle();
+ await panel.pick();
+
+ expect(panel.wait()).toBe('Loading…');
+ });
+});
diff --git a/frontend/src/lib/extensionMapSync.test.js b/frontend/src/lib/extensionMapSync.test.js
index d374a9d..8361348 100644
--- a/frontend/src/lib/extensionMapSync.test.js
+++ b/frontend/src/lib/extensionMapSync.test.js
@@ -321,30 +321,27 @@ describe('the beta badge', () => {
const badge = () =>
document.getElementById('azimut-map-tools').shadowRoot.querySelector('header .beta');
- it('marks Google Earth, where the tools drift the most', async () => {
- panel = open({
- answers: {
- '/api/ingest/parse': {
- site: 'google-earth',
- label: 'Google Earth',
- lat: 50.45,
- lon: 30.52,
- zoom: 17,
- bearing: 0,
- projection: 'webmercator',
- view_kind: 'satellite',
- geometry: true,
- scale_source: 'distance',
- },
- },
- });
+ it('marks every tool that draws on the ground, on whichever map', async () => {
+ // It used to name Google Earth. The caveat was never about the site: these
+ // four work from what a site writes about its own camera, and all of them
+ // are still settling — so it follows the tool now.
+ panel = open();
await settle();
- await vi.waitFor(() => expect(badge()?.textContent).toBe('Beta'));
+ for (const id of ['measure', 'pins', 'grid', 'fires']) {
+ panel.pick(id);
+ await settle(0);
+ expect(badge()?.textContent, id).toBe('Beta');
+ }
});
- it('stays off every other map', async () => {
+ it('stays off the tools that measure nothing, and off the panel at rest', async () => {
panel = open();
await settle();
- expect(badge()).toBeNull();
+ expect(badge()).toBeNull(); // no tool picked yet
+ for (const id of ['sky', 'refs']) {
+ panel.pick(id);
+ await settle(0);
+ expect(badge(), id).toBeNull();
+ }
});
});
diff --git a/frontend/src/lib/geoTree.js b/frontend/src/lib/geoTree.js
index 39544b0..65059d7 100644
--- a/frontend/src/lib/geoTree.js
+++ b/frontend/src/lib/geoTree.js
@@ -13,16 +13,18 @@
import { matchesTerms } from './folderBrowse.js';
import { haversine } from './measure.js';
-/** The switch's four positions. The first three filter the saved rows — a
+/** The switch's five positions. The first three filter the saved rows — a
* screenshot is a capture with a different origin, not a thing to choose
- * between. The fourth is a *mode*: a proof carries no point of its own and
- * borrows its capture's, so drawing both at once would stack two marks on one
- * place. It swaps the rows the panel reads instead. */
+ * between. The last two are *modes*: a proof and a photo carry no point of
+ * their own and stand where the graph puts them, so drawing them with the
+ * places they borrow from would stack two marks on one spot. Each swaps the
+ * rows the panel reads instead. */
export const KINDS = [
{ id: 'all', label: 'All' },
{ id: 'places', label: 'Places' },
{ id: 'captures', label: 'Captures' },
{ id: 'proofs', label: 'Proofs', mode: true },
+ { id: 'media', label: 'Media', mode: true },
];
/** True when this position swaps the row source rather than filtering it. */
diff --git a/frontend/src/lib/geoTree.test.js b/frontend/src/lib/geoTree.test.js
index d5838c1..27920f1 100644
--- a/frontend/src/lib/geoTree.test.js
+++ b/frontend/src/lib/geoTree.test.js
@@ -148,7 +148,7 @@ describe('buildGeoTree filtering', () => {
// A proof sits on the capture it composes, so drawing both at once would
// stack two marks on one point. The fourth position swaps the source
// instead: `isMode` tells the panel to fetch, not to filter.
- expect(KINDS.map((k) => k.id)).toEqual(['all', 'places', 'captures', 'proofs']);
+ expect(KINDS.map((k) => k.id)).toEqual(['all', 'places', 'captures', 'proofs', 'media']);
expect(isMode('proofs')).toBe(true);
expect(isMode('all')).toBe(false);
@@ -156,6 +156,13 @@ describe('buildGeoTree filtering', () => {
expect(filterSaved(rows, { kind: 'proofs' })).toHaveLength(3);
});
+ it('switches to located media the same way', () => {
+ // a photo stands where a place, a proof or a capture puts it, so it is a
+ // source of its own rather than a filter over the places it borrows from
+ expect(isMode('media')).toBe(true);
+ expect(filterSaved(rows, { kind: 'media' })).toHaveLength(3);
+ });
+
it('lists a two-place proof once, however many marks it draws', () => {
// the map is about places, a flat list is about things
const twice = [
diff --git a/frontend/src/lib/guide.js b/frontend/src/lib/guide.js
index ead9396..e81a929 100644
--- a/frontend/src/lib/guide.js
+++ b/frontend/src/lib/guide.js
@@ -188,7 +188,7 @@ export const GUIDE = [
id: 'map',
title: 'Map',
lead: 'Where a finding gets a coordinate, and where a coordinate gets a picture.',
- tools: ['satellite', 'coordinates'],
+ tools: ['satellite', 'compare', 'coordinates'],
points: [
{
label: 'Four providers need no key',
@@ -200,18 +200,26 @@ export const GUIDE = [
},
{
label: 'Layers cost nothing until they are on',
- text: 'Borders, roads, railways, power lines, sea marks, GPS traces, fires and night lights are listed in the Saved panel, and none of them is fetched before its switch is pressed.',
+ text: 'Roads, railways, power lines, sea marks, GPS traces, fires and night lights are listed in the Saved panel, and none of them is fetched before its switch is pressed. Borders are the one layer the map opens with.',
},
{
label: 'The search bar answers before it asks',
text: 'Saved places, a pasted coordinate and a bundled gazetteer answer while you type. The geocoder is only asked once you stop.',
},
+ {
+ label: 'Your footage on the map',
+ text: 'Photos and videos stand where a relation, their own GPS or a proof puts them. Press a mark to play everything filed on that spot beside the imagery.',
+ },
{
label: 'A capture is evidence',
text: 'It records its provider, coordinates, zoom and bearing, so the view can be reproduced and the attribution is already written.',
},
{
- label: 'Coords & Sky is the other tab',
+ label: 'Compare keeps the ground fixed',
+ text: 'Read two locked views side by side, by swipe, opacity or blink. Matched products also get Change assist; notes and shapes stay editable in the saved comparison and appear in its outputs.',
+ },
+ {
+ label: 'Coords & Sky keeps calculations separate',
text: 'It converts between coordinate formats and reads sun, moon, twilight and local time for one point on a date.',
},
{
diff --git a/frontend/src/lib/map/acquisitions.js b/frontend/src/lib/map/acquisitions.js
new file mode 100644
index 0000000..b0090df
--- /dev/null
+++ b/frontend/src/lib/map/acquisitions.js
@@ -0,0 +1,92 @@
+/**
+ * Sentinel-2 passes over the areas a sweep would cover.
+ *
+ * A crosshair date picker asks "is there imagery here"; a sweep has to ask "is
+ * there imagery over all of this", and the two have different answers. Sentinel-2
+ * flies 290 km-wide swaths on a five-day revisit, so an area can sit across two
+ * of them and have no single day that covers it at all. Pinned to one date
+ * anyway, half the sweep reads nodata and reports nothing found over ground it
+ * never saw.
+ *
+ * The lookup itself is `POST /api/satellite/sentinel/acquisitions`; everything
+ * here is the pure part around it, so the panel stays a view.
+ */
+
+import { daysBefore, isoDay } from '../sentinel.js';
+
+/** How far back to look. A month is several passes; a year is a last resort. */
+export const LOOKBACK_WINDOWS = Object.freeze([
+ { id: 30, label: '30 days' },
+ { id: 90, label: '90 days' },
+ { id: 365, label: '1 year' },
+]);
+
+/**
+ * Coverage at or above this counts as covering the whole area. Not 1.0 because
+ * the backend measures it by sampling, and a ring's own edge lands a point or
+ * two outside a granule that in truth reaches it. Mirrors `FULL_COVER` in
+ * `engine/analyzers.py`.
+ */
+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()) {
+ return {
+ zones: zones.map(({ id, name, kind, points }) => ({ id, name, kind, points })),
+ start: daysBefore(days, now),
+ end: isoDay(now),
+ };
+}
+
+/**
+ * What a coverage share was measured over, as a comparable key.
+ *
+ * A share describes one set of shapes. Redraw them and every number in the list
+ * is about ground that is no longer being asked about, so the list has to go
+ * rather than quietly age into a lie. Geometry only: renaming an area changes
+ * nothing a satellite swath cares about, and dropping the list for it would
+ * charge a request for a rename.
+ */
+export function areaKey(zones) {
+ return JSON.stringify((zones ?? []).map((zone) => [zone.kind, zone.points]));
+}
+
+/** How much of the drawn areas a pass reaches, as a badge. */
+export function coverLabel(coverage) {
+ if (!Number.isFinite(coverage)) return '';
+ if (coverage >= FULL_COVER) return 'Full cover';
+ return `${Math.round(coverage * 100)}% of the areas`;
+}
+
+/** Whole, partial or barely there — what colours the badge. */
+export function coverClass(coverage) {
+ if (!Number.isFinite(coverage)) return 'unknown';
+ if (coverage >= FULL_COVER) return 'full';
+ return coverage >= 0.5 ? 'part' : 'thin';
+}
+
+/**
+ * Passes the cloud ceiling still allows, newest first. A pass the service gave
+ * no cloud figure for is kept: an unknown is not a reason to hide real imagery.
+ */
+export function allowed(list, maxcc) {
+ return (list ?? []).filter(
+ (entry) => entry.cloud == null || entry.cloud <= maxcc
+ );
+}
+
+/**
+ * What to warn about once a date is chosen, or '' when there is nothing to say.
+ * Stated before the run, this is a row in a list; discovered after it, it is a
+ * sweep paid for in tiles that found nothing.
+ */
+export function coverageWarning(entry) {
+ if (!entry || !Number.isFinite(entry.coverage) || entry.coverage >= FULL_COVER) return '';
+ return `${entry.date} reaches ${Math.round(entry.coverage * 100)}% of the areas. The rest has no imagery that day and will be reported as not swept.`;
+}
+
+/** The share of a finished run's areas that had imagery on both dates. */
+export function sweptNote(swept) {
+ if (!Number.isFinite(swept) || swept >= FULL_COVER) return '';
+ return `Swept ${Math.round(swept * 100)}% of the areas; the rest had no imagery on these dates.`;
+}
diff --git a/frontend/src/lib/map/acquisitions.test.js b/frontend/src/lib/map/acquisitions.test.js
new file mode 100644
index 0000000..1cb5ba2
--- /dev/null
+++ b/frontend/src/lib/map/acquisitions.test.js
@@ -0,0 +1,90 @@
+import { describe, expect, it } from 'vitest';
+import {
+ FULL_COVER,
+ acquisitionQuery,
+ allowed,
+ areaKey,
+ coverClass,
+ coverLabel,
+ coverageWarning,
+ sweptNote,
+} from './acquisitions.js';
+
+const zone = (id) => ({
+ id,
+ name: 'Harbour',
+ kind: 'rect',
+ points: [[2.2, 48.8], [2.3, 48.9]],
+});
+
+describe('acquisitions over drawn areas', () => {
+ it('asks about the areas over a window ending today', () => {
+ const now = new Date('2026-05-31T09:00:00Z');
+ const query = acquisitionQuery([zone('a'), zone('b')], 30, now);
+ expect(query.start).toBe('2026-05-01');
+ expect(query.end).toBe('2026-05-31');
+ expect(query.zones).toHaveLength(2);
+ // only the shape the backend's Zone model accepts; extra:'forbid' there
+ // turns a stray key into a 422 rather than an ignored field
+ expect(Object.keys(query.zones[0]).sort()).toEqual(['id', 'kind', 'name', 'points']);
+ });
+
+ it('drops nothing a stray editor field added to a zone', () => {
+ const query = acquisitionQuery([{ ...zone('a'), selected: true, colour: '#fff' }], 30);
+ expect(query.zones[0].selected).toBeUndefined();
+ expect(query.zones[0].points).toEqual([[2.2, 48.8], [2.3, 48.9]]);
+ });
+
+ it('ties a coverage share to the shapes it was measured over', () => {
+ // redraw the areas and every number in the list is about ground nobody is
+ // asking about any more, so the key changes and the list goes
+ const drawn = [zone('a')];
+ expect(areaKey(drawn)).toBe(areaKey([zone('a')]));
+ expect(areaKey(drawn)).not.toBe(areaKey([{ ...zone('a'), points: [[9, 40], [9.1, 40.1]] }]));
+ expect(areaKey(drawn)).not.toBe(areaKey([zone('a'), zone('b')]));
+ expect(areaKey([])).toBe(areaKey(undefined));
+ });
+
+ it('does not charge a Copernicus request for renaming an area', () => {
+ // geometry only: a name is nothing a satellite swath cares about
+ const drawn = [zone('a')];
+ expect(areaKey(drawn)).toBe(areaKey([{ ...zone('a'), id: 'other', name: 'Renamed' }]));
+ });
+
+ it('reads a coverage share as whole, partial or barely there', () => {
+ expect(coverLabel(1)).toBe('Full cover');
+ expect(coverLabel(FULL_COVER)).toBe('Full cover');
+ expect(coverLabel(0.62)).toBe('62% of the areas');
+ expect(coverClass(1)).toBe('full');
+ expect(coverClass(0.62)).toBe('part');
+ expect(coverClass(0.2)).toBe('thin');
+ expect(coverClass(undefined)).toBe('unknown');
+ });
+
+ it('keeps a pass the service gave no cloud figure for', () => {
+ const list = [
+ { date: '2026-05-11', cloud: 3 },
+ { date: '2026-05-08', cloud: 74 },
+ { date: '2026-05-06', cloud: null },
+ ];
+ // an unknown is not a reason to hide real imagery
+ expect(allowed(list, 30).map((entry) => entry.date)).toEqual(['2026-05-11', '2026-05-06']);
+ expect(allowed(undefined, 30)).toEqual([]);
+ });
+
+ it('warns before the run about the part of the area a pass misses', () => {
+ expect(coverageWarning({ date: '2026-05-11', coverage: 1 })).toBe('');
+ expect(coverageWarning(null)).toBe('');
+ const note = coverageWarning({ date: '2026-05-08', coverage: 0.62 });
+ expect(note).toContain('2026-05-08');
+ expect(note).toContain('62%');
+ expect(note).toContain('not swept');
+ });
+
+ it('says afterwards how much of the areas the run actually read', () => {
+ // "nothing found" and "never looked" are not the same answer
+ expect(sweptNote(1)).toBe('');
+ expect(sweptNote(undefined)).toBe('');
+ expect(sweptNote(0.62)).toContain('Swept 62%');
+ });
+});
diff --git a/frontend/src/lib/map/analyzers.js b/frontend/src/lib/map/analyzers.js
new file mode 100644
index 0000000..0725050
--- /dev/null
+++ b/frontend/src/lib/map/analyzers.js
@@ -0,0 +1,138 @@
+/** Geographic analyzer inputs have no dependency on a screen or camera. */
+export const clone = (value) => JSON.parse(JSON.stringify(value));
+
+export function zoneMarks(zones) {
+ return zones.map((zone) => ({ ...zone, side: 'both', colour: '#38bdf8',
+ stroke_width: 2, fill_opacity: 0.08, font_size: 12, text: zone.name }));
+}
+
+export function marksToZones(marks, previous = []) {
+ return marks.filter((mark) => ['rect', 'polygon', 'ellipse'].includes(mark.kind)).map((mark, i) => ({
+ id: mark.id, name: previous.find((zone) => zone.id === mark.id)?.name || `Area ${i + 1}`,
+ kind: mark.kind, points: clone(mark.points),
+ }));
+}
+
+export function mapSource(side) {
+ if (!side || !['esri-wayback', 'sentinel2'].includes(side.provider)) return null;
+ return { provider: side.provider, date: side.sentinel?.date || '',
+ release: side.wayback_release ?? null, layer: side.sentinel?.layer || 'TRUE_COLOR',
+ maxcc: side.sentinel?.maxcc ?? 30 };
+}
+
+/** Display clustering changes only marker layout; persisted candidates stay intact. */
+export function displayGroups(rows, project, radius = 24) {
+ const groups = [];
+ for (const row of rows) {
+ const at = project(row.coordinates);
+ if (!Number.isFinite(at.x) || !Number.isFinite(at.y)) continue;
+ const near = groups.find((group) => Math.hypot(group.x - at.x, group.y - at.y) < radius);
+ if (near) near.rows.push(row);
+ else groups.push({ ...at, rows: [row] });
+ }
+ return groups;
+}
+
+export function sourceLabel(source) {
+ return source.provider === 'sentinel2'
+ ? `Sentinel-2 · ${source.date} · ${source.layer}`
+ : `Wayback · release ${source.release}`;
+}
+
+/** A zone's outline, the way the engine reads it: `Zone.ring()` in JavaScript. */
+export function zoneRing(zone) {
+ if (zone.kind === 'polygon') return zone.points;
+ const [[x1, y1], [x2, y2]] = zone.points;
+ if (zone.kind === 'rect') return [[x1, y1], [x2, y1], [x2, y2], [x1, y2]];
+ const [cx, cy, rx, ry] = [(x1 + x2) / 2, (y1 + y2) / 2, Math.abs(x2 - x1) / 2, Math.abs(y2 - y1) / 2];
+ return Array.from({ length: 64 }, (_, i) => {
+ const angle = (i * Math.PI * 2) / 64;
+ return [cx + rx * Math.cos(angle), cy + ry * Math.sin(angle)];
+ });
+}
+
+const mercator = (lon, lat) => [
+ (lon + 180) / 360,
+ (1 - Math.asinh(Math.tan((lat * Math.PI) / 180)) / Math.PI) / 2,
+];
+
+/**
+ * What a run will cost, before anything is fetched: ground area, and how many
+ * native tiles the areas touch. The tile count enumerates each zone's bounding
+ * box, where the engine masks the outline, so a diagonal polygon is counted
+ * high rather than low — a pre-flight number should never promise less work
+ * than the run does. The grid comes from the catalogue, so this cannot drift
+ * away from the engine's own levels.
+ */
+export function coverage(zones, grid) {
+ let metres = 0;
+ const tiles = new Set();
+ for (const zone of zones) {
+ const ring = zoneRing(zone);
+ if (ring.length < 3) continue;
+ // Shoelace on a local equirectangular plane: metres per degree of longitude
+ // shrink with latitude, and over one area that factor is near enough flat.
+ const mid = ring.reduce((sum, [, lat]) => sum + lat, 0) / ring.length;
+ const scale = Math.cos((mid * Math.PI) / 180) * 111_320;
+ let sum = 0;
+ for (let i = 0; i < ring.length; i++) {
+ const [x1, y1] = ring[i];
+ const [x2, y2] = ring[(i + 1) % ring.length];
+ sum += x1 * scale * (y2 * 111_320) - x2 * scale * (y1 * 111_320);
+ }
+ metres += Math.abs(sum) / 2;
+ if (!grid) continue;
+ const [zoom, size] = grid;
+ const count = 2 ** zoom;
+ const xs = ring.map(([lon, lat]) => mercator(lon, lat)[0]);
+ const ys = ring.map(([lon, lat]) => mercator(lon, lat)[1]);
+ const left = Math.floor(Math.min(...xs) * count);
+ const right = Math.ceil(Math.max(...xs) * count) - 1;
+ const top = Math.floor(Math.min(...ys) * count);
+ const bottom = Math.ceil(Math.max(...ys) * count) - 1;
+ if ((right - left + 1) * (bottom - top + 1) > 1e6) return { km2: Infinity, tiles: Infinity, size };
+ for (let y = Math.max(0, top); y <= Math.min(count - 1, bottom); y++) {
+ for (let x = Math.max(0, left); x <= Math.min(count - 1, right); x++) tiles.add(`${x}/${y}`);
+ }
+ }
+ return { km2: metres / 1e6, tiles: grid ? tiles.size : 0, size: grid?.[1] ?? 0 };
+}
+
+/**
+ * What a sweep costs in provider requests and in waiting.
+ *
+ * One frame is one request, and the request is what the run spends its time
+ * on — the detection itself is a few milliseconds a tile. The rate below is a
+ * round number for a network round trip, so the answer is an order of
+ * magnitude, and the panel says "about". Nobody should discover that an area
+ * meant forty minutes by starting it.
+ */
+export const SECONDS_PER_FRAME = 0.35;
+
+/** Frames fetched per tile: the picture reviewed, plus any bands measured. */
+export function framesPerTile({ single = false, bands = false } = {}) {
+ const pictures = single ? 1 : 2;
+ return bands ? pictures * 2 : pictures;
+}
+
+export function readableDuration(seconds) {
+ if (!Number.isFinite(seconds)) return 'a long time';
+ if (seconds < 90) return `${Math.max(1, Math.round(seconds))} s`;
+ if (seconds < 5400) return `${Math.round(seconds / 60)} min`;
+ return `${(seconds / 3600).toFixed(1)} h`;
+}
+
+/**
+ * The rectangle the camera is looking at, as a zone. Ids match the annotation
+ * marks the drawing canvas makes, because a zone and its mark are the same
+ * object seen from the panel and from the map.
+ */
+export function viewZone(bounds, name = 'Current view') {
+ const { west, south, east, north } = bounds;
+ return {
+ id: crypto.randomUUID(),
+ name,
+ kind: 'rect',
+ points: [[west, north], [east, south]],
+ };
+}
diff --git a/frontend/src/lib/map/analyzers.test.js b/frontend/src/lib/map/analyzers.test.js
new file mode 100644
index 0000000..c992a56
--- /dev/null
+++ b/frontend/src/lib/map/analyzers.test.js
@@ -0,0 +1,84 @@
+import { describe, expect, it } from 'vitest';
+import {
+ coverage,
+ displayGroups,
+ framesPerTile,
+ mapSource,
+ readableDuration,
+ marksToZones,
+ viewZone,
+ zoneMarks,
+ zoneRing,
+} from './analyzers.js';
+
+describe('saved analysis geometry', () => {
+ it('keeps geographic points and names when drawings are edited', () => {
+ const zones = [{ id: 'one', name: 'Port', kind: 'polygon', points: [[0, 0], [1, 0], [1, 1]] }];
+ const marks = zoneMarks(zones);
+ expect(marksToZones(marks, zones)).toEqual(zones);
+ expect(marksToZones([{ ...marks[0], points: [[2, 2], [3, 2], [3, 3]] }], zones)[0].name).toBe('Port');
+ });
+ it('restricts sources without silently converting another provider', () => {
+ expect(mapSource({ provider: 'google' })).toBeNull();
+ expect(mapSource({ provider: 'esri-world-imagery' })).toBeNull();
+ expect(mapSource({ provider: 'esri-wayback', wayback_release: 123 })).toMatchObject({ release: 123 });
+ });
+ it('changes screen clustering without changing saved detection geometry', () => {
+ const rows = [{ id: 1, coordinates: [1, 1] }, { id: 2, coordinates: [2, 1] }];
+ const before = JSON.stringify(rows);
+ expect(displayGroups(rows, ([x, y]) => ({ x, y }))).toHaveLength(1);
+ expect(displayGroups(rows, ([x, y]) => ({ x: x * 100, y }))).toHaveLength(2);
+ expect(JSON.stringify(rows)).toBe(before);
+ });
+ it('closes each kind of outline the way the engine does', () => {
+ expect(zoneRing({ kind: 'rect', points: [[0, 1], [2, 3]] }))
+ .toEqual([[0, 1], [2, 1], [2, 3], [0, 3]]);
+ expect(zoneRing({ kind: 'polygon', points: [[0, 0], [1, 0], [1, 1]] })).toHaveLength(3);
+ const ellipse = zoneRing({ kind: 'ellipse', points: [[0, 0], [2, 2]] });
+ expect(ellipse).toHaveLength(64);
+ expect(ellipse[0][0]).toBeCloseTo(2, 6);
+ expect(ellipse[16][1]).toBeCloseTo(2, 6);
+ });
+});
+
+describe('what a run will cost before it starts', () => {
+ const kmSquare = (size) => [{ id: 'a', kind: 'rect', points: [[0, 0], [size, size]] }];
+
+ it('reads ground area from the outline, not the bounding box', () => {
+ // A tenth of a degree at the equator is 11.132 km, so 123.9 km².
+ expect(coverage(kmSquare(0.1), null).km2).toBeCloseTo(123.92, 1);
+ const triangle = [{ id: 'a', kind: 'polygon', points: [[0, 0], [0.1, 0], [0.1, 0.1]] }];
+ expect(coverage(triangle, null).km2).toBeCloseTo(61.96, 1);
+ });
+
+ it('counts native tiles per grid, and never promises less work than the run', () => {
+ // Sentinel's 512px level-13 tiles are 4.9 km across; Wayback's are 76 m.
+ expect(coverage(kmSquare(0.01), [13, 512]).tiles).toBe(1);
+ expect(coverage(kmSquare(0.01), [19, 256]).tiles).toBe(225);
+ // Overlapping areas are the same tiles, counted once.
+ const twice = [...kmSquare(0.01), { id: 'b', kind: 'rect', points: [[0, 0], [0.005, 0.005]] }];
+ expect(coverage(twice, [19, 256]).tiles).toBe(225);
+ });
+
+ it('gives up rather than enumerate an impossible area', () => {
+ expect(coverage(kmSquare(5), [19, 256]).tiles).toBe(Infinity);
+ });
+
+ it('counts the requests a sweep makes, and says how long that is', () => {
+ expect(framesPerTile({ single: false })).toBe(2);
+ expect(framesPerTile({ single: true })).toBe(1);
+ // A band detector fetches the picture reviewed and the bands measured.
+ expect(framesPerTile({ single: true, bands: true })).toBe(2);
+ expect(framesPerTile({ single: false, bands: true })).toBe(4);
+ expect(readableDuration(20)).toBe('20 s');
+ expect(readableDuration(600)).toBe('10 min');
+ expect(readableDuration(7200)).toBe('2.0 h');
+ expect(readableDuration(Infinity)).toBe('a long time');
+ });
+
+ it('turns the camera into a rectangle the engine accepts', () => {
+ const zone = viewZone({ west: 2, south: 48, east: 3, north: 49 }, 'Harbour');
+ expect(zone).toMatchObject({ name: 'Harbour', kind: 'rect', points: [[2, 49], [3, 48]] });
+ expect(zone.id).toMatch(/^[a-z0-9-]{8,48}$/);
+ });
+});
diff --git a/frontend/src/lib/map/basemap.js b/frontend/src/lib/map/basemap.js
index ffd1e17..4346759 100644
--- a/frontend/src/lib/map/basemap.js
+++ b/frontend/src/lib/map/basemap.js
@@ -59,7 +59,9 @@ const OVERLAYS = [
url: nightTemplate,
attribution: 'Night lights: NASA EOSDIS GIBS, VIIRS',
maxZoom: 8,
- viewMaxZoom: 13,
+ // The native product is coarse, but it remains useful as a translucent
+ // context layer while reading a street or site at a deeper map zoom.
+ viewMaxZoom: 24,
// just enough of the ground through it to tell which street is lit
opacity: 0.85,
},
@@ -277,6 +279,8 @@ export function createBasemaps(engine, hooks = {}) {
const shown = new Map();
let wanted = null; // the provider id last asked for, so a slow load can tell
let metered = null; // the billed provider whose tiles we are counting
+ let current = null; // the provider the zoom cap was last taken from
+ let sharedCeiling = null; // a view zoom this map must not pass, whatever it shows
// Drawn shapes are appended by `surface.js`, so the first layer this module
// does not own is where the basemap stops and a tool's own marks begin.
@@ -326,7 +330,11 @@ export function createBasemaps(engine, hooks = {}) {
* while zoomed deep needs.
*/
function capZoom(provider) {
- map.setMaxZoom(provider.max_zoom - 1);
+ current = provider;
+ // A map linked to another one stops where the shallower of the two does,
+ // or the deeper one would pull its partner's camera past its pixels.
+ const deepest = Math.min(provider.max_zoom, sharedCeiling ?? Infinity);
+ map.setMaxZoom(deepest - 1);
}
function showTiles(provider, providerId, cell) {
@@ -458,6 +466,15 @@ export function createBasemaps(engine, hooks = {}) {
}
},
+ /**
+ * Cap the view zoom below the provider's own ceiling, or lift that cap with
+ * null. Compare hands both of its maps the shallower of their two ceilings.
+ */
+ setZoomCeiling(value) {
+ sharedCeiling = Number.isFinite(value) ? value : null;
+ if (current) capZoom(current);
+ },
+
dispose() {
map.off('sourcedata', onSourceData);
glass?.destroy();
diff --git a/frontend/src/lib/map/basemap.test.js b/frontend/src/lib/map/basemap.test.js
index e201bfe..5294d20 100644
--- a/frontend/src/lib/map/basemap.test.js
+++ b/frontend/src/lib/map/basemap.test.js
@@ -211,6 +211,18 @@ describe('the layers on a map', () => {
});
});
+ it('stops a linked map at the shallower of its own and the shared ceiling', async () => {
+ await withStubbedGoogle(async ({ createBasemaps }) => {
+ const map = stubMap();
+ const basemaps = createBasemaps(stubEngine(map));
+ basemaps.show({ ...ESRI, max_zoom: 19 }, ESRI.id, 256);
+ basemaps.setZoomCeiling(17);
+ basemaps.setZoomCeiling(21);
+ basemaps.setZoomCeiling(null);
+ expect(map.calls.setMaxZoom).toEqual([[18], [16], [18], [18]]);
+ });
+ });
+
it('leaves a layer alone when nothing about it changed', async () => {
// returning to the tab refetches the providers, and the fresh objects re-run
// the layer effect, so this is the common path rather than an edge case
@@ -531,7 +543,7 @@ describe('the layers on a map', () => {
expect(source.tiles[0]).toContain('/VIIRS_SNPP_DayNightBand_At_Sensor_Radiance/default/2022-02-24/');
expect(source.maxzoom).toBe(8);
const layer = map.getLayer('basemap-nightlights');
- expect(layer.maxzoom).toBe(13);
+ expect(layer.maxzoom).toBe(24);
expect(layer.paint['raster-opacity']).toBeLessThan(1);
basemaps.setOverlay('nightlights', true, { source: 'snpp', day: '2022-02-25' });
diff --git a/frontend/src/lib/map/cameraLink.js b/frontend/src/lib/map/cameraLink.js
new file mode 100644
index 0000000..4a8da13
--- /dev/null
+++ b/frontend/src/lib/map/cameraLink.js
@@ -0,0 +1,57 @@
+/**
+ * Several maps on one page, held on one camera.
+ *
+ * Compare puts two maps over the same ground. Whichever one the hand is on
+ * leads, and every other map copies its frame synchronously inside the same
+ * engine event, fractional zoom and bearing included. The copy is a jump, and
+ * a jump fires its own move events while it runs: `follow` marks the map as a
+ * copy for exactly that long, so those events are recognised and never sent
+ * back. Nothing is compared after the fact, which is where the previous
+ * approach (matching echoes by position) drifted apart after a resize.
+ *
+ * Only the leader settles on a whole zoom level (`engine.js`). Its settling
+ * animation is itself a run of move events, so the copies follow it too and
+ * come to rest on the same level in the same frame.
+ *
+ * Engine events are read here rather than through `on()`: this module is on
+ * the engine's side of the façade, and it needs every intermediate frame.
+ */
+
+/**
+ * @param {object[]} engines map façades (`facade.js`), in display order
+ * @returns {{ align: (from?: number) => void, dispose: () => void }}
+ */
+export function linkCameras(engines) {
+ const maps = engines.filter(Boolean);
+
+ function mirror(leader, settled) {
+ if (leader.following()) return;
+ const frame = leader.frame();
+ for (const peer of maps) {
+ if (peer !== leader) peer.follow(frame, { settled });
+ }
+ }
+
+ const releases = maps.map((engine) => {
+ const move = () => mirror(engine, false);
+ const end = () => mirror(engine, true);
+ engine.impl.on('move', move);
+ engine.impl.on('moveend', end);
+ return () => {
+ engine.impl.off('move', move);
+ engine.impl.off('moveend', end);
+ };
+ });
+
+ return {
+ /** Put every map back on one map's camera, after a layout change. */
+ align(from = 0) {
+ const leader = maps[from];
+ if (leader) mirror(leader, true);
+ },
+ dispose() {
+ for (const release of releases) release();
+ releases.length = 0;
+ },
+ };
+}
diff --git a/frontend/src/lib/map/cameraLink.test.js b/frontend/src/lib/map/cameraLink.test.js
new file mode 100644
index 0000000..72e99c7
--- /dev/null
+++ b/frontend/src/lib/map/cameraLink.test.js
@@ -0,0 +1,103 @@
+import { describe, expect, it, vi } from 'vitest';
+import { linkCameras } from './cameraLink.js';
+import { mapFacade } from './facade.js';
+
+/**
+ * A map whose jumps fire move events synchronously, the way the engine's own
+ * `jumpTo` does. That synchronicity is what the link's guard relies on.
+ */
+function fakeMap(frame = { lng: 2, lat: 48, zoom: 15, bearing: 0 }) {
+ const listeners = new Map();
+ const map = {
+ frame: { ...frame },
+ jumps: 0,
+ on(name, handler) {
+ if (!listeners.has(name)) listeners.set(name, new Set());
+ listeners.get(name).add(handler);
+ },
+ off(name, handler) {
+ listeners.get(name)?.delete(handler);
+ },
+ fire(name) {
+ for (const handler of [...(listeners.get(name) ?? [])]) handler({});
+ },
+ getCenter: () => ({ lng: map.frame.lng, lat: map.frame.lat }),
+ getZoom: () => map.frame.zoom,
+ getBearing: () => map.frame.bearing,
+ jumpTo({ center, zoom, bearing }) {
+ map.jumps += 1;
+ map.frame = { lng: center[0], lat: center[1], zoom, bearing };
+ map.fire('move');
+ map.fire('moveend');
+ },
+ /** What a gesture does: move the camera, then report it. */
+ gesture(next, { end = false } = {}) {
+ map.frame = { ...map.frame, ...next };
+ map.fire('move');
+ if (end) map.fire('moveend');
+ },
+ };
+ return map;
+}
+
+function pair() {
+ const leftMap = fakeMap();
+ const rightMap = fakeMap({ lng: 30, lat: 10, zoom: 4, bearing: 0 });
+ return { leftMap, rightMap, left: mapFacade(leftMap), right: mapFacade(rightMap) };
+}
+
+describe('linked map cameras', () => {
+ it('copies a live gesture frame by frame, fractional zoom and bearing included', () => {
+ const { leftMap, rightMap, left, right } = pair();
+ linkCameras([left, right]);
+ leftMap.gesture({ lng: 2.5, lat: 48.2, zoom: 15.37, bearing: -12 });
+ expect(rightMap.frame).toEqual({ lng: 2.5, lat: 48.2, zoom: 15.37, bearing: -12 });
+ });
+
+ it('never sends a copied frame back to the map that led it', () => {
+ const { leftMap, rightMap, left, right } = pair();
+ linkCameras([left, right]);
+ leftMap.gesture({ zoom: 15.5 }, { end: true });
+ // one jump per leader event (move, moveend) and none coming back
+ expect(rightMap.jumps).toBe(2);
+ expect(leftMap.jumps).toBe(0);
+ });
+
+ it('reports a settled view on the copy only for the leader’s last frame', () => {
+ const { leftMap, right, left } = pair();
+ const settled = vi.fn();
+ right.on('view-settled', settled);
+ linkCameras([left, right]);
+ leftMap.gesture({ zoom: 15.4 });
+ leftMap.gesture({ zoom: 15.8 });
+ expect(settled).not.toHaveBeenCalled();
+ leftMap.gesture({ zoom: 16 }, { end: true });
+ expect(settled).toHaveBeenCalledOnce();
+ expect(settled.mock.calls[0][0].zoom).toBe(17);
+ });
+
+ it('marks the copy as following only while the jump runs', () => {
+ const { leftMap, rightMap, left, right } = pair();
+ const seen = [];
+ rightMap.on('move', () => seen.push(right.following()));
+ linkCameras([left, right]);
+ leftMap.gesture({ zoom: 12 });
+ expect(seen).toEqual([true]);
+ expect(right.following()).toBe(false);
+ });
+
+ it('realigns every map on one of them after a layout change', () => {
+ const { rightMap, left, right } = pair();
+ const link = linkCameras([left, right]);
+ link.align(0);
+ expect(rightMap.frame).toEqual({ lng: 2, lat: 48, zoom: 15, bearing: 0 });
+ });
+
+ it('stops following once disposed', () => {
+ const { leftMap, rightMap, left, right } = pair();
+ const link = linkCameras([left, right]);
+ link.dispose();
+ leftMap.gesture({ zoom: 9 }, { end: true });
+ expect(rightMap.jumps).toBe(0);
+ });
+});
diff --git a/frontend/src/lib/map/changeAssist.js b/frontend/src/lib/map/changeAssist.js
new file mode 100644
index 0000000..34ac094
--- /dev/null
+++ b/frontend/src/lib/map/changeAssist.js
@@ -0,0 +1,244 @@
+/**
+ * What Change assist is allowed to read, and the settings it reads with.
+ *
+ * A pixel difference is only worth showing when both pictures come from one
+ * rendering chain: a highlighted provider or style difference would otherwise
+ * pass for a change on the ground. `changeCompatibility` answers that before
+ * anything is computed, and grades a fair pair as `matched` (one product, one
+ * render) or `indicative` (one chain, but something the analyst should keep in
+ * mind). `api/compare.py` refuses the same pairs on save.
+ *
+ * The detection itself lives in `changeDetect.js` and runs in a worker.
+ */
+
+const same = (left, right) => JSON.stringify(left) === JSON.stringify(right);
+
+export const CHANGE_METHODS = Object.freeze([
+ { id: 'colour', label: 'Colour', hint: 'Perceptual colour distance. The general reading.' },
+ { id: 'structure', label: 'Structure', hint: 'Edges that appear or vanish. Steadier across seasons and sensors.' },
+ { id: 'brightness', label: 'Brightness', hint: 'Lighter or darker only. Suits night lights and burn scars.' },
+ { id: 'index', label: 'Spectral index', hint: 'Real Sentinel-2 bands for both dates, fetched on demand.' },
+]);
+
+export const CHANGE_INDICES = Object.freeze([
+ { id: 'ndvi', label: 'NDVI', hint: 'Vegetation', gain: 'Greener', loss: 'Vegetation lost' },
+ { id: 'ndwi', label: 'NDWI', hint: 'Water', gain: 'Wetter', loss: 'Water receded' },
+ { id: 'nbr', label: 'NBR', hint: 'Burn scars', gain: 'Recovered', loss: 'Burnt' },
+ { id: 'ndbi', label: 'NDBI', hint: 'Built-up', gain: 'Built or cleared', loss: 'Less built-up' },
+]);
+
+export const CHANGE_DISPLAYS = Object.freeze([
+ { id: 'classes', label: 'Classes' },
+ { id: 'heat', label: 'Heat' },
+ { id: 'outline', label: 'Outline' },
+]);
+
+export const CHANGE_PALETTES = Object.freeze({
+ directional: Object.freeze({
+ gain: [34, 197, 94],
+ loss: [239, 68, 68],
+ changed: [250, 204, 21],
+ }),
+ // Okabe-Ito hues: distinguishable under the common red/green deficiencies.
+ colourblind: Object.freeze({
+ gain: [0, 114, 178],
+ loss: [230, 159, 0],
+ changed: [204, 121, 167],
+ }),
+ // Direction still reads through hue, but the three sit on one warm ramp so a
+ // heat display stays legible over green vegetation and blue water.
+ thermal: Object.freeze({
+ gain: [255, 214, 10],
+ loss: [120, 40, 200],
+ changed: [255, 120, 30],
+ }),
+});
+
+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.
+ */
+export const CHANGE_BASES = Object.freeze([
+ { id: 'a', label: 'A' },
+ { id: 'b', label: 'B' },
+ { id: 'side', label: 'Both' },
+]);
+
+export const CHANGE_DEFAULTS = Object.freeze({
+ method: 'colour',
+ index: 'ndvi',
+ threshold: 'auto',
+ sensitivity: 55,
+ normalize: 'histogram',
+ smoothing: 1,
+ alignment: 4,
+ cleanup: 1,
+ min_area: 0,
+ ignore_clouds: false,
+ ignore_shadows: false,
+ // A cloud fades out at its edges and its shadow has no edge at all, so both
+ // masks stop short of where a reader would put the cloud. Growing them takes
+ // the fringe that otherwise survives as a ring of highlights around the mask.
+ cloud_margin: 2,
+ classes: ['gain', 'loss', 'changed'],
+ display: 'classes',
+ palette: 'directional',
+ zones: true,
+ opacity: 70,
+ base: 'b',
+ visible: true,
+ live: true,
+});
+
+const pick = (value, allowed, fallback) => (allowed.includes(value) ? value : fallback);
+const whole = (value, min, max, fallback) => {
+ const number = Number(value);
+ return Number.isFinite(number) ? Math.min(max, Math.max(min, Math.round(number))) : fallback;
+};
+
+/** Every setting inside its range, whatever a saved session or a slider held. */
+export function changeSettings(raw = {}) {
+ const value = raw && typeof raw === 'object' ? raw : {};
+ const classes = Array.isArray(value.classes)
+ ? CHANGE_CLASSES.filter((entry) => value.classes.includes(entry))
+ : [...CHANGE_DEFAULTS.classes];
+ const area = Number(value.min_area);
+ return {
+ method: pick(value.method, CHANGE_METHODS.map((entry) => entry.id), CHANGE_DEFAULTS.method),
+ index: pick(value.index, CHANGE_INDICES.map((entry) => entry.id), CHANGE_DEFAULTS.index),
+ threshold: pick(value.threshold, ['auto', 'manual'], CHANGE_DEFAULTS.threshold),
+ sensitivity: whole(value.sensitivity, 0, 100, CHANGE_DEFAULTS.sensitivity),
+ normalize: pick(value.normalize, ['none', 'mean', 'histogram'], CHANGE_DEFAULTS.normalize),
+ smoothing: whole(value.smoothing, 0, 4, CHANGE_DEFAULTS.smoothing),
+ alignment: whole(value.alignment, 0, 8, CHANGE_DEFAULTS.alignment),
+ cleanup: whole(value.cleanup, 0, 3, CHANGE_DEFAULTS.cleanup),
+ min_area: Number.isFinite(area) ? Math.min(1_000_000, Math.max(0, area)) : 0,
+ ignore_clouds: value.ignore_clouds ?? CHANGE_DEFAULTS.ignore_clouds,
+ ignore_shadows: value.ignore_shadows ?? CHANGE_DEFAULTS.ignore_shadows,
+ cloud_margin: whole(value.cloud_margin, 0, 10, CHANGE_DEFAULTS.cloud_margin),
+ classes,
+ display: pick(value.display, CHANGE_DISPLAYS.map((entry) => entry.id), CHANGE_DEFAULTS.display),
+ palette: pick(value.palette, Object.keys(CHANGE_PALETTES), CHANGE_DEFAULTS.palette),
+ 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,
+ live: value.live !== false,
+ };
+}
+
+function layerReading(side, skipped) {
+ return (side?.overlays ?? [])
+ .filter((id) => id !== skipped)
+ .map((id) => {
+ if (id === 'firms') return [id, side.firms];
+ if (id === 'nightlights') return [id, side.nightlights];
+ return [id];
+ });
+}
+
+const refuse = (reason) => ({ ok: false, reason, methods: [] });
+const PIXEL_METHODS = ['colour', 'structure', 'brightness'];
+const ESRI = new Set(['esri-world-imagery', 'esri-wayback']);
+
+/**
+ * Whether a pixel reading of this pair is honest, and how much to trust it.
+ *
+ * @returns {{ ok: boolean, reason?: string, grade?: 'matched'|'indicative',
+ * label?: string, from?: string, to?: string, notes?: string[], methods: string[] }}
+ */
+export function changeCompatibility(a, b) {
+ if (!a?.present || !b?.present) return refuse('Add imagery A and B first.');
+ if (a.widget || b.widget) {
+ return refuse('Change assist needs app-rendered pixels, not a web map widget.');
+ }
+
+ if (a.provider === 'sentinel2' && b.provider === 'sentinel2') {
+ const dateA = a.sentinel?.effectiveDate || a.sentinel?.date;
+ const dateB = b.sentinel?.effectiveDate || b.sentinel?.date;
+ if (!dateA || !dateB || dateA === dateB) {
+ return refuse('Choose two different dated Sentinel-2 passes.');
+ }
+ const notes = [];
+ const methods = ['index'];
+ if (a.sentinel?.layer === b.sentinel?.layer && same(layerReading(a), layerReading(b))) {
+ methods.unshift(...PIXEL_METHODS);
+ } else {
+ notes.push('Pixel methods need the same layer and reference layers on A and B.');
+ }
+ if (a.sentinel?.maxcc !== b.sentinel?.maxcc) {
+ notes.push('The two sides use different cloud ceilings.');
+ }
+ return {
+ ok: true,
+ grade: notes.length ? 'indicative' : 'matched',
+ label: `Sentinel-2 · ${String(a.sentinel.layer).replace(/_/g, ' ')}`,
+ from: dateA,
+ to: dateB,
+ notes,
+ 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';
+ if (a.provider === b.provider && releaseA === releaseB) {
+ return refuse('Choose two different Esri releases.');
+ }
+ if (!same(layerReading(a), layerReading(b))) {
+ return refuse('Match the reference layers on A and B before comparing pixels.');
+ }
+ const mixed = a.provider !== b.provider;
+ return {
+ ok: true,
+ grade: mixed ? 'indicative' : 'matched',
+ label: mixed ? 'Esri World Imagery and Wayback' : 'Esri Wayback',
+ from: releaseA == null ? 'latest' : String(releaseA),
+ to: releaseB == null ? 'latest' : String(releaseB),
+ notes: [
+ ...(mixed ? ['World Imagery is the live mosaic, so its date varies from place to place.'] : []),
+ 'Releases often share pixels, so an unchanged spot is not proof of no change.',
+ ],
+ methods: PIXEL_METHODS,
+ };
+ }
+
+ const nightA = (a.overlays ?? []).includes('nightlights');
+ const nightB = (b.overlays ?? []).includes('nightlights');
+ if (nightA && nightB) {
+ if (a.provider !== b.provider) {
+ return refuse('Night lights need the same background imagery on A and B.');
+ }
+ if (a.nightlights?.source !== b.nightlights?.source) {
+ return refuse('Night lights need the same VIIRS product on A and B.');
+ }
+ if (a.nightlights?.source === 'composite') {
+ return refuse('The night-light composite has one date only.');
+ }
+ if (!a.nightlights?.day || !b.nightlights?.day || a.nightlights.day === b.nightlights.day) {
+ return refuse('Choose two different nights from the same VIIRS sensor.');
+ }
+ if (!same(a.sentinel, b.sentinel) || a.waybackRelease !== b.waybackRelease) {
+ return refuse('Match the background imagery on A and B before comparing night lights.');
+ }
+ if (!same(layerReading(a, 'nightlights'), layerReading(b, 'nightlights'))) {
+ return refuse('Match every other layer on A and B before comparing night lights.');
+ }
+ return {
+ ok: true,
+ grade: 'matched',
+ label: `VIIRS · ${a.nightlights.source === 'noaa20' ? 'NOAA-20' : 'Suomi NPP'}`,
+ from: a.nightlights.day,
+ to: b.nightlights.day,
+ notes: ['Moonlight and cloud change a single night. Compare several before concluding.'],
+ methods: ['brightness', 'colour'],
+ };
+ }
+
+ return refuse('Change assist reads Sentinel-2 passes, Esri releases or VIIRS night lights.');
+}
diff --git a/frontend/src/lib/map/changeAssist.test.js b/frontend/src/lib/map/changeAssist.test.js
new file mode 100644
index 0000000..3fbadc1
--- /dev/null
+++ b/frontend/src/lib/map/changeAssist.test.js
@@ -0,0 +1,109 @@
+import { describe, expect, it } from 'vitest';
+import { CHANGE_DEFAULTS, changeCompatibility, changeSettings } from './changeAssist.js';
+
+const side = (patch = {}) => ({
+ present: true,
+ provider: 'esri-wayback',
+ overlays: [],
+ sentinel: { layer: 'TRUE_COLOR', date: '', effectiveDate: '', maxcc: 100 },
+ waybackRelease: 1,
+ nightlights: { source: 'noaa20', day: '2026-09-01' },
+ ...patch,
+});
+
+const sentinel = (date, patch = {}) =>
+ side({
+ provider: 'sentinel2',
+ sentinel: { layer: 'TRUE_COLOR', effectiveDate: date, maxcc: 40, ...patch },
+ });
+
+describe('which pairs Change assist reads', () => {
+ it('reads two Wayback releases as matched when unrelated layers agree', () => {
+ expect(changeCompatibility(side(), side({ waybackRelease: 2 }))).toMatchObject({
+ ok: true,
+ grade: 'matched',
+ methods: ['colour', 'structure', 'brightness'],
+ });
+ expect(
+ changeCompatibility(side({ overlays: ['roads'] }), side({ waybackRelease: 2 }))
+ ).toMatchObject({ ok: false, reason: expect.stringContaining('layers') });
+ expect(changeCompatibility(side(), side())).toMatchObject({ ok: false });
+ });
+
+ it('reads World Imagery against a Wayback release as indicative, with the reason', () => {
+ const answer = changeCompatibility(side({ provider: 'esri-world-imagery' }), side());
+ expect(answer).toMatchObject({ ok: true, grade: 'indicative' });
+ expect(answer.notes.join(' ')).toContain('live mosaic');
+ });
+
+ it('reads dated Sentinel-2 passes, and offers indices even across layers', () => {
+ expect(changeCompatibility(sentinel('2026-08-01'), sentinel('2026-09-01'))).toMatchObject({
+ ok: true,
+ grade: 'matched',
+ methods: ['colour', 'structure', 'brightness', 'index'],
+ });
+ const acrossLayers = changeCompatibility(
+ sentinel('2026-08-01'),
+ sentinel('2026-09-01', { layer: 'SWIR', maxcc: 10 })
+ );
+ expect(acrossLayers).toMatchObject({ ok: true, grade: 'indicative', methods: ['index'] });
+ expect(acrossLayers.notes).toHaveLength(2);
+ expect(changeCompatibility(sentinel('2026-08-01'), sentinel('2026-08-01'))).toMatchObject({
+ ok: false,
+ });
+ });
+
+ it('refuses cross-provider pixels, widgets and mismatched VIIRS products', () => {
+ expect(changeCompatibility(side(), side({ provider: 'osm' }))).toMatchObject({ ok: false });
+ expect(changeCompatibility(side({ widget: true }), side({ waybackRelease: 2 }))).toMatchObject({
+ ok: false,
+ reason: expect.stringContaining('widget'),
+ });
+ expect(
+ changeCompatibility(
+ side({ provider: 'osm', overlays: ['nightlights'] }),
+ side({ provider: 'osm', overlays: ['nightlights'], nightlights: { source: 'snpp', day: '2026-09-02' } })
+ )
+ ).toMatchObject({ ok: false, reason: expect.stringContaining('same VIIRS') });
+ });
+
+ it('reads two nights of one sensor with brightness first', () => {
+ const night = (day) =>
+ side({ provider: 'osm', overlays: ['nightlights'], nightlights: { source: 'noaa20', day } });
+ expect(changeCompatibility(night('2026-01-01'), night('2026-02-01'))).toMatchObject({
+ ok: true,
+ methods: ['brightness', 'colour'],
+ });
+ });
+});
+
+describe('Change assist settings', () => {
+ it('fills a missing or older session with the defaults', () => {
+ expect(changeSettings({})).toEqual({ ...CHANGE_DEFAULTS, classes: ['gain', 'loss', 'changed'] });
+ expect(changeSettings({ normalize: true, noise: 3 })).toMatchObject({ normalize: 'histogram' });
+ });
+
+ it('keeps every value inside its range', () => {
+ expect(
+ changeSettings({
+ method: 'ratio',
+ sensitivity: 400,
+ smoothing: -2,
+ alignment: 8.6,
+ min_area: -5,
+ classes: ['loss', 'nope', 'loss'],
+ opacity: '35',
+ base: 'c',
+ })
+ ).toMatchObject({
+ method: 'colour',
+ sensitivity: 100,
+ smoothing: 0,
+ alignment: 8,
+ min_area: 0,
+ classes: ['loss'],
+ opacity: 35,
+ base: 'b',
+ });
+ });
+});
diff --git a/frontend/src/lib/map/changeCapture.js b/frontend/src/lib/map/changeCapture.js
new file mode 100644
index 0000000..302d089
--- /dev/null
+++ b/frontend/src/lib/map/changeCapture.js
@@ -0,0 +1,58 @@
+/** Capture-sized change detection, with on-demand spectral frames. */
+import { runChangeDetection } from './changeRunner.js';
+import { compose, frameBox, groundPerPixel, imageToMercator, invert, scale, screenToMercator } from './groundFrame.js';
+
+export async function spectralPixels(frame, width, height, side, index) {
+ const box = frameBox(frame);
+ const response = await fetch('/api/compare/sentinel-index', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ ...box, width, height, day: side.sentinel.effectiveDate || side.sentinel.date,
+ maxcc: side.sentinel.maxcc, layer: side.sentinel.layer, index }),
+ });
+ if (!response.ok) {
+ const body = await response.json().catch(() => ({}));
+ throw new Error(typeof body.detail === 'string' ? body.detail : `Spectral request failed (${response.status})`);
+ }
+ const bitmap = await createImageBitmap(await response.blob());
+ try {
+ const canvas = document.createElement('canvas');
+ canvas.width = width;
+ canvas.height = height;
+ const ctx = canvas.getContext('2d');
+ const matrix = compose(scale(width / frame.width), compose(invert(screenToMercator(frame)), imageToMercator(box, width, height)));
+ ctx.imageSmoothingEnabled = false;
+ ctx.setTransform(matrix.a, matrix.b, matrix.c, matrix.d, matrix.e, matrix.f);
+ ctx.drawImage(bitmap, 0, 0);
+ return ctx.getImageData(0, 0, width, height).data;
+ } finally {
+ bitmap.close();
+ }
+}
+
+export async function detectCaptures(sources, settings, sides) {
+ const frame = sources.a.frame;
+ const ratio = Math.min(1, 1536 / Math.max(sources.a.canvas.width, sources.a.canvas.height));
+ const width = Math.max(1, Math.round(sources.a.canvas.width * ratio));
+ const height = Math.max(1, Math.round(sources.a.canvas.height * ratio));
+ const pixels = (source) => {
+ const canvas = document.createElement('canvas');
+ canvas.width = width;
+ canvas.height = height;
+ const context = canvas.getContext('2d');
+ context.drawImage(source.canvas, 0, 0, width, height);
+ return context.getImageData(0, 0, width, height).data;
+ };
+ let index = null;
+ if (settings.method === 'index') {
+ const [a, b] = await Promise.all(sides.map((side) => spectralPixels(frame, width, height, side, settings.index)));
+ index = { a, b };
+ }
+ const result = await runChangeDetection({ a: pixels(sources.a), b: pixels(sources.b), width, height,
+ settings, index, metresPerPixel: groundPerPixel(frame) * frame.width / width });
+ const canvas = document.createElement('canvas');
+ canvas.width = width;
+ canvas.height = height;
+ canvas.getContext('2d').putImageData(new ImageData(result.pixels, width, height), 0, 0);
+ return { ...result, canvas, frame };
+}
diff --git a/frontend/src/lib/map/changeCapture.test.js b/frontend/src/lib/map/changeCapture.test.js
new file mode 100644
index 0000000..c48b016
--- /dev/null
+++ b/frontend/src/lib/map/changeCapture.test.js
@@ -0,0 +1,69 @@
+// @vitest-environment happy-dom
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { changeSettings } from './changeAssist.js';
+
+const runChangeDetection = vi.fn(async ({ width, height }) => ({
+ pixels: new Uint8ClampedArray(width * height * 4), width, height, counts: {},
+}));
+vi.mock('./changeRunner.js', () => ({ runChangeDetection }));
+const { detectCaptures, spectralPixels } = await import('./changeCapture.js');
+const frame = { lng: 2.3, lat: 48.8, zoom: 15, bearing: 35, width: 800, height: 600 };
+const contexts = [];
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ contexts.length = 0;
+ vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockImplementation(function () {
+ const context = {
+ drawImage: vi.fn(), setTransform: vi.fn(), putImageData: vi.fn(),
+ getImageData: vi.fn(() => ({ data: new Uint8ClampedArray(this.width * this.height * 4) })),
+ };
+ contexts.push(context);
+ return context;
+ });
+ vi.stubGlobal('ImageData', class {
+ constructor(data, width, height) { Object.assign(this, { data, width, height }); }
+ });
+ vi.stubGlobal('fetch', vi.fn());
+});
+
+afterEach(() => { vi.restoreAllMocks(); vi.unstubAllGlobals(); });
+
+describe('captured change frames', () => {
+ it('bounds worker frames and retains their exact ground frame without network', async () => {
+ const capture = { canvas: { width: 1600, height: 1200 }, frame };
+ const result = await detectCaptures({ a: capture, b: capture }, changeSettings(), []);
+ expect(result.frame).toEqual(frame);
+ expect(result.canvas.width).toBe(1536);
+ expect(result.canvas.height).toBe(1152);
+ expect(runChangeDetection).toHaveBeenCalledWith(expect.objectContaining({
+ width: 1536, height: 1152, index: null, metresPerPixel: expect.any(Number),
+ }));
+ expect(fetch).not.toHaveBeenCalled();
+ });
+
+ it('requests the named pass and projects its index pixels onto a rotated frame', async () => {
+ const bitmap = { close: vi.fn() };
+ vi.stubGlobal('createImageBitmap', vi.fn(async () => bitmap));
+ fetch.mockResolvedValue({ ok: true, blob: async () => new Blob() });
+ const data = await spectralPixels(frame, 80, 60, {
+ sentinel: { date: '2026-09-01', layer: 'TRUE_COLOR', maxcc: 30 },
+ }, 'ndvi');
+ expect(data.length).toBe(80 * 60 * 4);
+ const [url, request] = fetch.mock.calls[0];
+ expect(url).toBe('/api/compare/sentinel-index');
+ expect(request.method).toBe('POST');
+ expect(JSON.parse(request.body)).toMatchObject({ day: '2026-09-01', index: 'ndvi', maxcc: 30, width: 80, height: 60 });
+ const matrix = contexts[0].setTransform.mock.calls[0];
+ expect(matrix.every(Number.isFinite)).toBe(true);
+ expect(matrix[1]).not.toBe(0);
+ expect(bitmap.close).toHaveBeenCalledOnce();
+ });
+
+ it('reports a quota refusal without decoding or computing a mask', async () => {
+ fetch.mockResolvedValue({ ok: false, status: 429, json: async () => ({ detail: 'Sentinel Hub is paused' }) });
+ await expect(spectralPixels(frame, 80, 60, { sentinel: { date: '2026-09-01' } }, 'ndvi'))
+ .rejects.toThrow('Sentinel Hub is paused');
+ expect(runChangeDetection).not.toHaveBeenCalled();
+ });
+});
diff --git a/frontend/src/lib/map/changeDetect.js b/frontend/src/lib/map/changeDetect.js
new file mode 100644
index 0000000..fcf1197
--- /dev/null
+++ b/frontend/src/lib/map/changeDetect.js
@@ -0,0 +1,681 @@
+/**
+ * Change detection over two registered frames of the same ground.
+ *
+ * Pure and synchronous, so it runs the same in the worker (`changeWorker.js`)
+ * and under test. Every buffer is RGBA at one working size; the caller
+ * downsamples the map canvases first. The pipeline:
+ *
+ * 1. **Register.** A small integer shift that best lays B over A absorbs the
+ * sub-tile offsets two renders can carry.
+ * 2. **Match tone.** B's channels are moved onto A's, by mean or by histogram,
+ * so a hazier or brighter day is not read as change everywhere.
+ * 3. **Measure.** One signed difference per pixel: perceptual colour distance,
+ * lightness, edge strength, or a real spectral index when both are given.
+ * 4. **Mask.** Pixels without data, and optionally cloud and shadow, drop out.
+ * 5. **Threshold.** Otsu's split of the difference histogram, or the analyst's
+ * own level, over a floor that keeps rendering noise out.
+ * 6. **Clean.** A morphological opening removes speckle, a closing fills pinholes.
+ * 7. **Group.** Connected regions become zones with an area on the ground,
+ * a dominant direction and a score; zones under the minimum area go.
+ * 8. **Draw.** Classes, a continuous heat ramp or outlines, into a mask whose
+ * alpha carries the strength.
+ */
+
+import { CHANGE_PALETTES, changeSettings } from './changeAssist.js';
+
+const clamp = (value, min, max) => Math.min(max, Math.max(min, value));
+
+// -- colour -------------------------------------------------------------------
+
+const LINEAR = new Float32Array(256);
+for (let value = 0; value < 256; value += 1) {
+ const channel = value / 255;
+ LINEAR[value] = channel <= 0.04045 ? channel / 12.92 : ((channel + 0.055) / 1.055) ** 2.4;
+}
+
+const labF = (t) => (t > 0.008856 ? Math.cbrt(t) : 7.787 * t + 16 / 116);
+
+/** sRGB bytes to CIE L*a*b* (D65), the space a colour distance means something in. */
+export function toLab(red, green, blue, out = [0, 0, 0]) {
+ const r = LINEAR[red];
+ const g = LINEAR[green];
+ const b = LINEAR[blue];
+ const x = labF((r * 0.4124 + g * 0.3576 + b * 0.1805) / 0.95047);
+ const y = labF(r * 0.2126 + g * 0.7152 + b * 0.0722);
+ const z = labF((r * 0.0193 + g * 0.1192 + b * 0.9505) / 1.08883);
+ out[0] = 116 * y - 16;
+ out[1] = 500 * (x - y);
+ out[2] = 200 * (y - z);
+ return out;
+}
+
+// -- registration and tone ------------------------------------------------------
+
+const luminanceAt = (pixels, index) =>
+ pixels[index] * 0.2126 + pixels[index + 1] * 0.7152 + pixels[index + 2] * 0.0722;
+
+/** The small integer translation that best registers B onto A. */
+export function estimateAlignment(left, right, width, height, maximum = 4) {
+ const limit = Math.min(
+ Math.floor((Math.min(width, height) - 1) / 2),
+ Math.round(clamp(Number(maximum) || 0, 0, 8)),
+ );
+ if (!limit) return { x: 0, y: 0, score: 0 };
+ const step = Math.max(2, Math.floor(Math.min(width, height) / 160));
+ let best = { x: 0, y: 0, score: Infinity };
+ for (let dy = -limit; dy <= limit; dy += 1) {
+ for (let dx = -limit; dx <= limit; dx += 1) {
+ let score = 0;
+ let samples = 0;
+ for (let y = limit; y < height - limit; y += step) {
+ for (let x = limit; x < width - limit; x += step) {
+ const li = (y * width + x) * 4;
+ const ri = ((y + dy) * width + x + dx) * 4;
+ if (left[li + 3] < 200 || right[ri + 3] < 200) continue;
+ score += Math.abs(luminanceAt(left, li) - luminanceAt(right, ri));
+ samples += 1;
+ }
+ }
+ const average = samples ? score / samples : Infinity;
+ // ties keep the smaller shift, so a flat frame is never "registered" sideways
+ if (average < best.score - 1e-9) best = { x: dx, y: dy, score: average };
+ }
+ }
+ return best;
+}
+
+/** Shift B by the registration offset, leaving no-data where it has no pixels. */
+function shifted(right, width, height, offset) {
+ if (!offset.x && !offset.y) return right;
+ const out = new Uint8ClampedArray(right.length);
+ for (let y = 0; y < height; y += 1) {
+ const sy = y + offset.y;
+ if (sy < 0 || sy >= height) continue;
+ for (let x = 0; x < width; x += 1) {
+ const sx = x + offset.x;
+ if (sx < 0 || sx >= width) continue;
+ const to = (y * width + x) * 4;
+ const from = (sy * width + sx) * 4;
+ out[to] = right[from];
+ out[to + 1] = right[from + 1];
+ out[to + 2] = right[from + 2];
+ out[to + 3] = right[from + 3];
+ }
+ }
+ return out;
+}
+
+/** B's three channels moved onto A's, by their means or by their whole histograms. */
+export function matchTone(left, right, mode = 'histogram') {
+ if (mode !== 'mean' && mode !== 'histogram') return right;
+ const out = new Uint8ClampedArray(right);
+ for (let channel = 0; channel < 3; channel += 1) {
+ const histA = new Float64Array(256);
+ const histB = new Float64Array(256);
+ let count = 0;
+ for (let index = 0; index < left.length; index += 4) {
+ if (left[index + 3] < 200 || right[index + 3] < 200) continue;
+ histA[left[index + channel]] += 1;
+ histB[right[index + channel]] += 1;
+ count += 1;
+ }
+ if (!count) continue;
+ const lookup = new Uint8ClampedArray(256);
+ if (mode === 'mean') {
+ let sumA = 0;
+ let sumB = 0;
+ for (let value = 0; value < 256; value += 1) {
+ sumA += histA[value] * value;
+ sumB += histB[value] * value;
+ }
+ const shift = clamp((sumA - sumB) / count, -80, 80);
+ for (let value = 0; value < 256; value += 1) lookup[value] = value + shift;
+ } else {
+ let cumulativeA = 0;
+ let cumulativeB = 0;
+ let target = 0;
+ for (let value = 0; value < 256; value += 1) {
+ cumulativeB += histB[value];
+ while (target < 255 && cumulativeA + histA[target] < cumulativeB) {
+ cumulativeA += histA[target];
+ target += 1;
+ }
+ lookup[value] = target;
+ }
+ }
+ for (let index = 0; index < out.length; index += 4) {
+ out[index + channel] = lookup[right[index + channel]];
+ }
+ }
+ return out;
+}
+
+// -- measuring ------------------------------------------------------------------
+
+function sobel(lightness, width, height) {
+ const out = new Float32Array(width * height);
+ for (let y = 1; y < height - 1; y += 1) {
+ for (let x = 1; x < width - 1; x += 1) {
+ const i = y * width + x;
+ const gx =
+ -lightness[i - width - 1] - 2 * lightness[i - 1] - lightness[i + width - 1] +
+ lightness[i - width + 1] + 2 * lightness[i + 1] + lightness[i + width + 1];
+ const gy =
+ -lightness[i - width - 1] - 2 * lightness[i - width] - lightness[i - width + 1] +
+ lightness[i + width - 1] + 2 * lightness[i + width] + lightness[i + width + 1];
+ out[i] = Math.hypot(gx, gy) / 4;
+ }
+ }
+ return out;
+}
+
+/** Decode an index frame (`engine/sentinel.py`): R = index, G = scene class, A = data. */
+export function decodeIndex(pixels) {
+ const count = pixels.length / 4;
+ const value = new Float32Array(count);
+ const scene = new Uint8Array(count);
+ const valid = new Uint8Array(count);
+ for (let pixel = 0; pixel < count; pixel += 1) {
+ const index = pixel * 4;
+ value[pixel] = pixels[index] / 127.5 - 1;
+ scene[pixel] = pixels[index + 1];
+ valid[pixel] = pixels[index + 3] > 127 ? 1 : 0;
+ }
+ return { value, scene, valid };
+}
+
+// Sentinel-2 L2A scene classes: 3 cloud shadow, 8–10 cloud and cirrus, 11 snow.
+const SHADOW_CLASSES = new Set([3]);
+const CLOUD_CLASSES = new Set([8, 9, 10]);
+
+/**
+ * Grow a flag array by `radius`, separably: a horizontal pass then a vertical
+ * one, which is the same result as a square dilation for a fraction of the work.
+ *
+ * Both cloud masks stop short of where a reader would put the cloud's edge —
+ * a classification calls the soft rim ground, and a brightness test loses the
+ * rim where it fades. That rim is where the ring of highlights around every
+ * mask comes from, so the mask is grown rather than trusted as drawn.
+ */
+export function growMask(flags, width, height, radius) {
+ if (!radius) return flags;
+ const wide = new Uint8Array(flags.length);
+ for (let y = 0; y < height; y += 1) {
+ const row = y * width;
+ for (let x = 0; x < width; x += 1) {
+ if (!flags[row + x]) continue;
+ const from = Math.max(0, x - radius);
+ const to = Math.min(width - 1, x + radius);
+ for (let near = from; near <= to; near += 1) wide[row + near] = 1;
+ }
+ }
+ const grown = new Uint8Array(flags.length);
+ for (let y = 0; y < height; y += 1) {
+ const from = Math.max(0, y - radius);
+ const to = Math.min(height - 1, y + radius);
+ for (let x = 0; x < width; x += 1) {
+ if (!wide[y * width + x]) continue;
+ for (let near = from; near <= to; near += 1) grown[near * width + x] = 1;
+ }
+ }
+ return grown;
+}
+
+/**
+ * One signed difference per pixel and the pixels it is valid for.
+ * `magnitude` is on a 0…255 scale for every method, so one threshold rule fits.
+ */
+export function measure(left, right, width, height, settings, index = null) {
+ const count = width * height;
+ const magnitude = new Float32Array(count);
+ const direction = new Int8Array(count);
+ const chroma = new Uint8Array(count);
+ const valid = new Uint8Array(count);
+
+ const masking = settings.ignore_clouds || settings.ignore_shadows;
+
+ if (settings.method === 'index' && index) {
+ const a = decodeIndex(index.a);
+ const b = decodeIndex(index.b);
+ // Cloud on either date invalidates the pixel: a difference is a measurement
+ // only when both sides of it are ground.
+ let blocked = new Uint8Array(count);
+ if (masking) {
+ for (let pixel = 0; pixel < count; pixel += 1) {
+ const clouded = CLOUD_CLASSES.has(a.scene[pixel]) || CLOUD_CLASSES.has(b.scene[pixel]);
+ const shaded = SHADOW_CLASSES.has(a.scene[pixel]) || SHADOW_CLASSES.has(b.scene[pixel]);
+ if ((settings.ignore_clouds && clouded) || (settings.ignore_shadows && shaded)) {
+ blocked[pixel] = 1;
+ }
+ }
+ blocked = growMask(blocked, width, height, settings.cloud_margin);
+ }
+ for (let pixel = 0; pixel < count; pixel += 1) {
+ if (!a.valid[pixel] || !b.valid[pixel] || blocked[pixel]) continue;
+ const delta = b.value[pixel] - a.value[pixel];
+ valid[pixel] = 1;
+ // a full index swing of 1.0 reads as 255
+ magnitude[pixel] = Math.min(255, Math.abs(delta) * 255);
+ direction[pixel] = delta > 0 ? 1 : -1;
+ }
+ return { magnitude, direction, chroma, valid };
+ }
+
+ const lightA = new Float32Array(count);
+ const lightB = new Float32Array(count);
+ const labA = new Float32Array(count * 2);
+ const labB = new Float32Array(count * 2);
+ const labOfA = [0, 0, 0];
+ const labOfB = [0, 0, 0];
+ // Cloud reads as near-white with no colour, shadow as near-black. There is no
+ // scene classification behind a rendered picture, so this is a guess — it is
+ // offered as an option, and the panel says as much, for exactly that reason.
+ const cloudy = (lab) => lab[0] > 86 && Math.hypot(lab[1], lab[2]) < 12;
+ const shaded = (lab) => lab[0] < 10;
+ let blocked = new Uint8Array(count);
+ const inFrame = new Uint8Array(count);
+ for (let pixel = 0; pixel < count; pixel += 1) {
+ const i = pixel * 4;
+ if (left[i + 3] < 200 || right[i + 3] < 200) continue;
+ toLab(left[i], left[i + 1], left[i + 2], labOfA);
+ toLab(right[i], right[i + 1], right[i + 2], labOfB);
+ lightA[pixel] = labOfA[0];
+ lightB[pixel] = labOfB[0];
+ labA[pixel * 2] = labOfA[1];
+ labA[pixel * 2 + 1] = labOfA[2];
+ labB[pixel * 2] = labOfB[1];
+ labB[pixel * 2 + 1] = labOfB[2];
+ inFrame[pixel] = 1;
+ if (settings.ignore_clouds && (cloudy(labOfA) || cloudy(labOfB))) blocked[pixel] = 1;
+ else if (settings.ignore_shadows && (shaded(labOfA) || shaded(labOfB))) blocked[pixel] = 1;
+ }
+ if (masking) blocked = growMask(blocked, width, height, settings.cloud_margin);
+ for (let pixel = 0; pixel < count; pixel += 1) {
+ if (inFrame[pixel] && !blocked[pixel]) valid[pixel] = 1;
+ }
+
+ if (settings.method === 'structure') {
+ const edgesA = sobel(lightA, width, height);
+ const edgesB = sobel(lightB, width, height);
+ for (let pixel = 0; pixel < count; pixel += 1) {
+ if (!valid[pixel]) continue;
+ const delta = edgesB[pixel] - edgesA[pixel];
+ magnitude[pixel] = Math.min(255, Math.abs(delta) * 4);
+ direction[pixel] = delta > 0 ? 1 : -1;
+ }
+ return { magnitude, direction, chroma, valid };
+ }
+
+ for (let pixel = 0; pixel < count; pixel += 1) {
+ if (!valid[pixel]) continue;
+ const dl = lightB[pixel] - lightA[pixel];
+ if (settings.method === 'brightness') {
+ magnitude[pixel] = Math.min(255, Math.abs(dl) * 2.55);
+ direction[pixel] = dl > 0 ? 1 : -1;
+ continue;
+ }
+ const da = labB[pixel * 2] - labA[pixel * 2];
+ const db = labB[pixel * 2 + 1] - labA[pixel * 2 + 1];
+ const distance = Math.hypot(dl, da, db);
+ magnitude[pixel] = Math.min(255, distance * 2.55);
+ // A change is directional when lightness carries most of it; a hue shift
+ // at the same lightness (roof repainted, crop turned) is "changed".
+ const chromatic = Math.hypot(da, db);
+ if (Math.abs(dl) >= chromatic * 0.8) direction[pixel] = dl > 0 ? 1 : -1;
+ else chroma[pixel] = 1;
+ }
+ return { magnitude, direction, chroma, valid };
+}
+
+// -- filtering and thresholds -----------------------------------------------------
+
+/** Box blur of a float field, by a summed-area table so the radius costs nothing. */
+export function boxBlur(field, width, height, radius, valid) {
+ if (!radius) return field;
+ const stride = width + 1;
+ const sums = new Float64Array(stride * (height + 1));
+ const counts = new Float64Array(stride * (height + 1));
+ for (let y = 0; y < height; y += 1) {
+ let row = 0;
+ let rowCount = 0;
+ for (let x = 0; x < width; x += 1) {
+ const pixel = y * width + x;
+ if (valid[pixel]) {
+ row += field[pixel];
+ rowCount += 1;
+ }
+ sums[(y + 1) * stride + x + 1] = sums[y * stride + x + 1] + row;
+ counts[(y + 1) * stride + x + 1] = counts[y * stride + x + 1] + rowCount;
+ }
+ }
+ const out = new Float32Array(field.length);
+ for (let y = 0; y < height; y += 1) {
+ const top = Math.max(0, y - radius);
+ const bottom = Math.min(height, y + radius + 1);
+ for (let x = 0; x < width; x += 1) {
+ const pixel = y * width + x;
+ if (!valid[pixel]) continue;
+ const left = Math.max(0, x - radius);
+ const right = Math.min(width, x + radius + 1);
+ const total = sums[bottom * stride + right] - sums[top * stride + right]
+ - sums[bottom * stride + left] + sums[top * stride + left];
+ const n = counts[bottom * stride + right] - counts[top * stride + right]
+ - counts[bottom * stride + left] + counts[top * stride + left];
+ out[pixel] = n ? total / n : 0;
+ }
+ }
+ return out;
+}
+
+/** Otsu's threshold over a 0…255 field: the split that best separates two populations. */
+export function otsu(field, valid) {
+ const histogram = new Float64Array(256);
+ let total = 0;
+ for (let pixel = 0; pixel < field.length; pixel += 1) {
+ if (!valid[pixel]) continue;
+ histogram[Math.min(255, Math.round(field[pixel]))] += 1;
+ total += 1;
+ }
+ if (!total) return 0;
+ let sum = 0;
+ for (let value = 0; value < 256; value += 1) sum += value * histogram[value];
+ let background = 0;
+ let backgroundSum = 0;
+ let best = 0;
+ let threshold = 0;
+ let plateauEnd = 0;
+ for (let value = 0; value < 256; value += 1) {
+ background += histogram[value];
+ if (!background) continue;
+ const foreground = total - background;
+ if (!foreground) break;
+ backgroundSum += value * histogram[value];
+ const meanBackground = backgroundSum / background;
+ const meanForeground = (sum - backgroundSum) / foreground;
+ const between = background * foreground * (meanBackground - meanForeground) ** 2;
+ if (between > best * (1 + 1e-9)) {
+ best = between;
+ threshold = value;
+ plateauEnd = value;
+ } else if (between >= best * (1 - 1e-9)) {
+ plateauEnd = value;
+ }
+ }
+ // Two clean populations leave a plateau of equally good splits between them;
+ // its middle is the one that sits furthest from both.
+ return (threshold + plateauEnd) / 2;
+}
+
+/** The level below which nothing counts: what a re-render of the same pixels leaves. */
+const FLOORS = { colour: 18, brightness: 16, structure: 22, index: 38 };
+
+export function thresholdFor(field, valid, settings) {
+ const floor = FLOORS[settings.method] ?? 18;
+ const lean = (settings.sensitivity - 50) / 50; // -1 … 1
+ if (settings.threshold === 'manual') {
+ // 0 % asks for only the strongest changes, 100 % reaches down to the floor
+ return floor + (1 - settings.sensitivity / 100) * (200 - floor);
+ }
+ const split = otsu(field, valid);
+ return Math.max(floor * (1 - lean * 0.35), split * (1 - lean * 0.45));
+}
+
+/**
+ * A square min (erode) or max (dilate) filter, run as a row pass then a column
+ * pass: the same result as the full square at a fraction of the work.
+ */
+function squareFilter(mask, width, height, radius, keepIfAll) {
+ const pass = (source, horizontal) => {
+ const out = new Uint8Array(source.length);
+ const outer = horizontal ? height : width;
+ const inner = horizontal ? width : height;
+ for (let o = 0; o < outer; o += 1) {
+ for (let i = 0; i < inner; i += 1) {
+ let hit = keepIfAll ? 1 : 0;
+ for (let k = i - radius; k <= i + radius; k += 1) {
+ const inside = k >= 0 && k < inner;
+ const value = inside ? source[horizontal ? o * width + k : k * width + o] : 0;
+ if (keepIfAll && !value) { hit = 0; break; }
+ if (!keepIfAll && value) { hit = 1; break; }
+ }
+ out[horizontal ? o * width + i : i * width + o] = hit;
+ }
+ }
+ return out;
+ };
+ return pass(pass(mask, true), false);
+}
+
+const erode = (mask, width, height, radius) => squareFilter(mask, width, height, radius, true);
+const dilate = (mask, width, height, radius) => squareFilter(mask, width, height, radius, false);
+
+/** Opening then closing: speckle smaller than the radius goes, pinholes fill. */
+export function cleanMask(mask, width, height, radius) {
+ if (!radius) return mask;
+ const opened = dilate(erode(mask, width, height, radius), width, height, radius);
+ return erode(dilate(opened, width, height, 1), width, height, 1);
+}
+
+// -- zones ------------------------------------------------------------------------
+
+/**
+ * Connected regions of the mask, each with its extent, its area on the ground
+ * and its dominant direction. Returned in frame fractions so a caller can place
+ * them on whichever map they belong to.
+ */
+export function findZones(mask, classes, strength, width, height, metresPerPixel, minimumArea = 0) {
+ const labels = new Int32Array(mask.length);
+ const zones = [];
+ const stack = [];
+ const cellArea = metresPerPixel > 0 ? metresPerPixel * metresPerPixel : 0;
+ let next = 0;
+ for (let start = 0; start < mask.length; start += 1) {
+ if (!mask[start] || labels[start]) continue;
+ next += 1;
+ labels[start] = next;
+ stack.push(start);
+ const zone = {
+ id: next, pixels: 0, gain: 0, loss: 0, changed: 0, strength: 0,
+ minX: width, minY: height, maxX: 0, maxY: 0, sumX: 0, sumY: 0,
+ };
+ while (stack.length) {
+ const pixel = stack.pop();
+ const x = pixel % width;
+ const y = (pixel - x) / width;
+ zone.pixels += 1;
+ zone.strength += strength[pixel];
+ zone.sumX += x;
+ zone.sumY += y;
+ if (x < zone.minX) zone.minX = x;
+ if (x > zone.maxX) zone.maxX = x;
+ if (y < zone.minY) zone.minY = y;
+ if (y > zone.maxY) zone.maxY = y;
+ const group = classes[pixel];
+ if (group === 1) zone.gain += 1;
+ else if (group === 2) zone.loss += 1;
+ else zone.changed += 1;
+ for (let dy = -1; dy <= 1; dy += 1) {
+ const ny = y + dy;
+ if (ny < 0 || ny >= height) continue;
+ for (let dx = -1; dx <= 1; dx += 1) {
+ const nx = x + dx;
+ if (nx < 0 || nx >= width) continue;
+ const neighbour = ny * width + nx;
+ if (mask[neighbour] && !labels[neighbour]) {
+ labels[neighbour] = next;
+ stack.push(neighbour);
+ }
+ }
+ }
+ }
+ zones.push(zone);
+ }
+
+ const kept = new Set();
+ const out = [];
+ for (const zone of zones) {
+ const area = zone.pixels * cellArea;
+ if (cellArea && area < minimumArea) continue;
+ kept.add(zone.id);
+ const kind = zone.gain >= zone.loss && zone.gain >= zone.changed
+ ? 'gain'
+ : zone.loss >= zone.changed ? 'loss' : 'changed';
+ const intensity = zone.strength / zone.pixels / 255;
+ out.push({
+ id: zone.id,
+ kind,
+ pixels: zone.pixels,
+ area,
+ intensity: Math.round(intensity * 100) / 100,
+ score: zone.pixels * intensity,
+ box: {
+ x1: zone.minX / width,
+ y1: zone.minY / height,
+ x2: (zone.maxX + 1) / width,
+ y2: (zone.maxY + 1) / height,
+ },
+ centre: { x: (zone.sumX / zone.pixels + 0.5) / width, y: (zone.sumY / zone.pixels + 0.5) / height },
+ });
+ }
+ out.sort((left, right) => right.score - left.score);
+ return { zones: out, labels, kept };
+}
+
+// -- drawing ----------------------------------------------------------------------
+
+/** A warm ramp from transparent violet to white-hot yellow, for the heat display. */
+function heatColour(t) {
+ const stops = [
+ [0, [60, 16, 110]],
+ [0.35, [180, 40, 120]],
+ [0.65, [245, 110, 40]],
+ [1, [255, 236, 120]],
+ ];
+ for (let i = 1; i < stops.length; i += 1) {
+ if (t <= stops[i][0]) {
+ const [p0, c0] = stops[i - 1];
+ const [p1, c1] = stops[i];
+ const k = (t - p0) / (p1 - p0);
+ return c0.map((value, channel) => Math.round(value + (c1[channel] - value) * k));
+ }
+ }
+ return stops.at(-1)[1];
+}
+
+const CLASS_CODE = { gain: 1, loss: 2, changed: 3 };
+
+/**
+ * @param {object} input
+ * @param {Uint8ClampedArray} input.a RGBA frame of A
+ * @param {Uint8ClampedArray} input.b RGBA frame of B, same size
+ * @param {number} input.width
+ * @param {number} input.height
+ * @param {object} input.settings see `changeSettings`
+ * @param {number} [input.metresPerPixel] ground size of one working pixel
+ * @param {{a: Uint8ClampedArray, b: Uint8ClampedArray}} [input.index] index frames
+ */
+export function detectChange({ a, b, width, height, settings: raw, metresPerPixel = 0, index = null }) {
+ if (!a || !b || a.length !== b.length || a.length !== width * height * 4) {
+ throw new Error('change frames must have the same pixel geometry');
+ }
+ const settings = changeSettings(raw);
+ if (settings.method === 'index' && (!index?.a || !index?.b)) {
+ throw new Error('the spectral index frames are missing');
+ }
+ const count = width * height;
+ const usesPixels = settings.method !== 'index';
+ const offset = usesPixels
+ ? estimateAlignment(a, b, width, height, settings.alignment)
+ : { x: 0, y: 0, score: 0 };
+ const registered = usesPixels ? shifted(b, width, height, offset) : b;
+ const toned = usesPixels ? matchTone(a, registered, settings.normalize) : registered;
+ const measured = measure(a, toned, width, height, settings, index);
+ const field = boxBlur(measured.magnitude, width, height, settings.smoothing, measured.valid);
+ const threshold = thresholdFor(field, measured.valid, settings);
+
+ const wanted = new Set(settings.classes.map((entry) => CLASS_CODE[entry]));
+ const classes = new Uint8Array(count);
+ const candidate = new Uint8Array(count);
+ let validPixels = 0;
+ for (let pixel = 0; pixel < count; pixel += 1) {
+ if (!measured.valid[pixel]) continue;
+ validPixels += 1;
+ if (field[pixel] < threshold) continue;
+ const group = measured.chroma[pixel] ? 3 : measured.direction[pixel] > 0 ? 1 : 2;
+ classes[pixel] = group;
+ if (wanted.has(group)) candidate[pixel] = 1;
+ }
+ const mask = cleanMask(candidate, width, height, settings.cleanup);
+ for (let pixel = 0; pixel < count; pixel += 1) {
+ // a pinhole the closing filled takes the class of what surrounds it
+ if (mask[pixel] && !classes[pixel]) {
+ const x = pixel % width;
+ const neighbour = [pixel - 1, pixel + 1, pixel - width, pixel + width]
+ .find((near) => near >= 0 && near < count && classes[near] && Math.abs((near % width) - x) <= 1);
+ classes[pixel] = neighbour == null ? 3 : classes[neighbour];
+ }
+ }
+
+ const { zones, labels, kept } = findZones(
+ mask, classes, field, width, height, metresPerPixel, settings.min_area
+ );
+
+ const palette = CHANGE_PALETTES[settings.palette] ?? CHANGE_PALETTES.directional;
+ const colourOf = { 1: palette.gain, 2: palette.loss, 3: palette.changed };
+ const pixels = new Uint8ClampedArray(count * 4);
+ const counts = { gained: 0, lost: 0, changed: 0, quiet: 0 };
+ const ceiling = Math.max(threshold + 1, 160);
+ for (let pixel = 0; pixel < count; pixel += 1) {
+ const inZone = mask[pixel] && kept.has(labels[pixel]);
+ if (!inZone) {
+ if (measured.valid[pixel]) counts.quiet += 1;
+ continue;
+ }
+ const group = classes[pixel];
+ if (group === 1) counts.gained += 1;
+ else if (group === 2) counts.lost += 1;
+ else counts.changed += 1;
+ const t = clamp((field[pixel] - threshold) / (ceiling - threshold), 0, 1);
+ const i = pixel * 4;
+ if (settings.display === 'outline') {
+ const x = pixel % width;
+ const edge =
+ x === 0 || x === width - 1 || pixel < width || pixel >= count - width ||
+ labels[pixel - 1] !== labels[pixel] || labels[pixel + 1] !== labels[pixel] ||
+ labels[pixel - width] !== labels[pixel] || labels[pixel + width] !== labels[pixel];
+ const colour = colourOf[group];
+ pixels[i] = colour[0];
+ pixels[i + 1] = colour[1];
+ pixels[i + 2] = colour[2];
+ pixels[i + 3] = edge ? 255 : 38;
+ } else if (settings.display === 'heat') {
+ const colour = heatColour(t);
+ pixels[i] = colour[0];
+ pixels[i + 1] = colour[1];
+ pixels[i + 2] = colour[2];
+ pixels[i + 3] = Math.round(90 + t * 165);
+ } else {
+ const colour = colourOf[group];
+ pixels[i] = colour[0];
+ pixels[i + 1] = colour[1];
+ pixels[i + 2] = colour[2];
+ pixels[i + 3] = Math.round(110 + t * 145);
+ }
+ }
+
+ const changedPixels = counts.gained + counts.lost + counts.changed;
+ return {
+ pixels,
+ width,
+ height,
+ counts,
+ zones: zones.slice(0, 250),
+ zoneCount: zones.length,
+ threshold: Math.round(threshold * 10) / 10,
+ offset: { x: offset.x, y: offset.y },
+ share: validPixels ? changedPixels / validPixels : 0,
+ coverage: count ? validPixels / count : 0,
+ area: changedPixels * metresPerPixel * metresPerPixel,
+ settings,
+ };
+}
diff --git a/frontend/src/lib/map/changeDetect.test.js b/frontend/src/lib/map/changeDetect.test.js
new file mode 100644
index 0000000..4608e8c
--- /dev/null
+++ b/frontend/src/lib/map/changeDetect.test.js
@@ -0,0 +1,255 @@
+import { describe, expect, it } from 'vitest';
+import {
+ boxBlur,
+ cleanMask,
+ decodeIndex,
+ detectChange,
+ estimateAlignment,
+ findZones,
+ matchTone,
+ otsu,
+ toLab,
+} from './changeDetect.js';
+
+/** An opaque frame filled with one colour, and a way to paint rectangles on it. */
+function frame(width, height, colour = [90, 110, 80]) {
+ const pixels = new Uint8ClampedArray(width * height * 4);
+ for (let index = 0; index < pixels.length; index += 4) {
+ pixels.set([...colour, 255], index);
+ }
+ return {
+ pixels,
+ paint(x1, y1, x2, y2, rgb) {
+ for (let y = y1; y < y2; y += 1) {
+ for (let x = x1; x < x2; x += 1) pixels.set([...rgb, 255], (y * width + x) * 4);
+ }
+ return this;
+ },
+ };
+}
+
+const settings = (patch = {}) => ({
+ method: 'colour',
+ threshold: 'auto',
+ sensitivity: 55,
+ normalize: 'none',
+ smoothing: 0,
+ alignment: 0,
+ cleanup: 0,
+ ...patch,
+});
+
+describe('colour', () => {
+ it('converts sRGB to Lab on the standard white and black points', () => {
+ const white = toLab(255, 255, 255);
+ expect(white[0]).toBeCloseTo(100, 0);
+ expect(Math.abs(white[1])).toBeLessThan(0.5);
+ expect(toLab(0, 0, 0)[0]).toBeCloseTo(0, 5);
+ });
+});
+
+describe('preparing the pair', () => {
+ it('finds a small translation that registers B onto A', () => {
+ const a = frame(24, 24, [0, 0, 0]).paint(8, 8, 12, 12, [240, 240, 240]);
+ const b = frame(24, 24, [0, 0, 0]).paint(10, 7, 14, 11, [240, 240, 240]);
+ expect(estimateAlignment(a.pixels, b.pixels, 24, 24, 4)).toMatchObject({ x: 2, y: -1 });
+ });
+
+ it('moves B’s tones onto A so a brighter day is not change everywhere', () => {
+ const a = frame(10, 10, [80, 80, 80]).paint(0, 0, 5, 10, [40, 40, 40]);
+ const b = frame(10, 10, [130, 130, 130]).paint(0, 0, 5, 10, [90, 90, 90]);
+ for (const mode of ['mean', 'histogram']) {
+ const toned = matchTone(a.pixels, b.pixels, mode);
+ expect(toned[0]).toBeCloseTo(40, -1);
+ expect(toned[(9 * 10 + 9) * 4]).toBeCloseTo(80, -1);
+ }
+ expect(matchTone(a.pixels, b.pixels, 'none')).toBe(b.pixels);
+ });
+});
+
+describe('thresholds and filters', () => {
+ it('splits a two-population field between its modes', () => {
+ const field = new Float32Array([...Array(80).fill(10), ...Array(20).fill(200)]);
+ const split = otsu(field, new Uint8Array(100).fill(1));
+ expect(split).toBeGreaterThanOrEqual(10);
+ expect(split).toBeLessThan(200);
+ });
+
+ it('blurs only over valid pixels', () => {
+ const field = new Float32Array([0, 90, 0, 0]);
+ const blurred = boxBlur(field, 2, 2, 1, new Uint8Array([1, 1, 1, 0]));
+ expect(blurred[0]).toBeCloseTo(30);
+ expect(blurred[3]).toBe(0);
+ });
+
+ it('drops speckle smaller than the cleanup radius and keeps solid regions', () => {
+ const width = 12;
+ const mask = new Uint8Array(width * width);
+ mask[2 * width + 2] = 1; // one stray pixel
+ for (let y = 5; y < 10; y += 1) for (let x = 5; x < 10; x += 1) mask[y * width + x] = 1;
+ const cleaned = cleanMask(mask, width, width, 1);
+ expect(cleaned[2 * width + 2]).toBe(0);
+ expect(cleaned[7 * width + 7]).toBe(1);
+ });
+});
+
+describe('zones', () => {
+ it('groups connected pixels with their area on the ground and dominant direction', () => {
+ const width = 10;
+ const mask = new Uint8Array(100);
+ const classes = new Uint8Array(100);
+ const strength = new Float32Array(100).fill(128);
+ for (let y = 1; y < 3; y += 1) for (let x = 1; x < 4; x += 1) {
+ mask[y * width + x] = 1;
+ classes[y * width + x] = 2;
+ }
+ mask[88] = 1;
+ classes[88] = 1;
+ const { zones } = findZones(mask, classes, strength, width, 10, 2, 10);
+ expect(zones).toHaveLength(1);
+ expect(zones[0]).toMatchObject({ kind: 'loss', pixels: 6, area: 24 });
+ expect(zones[0].box).toEqual({ x1: 0.1, y1: 0.1, x2: 0.4, y2: 0.3 });
+ });
+});
+
+describe('detecting change', () => {
+ it('finds a new bright roof as a gain and nothing where the ground is the same', () => {
+ const a = frame(40, 40);
+ const b = frame(40, 40).paint(10, 10, 20, 18, [235, 230, 220]);
+ const result = detectChange({
+ a: a.pixels, b: b.pixels, width: 40, height: 40,
+ settings: settings(), metresPerPixel: 0.5,
+ });
+ expect(result.counts.gained).toBe(80);
+ expect(result.counts.lost + result.counts.changed).toBe(0);
+ expect(result.zones).toHaveLength(1);
+ expect(result.zones[0]).toMatchObject({ kind: 'gain', area: 20 });
+ expect(result.pixels[(12 * 40 + 12) * 4 + 3]).toBeGreaterThan(0);
+ expect(result.pixels[3]).toBe(0);
+ });
+
+ it('reads a hue shift at the same lightness as another change, not a gain', () => {
+ const a = frame(30, 30, [120, 120, 120]).paint(5, 5, 15, 15, [170, 60, 60]);
+ const b = frame(30, 30, [120, 120, 120]).paint(5, 5, 15, 15, [40, 125, 60]);
+ const result = detectChange({ a: a.pixels, b: b.pixels, width: 30, height: 30, settings: settings() });
+ expect(result.counts.changed).toBeGreaterThan(90);
+ expect(result.counts.gained).toBe(0);
+ });
+
+ it('shows only the classes asked for, and drops zones under the minimum area', () => {
+ const a = frame(40, 40).paint(25, 25, 35, 35, [230, 230, 230]);
+ const b = frame(40, 40).paint(2, 2, 6, 6, [230, 230, 230]);
+ const losses = detectChange({
+ a: a.pixels, b: b.pixels, width: 40, height: 40,
+ settings: settings({ classes: ['loss'] }), metresPerPixel: 1,
+ });
+ expect(losses.counts.gained).toBe(0);
+ expect(losses.zones.map((zone) => zone.kind)).toEqual(['loss']);
+ const bigOnly = detectChange({
+ a: a.pixels, b: b.pixels, width: 40, height: 40,
+ settings: settings({ min_area: 50 }), metresPerPixel: 1,
+ });
+ expect(bigOnly.zones).toHaveLength(1);
+ expect(bigOnly.counts.gained).toBe(0);
+ });
+
+ it('ignores a uniform tone shift once tones are matched', () => {
+ const a = frame(30, 30, [80, 90, 70]).paint(0, 0, 15, 30, [60, 70, 50]);
+ const b = frame(30, 30, [120, 130, 110]).paint(0, 0, 15, 30, [100, 110, 90]);
+ const raw = detectChange({ a: a.pixels, b: b.pixels, width: 30, height: 30, settings: settings({ threshold: 'manual', sensitivity: 90 }) });
+ const toned = detectChange({ a: a.pixels, b: b.pixels, width: 30, height: 30, settings: settings({ threshold: 'manual', sensitivity: 90, normalize: 'histogram' }) });
+ expect(raw.share).toBeGreaterThan(0.9);
+ expect(toned.share).toBe(0);
+ });
+
+ it('reads structure, so a new wall shows even when its colour matches the ground', () => {
+ const a = frame(40, 40, [120, 120, 120]);
+ const b = frame(40, 40, [120, 120, 120]).paint(10, 10, 30, 30, [60, 60, 60]);
+ const result = detectChange({
+ a: a.pixels, b: b.pixels, width: 40, height: 40,
+ settings: settings({ method: 'structure', threshold: 'manual', sensitivity: 80 }),
+ });
+ expect(result.counts.gained).toBeGreaterThan(0);
+ // the inside of a flat patch has no edges of its own
+ expect(result.pixels[(20 * 40 + 20) * 4 + 3]).toBe(0);
+ });
+
+ /** Index frames with a cloud class from column `cloudFrom` rightwards. */
+ const indexFrame = (width, value, cloudFrom = 99) => {
+ const pixels = new Uint8ClampedArray(width * width * 4);
+ for (let pixel = 0; pixel < width * width; pixel += 1) {
+ const x = pixel % width;
+ pixels.set([Math.round((value(x) + 1) * 127.5), x >= cloudFrom ? 9 : 4, 0, 255], pixel * 4);
+ }
+ return pixels;
+ };
+
+ it('reads a real spectral index, masking clouded pixels', () => {
+ const width = 20;
+ const before = indexFrame(width, () => 0.7);
+ const after = indexFrame(width, (x) => (x < 10 ? 0.7 : -0.1), 16);
+ const blank = new Uint8ClampedArray(width * width * 4);
+ const result = detectChange({
+ a: blank, b: blank, width, height: width,
+ settings: settings({ method: 'index', ignore_clouds: true, cloud_margin: 0 }),
+ index: { a: before, b: after },
+ });
+ expect(result.counts.lost).toBe(6 * width);
+ expect(result.coverage).toBeCloseTo(16 / 20);
+ expect(decodeIndex(after).value[0]).toBeCloseTo(0.7, 1);
+ expect(() => detectChange({
+ a: blank, b: blank, width, height: width, settings: settings({ method: 'index' }),
+ })).toThrow('index frames');
+ });
+
+ it('grows the cloud mask by the margin, taking the edge it left behind', () => {
+ // A classification calls a cloud's soft rim ground, and that rim is where
+ // the ring of highlights around every mask comes from.
+ const width = 20;
+ const before = indexFrame(width, () => 0.7);
+ const after = indexFrame(width, (x) => (x < 10 ? 0.7 : -0.1), 16);
+ const blank = new Uint8ClampedArray(width * width * 4);
+ const read = (cloud_margin) => detectChange({
+ a: blank, b: blank, width, height: width,
+ settings: settings({ method: 'index', ignore_clouds: true, cloud_margin }),
+ index: { a: before, b: after },
+ });
+ // columns 10…15 changed and 16… are cloud; a 2px margin eats 14 and 15 too
+ expect(read(2).counts.lost).toBe(4 * width);
+ expect(read(2).coverage).toBeCloseTo(14 / 20);
+ // and the margin only ever costs what it says: off, the edge is exact
+ expect(read(0).counts.lost).toBe(6 * width);
+ });
+
+ it('leaves every pixel alone when nothing is being masked', () => {
+ // The margin must not eat anything on its own: it grows a mask, and with
+ // both switches off there is no mask to grow.
+ const width = 20;
+ const before = indexFrame(width, () => 0.7);
+ const after = indexFrame(width, (x) => (x < 10 ? 0.7 : -0.1), 16);
+ const blank = new Uint8ClampedArray(width * width * 4);
+ const result = detectChange({
+ a: blank, b: blank, width, height: width,
+ settings: settings({ method: 'index', cloud_margin: 4 }),
+ index: { a: before, b: after },
+ });
+ expect(result.counts.lost).toBe(10 * width);
+ expect(result.coverage).toBeCloseTo(1);
+ });
+
+ it('draws outlines and a heat ramp from the same zones', () => {
+ const a = frame(30, 30);
+ const b = frame(30, 30).paint(5, 5, 20, 20, [240, 240, 240]);
+ const outline = detectChange({ a: a.pixels, b: b.pixels, width: 30, height: 30, settings: settings({ display: 'outline' }) });
+ expect(outline.pixels[(5 * 30 + 10) * 4 + 3]).toBe(255);
+ expect(outline.pixels[(12 * 30 + 12) * 4 + 3]).toBeLessThan(60);
+ const heat = detectChange({ a: a.pixels, b: b.pixels, width: 30, height: 30, settings: settings({ display: 'heat' }) });
+ expect(heat.pixels[(12 * 30 + 12) * 4 + 3]).toBeGreaterThan(89);
+ });
+
+ it('refuses frames of different sizes', () => {
+ expect(() => detectChange({
+ a: new Uint8ClampedArray(16), b: new Uint8ClampedArray(12), width: 2, height: 2, settings: {},
+ })).toThrow('same pixel geometry');
+ });
+});
diff --git a/frontend/src/lib/map/changeRunner.js b/frontend/src/lib/map/changeRunner.js
new file mode 100644
index 0000000..85909bc
--- /dev/null
+++ b/frontend/src/lib/map/changeRunner.js
@@ -0,0 +1,58 @@
+/**
+ * Hand a change detection to the worker, or run it here where there is none.
+ *
+ * One worker, started on first use and kept: Change assist reruns on every
+ * settled camera, and a worker's start-up would cost more than the work. A
+ * newer request does not cancel an older one in the worker (a computation
+ * cannot be interrupted), so callers compare their own request number.
+ */
+import { detectChange } from './changeDetect.js';
+
+let worker = null;
+let serial = 0;
+const pending = new Map();
+
+function startWorker() {
+ if (worker || typeof Worker === 'undefined') return worker;
+ try {
+ worker = new Worker(new URL('./changeWorker.js', import.meta.url), { type: 'module' });
+ } catch {
+ worker = null;
+ return null;
+ }
+ worker.onmessage = (event) => {
+ const { id, result, error } = event.data;
+ const waiting = pending.get(id);
+ if (!waiting) return;
+ pending.delete(id);
+ if (error) waiting.reject(new Error(error));
+ else waiting.resolve(result);
+ };
+ worker.onerror = (event) => {
+ const failure = new Error(event.message || 'the change worker stopped');
+ for (const waiting of pending.values()) waiting.reject(failure);
+ pending.clear();
+ worker?.terminate();
+ worker = null;
+ };
+ return worker;
+}
+
+/** @param {Parameters<typeof detectChange>[0]} input */
+export function runChangeDetection(input) {
+ const running = startWorker();
+ if (!running) {
+ return new Promise((resolve, reject) => {
+ try {
+ resolve(detectChange(input));
+ } catch (error) {
+ reject(error);
+ }
+ });
+ }
+ const id = ++serial;
+ return new Promise((resolve, reject) => {
+ pending.set(id, { resolve, reject });
+ running.postMessage({ id, input });
+ });
+}
diff --git a/frontend/src/lib/map/changeRunner.test.js b/frontend/src/lib/map/changeRunner.test.js
new file mode 100644
index 0000000..ffb28d1
--- /dev/null
+++ b/frontend/src/lib/map/changeRunner.test.js
@@ -0,0 +1,17 @@
+import { describe, expect, it } from 'vitest';
+import { runChangeDetection } from './changeRunner.js';
+
+describe('running a change detection', () => {
+ it('answers on the main thread when the environment has no worker', async () => {
+ const a = new Uint8ClampedArray([10, 10, 10, 255]);
+ const b = new Uint8ClampedArray([10, 10, 10, 255]);
+ const result = await runChangeDetection({ a, b, width: 1, height: 1, settings: {} });
+ expect(result.counts.quiet).toBe(1);
+ });
+
+ it('rejects rather than throwing', async () => {
+ await expect(
+ runChangeDetection({ a: new Uint8ClampedArray(4), b: new Uint8ClampedArray(8), width: 1, height: 1 })
+ ).rejects.toThrow('same pixel geometry');
+ });
+});
diff --git a/frontend/src/lib/map/changeWorker.js b/frontend/src/lib/map/changeWorker.js
new file mode 100644
index 0000000..9090098
--- /dev/null
+++ b/frontend/src/lib/map/changeWorker.js
@@ -0,0 +1,12 @@
+/** Runs `detectChange` off the main thread, so a pan never waits on a heatmap. */
+import { detectChange } from './changeDetect.js';
+
+self.onmessage = (event) => {
+ const { id, input } = event.data;
+ try {
+ const result = detectChange(input);
+ self.postMessage({ id, result }, [result.pixels.buffer]);
+ } catch (error) {
+ self.postMessage({ id, error: error?.message ?? String(error) });
+ }
+};
diff --git a/frontend/src/lib/map/compare.js b/frontend/src/lib/map/compare.js
new file mode 100644
index 0000000..3a4ac47
--- /dev/null
+++ b/frontend/src/lib/map/compare.js
@@ -0,0 +1,116 @@
+/** 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.
+ */
+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' },
+]);
+
+/** 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 DEFAULT_DIVIDER = 50;
+export const DEFAULT_OPACITY = 50;
+export const DEFAULT_BLINK_INTERVAL = 800;
+export const BLINK_SPEEDS = Object.freeze([
+ { id: 400, label: 'Fast' },
+ { id: 800, label: 'Normal' },
+ { id: 1600, label: 'Slow' },
+]);
+
+/** Reference layers Compare can persist, grouped the way the sheet lists them. */
+export const COMPARE_LAYERS = Object.freeze([
+ { id: 'labels', label: 'Labels', hint: 'Roads and place names', group: 'reference' },
+ { id: 'boundaries', label: 'Borders', hint: 'Country, region and district borders', group: 'reference' },
+ { id: 'roads', label: 'Roads', hint: 'Road network', group: 'reference' },
+ { id: 'railway', label: 'Railways', hint: 'Tracks, sidings and stations', group: 'reference' },
+ { id: 'power', label: 'Power lines', hint: 'Lines, towers and substations', group: 'reference' },
+ { id: 'seamarks', label: 'Sea marks', hint: 'Buoys, lights, harbours and fairways', group: 'reference' },
+ { id: 'gpstraces', label: 'GPS traces', hint: 'Raw GPS tracks from OpenStreetMap', group: 'reference' },
+ { id: 'firms', label: 'Active fires', hint: 'Thermal detections from NASA FIRMS', group: 'events' },
+ { id: 'nightlights', label: 'Night lights', hint: 'The ground at night from NASA VIIRS', group: 'events' },
+ { id: 'saved', label: 'Saved work', hint: 'Places, captures and proofs in this case', group: 'case' },
+]);
+
+export const LAYER_GROUPS = Object.freeze([
+ { id: 'reference', label: 'Reference' },
+ { id: 'events', label: 'Dated observations' },
+ { id: 'case', label: 'This case' },
+]);
+
+const LAYER_IDS = new Set(COMPARE_LAYERS.map((layer) => layer.id));
+
+/** Keep a session's layer list ordered, unique and supported. */
+export function comparisonLayers(value) {
+ const asked = new Set(Array.isArray(value) ? value.filter((id) => LAYER_IDS.has(id)) : []);
+ return COMPARE_LAYERS.map((layer) => layer.id).filter((id) => asked.has(id));
+}
+
+/** A range value that is safe to use as a percentage in CSS. */
+export function percentage(value, fallback = 50) {
+ const number = Number(value);
+ if (!Number.isFinite(number)) return fallback;
+ return Math.min(100, Math.max(0, Math.round(number)));
+}
+
+/** 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';
+ return provider?.imagery === false ? 'map' : 'imagery';
+}
+
+export const PROVIDER_KINDS = Object.freeze([
+ { id: 'archive', label: 'Dated archives', hint: 'Pick the date of each side' },
+ { id: 'imagery', label: 'Current imagery' },
+ { id: 'map', label: 'Maps' },
+]);
+
+/**
+ * Two-sided starting points. Each names the providers it needs, so one whose
+ * provider is missing or keyless is simply not offered.
+ */
+export const COMPARE_PRESETS = Object.freeze([
+ {
+ id: 'archive',
+ label: 'Then and now',
+ hint: 'An Esri Wayback release against today’s World Imagery',
+ a: 'esri-wayback',
+ b: 'esri-world-imagery',
+ },
+ {
+ id: 'sentinel',
+ label: 'Two satellite passes',
+ hint: 'Sentinel-2 on both sides, each on its own day',
+ a: 'sentinel2',
+ b: 'sentinel2',
+ },
+ {
+ id: 'map',
+ label: 'Imagery and map',
+ hint: 'World Imagery beside OpenStreetMap',
+ a: 'esri-world-imagery',
+ b: 'osm',
+ },
+]);
+
+/** The presets this catalogue can actually start. */
+export function availablePresets(providers) {
+ const usable = new Set(
+ (providers ?? []).filter((provider) => !provider.needs_key).map((provider) => provider.id)
+ );
+ return COMPARE_PRESETS.filter((preset) => usable.has(preset.a) && usable.has(preset.b));
+}
diff --git a/frontend/src/lib/map/compare.test.js b/frontend/src/lib/map/compare.test.js
new file mode 100644
index 0000000..d118962
--- /dev/null
+++ b/frontend/src/lib/map/compare.test.js
@@ -0,0 +1,56 @@
+import { describe, expect, it } from 'vitest';
+import {
+ COMPARE_LAYERS,
+ COMPARE_MODES,
+ FIND_MODES,
+ availablePresets,
+ 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('keeps layers ordered, unique and supported', () => {
+ expect(comparisonLayers(['saved', 'roads', 'roads', 'buildings', 'labels'])).toEqual([
+ 'labels',
+ 'roads',
+ 'saved',
+ ]);
+ expect(comparisonLayers(null)).toEqual([]);
+ expect(new Set(COMPARE_LAYERS.map((layer) => layer.group))).toEqual(
+ new Set(['reference', 'events', 'case'])
+ );
+ });
+
+ it('clamps percentages for CSS', () => {
+ expect(percentage('73.4')).toBe(73);
+ expect(percentage(-4)).toBe(0);
+ expect(percentage(140)).toBe(100);
+ expect(percentage('nope', 12)).toBe(12);
+ });
+
+ it('files providers under archives, imagery or maps', () => {
+ expect(providerKind({ id: 'esri-wayback' })).toBe('archive');
+ expect(providerKind({ id: 'sentinel2' })).toBe('archive');
+ expect(providerKind({ id: 'osm', imagery: false })).toBe('map');
+ expect(providerKind({ id: 'esri-world-imagery', imagery: true })).toBe('imagery');
+ });
+
+ it('offers only the starting points the catalogue can start', () => {
+ const ids = (providers) => availablePresets(providers).map((preset) => preset.id);
+ const free = [{ id: 'esri-wayback' }, { id: 'esri-world-imagery' }, { id: 'osm' }];
+ 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']);
+ });
+});
diff --git a/frontend/src/lib/map/compareAnnotations.js b/frontend/src/lib/map/compareAnnotations.js
new file mode 100644
index 0000000..950ff93
--- /dev/null
+++ b/frontend/src/lib/map/compareAnnotations.js
@@ -0,0 +1,278 @@
+/**
+ * Compare's annotations, pinned to the ground.
+ *
+ * A mark stores `[lon, lat]` points, so it follows the imagery through a pan,
+ * a zoom or a turn and lands on the same spot of both maps. `side` says which
+ * picture it belongs to: a "before" note on A, a new building outlined on B, or
+ * 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.
+ */
+
+import { formatArea, formatDistance, haversine, polygonArea } from '../measure.js';
+
+export const ANNOTATION_COLOURS = Object.freeze([
+ '#f6a81a', '#22c55e', '#ef4444', '#38bdf8', '#e879f9', '#f4f5f6', '#111827',
+]);
+
+/** Each tool: how its points are collected, and what it draws. */
+export const ANNOTATION_TOOLS = Object.freeze([
+ { id: 'select', icon: 'cursor', label: 'Select and move', shortcut: 'V' },
+ { id: 'arrow', icon: 'arrow', label: 'Arrow', shortcut: 'A', points: 2 },
+ { id: 'rect', icon: 'square', label: 'Box', shortcut: 'R', points: 2, fill: true },
+ { id: 'ellipse', icon: 'circle', label: 'Ellipse', shortcut: 'E', points: 2, fill: true },
+ { id: 'polygon', icon: 'polygon', label: 'Area', shortcut: 'P', points: 'many', fill: true },
+ { id: 'measure', icon: 'ruler', label: 'Measure', shortcut: 'M', points: 2 },
+ { id: 'line', icon: 'line', label: 'Line', shortcut: 'L', points: 2 },
+ { id: 'freehand', icon: 'freehand', label: 'Freehand', shortcut: 'D', points: 'drag' },
+ { id: 'text', icon: 'text', label: 'Note', shortcut: 'T', points: 1 },
+]);
+
+const KINDS = new Set(ANNOTATION_TOOLS.filter((tool) => tool.points).map((tool) => tool.id));
+const LIMITS = {
+ text: [1, 1], arrow: [2, 2], line: [2, 2], measure: [2, 2], rect: [2, 2], ellipse: [2, 2],
+ freehand: [2, 400], polygon: [3, 200],
+};
+
+export const canFill = (kind) => kind === 'rect' || kind === 'ellipse' || kind === 'polygon';
+
+const bounded = (value, fallback, min, max) => {
+ const number = Number(value);
+ return Math.min(max, Math.max(min, Number.isFinite(number) ? number : fallback));
+};
+
+function groundPoint(raw) {
+ if (!Array.isArray(raw) || raw.length < 2) return null;
+ const lon = Number(raw[0]);
+ const lat = Number(raw[1]);
+ if (!Number.isFinite(lon) || !Number.isFinite(lat)) return null;
+ if (lon < -180 || lon > 180 || lat < -90 || lat > 90) return null;
+ return [lon, lat];
+}
+
+/** The marks a session can hold, cleaned; anything the server would refuse is dropped. */
+export function comparisonAnnotations(value) {
+ if (!Array.isArray(value)) return [];
+ return value.flatMap((raw, index) => {
+ if (!KINDS.has(raw?.kind) || !Array.isArray(raw.points)) return [];
+ const points = raw.points.map(groundPoint);
+ const [low, high] = LIMITS[raw.kind];
+ if (points.some((point) => !point) || points.length < low) return [];
+ const text = String(raw.text ?? '').trim().slice(0, 240);
+ if (raw.kind === 'text' && !text) return [];
+ return [{
+ id: String(raw.id || `mark-${index + 1}`).slice(0, 80),
+ kind: raw.kind,
+ side: raw.side === 'a' || raw.side === 'b' ? raw.side : 'both',
+ colour: /^#[0-9a-f]{6}$/i.test(String(raw.colour ?? ''))
+ ? String(raw.colour).toLowerCase()
+ : ANNOTATION_COLOURS[0],
+ points: points.slice(0, high),
+ stroke_width: Math.round(bounded(raw.stroke_width, 3, 1, 24)),
+ fill_opacity: canFill(raw.kind) ? bounded(raw.fill_opacity, 0, 0, 1) : 0,
+ font_size: Math.round(bounded(raw.font_size, 16, 8, 72)),
+ text,
+ }];
+ });
+}
+
+/** Whether a mark is drawn on the picture of one side. */
+export const onSide = (mark, letter) => mark.side === 'both' || mark.side === letter;
+
+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) {
+ const centreLon = (first[0] + second[0]) / 2;
+ const centreLat = (first[1] + second[1]) / 2;
+ const radiusLon = Math.abs(second[0] - first[0]) / 2;
+ const radiusLat = Math.abs(second[1] - first[1]) / 2;
+ return Array.from({ length: steps }, (_, step) => {
+ const angle = (step / steps) * Math.PI * 2;
+ return [centreLon + Math.cos(angle) * radiusLon, centreLat + Math.sin(angle) * radiusLat];
+ });
+}
+
+/** 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]],
+];
+
+/** 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 === 'polygon') return mark.points;
+ return null;
+}
+
+/** What a mark measures, in metres or square metres, when it measures anything. */
+export function markMetric(mark) {
+ if (mark.kind === 'measure' || mark.kind === 'line' || mark.kind === 'arrow') {
+ return { distance: haversine(asLatLon(mark.points[0]), asLatLon(mark.points[1])) };
+ }
+ const ring = markRing(mark);
+ return ring ? { area: polygonArea(ring.map(asLatLon)) } : {};
+}
+
+/** The words drawn beside a mark: its note, its length or its area. */
+export function markLabel(mark, units = 'metric') {
+ if (mark.kind === 'text') return mark.text;
+ if (mark.kind === 'measure') return formatDistance(markMetric(mark).distance, units);
+ if (mark.kind === 'polygon') return formatArea(markMetric(mark).area, units);
+ return mark.text;
+}
+
+/** Shift every point of a mark by a ground offset, clamped to valid coordinates. */
+export function movedMark(mark, dLon, dLat) {
+ return {
+ ...mark,
+ points: mark.points.map(([lon, lat]) => [
+ Math.min(180, Math.max(-180, lon + dLon)),
+ Math.min(90, Math.max(-90, lat + dLat)),
+ ]),
+ };
+}
+
+/**
+ * Screen geometry for one mark under a projection `([lon, lat]) => [x, y]`.
+ * `path` is the outline to stroke (closed when `closed`), `anchor` where its
+ * label sits, `head` the arrow's head triangle.
+ */
+export function projectMark(mark, project) {
+ const ring = markRing(mark);
+ const path = (ring ?? mark.points).map(project);
+ const shape = { path, closed: Boolean(ring), anchor: path[0], head: null };
+ if (mark.kind === 'arrow' || mark.kind === 'measure' || mark.kind === 'line') {
+ const [start, end] = path;
+ if (mark.kind === 'arrow') {
+ const angle = Math.atan2(end[1] - start[1], end[0] - start[0]);
+ const size = 10 + mark.stroke_width * 2.6;
+ const spread = Math.PI / 7;
+ shape.head = [
+ end,
+ [end[0] - Math.cos(angle - spread) * size, end[1] - Math.sin(angle - spread) * size],
+ [end[0] - Math.cos(angle + spread) * size, end[1] - Math.sin(angle + spread) * size],
+ ];
+ }
+ shape.anchor = [(start[0] + end[0]) / 2, (start[1] + end[1]) / 2];
+ } else if (ring) {
+ const xs = path.map((point) => point[0]);
+ const ys = path.map((point) => point[1]);
+ shape.anchor = [(Math.min(...xs) + Math.max(...xs)) / 2, (Math.min(...ys) + Math.max(...ys)) / 2];
+ }
+ return shape;
+}
+
+function roundedRect(ctx, x, y, width, height, radius) {
+ ctx.beginPath();
+ ctx.moveTo(x + radius, y);
+ ctx.arcTo(x + width, y, x + width, y + height, radius);
+ ctx.arcTo(x + width, y + height, x, y + height, radius);
+ ctx.arcTo(x, y + height, x, y, radius);
+ ctx.arcTo(x, y, x + width, y, radius);
+ ctx.closePath();
+}
+
+function hexWithAlpha(hex, alpha) {
+ const value = Number.parseInt(hex.slice(1), 16);
+ return `rgba(${(value >> 16) & 255},${(value >> 8) & 255},${value & 255},${alpha})`;
+}
+
+function textLines(ctx, text, maxWidth) {
+ const lines = [];
+ for (const paragraph of String(text).split('\n')) {
+ let line = '';
+ for (const word of paragraph.split(/\s+/)) {
+ const next = line ? `${line} ${word}` : word;
+ if (line && ctx.measureText(next).width > maxWidth) {
+ lines.push(line);
+ line = word;
+ } else {
+ line = next;
+ }
+ }
+ lines.push(line);
+ }
+ return lines.slice(0, 8);
+}
+
+/** A label plate: dark, legible over any imagery, edged in the mark's colour. */
+function drawPlate(ctx, text, x, y, { colour, fontSize, scale, centred }) {
+ const size = Math.max(9, Math.round(fontSize * scale));
+ const padX = Math.round(size * 0.55);
+ const padY = Math.round(size * 0.38);
+ ctx.font = `600 ${size}px system-ui, -apple-system, "Segoe UI", sans-serif`;
+ const lines = textLines(ctx, text, 360 * scale);
+ const width = Math.max(...lines.map((line) => ctx.measureText(line).width)) + padX * 2;
+ const height = lines.length * size * 1.25 + padY * 2;
+ const left = centred ? x - width / 2 : x + 6 * scale;
+ const top = centred ? y - height / 2 : y - height - 6 * scale;
+ ctx.fillStyle = 'rgba(12,14,17,.86)';
+ roundedRect(ctx, left, top, width, height, Math.min(6 * scale, height / 2));
+ ctx.fill();
+ ctx.lineWidth = Math.max(1, 1.5 * scale);
+ ctx.strokeStyle = colour;
+ ctx.stroke();
+ ctx.fillStyle = '#f5f6f7';
+ ctx.textBaseline = 'alphabetic';
+ lines.forEach((line, index) => {
+ ctx.fillText(line, left + padX, top + padY + size * 0.95 + index * size * 1.25);
+ });
+}
+
+/**
+ * Burn marks into an exported picture. `project` maps `[lon, lat]` to that
+ * picture's pixels; `scale` is its pixels per CSS pixel, so strokes and labels
+ * keep the weight they had on screen.
+ */
+export function drawAnnotations(ctx, marks, project, { scale = 1, units = 'metric' } = {}) {
+ const list = comparisonAnnotations(marks);
+ if (!list.length) return;
+ ctx.save();
+ ctx.lineCap = 'round';
+ ctx.lineJoin = 'round';
+ for (const mark of list) {
+ const shape = projectMark(mark, project);
+ ctx.lineWidth = Math.max(1, mark.stroke_width * scale);
+ ctx.strokeStyle = mark.colour;
+ if (mark.kind !== 'text') {
+ // a thin dark casing keeps a light stroke readable on bright ground
+ ctx.save();
+ ctx.shadowColor = 'rgba(0,0,0,.55)';
+ ctx.shadowBlur = 3 * scale;
+ ctx.beginPath();
+ shape.path.forEach(([x, y], index) => (index ? ctx.lineTo(x, y) : ctx.moveTo(x, y)));
+ if (shape.closed) {
+ ctx.closePath();
+ if (mark.fill_opacity > 0) {
+ ctx.fillStyle = hexWithAlpha(mark.colour, mark.fill_opacity);
+ ctx.fill();
+ }
+ }
+ if (mark.kind === 'measure') ctx.setLineDash([8 * scale, 6 * scale]);
+ ctx.stroke();
+ ctx.restore();
+ if (shape.head) {
+ ctx.fillStyle = mark.colour;
+ ctx.beginPath();
+ shape.head.forEach(([x, y], index) => (index ? ctx.lineTo(x, y) : ctx.moveTo(x, y)));
+ ctx.closePath();
+ ctx.fill();
+ }
+ }
+ const label = markLabel(mark, units);
+ if (label) {
+ drawPlate(ctx, label, shape.anchor[0], shape.anchor[1], {
+ colour: mark.colour,
+ fontSize: mark.font_size,
+ scale,
+ centred: mark.kind !== 'text',
+ });
+ }
+ }
+ ctx.restore();
+}
diff --git a/frontend/src/lib/map/compareAnnotations.test.js b/frontend/src/lib/map/compareAnnotations.test.js
new file mode 100644
index 0000000..5df701f
--- /dev/null
+++ b/frontend/src/lib/map/compareAnnotations.test.js
@@ -0,0 +1,84 @@
+import { describe, expect, it, vi } from 'vitest';
+import {
+ comparisonAnnotations,
+ drawAnnotations,
+ ellipseRing,
+ markLabel,
+ markMetric,
+ movedMark,
+ onSide,
+ projectMark,
+} from './compareAnnotations.js';
+
+const mark = (patch) => ({ id: 'm', colour: '#f6a81a', side: 'both', ...patch });
+
+describe('ground annotations', () => {
+ it('keeps marks the server accepts and drops the rest', () => {
+ expect(comparisonAnnotations([
+ mark({ kind: 'rect', colour: '#FF0000', points: [[2, 48], [2.1, 48.1]], fill_opacity: 4, side: 'x' }),
+ mark({ kind: 'text', text: ' ', points: [[2, 48]] }),
+ mark({ kind: 'arrow', points: [[2, 48]] }),
+ mark({ kind: 'line', points: [[200, 48], [2, 48]] }),
+ mark({ kind: 'unknown', points: [[2, 48]] }),
+ // an annotation saved on screen coordinates before they were pinned
+ { id: 'old', kind: 'rect', x1: 0.1, y1: 0.1, x2: 0.4, y2: 0.4 },
+ ])).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: '',
+ }]);
+ });
+
+ it('belongs to one side or both', () => {
+ expect(onSide(mark({ side: 'a' }), 'a')).toBe(true);
+ expect(onSide(mark({ side: 'a' }), 'b')).toBe(false);
+ expect(onSide(mark({ side: 'both' }), 'b')).toBe(true);
+ });
+
+ it('measures on the ground, not on the screen', () => {
+ const measure = mark({ kind: 'measure', points: [[0, 0], [0, 0.01]] });
+ expect(markMetric(measure).distance).toBeCloseTo(1113.2, 0);
+ expect(markLabel(measure)).toBe('1.11 km');
+ const square = mark({ kind: 'polygon', points: [[0, 0], [0.001, 0], [0.001, 0.001], [0, 0.001]] });
+ expect(markMetric(square).area).toBeCloseTo(12392, -2);
+ expect(markLabel(square, 'metric')).toBe('1.24 ha');
+ });
+
+ it('moves every point by a ground offset', () => {
+ expect(movedMark(mark({ kind: 'line', points: [[1, 1], [179.5, 2]] }), 1, 0.5).points)
+ .toEqual([[2, 1.5], [180, 2.5]]);
+ });
+
+ it('draws an ellipse as a ring inscribed in its ground box', () => {
+ const ring = ellipseRing([[0, 0], [2, 1]], 4);
+ expect(ring[0]).toEqual([2, 0.5]);
+ expect(ring[1][0]).toBeCloseTo(1);
+ expect(ring[1][1]).toBeCloseTo(1);
+ });
+
+ 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);
+ expect(box.closed).toBe(true);
+ expect(box.path).toHaveLength(4);
+ expect(box.anchor).toEqual([50, -50]);
+ const arrow = projectMark(mark({ kind: 'arrow', points: [[0, 0], [1, 0]], stroke_width: 3 }), project);
+ expect(arrow.head[0]).toEqual([100, -0]);
+ expect(arrow.anchor).toEqual([50, -0]);
+ });
+
+ it('burns marks and their labels into an exported picture through its projection', () => {
+ const ctx = {
+ save: vi.fn(), restore: vi.fn(), beginPath: vi.fn(), moveTo: vi.fn(), lineTo: vi.fn(),
+ closePath: vi.fn(), fill: vi.fn(), stroke: vi.fn(), arcTo: vi.fn(), fillText: vi.fn(),
+ setLineDash: vi.fn(), measureText: (text) => ({ width: text.length * 7 }),
+ };
+ drawAnnotations(ctx, [
+ mark({ kind: 'measure', points: [[0, 0], [0, 0.01]] }),
+ mark({ kind: 'text', points: [[0, 0]], text: 'Before' }),
+ ], ([lon, lat]) => [lon * 1000 + 10, 500 - lat * 1000], { scale: 2 });
+ expect(ctx.moveTo).toHaveBeenCalledWith(10, 500);
+ expect(ctx.lineTo).toHaveBeenCalledWith(10, 490);
+ expect(ctx.setLineDash).toHaveBeenCalledWith([16, 12]);
+ expect(ctx.fillText.mock.calls.map((call) => call[0])).toEqual(['1.11 km', 'Before']);
+ });
+});
diff --git a/frontend/src/lib/map/compareExport.js b/frontend/src/lib/map/compareExport.js
new file mode 100644
index 0000000..c717181
--- /dev/null
+++ b/frontend/src/lib/map/compareExport.js
@@ -0,0 +1,368 @@
+/**
+ * Turn two captured map frames into the comparison the analyst is reading.
+ *
+ * This composes pixels, not the Compare DOM: provider menus, zoom buttons and
+ * the swipe handle are controls. The picture is the two aligned images plus
+ * what explains them: which source and date each side is, where the camera
+ * was, a scale bar and north arrow, the Change assist legend, the credits, and
+ * the annotations projected onto the ground they were pinned to.
+ *
+ * Everything is placed from each side's camera frame (`groundFrame.js`), so
+ * the composer needs no map: a projection is recomputed from the frame, and
+ * a change mask computed for an earlier camera is laid where its ground is.
+ */
+
+import { drawAnnotations, onSide } from './compareAnnotations.js';
+import {
+ apply,
+ compose,
+ frameToFrame,
+ groundPerPixel,
+ invert,
+ scale as scaleBy,
+ screenToMercator,
+ toMercator,
+} from './groundFrame.js';
+import { CHANGE_PALETTES } from './changeAssist.js';
+
+const clamp = (value, min, max) => Math.min(max, Math.max(min, value));
+const INK = '#f3f4f6';
+const MUTED = '#a7adb5';
+const BAND = '#0f1114';
+const ACCENT = '#e8a33d';
+const FONT = 'system-ui, -apple-system, "Segoe UI", Roboto, sans-serif';
+const MONO = 'ui-monospace, "SF Mono", "Cascadia Code", monospace';
+
+export function comparisonFilename(title = '', at = new Date()) {
+ const stamp = at.toISOString().replace(/[^0-9]/g, '').slice(0, 12);
+ const stem = String(title).trim().replace(/[\\/:*?"<>|#%]+/g, ' ').replace(/\s+/g, ' ').slice(0, 80);
+ return stem ? `${stem} ${stamp}` : `compare-${stamp || 'undated'}`;
+}
+
+function canvasOf(width, height, makeCanvas) {
+ const canvas = makeCanvas ? makeCanvas() : document.createElement('canvas');
+ canvas.width = Math.max(1, Math.round(width));
+ canvas.height = Math.max(1, Math.round(height));
+ return canvas;
+}
+
+/** `[lon, lat]` → pixel of a captured canvas, from the frame it was captured at. */
+export function captureProjection(capture, offsetX = 0, offsetY = 0) {
+ const pixelScale = capture.canvas.width / capture.frame.width;
+ const toPixels = compose(scaleBy(pixelScale), invert(screenToMercator(capture.frame)));
+ return ([lon, lat]) => {
+ const [x, y] = apply(toPixels, ...toMercator(lon, lat));
+ return [x + offsetX, y + offsetY];
+ };
+}
+
+/** A round ground length that fits in about `target` pixels. */
+export function scaleBarLength(metresPerPixel, target = 120) {
+ const raw = metresPerPixel * target;
+ const magnitude = 10 ** Math.floor(Math.log10(raw));
+ const step = [1, 2, 5, 10].find((candidate) => candidate * magnitude >= raw * 0.62) ?? 10;
+ const metres = step * magnitude;
+ return { metres, pixels: metres / metresPerPixel };
+}
+
+const readableLength = (metres) =>
+ metres >= 1000 ? `${metres / 1000} km` : `${metres} m`;
+
+function drawTag(ctx, text, x, y, { scale, accent = false, align = 'left' }) {
+ ctx.font = `700 ${Math.round(12 * scale)}px ${FONT}`;
+ const padX = 8 * scale;
+ const height = 22 * scale;
+ const width = ctx.measureText(text).width + padX * 2;
+ const left = align === 'right' ? x - width : x;
+ ctx.fillStyle = 'rgba(12,14,17,.82)';
+ ctx.beginPath();
+ ctx.roundRect?.(left, y, width, height, 5 * scale) ?? ctx.rect(left, y, width, height);
+ ctx.fill();
+ ctx.fillStyle = accent ? ACCENT : INK;
+ ctx.textBaseline = 'middle';
+ ctx.fillText(text, left + padX, y + height / 2 + 0.5);
+ ctx.textBaseline = 'alphabetic';
+}
+
+function drawScaleAndNorth(ctx, frame, x, y, { scale, bearing, units }) {
+ const perPixel = groundPerPixel(frame) / scale;
+ let { metres, pixels } = scaleBarLength(perPixel, 120 * scale);
+ let label = readableLength(metres);
+ if (units === 'imperial') {
+ const feetPerPixel = perPixel * 3.28084;
+ const bar = scaleBarLength(feetPerPixel, 120 * scale);
+ pixels = bar.pixels;
+ label = bar.metres >= 5280 ? `${bar.metres / 5280} mi` : `${bar.metres} ft`;
+ }
+ const height = 30 * scale;
+ const width = pixels + 70 * scale;
+ ctx.fillStyle = 'rgba(12,14,17,.78)';
+ ctx.beginPath();
+ ctx.roundRect?.(x, y - height, width, height, 5 * scale) ?? ctx.rect(x, y - height, width, height);
+ ctx.fill();
+ const barX = x + 10 * scale;
+ const barY = y - 11 * scale;
+ ctx.strokeStyle = INK;
+ ctx.lineWidth = 2 * scale;
+ ctx.beginPath();
+ ctx.moveTo(barX, barY - 5 * scale);
+ ctx.lineTo(barX, barY);
+ ctx.lineTo(barX + pixels, barY);
+ ctx.lineTo(barX + pixels, barY - 5 * scale);
+ ctx.stroke();
+ ctx.fillStyle = INK;
+ ctx.font = `600 ${Math.round(11 * scale)}px ${FONT}`;
+ ctx.fillText(label, barX + 2 * scale, barY - 7 * scale);
+ // north needle, turned with the picture
+ const cx = x + width - 18 * scale;
+ const cy = y - height / 2;
+ ctx.save();
+ ctx.translate(cx, cy);
+ ctx.rotate((-bearing * Math.PI) / 180);
+ ctx.beginPath();
+ ctx.moveTo(0, -10 * scale);
+ ctx.lineTo(5 * scale, 7 * scale);
+ ctx.lineTo(0, 3 * scale);
+ ctx.closePath();
+ ctx.fill();
+ ctx.beginPath();
+ ctx.moveTo(0, -10 * scale);
+ ctx.lineTo(-5 * scale, 7 * scale);
+ ctx.lineTo(0, 3 * scale);
+ ctx.closePath();
+ ctx.lineWidth = 1.2 * scale;
+ ctx.stroke();
+ ctx.restore();
+}
+
+/** Lay a change mask computed for `mask.frame` onto a picture captured at `target`. */
+function drawChangeMask(ctx, mask, target, x, y, pixelScale, opacity) {
+ const toTarget = compose(
+ scaleBy(pixelScale),
+ compose(frameToFrame(mask.frame, target), scaleBy(mask.frame.width / mask.canvas.width))
+ );
+ ctx.save();
+ ctx.beginPath();
+ ctx.rect(x, y, target.width * pixelScale, target.height * pixelScale);
+ ctx.clip();
+ 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);
+ ctx.drawImage(mask.canvas, 0, 0);
+ ctx.restore();
+}
+
+/**
+ * @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
+ */
+export function composeComparison({
+ a,
+ b,
+ mode,
+ title = '',
+ divider = 50,
+ opacity = 50,
+ blinkB = false,
+ change = null,
+ annotations = [],
+ labelA = 'Imagery A',
+ labelB = 'Imagery B',
+ attributionA = '',
+ attributionB = '',
+ view,
+ bearing = 0,
+ units = 'metric',
+ makeCanvas,
+}) {
+ if (!a?.canvas?.width || !b?.canvas?.width || !a?.frame || !b?.frame) {
+ throw new Error('both maps must be ready before they 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 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 footer = Math.round(26 * s) + legend;
+ const output = canvasOf(mapWidth, header + mapHeight + footer, makeCanvas);
+ const ctx = output.getContext('2d');
+ if (!ctx) throw new Error('this browser cannot compose the comparison');
+
+ ctx.fillStyle = BAND;
+ ctx.fillRect(0, 0, output.width, output.height);
+
+ const top = header;
+ const paneB = side ? a.canvas.width : 0;
+ const markAnnotations = (capture, letter, offsetX) => {
+ const marks = annotations.filter((mark) => onSide(mark, letter));
+ drawAnnotations(ctx, marks, captureProjection(capture, offsetX, top), { scale: s, units });
+ };
+
+ 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);
+ }
+ markAnnotations(a, 'a', 0);
+ markAnnotations(b, 'b', paneB);
+ ctx.fillStyle = 'rgba(255,255,255,.92)';
+ ctx.fillRect(paneB - Math.round(s), top, Math.max(2, Math.round(2 * s)), mapHeight);
+ drawTag(ctx, 'A', 12 * s, top + 12 * s, { scale: s, accent: true });
+ drawTag(ctx, 'B', paneB + 12 * s, top + 12 * s, { scale: s, accent: true });
+ } else if (mode === 'swipe') {
+ const split = Math.round((clamp(Number(divider), 0, 100) / 100) * mapWidth);
+ ctx.save();
+ ctx.beginPath();
+ ctx.rect(0, top, split, mapHeight);
+ ctx.clip();
+ ctx.drawImage(a.canvas, 0, top);
+ markAnnotations(a, 'a', 0);
+ ctx.restore();
+ ctx.save();
+ ctx.beginPath();
+ ctx.rect(split, top, mapWidth - split, mapHeight);
+ ctx.clip();
+ ctx.drawImage(b.canvas, 0, top);
+ markAnnotations(b, 'b', 0);
+ ctx.restore();
+ ctx.fillStyle = 'rgba(255,255,255,.95)';
+ ctx.fillRect(split - Math.round(s), top, Math.max(2, Math.round(2 * s)), mapHeight);
+ if (split > 40 * s) drawTag(ctx, 'A', 12 * s, top + 12 * s, { scale: s, accent: true });
+ if (mapWidth - split > 40 * s) {
+ drawTag(ctx, 'B', mapWidth - 12 * s, top + 12 * s, { scale: s, accent: true, align: 'right' });
+ }
+ } else if (mode === 'opacity') {
+ ctx.drawImage(a.canvas, 0, top);
+ ctx.save();
+ ctx.globalAlpha = clamp(Number(opacity), 0, 100) / 100;
+ ctx.drawImage(b.canvas, 0, top);
+ ctx.restore();
+ markAnnotations(a, 'a', 0);
+ const onlyB = annotations.filter((mark) => mark.side === 'b');
+ 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);
+ markAnnotations(shown, letter, 0);
+ drawTag(ctx, letter.toUpperCase(), 12 * s, top + 12 * s, { scale: s, accent: true });
+ }
+
+ drawScaleAndNorth(ctx, a.frame, 12 * s, top + mapHeight - 12 * s, { scale: s, bearing, units });
+
+ // Header: what is being compared, then where.
+ const left = 16 * s;
+ let line = 0;
+ if (title) {
+ ctx.fillStyle = INK;
+ ctx.font = `700 ${Math.round(17 * s)}px ${FONT}`;
+ ctx.fillText(title, left, 25 * s, mapWidth * 0.6);
+ line = 20 * s;
+ }
+ ctx.font = `600 ${Math.round(12 * s)}px ${FONT}`;
+ ctx.fillStyle = ACCENT;
+ ctx.fillText('A', left, 24 * s + line);
+ ctx.fillStyle = INK;
+ ctx.fillText(labelA, left + 14 * s, 24 * s + line, mapWidth * 0.3);
+ const labelAWidth = Math.min(ctx.measureText(labelA).width, mapWidth * 0.3);
+ const bx = left + 14 * s + labelAWidth + 22 * s;
+ ctx.fillStyle = ACCENT;
+ ctx.fillText('B', bx, 24 * s + line);
+ ctx.fillStyle = INK;
+ ctx.fillText(labelB, bx + 14 * s, 24 * s + line, mapWidth * 0.3);
+
+ const lat = Number(view?.lat);
+ const lon = Number(view?.lon);
+ const zoom = Number(view?.zoom);
+ if (Number.isFinite(lat) && Number.isFinite(lon)) {
+ const camera = `${lat.toFixed(5)}, ${lon.toFixed(5)} · z${Math.round(zoom)} · ${Math.round(bearing)}°`;
+ ctx.font = `${Math.round(11 * s)}px ${MONO}`;
+ ctx.fillStyle = MUTED;
+ const width = ctx.measureText(camera).width;
+ ctx.fillText(camera, Math.max(left, mapWidth - width - 16 * s), (title ? 25 : 24) * s);
+ }
+
+ // Legend for a change reading, stated as what it is: an assist.
+ const bottom = top + mapHeight;
+ if (legend) {
+ const palette = CHANGE_PALETTES[change.palette] ?? CHANGE_PALETTES.directional;
+ const entries = [
+ ['gain', change.labels?.gain ?? 'Appeared or brighter in B'],
+ ['loss', change.labels?.loss ?? 'Gone or darker in B'],
+ ['changed', 'Other change'],
+ ];
+ let x = left;
+ const y = bottom + 20 * s;
+ ctx.font = `${Math.round(11 * s)}px ${FONT}`;
+ for (const [key, text] of entries) {
+ const [r, g, bl] = palette[key];
+ ctx.fillStyle = `rgb(${r},${g},${bl})`;
+ ctx.fillRect(x, y - 9 * s, 10 * s, 10 * s);
+ ctx.fillStyle = INK;
+ ctx.fillText(text, x + 15 * s, y);
+ x += ctx.measureText(text).width + 34 * s;
+ }
+ if (change.summary) {
+ ctx.fillStyle = MUTED;
+ const width = ctx.measureText(change.summary).width;
+ ctx.fillText(change.summary, Math.max(x, mapWidth - width - 16 * s), y);
+ }
+ }
+
+ ctx.fillStyle = MUTED;
+ ctx.font = `${Math.round(10 * s)}px ${FONT}`;
+ const credits = `A: ${attributionA || labelA} | B: ${attributionB || labelB}`;
+ ctx.fillText(credits, left, output.height - 9 * s, Math.max(0, mapWidth - 32 * s));
+ return output;
+}
+
+export function canvasBlob(canvas) {
+ return new Promise((resolve, reject) => {
+ try {
+ canvas.toBlob(
+ (blob) => (blob ? resolve(blob) : reject(new Error('the comparison could not be encoded'))),
+ 'image/png'
+ );
+ } catch (error) {
+ reject(new Error(`these imagery pixels cannot be exported: ${error.message}`));
+ }
+ });
+}
+
+export async function blobBase64(blob) {
+ const bytes = new Uint8Array(await blob.arrayBuffer());
+ let binary = '';
+ // Bounded by the server's image limit, but chunking avoids the argument-size
+ // limit that spreading a multi-megabyte Uint8Array would hit.
+ for (let start = 0; start < bytes.length; start += 0x8000) {
+ binary += String.fromCharCode(...bytes.subarray(start, start + 0x8000));
+ }
+ return btoa(binary);
+}
diff --git a/frontend/src/lib/map/compareExport.test.js b/frontend/src/lib/map/compareExport.test.js
new file mode 100644
index 0000000..4c52848
--- /dev/null
+++ b/frontend/src/lib/map/compareExport.test.js
@@ -0,0 +1,161 @@
+import { describe, expect, it, vi } from 'vitest';
+import {
+ blobBase64,
+ canvasBlob,
+ captureProjection,
+ comparisonFilename,
+ composeComparison,
+ scaleBarLength,
+} from './compareExport.js';
+
+const FRAME = { lng: 2.3, lat: 48.8, zoom: 16, bearing: 0, width: 500, height: 300 };
+
+function capture(name, pixelScale = 1) {
+ return {
+ canvas: { width: 500 * pixelScale, height: 300 * pixelScale, name },
+ frame: FRAME,
+ };
+}
+
+function fakeCanvas() {
+ const calls = [];
+ const record = (name) => (...args) => calls.push([name, ...args]);
+ const context = {
+ calls,
+ fillStyle: '',
+ strokeStyle: '',
+ font: '',
+ globalAlpha: 1,
+ lineWidth: 1,
+ imageSmoothingEnabled: true,
+ textBaseline: 'alphabetic',
+ fillRect: record('fillRect'),
+ drawImage: record('drawImage'),
+ fillText: record('fillText'),
+ measureText: (text) => ({ width: String(text).length * 6 }),
+ save: record('save'),
+ restore: record('restore'),
+ beginPath: record('beginPath'),
+ rect: record('rect'),
+ roundRect: record('roundRect'),
+ clip: record('clip'),
+ fill: record('fill'),
+ stroke: record('stroke'),
+ moveTo: record('moveTo'),
+ lineTo: record('lineTo'),
+ closePath: record('closePath'),
+ translate: record('translate'),
+ rotate: record('rotate'),
+ transform: record('transform'),
+ setTransform: record('setTransform'),
+ setLineDash: record('setLineDash'),
+ arcTo: record('arcTo'),
+ };
+ return { width: 0, height: 0, context, getContext: () => context };
+}
+
+const BASE = {
+ a: capture('a'),
+ b: capture('b'),
+ view: { lat: 48.8, lon: 2.3, zoom: 17 },
+ bearing: 32,
+ labelA: 'Old',
+ labelB: 'New',
+ makeCanvas: fakeCanvas,
+};
+
+const draws = (out) => out.context.calls.filter(([name]) => name === 'drawImage');
+
+describe('comparison export', () => {
+ it('puts side-by-side pixels beside each other under a header', () => {
+ const out = composeComparison({ ...BASE, mode: 'side' });
+ expect([out.width, out.height]).toEqual([1000, 48 + 300 + 26]);
+ expect(draws(out).map((call) => call.slice(1))).toEqual([
+ [BASE.a.canvas, 0, 48],
+ [BASE.b.canvas, 500, 48],
+ ]);
+ });
+
+ it('gives a titled export a taller header', () => {
+ const out = composeComparison({ ...BASE, mode: 'side', title: 'Harbour' });
+ expect(out.height).toBe(64 + 300 + 26);
+ expect(out.context.calls).toContainEqual(['fillText', 'Harbour', 16, 25, 600]);
+ });
+
+ it('clips A and B at the swipe divider', () => {
+ const out = composeComparison({ ...BASE, mode: 'swipe', divider: 73 });
+ expect(out.context.calls).toContainEqual(['rect', 0, 48, 365, 300]);
+ expect(out.context.calls).toContainEqual(['rect', 365, 48, 135, 300]);
+ });
+
+ it('blends B over A in opacity mode', () => {
+ const out = composeComparison({ ...BASE, mode: 'opacity', opacity: 25 });
+ 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]);
+ // 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.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);
+ expect(draws(out).map((call) => call[1]))
+ .toEqual([BASE.a.canvas, BASE.b.canvas, mask.canvas, mask.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('shows only the frame blink is on', () => {
+ const out = composeComparison({ ...BASE, mode: 'blink', blinkB: true });
+ expect(draws(out).map((call) => call[1])).toEqual([BASE.b.canvas]);
+ });
+
+ it('projects the ground into a high-density capture', () => {
+ const project = captureProjection(capture('a', 2), 0, 48);
+ const [x, y] = project([2.3, 48.8]);
+ expect(x).toBeCloseTo(500);
+ expect(y).toBeCloseTo(300 + 48);
+ });
+
+ it('picks a round scale bar length', () => {
+ expect(scaleBarLength(1, 120)).toEqual({ metres: 100, pixels: 100 });
+ expect(scaleBarLength(3.7, 120).metres).toBe(500);
+ });
+
+ it('names the file after the comparison and a stable UTC minute', () => {
+ const at = new Date('2026-09-14T08:09:10Z');
+ expect(comparisonFilename('', at)).toBe('compare-202609140809');
+ expect(comparisonFilename('Harbour: after/before', at)).toBe('Harbour after before 202609140809');
+ });
+});
+
+describe('comparison image encoding', () => {
+ it('encodes a canvas as PNG', async () => {
+ const blob = new Blob(['png'], { type: 'image/png' });
+ const canvas = { toBlob: (done, type) => done(type === 'image/png' ? blob : null) };
+ await expect(canvasBlob(canvas)).resolves.toBe(blob);
+ });
+
+ it('turns the blob into base64 without a FileReader', async () => {
+ expect(await blobBase64(new Blob([new Uint8Array([0, 1, 2, 255])]))).toBe('AAEC/w==');
+ });
+
+ it('reports a tainted provider canvas clearly', async () => {
+ const canvas = { toBlob: vi.fn(() => { throw new DOMException('tainted'); }) };
+ await expect(canvasBlob(canvas)).rejects.toThrow('cannot be exported');
+ });
+});
diff --git a/frontend/src/lib/map/engine.js b/frontend/src/lib/map/engine.js
index fcb040c..d8b373c 100644
--- a/frontend/src/lib/map/engine.js
+++ b/frontend/src/lib/map/engine.js
@@ -63,9 +63,16 @@ const WHEEL_ZOOM_RATE = 1 / 15;
* capture and saved view records one whole number. The gesture itself stays
* continuous — this only decides where it stops.
*/
-function settleOnLevel(map) {
+function settleOnLevel(map, following) {
let settling = false;
map.on('moveend', () => {
+ // A map linked to another one copies its camera frame by frame, fractional
+ // zooms included. The map being handled settles; the copy only follows, or
+ // the two would each start their own snap and pull the pair apart.
+ if (following()) {
+ settling = false;
+ return;
+ }
// the settling ease ends in a moveend of its own; that one is already level
if (settling) {
settling = false;
@@ -123,7 +130,8 @@ export async function createMapEngine(container, { view, imperial = false } = {}
// A source cannot be added before the style is up, and `basemap.js` adds one
// as soon as this returns.
await map.once('load');
- settleOnLevel(map);
+ const facade = mapFacade(map, container);
+ settleOnLevel(map, facade.following);
// A stable class for the tool's own cursor rules: a mode armed above the map
// says so on the surface, whichever engine drew it.
container.classList.add('map-surface');
@@ -131,5 +139,5 @@ export async function createMapEngine(container, { view, imperial = false } = {}
// whether the map is up, and asking it to recognise the engine's own class
// names is how a suite ends up pinned to the engine it was written against.
container.dataset.mapReady = 'true';
- return mapFacade(map, container);
+ return facade;
}
diff --git a/frontend/src/lib/map/facade.js b/frontend/src/lib/map/facade.js
index 3e560f2..ac170ba 100644
--- a/frontend/src/lib/map/facade.js
+++ b/frontend/src/lib/map/facade.js
@@ -36,6 +36,9 @@ const EVENTS = {
// MapLibre fires move events for any camera change, a zoom included, so one
// name covers what used to take two.
'view-settled': ['moveend'],
+ // Every frame of a movement, for what is drawn over the map in the page
+ // rather than in the engine and has to be placed again as the ground moves.
+ 'view-move': ['move'],
rotate: ['rotate'],
click: ['click'],
// The engine only fires it for a right-click that did not drag, and stops
@@ -135,6 +138,10 @@ export function framePadding(padding) {
* @param {HTMLElement} [container] the element the map was built in
*/
export function mapFacade(map, container) {
+ // Set while another map's frame is being copied onto this one (`follow`).
+ let following = false;
+ const settledHandlers = new Set();
+
/**
* Layers that answer their own click.
*
@@ -234,9 +241,97 @@ export function mapFacade(map, container) {
};
},
+ /**
+ * The ground rectangle the camera is looking at. A turned map reports the
+ * box that encloses its corners, which is what a rectangle drawn from the
+ * view has to be anyway.
+ */
+ viewBounds() {
+ const bounds = map.getBounds();
+ return {
+ west: wrapLon(bounds.getWest()),
+ south: bounds.getSouth(),
+ east: wrapLon(bounds.getEast()),
+ north: bounds.getNorth(),
+ };
+ },
+
/** The container changed size; re-read it. */
resize: () => map.resize(),
+ /**
+ * The camera exactly as the engine holds it, fractional zoom included. Only
+ * a second map copying this one reads it (`cameraLink.js`): anything that
+ * states a view uses `camera()`, which speaks whole app zoom levels.
+ */
+ frame() {
+ const centre = map.getCenter();
+ return { lng: centre.lng, lat: centre.lat, zoom: map.getZoom(), bearing: map.getBearing() };
+ },
+
+ /**
+ * Take another map's frame. While the jump runs this map is only a copy:
+ * it does not settle on a level of its own, and it does not report a
+ * settled view for each intermediate frame. `settled` marks the leader's
+ * last frame, and that one is reported once the jump is done.
+ */
+ follow(next, { settled = false } = {}) {
+ following = true;
+ try {
+ map.jumpTo({ center: [next.lng, next.lat], zoom: next.zoom, bearing: next.bearing });
+ } finally {
+ following = false;
+ }
+ if (settled) for (const handler of settledHandlers) handler(camera());
+ },
+
+ /** True while `follow` is moving this map. */
+ following: () => following,
+
+ /**
+ * The drawn pixels, once every visible tile is in.
+ *
+ * WebGL clears its buffer after each frame reaches the screen, so a canvas
+ * read at any other moment is transparent. The copy is taken inside the
+ * engine's own `render` event, which runs in the same frame as the draw.
+ * `complete` is false when the wait gave up with tiles still loading.
+ */
+ async snapshot({ timeout = 12000 } = {}) {
+ const complete = await new Promise((resolve) => {
+ if (!map.isMoving() && map.areTilesLoaded()) {
+ resolve(true);
+ return;
+ }
+ const timer = setTimeout(() => {
+ map.off('idle', idle);
+ resolve(false);
+ }, timeout);
+ const idle = () => {
+ clearTimeout(timer);
+ resolve(true);
+ };
+ map.once('idle', idle);
+ });
+ const canvas = await new Promise((resolve, reject) => {
+ map.once('render', () => {
+ try {
+ const source = map.getCanvas();
+ const copy = document.createElement('canvas');
+ copy.width = source.width;
+ copy.height = source.height;
+ const context = copy.getContext('2d');
+ if (!context) throw new Error('this browser cannot capture the map');
+ context.drawImage(source, 0, 0);
+ resolve(copy);
+ } catch (error) {
+ reject(error);
+ }
+ });
+ map.triggerRepaint();
+ });
+ return { canvas, complete };
+ },
+
/**
* Listen for something happening to the view. Returns the unsubscribe, so
* a caller cannot hold one half of the pair.
@@ -253,9 +348,15 @@ export function mapFacade(map, container) {
const at = { lat: event.lngLat.lat, lon: wrapLon(event.lngLat.lng) };
handler(name === 'click' ? at : { ...at, x: event.point.x, y: event.point.y });
}
- : () => handler(camera());
+ : name === 'view-settled'
+ ? () => {
+ if (!following) handler(camera());
+ }
+ : () => handler(camera());
+ if (name === 'view-settled') settledHandlers.add(handler);
for (const event of events) map.on(event, relay);
return () => {
+ settledHandlers.delete(handler);
for (const event of events) map.off(event, relay);
};
},
diff --git a/frontend/src/lib/map/facade.test.js b/frontend/src/lib/map/facade.test.js
index ae86c61..52304c0 100644
--- a/frontend/src/lib/map/facade.test.js
+++ b/frontend/src/lib/map/facade.test.js
@@ -165,6 +165,14 @@ describe('the map façade keeps the engine on its own side', () => {
mapFacade(map).resize();
expect(map.calls.resize).toBe(1);
});
+
+ it('reports the ground rectangle in view, wrapped back inside ±180', () => {
+ expect(mapFacade(stubMap()).viewBounds()).toEqual({ west: 0, south: -1, east: 1, north: 0 });
+ const wrapped = stubMap({
+ getBounds: () => ({ getNorth: () => 10, getSouth: () => 9, getWest: () => 179, getEast: () => 181 }),
+ });
+ expect(mapFacade(wrapped).viewBounds()).toMatchObject({ west: 179, east: -179 });
+ });
});
describe('framing an extent', () => {
@@ -254,7 +262,7 @@ describe('framing a set of points', () => {
describe('the event vocabulary', () => {
it('names what happened to the view, not what the engine calls it', () => {
- expect(MAP_EVENTS).toEqual(['view-settled', 'rotate', 'click', 'contextmenu']);
+ expect(MAP_EVENTS).toEqual(['view-settled', 'view-move', 'rotate', 'click', 'contextmenu']);
expect(engineEvents('view-settled')).toEqual(['moveend']);
});
@@ -373,3 +381,49 @@ describe('spans and teardown', () => {
expect(map.calls.removed).toBe(1);
});
});
+
+describe('capturing the drawn pixels', () => {
+ function capturable({ loaded = true } = {}) {
+ const once = new Map();
+ const copy = { width: 0, height: 0, drawn: null };
+ copy.getContext = () => ({ drawImage: (source) => (copy.drawn = source) });
+ const map = stubMap({
+ isMoving: () => false,
+ areTilesLoaded: () => loaded,
+ getCanvas: () => ({ width: 800, height: 600 }),
+ once: (name, handler) => once.set(name, handler),
+ off: (name) => once.delete(name),
+ triggerRepaint: () => once.get('render')?.(),
+ });
+ vi.stubGlobal('document', { createElement: () => copy });
+ return { map, once, copy };
+ }
+
+ it('reads the canvas inside the frame that drew it, once the tiles are in', async () => {
+ const { map, copy } = capturable();
+ try {
+ const shot = await mapFacade(map).snapshot();
+ expect(shot.complete).toBe(true);
+ expect(shot.canvas).toBe(copy);
+ expect([copy.width, copy.height]).toEqual([800, 600]);
+ expect(copy.drawn).toEqual({ width: 800, height: 600 });
+ } finally {
+ vi.unstubAllGlobals();
+ }
+ });
+
+ it('waits for the map to go idle, and says so when it gave up', async () => {
+ vi.useFakeTimers();
+ const { map, once } = capturable({ loaded: false });
+ try {
+ const waiting = mapFacade(map).snapshot({ timeout: 50 });
+ expect(once.has('idle')).toBe(true);
+ await vi.advanceTimersByTimeAsync(60);
+ const shot = await waiting;
+ expect(shot.complete).toBe(false);
+ } finally {
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+ }
+ });
+});
diff --git a/frontend/src/lib/map/groundFrame.js b/frontend/src/lib/map/groundFrame.js
new file mode 100644
index 0000000..792275d
--- /dev/null
+++ b/frontend/src/lib/map/groundFrame.js
@@ -0,0 +1,131 @@
+/**
+ * A map view as a rectangle on the ground, and the affine maps between them.
+ *
+ * On Web Mercator a screen is an exact affine image of the ground: a scale, a
+ * turn and a shift. So a picture computed for one camera can be laid over any
+ * later camera with one CSS matrix, and a Sentinel Hub frame fetched as an
+ * axis-aligned box can be drawn into a turned view the same way. Matrices use
+ * the canvas convention: `x' = a·x + c·y + e`, `y' = b·x + d·y + f`.
+ *
+ * A frame is the engine's raw camera (`facade.frame()`) plus the container's
+ * size in CSS pixels. Its `bearing` is the engine's: the compass direction
+ * that is up.
+ */
+
+const EARTH_RADIUS = 6378137;
+const WORLD = 2 * Math.PI * EARTH_RADIUS;
+const MAX_LAT = 85.05112878;
+
+export function toMercator(lon, lat) {
+ const clamped = Math.max(-MAX_LAT, Math.min(MAX_LAT, lat));
+ return [
+ EARTH_RADIUS * ((lon * Math.PI) / 180),
+ EARTH_RADIUS * Math.log(Math.tan(Math.PI / 4 + (clamped * Math.PI) / 360)),
+ ];
+}
+
+export function fromMercator(x, y) {
+ return [
+ (x / EARTH_RADIUS) * (180 / Math.PI),
+ (2 * Math.atan(Math.exp(y / EARTH_RADIUS)) - Math.PI / 2) * (180 / Math.PI),
+ ];
+}
+
+/** Ground metres per CSS pixel at an engine zoom (512 px tiles), along the projection. */
+export function mercatorPerPixel(zoom) {
+ return WORLD / (512 * 2 ** zoom);
+}
+
+/** Metres on the ground per CSS pixel at the frame's centre. */
+export function groundPerPixel(frame) {
+ return mercatorPerPixel(frame.zoom) * Math.cos((frame.lat * Math.PI) / 180);
+}
+
+export const apply = (m, x, y) => [m.a * x + m.c * y + m.e, m.b * x + m.d * y + m.f];
+
+/** `outer ∘ inner`: first inner, then outer. */
+export function compose(outer, inner) {
+ return {
+ a: outer.a * inner.a + outer.c * inner.b,
+ b: outer.b * inner.a + outer.d * inner.b,
+ c: outer.a * inner.c + outer.c * inner.d,
+ d: outer.b * inner.c + outer.d * inner.d,
+ e: outer.a * inner.e + outer.c * inner.f + outer.e,
+ f: outer.b * inner.e + outer.d * inner.f + outer.f,
+ };
+}
+
+export function invert(m) {
+ const det = m.a * m.d - m.b * m.c;
+ if (!det) throw new Error('this frame cannot be inverted');
+ return {
+ a: m.d / det,
+ b: -m.b / det,
+ c: -m.c / det,
+ d: m.a / det,
+ e: (m.c * m.f - m.d * m.e) / det,
+ f: (m.b * m.e - m.a * m.f) / det,
+ };
+}
+
+export const scale = (s) => ({ a: s, b: 0, c: 0, d: s, e: 0, f: 0 });
+
+/** Container pixel → Web Mercator metres for this frame. */
+export function screenToMercator(frame) {
+ const mpp = mercatorPerPixel(frame.zoom);
+ const turn = (frame.bearing * Math.PI) / 180;
+ const cos = Math.cos(turn);
+ const sin = Math.sin(turn);
+ const [cx, cy] = toMercator(frame.lng, frame.lat);
+ const halfW = frame.width / 2;
+ const halfH = frame.height / 2;
+ return {
+ a: mpp * cos,
+ b: -mpp * sin,
+ c: -mpp * sin,
+ d: -mpp * cos,
+ e: cx + mpp * (-halfW * cos + halfH * sin),
+ f: cy + mpp * (halfW * sin + halfH * cos),
+ };
+}
+
+/** The axis-aligned Web Mercator box that covers the whole (possibly turned) view. */
+export function frameBox(frame) {
+ const toGround = screenToMercator(frame);
+ const corners = [
+ [0, 0], [frame.width, 0], [0, frame.height], [frame.width, frame.height],
+ ].map(([x, y]) => apply(toGround, x, y));
+ const xs = corners.map((point) => point[0]);
+ const ys = corners.map((point) => point[1]);
+ return { west: Math.min(...xs), south: Math.min(...ys), east: Math.max(...xs), north: Math.max(...ys) };
+}
+
+/** Pixel (column, row) of an image covering `box` → Web Mercator metres. */
+export function imageToMercator(box, width, height) {
+ return {
+ a: (box.east - box.west) / width,
+ b: 0,
+ c: 0,
+ d: -(box.north - box.south) / height,
+ e: box.west,
+ f: box.north,
+ };
+}
+
+/** A container pixel of frame `from` → the container pixel of frame `to` on the same ground. */
+export function frameToFrame(from, to) {
+ return compose(invert(screenToMercator(to)), screenToMercator(from));
+}
+
+/**
+ * The ground corners of a view, as `[lon, lat]`, clockwise from top-left.
+ * What a computed overlay remembers about where it lies.
+ */
+export function frameCorners(frame) {
+ const toGround = screenToMercator(frame);
+ return [[0, 0], [frame.width, 0], [frame.width, frame.height], [0, frame.height]].map(
+ ([x, y]) => fromMercator(...apply(toGround, x, y))
+ );
+}
+
+export const cssMatrix = (m) => `matrix(${m.a}, ${m.b}, ${m.c}, ${m.d}, ${m.e}, ${m.f})`;
diff --git a/frontend/src/lib/map/groundFrame.test.js b/frontend/src/lib/map/groundFrame.test.js
new file mode 100644
index 0000000..76fcfe9
--- /dev/null
+++ b/frontend/src/lib/map/groundFrame.test.js
@@ -0,0 +1,79 @@
+import { describe, expect, it } from 'vitest';
+import {
+ apply,
+ compose,
+ frameBox,
+ frameToFrame,
+ fromMercator,
+ groundPerPixel,
+ imageToMercator,
+ invert,
+ screenToMercator,
+ toMercator,
+} from './groundFrame.js';
+
+const frame = (patch = {}) => ({ lng: 2.2945, lat: 48.8584, zoom: 15, bearing: 0, width: 800, height: 600, ...patch });
+const close = (actual, expected, digits = 6) =>
+ actual.forEach((value, index) => expect(value).toBeCloseTo(expected[index], digits));
+
+describe('the ground under a view', () => {
+ it('round-trips Web Mercator', () => {
+ close(fromMercator(...toMercator(2.2945, 48.8584)), [2.2945, 48.8584]);
+ });
+
+ it('puts the camera centre at the middle of the container', () => {
+ const toGround = screenToMercator(frame());
+ close(apply(toGround, 400, 300), toMercator(2.2945, 48.8584), 3);
+ });
+
+ it('reads north as up and east as right with no bearing', () => {
+ const toGround = screenToMercator(frame());
+ const [cx, cy] = apply(toGround, 400, 300);
+ const [ux, uy] = apply(toGround, 400, 0);
+ const [rx] = apply(toGround, 800, 300);
+ expect(uy).toBeGreaterThan(cy);
+ expect(ux).toBeCloseTo(cx, 3);
+ expect(rx).toBeGreaterThan(cx);
+ });
+
+ it('turns with the engine bearing: at 90° east is up', () => {
+ const toGround = screenToMercator(frame({ bearing: 90 }));
+ const [cx, cy] = apply(toGround, 400, 300);
+ const [ux, uy] = apply(toGround, 400, 0);
+ expect(ux).toBeGreaterThan(cx);
+ expect(uy).toBeCloseTo(cy, 3);
+ });
+
+ it('covers a turned view with a larger axis-aligned box', () => {
+ const flat = frameBox(frame());
+ const turned = frameBox(frame({ bearing: 30 }));
+ expect(turned.east - turned.west).toBeGreaterThan(flat.east - flat.west);
+ });
+
+ it('measures ground metres per pixel shrinking towards the poles', () => {
+ expect(groundPerPixel(frame({ lat: 0 }))).toBeGreaterThan(groundPerPixel(frame({ lat: 60 })));
+ });
+});
+
+describe('affine maps between frames', () => {
+ it('inverts and composes', () => {
+ const m = { a: 2, b: 0.5, c: -1, d: 3, e: 10, f: -4 };
+ close(apply(compose(invert(m), m), 7, -2), [7, -2]);
+ });
+
+ it('carries a point of an old view to where the same ground is now', () => {
+ const before = frame();
+ const panned = frame({ lng: 2.3, zoom: 16, bearing: 20 });
+ const ground = apply(screenToMercator(before), 120, 80);
+ const expected = apply(invert(screenToMercator(panned)), ...ground);
+ close(apply(frameToFrame(before, panned), 120, 80), expected, 4);
+ });
+
+ it('lays an axis-aligned image over the view that asked for it', () => {
+ const view = frame({ bearing: 25 });
+ const box = frameBox(view);
+ const toView = compose(invert(screenToMercator(view)), imageToMercator(box, 1000, 900));
+ const ground = [box.west, box.north];
+ close(apply(toView, 0, 0), apply(invert(screenToMercator(view)), ...ground), 4);
+ });
+});
diff --git a/frontend/src/lib/mediaViewer.js b/frontend/src/lib/mediaViewer.js
new file mode 100644
index 0000000..908f23f
--- /dev/null
+++ b/frontend/src/lib/mediaViewer.js
@@ -0,0 +1,44 @@
+/**
+ * The Saved panel's media viewer, as data: which files a press opens, how the
+ * arrows walk them, and why each one stands where it does.
+ *
+ * A file holds no coordinates of its own, so the row carries the roads that put
+ * it on the map (GET /satellite/media) and this turns them into the one line the
+ * viewer prints under the title.
+ */
+import { groupSavedMarkers } from './savedMarkers.js';
+
+/** The index one step away, wrapping at both ends of the stack. */
+export function step(index, delta, length) {
+ if (!length) return 0;
+ return (((index + delta) % length) + length) % length;
+}
+
+/**
+ * The files standing on the same metre as `row`, and where `row` sits among them.
+ *
+ * A row pressed in the tree opens the same stack its mark opens at street zoom,
+ * so the arrows walk what the map draws there rather than the one file.
+ */
+export function stackOf(rows, row) {
+ const key = row.key ?? row.id;
+ const mark = groupSavedMarkers(rows, 5).find((one) =>
+ one.items.some((item) => (item.key ?? item.id) === key)
+ );
+ const items = mark?.items ?? [row];
+ return { items, index: Math.max(0, items.findIndex((item) => (item.key ?? item.id) === key)) };
+}
+
+/** Why a file stands here, in the words the viewer prints. */
+export function roadWords(row) {
+ const words = [];
+ for (const road of row?.roads ?? []) {
+ let said = '';
+ if (road.type === 'located-at') said = 'Recorded here';
+ else if (road.type === 'depicts') said = 'Shows this place';
+ else if (road.title) said = `Via ${road.title}`;
+ else if (road.type) said = `Via a ${road.type}`;
+ if (said && !words.includes(said)) words.push(said);
+ }
+ return words.join(' · ');
+}
diff --git a/frontend/src/lib/mediaViewer.test.js b/frontend/src/lib/mediaViewer.test.js
new file mode 100644
index 0000000..7360182
--- /dev/null
+++ b/frontend/src/lib/mediaViewer.test.js
@@ -0,0 +1,63 @@
+import { describe, expect, it } from 'vitest';
+import { roadWords, stackOf, step } from './mediaViewer.js';
+
+const at = (key, lat, lon) => ({ id: key.split('@')[0], key, kind: 'media', lat, lon });
+
+describe('walking a stack', () => {
+ it('wraps at both ends', () => {
+ expect(step(0, 1, 3)).toBe(1);
+ expect(step(2, 1, 3)).toBe(0);
+ expect(step(0, -1, 3)).toBe(2);
+ });
+
+ it('stays put on an empty stack', () => {
+ expect(step(0, 1, 0)).toBe(0);
+ });
+});
+
+describe('the stack a row opens', () => {
+ it('is every file on the same metre, with the pressed one selected', () => {
+ const rows = [
+ at('[email protected],2.1', 48.1, 2.1),
+ at('[email protected],2.1', 48.1, 2.1),
+ at('c@50,3', 50, 3),
+ ];
+ const { items, index } = stackOf(rows, rows[1]);
+ expect(items.map((row) => row.key)).toEqual(['[email protected],2.1', '[email protected],2.1']);
+ expect(index).toBe(1);
+ });
+
+ it('tells apart two points of one file', () => {
+ // one video recorded on a roof and showing the street is two stacks
+ const rows = [at('[email protected],2.1', 48.1, 2.1), at('[email protected],2.2', 48.2, 2.2)];
+ expect(stackOf(rows, rows[1]).items).toEqual([rows[1]]);
+ });
+
+ it('opens the row alone when it is no longer in the list', () => {
+ const gone = at('z@1,1', 1, 1);
+ expect(stackOf([], gone)).toEqual({ items: [gone], index: 0 });
+ });
+});
+
+describe('why a file stands here', () => {
+ it('names each road once, in the order they were found', () => {
+ expect(
+ roadWords({
+ roads: [
+ { type: 'located-at', status: 'confirmed' },
+ { type: 'depicts', status: 'confirmed' },
+ { type: 'proof', title: 'Roofline', status: 'confirmed' },
+ { type: 'proof', title: 'Roofline', status: 'confirmed' },
+ ],
+ })
+ ).toBe('Recorded here · Shows this place · Via Roofline');
+ });
+
+ it('names an untitled artifact by its type', () => {
+ expect(roadWords({ roads: [{ type: 'capture', title: '' }] })).toBe('Via a capture');
+ });
+
+ it('says nothing about a row with no roads', () => {
+ expect(roadWords({})).toBe('');
+ });
+});
diff --git a/frontend/src/lib/navigate.js b/frontend/src/lib/navigate.js
index e889353..f5259db 100644
--- a/frontend/src/lib/navigate.js
+++ b/frontend/src/lib/navigate.js
@@ -41,6 +41,10 @@ export const ENTITY_TOOL = {
place: 'satellite',
post: 'post',
'inspect-session': 'inspect',
+ 'compare-session': 'compare',
+ 'analysis-zones': 'compare',
+ 'analysis-follow-up': 'compare',
+ 'analysis-run': 'compare',
};
/**
@@ -96,6 +100,17 @@ export function openEntity(entity) {
uiState.tool = 'inspect';
return;
}
+ if (entity.type === 'compare-session') {
+ const name = specName(entity.attrs?.spec);
+ if (name) uiState.openCompare = name;
+ uiState.tool = 'compare';
+ return;
+ }
+ if (['analysis-zones', 'analysis-follow-up', 'analysis-run'].includes(entity.type)) {
+ uiState.openAnalyzer = specName(entity.attrs?.spec);
+ uiState.tool = 'compare';
+ return;
+ }
if (entity.type === 'place') {
const lat = Number(entity.attrs?.lat);
const lon = Number(entity.attrs?.lon);
diff --git a/frontend/src/lib/navigate.test.js b/frontend/src/lib/navigate.test.js
index c617e5e..7aba06e 100644
--- a/frontend/src/lib/navigate.test.js
+++ b/frontend/src/lib/navigate.test.js
@@ -13,6 +13,7 @@ beforeEach(() => {
uiState.gotoCoords = null;
uiState.focusCapture = null;
uiState.openBoardEntity = null;
+ uiState.openCompare = null;
post.mockClear();
caseState.current = { id: 'c1', name: 'Case', entities: [], links: [], folders: [] };
vi.stubGlobal('window', { open: vi.fn() });
@@ -172,6 +173,13 @@ describe('reopening an artifact in its tool', () => {
expect(uiState.tool).toBe('inspect');
});
+ it('names a comparison session by its spec file', () => {
+ openEntity({ type: 'compare-session', attrs: { spec: 'comparisons/.meta/Harbour change.json' } });
+
+ expect(uiState.openCompare).toBe('Harbour change');
+ expect(uiState.tool).toBe('compare');
+ });
+
it('opens the tool empty rather than on a name it could not read', () => {
uiState.openProof = null;
openEntity({ type: 'proof', attrs: {} });
diff --git a/frontend/src/lib/state.svelte.js b/frontend/src/lib/state.svelte.js
index f80bf85..870f788 100644
--- a/frontend/src/lib/state.svelte.js
+++ b/frontend/src/lib/state.svelte.js
@@ -237,6 +237,8 @@ export const uiState = $state({
inspectPath: null, // media path to open in the Inspect tool
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
// 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.
@@ -520,6 +522,8 @@ function clearCaseHandoffs() {
uiState.focusMedia = null;
uiState.focusCapture = null;
uiState.openInspect = null;
+ uiState.openCompare = null;
+ uiState.openAnalyzer = null;
uiState.drawInGraph = null;
uiState.openBoardEntity = null;
uiState.openGraphEntity = null;
diff --git a/frontend/src/lib/state.test.js b/frontend/src/lib/state.test.js
index 59c3c13..21eec88 100644
--- a/frontend/src/lib/state.test.js
+++ b/frontend/src/lib/state.test.js
@@ -40,6 +40,7 @@ describe('closeCase', () => {
uiState.inspectPath = 'media/a.jpg';
uiState.focusMedia = 'media/a.jpg';
uiState.openInspect = 'session-a';
+ uiState.openAnalyzer = 'runs-123456789abc';
uiState.drawInGraph = { label: 'A question' };
uiState.openBoardEntity = 'entity-a';
uiState.openGraphEntity = 'entity-a';
@@ -63,6 +64,7 @@ describe('closeCase', () => {
expect(uiState.inspectPath).toBeNull();
expect(uiState.focusMedia).toBeNull();
expect(uiState.openInspect).toBeNull();
+ expect(uiState.openAnalyzer).toBeNull();
expect(uiState.drawInGraph).toBeNull();
expect(uiState.openBoardEntity).toBeNull();
expect(uiState.openGraphEntity).toBeNull();
@@ -78,16 +80,16 @@ describe('closeCase', () => {
});
describe('setSidebarWidth', () => {
- afterEach(() => vi.unstubAllGlobals());
+ afterEach(() => vi.restoreAllMocks());
it('takes a dragged width as-is when it fits', () => {
- vi.stubGlobal('window', { innerWidth: 1600 });
+ vi.spyOn(window, 'innerWidth', 'get').mockReturnValue(1600);
setSidebarWidth(440);
expect(uiState.sidebarW).toBe(440);
});
it('clamps against the live window, not just the fixed bounds', () => {
- vi.stubGlobal('window', { innerWidth: 900 });
+ vi.spyOn(window, 'innerWidth', 'get').mockReturnValue(900);
setSidebarWidth(MAX_W); // legal on a wide screen, half the canvas here
expect(uiState.sidebarW).toBe(450);
diff --git a/frontend/src/lib/trash.js b/frontend/src/lib/trash.js
index 9823502..918b544 100644
--- a/frontend/src/lib/trash.js
+++ b/frontend/src/lib/trash.js
@@ -25,6 +25,10 @@ export const FILE_BACKED = new Set([
'proof',
'post',
'inspect-session',
+ 'compare-session',
+ 'analysis-zones',
+ 'analysis-follow-up',
+ 'analysis-run',
'note',
'sheet',
]);
diff --git a/frontend/src/lib/workspaces.js b/frontend/src/lib/workspaces.js
index d127e9c..a4f748c 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', 'coordinates'] },
+ { id: 'map', label: 'Map', icon: 'satellite', tools: ['satellite', 'compare', 'coordinates'] },
{ id: 'compose', label: 'Compose', icon: 'proof', tools: ['proof', 'post', 'notebook'] },
];
@@ -63,6 +63,7 @@ export const TOOL_LABELS = {
reverse: 'Reverse Search',
inspect: 'Inspect',
satellite: 'Satellite',
+ compare: 'Compare',
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 a5474ce..a52572c 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', 'coordinates', 'proof', 'post', 'notebook',
+ 'board', 'graph', 'timeline', 'sheet', 'media', 'files', 'reverse', 'inspect', 'satellite', 'compare', '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', 'coordinates', 'proof', 'post', 'notebook']) {
+ for (const tool of ['overview', 'guide', 'board', 'graph', 'timeline', 'sheet', 'media', 'files', 'reverse', 'inspect', 'satellite', 'compare', 'coordinates', 'proof', 'post', 'notebook']) {
const owners = ALL_WORKSPACES.filter((w) => w.tools.includes(tool));
expect(owners).toHaveLength(1);
expect(workspaceOf(tool)).toBe(owners[0]);
@@ -55,8 +55,9 @@ describe('workspaceOf', () => {
expect(workspaceOf('reverse').id).toBe('collect');
});
- it('groups satellite and coordinates under map', () => {
+ it('groups satellite, compare and coordinates under map', () => {
expect(workspaceOf('satellite').id).toBe('map');
+ expect(workspaceOf('compare').id).toBe('map');
expect(workspaceOf('coordinates').id).toBe('map');
});
diff --git a/frontend/src/tools/Compare.render.test.js b/frontend/src/tools/Compare.render.test.js
new file mode 100644
index 0000000..275b0ec
--- /dev/null
+++ b/frontend/src/tools/Compare.render.test.js
@@ -0,0 +1,582 @@
+// @vitest-environment happy-dom
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { flushSync, mount, unmount } from 'svelte';
+
+const PROVIDERS = [
+ {
+ id: 'esri-world-imagery',
+ label: 'Esri World Imagery',
+ imagery: true,
+ max_zoom: 19,
+ tile_size: 256,
+ oversample: 1,
+ },
+ {
+ id: 'esri-wayback',
+ label: 'Esri Wayback',
+ imagery: true,
+ max_zoom: 19,
+ tile_size: 256,
+ oversample: 1,
+ },
+];
+
+const SESSION = {
+ azimut_compare: 1,
+ title: 'Harbour change',
+ spec: {
+ version: 2,
+ camera: { lat: 43.3, lon: 5.4, zoom: 18, bearing: 27 },
+ mode: 'swipe',
+ divider: 61,
+ opacity: 44,
+ change_assist: { sensitivity: 60, opacity: 75 },
+ annotations: [
+ { id: 'before', kind: 'text', colour: '#f6a81a', points: [[5.4, 43.3]], text: 'Before' },
+ ],
+ a: { present: true, provider: 'esri-world-imagery', overlays: ['roads'] },
+ b: { present: true, provider: 'esri-wayback', overlays: ['railway'] },
+ },
+};
+
+const RECIPE = {
+ id: 'pair', name: 'Large surface change', description: 'Changes to review',
+ phenomenon: 'Change', method: 'colour', providers: ['esri-wayback', 'sentinel2'], zones: [],
+ colour: '#f6a81a', style: 'both',
+ parameters: { sensitivity: 55, min_area: 20, min_score: 0, cleanup: 1, smoothing: 0,
+ normalize: false, index: 'ndvi', direction: 'both', ignore_clouds: true,
+ ignore_shadows: true, merge_metres: 0 },
+};
+const ANALYZERS = {
+ builtins: [RECIPE, { ...RECIPE, id: 'solo', name: 'Vessels on water', method: 'vessels',
+ providers: ['sentinel2'] }],
+ custom: [],
+ methods: [
+ { id: 'colour', label: 'Colour change', single: false, sentinel_only: false, classes: false },
+ { id: 'vessels', label: 'Infrared contrast over water', single: true, sentinel_only: true, classes: true },
+ ],
+ max_tiles: 4096, max_results: 2000,
+ grids: { sentinel2: [13, 512], 'esri-wayback': [19, 256] },
+};
+
+const get = vi.fn(async (path) => {
+ if (path === '/api/compare/analyzers') return structuredClone(ANALYZERS);
+ if (path.startsWith('/api/cases/case-a/analysis/')) return [];
+ if (path === '/api/satellite/providers') return PROVIDERS;
+ if (path === '/api/firms/sensors') {
+ return {
+ keyed: true,
+ sensors: [
+ { id: 'viirs', label: 'VIIRS (S-NPP + NOAA-20)' },
+ { id: 'modis', label: 'MODIS (Terra + Aqua)' },
+ ],
+ };
+ }
+ 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/cases/case-a/compare/sessions') {
+ return [{ name: 'Harbour change', title: 'Harbour change', provider_a: 'esri-world-imagery', provider_b: 'esri-wayback', mode: 'swipe' }];
+ }
+ if (path === '/api/cases/case-a/compare/sessions/Harbour%20change') return SESSION;
+ return {};
+});
+const post = vi.fn(async (path) => {
+ if (path === '/api/cases/case-a/compare/sessions') {
+ return { name: 'Comparison', title: 'Comparison', spec_path: 'comparisons/.meta/Comparison.json' };
+ }
+ return { file: 'comparison.png', path: '' };
+});
+vi.mock('../lib/api.js', () => ({
+ api: { get, post, put: vi.fn(), patch: vi.fn(), del: vi.fn() },
+}));
+
+const toast = vi.fn();
+const ensureCase = vi.fn(async () => ({ id: 'case-a' }));
+const reloadCase = vi.fn(async () => {});
+const caseState = { current: { id: 'case-a' } };
+vi.mock('../lib/state.svelte.js', () => ({
+ caseState,
+ ensureCase,
+ prefs: { homeView: { lat: 48.8566, lon: 2.3522, zoom: 16 }, units: 'metric' },
+ prefsReady: Promise.resolve(),
+ reloadCase,
+ toast,
+ uiState: { tool: 'compare', openCompare: null },
+}));
+
+const engines = [];
+function fakeEngine(opening, container) {
+ const handlers = {};
+ let camera = { ...opening, bearing: 0 };
+ const engine = {
+ handlers,
+ impl: { on: vi.fn(), off: vi.fn() },
+ frame: vi.fn(() => ({ lng: camera.lon, lat: camera.lat, zoom: camera.zoom - 1, bearing: camera.bearing })),
+ follow: vi.fn((frame) => { camera = { lon: frame.lng, lat: frame.lat, zoom: frame.zoom + 1, bearing: frame.bearing }; }),
+ following: () => false,
+ camera: vi.fn(() => ({ ...camera })),
+ getZoom: vi.fn(() => camera.zoom),
+ container,
+ setBearing: vi.fn((bearing) => (camera.bearing = bearing)),
+ setView: vi.fn((view, zoom) => (camera = { ...camera, ...view, zoom })),
+ syncView: vi.fn((view, zoom) => (camera = { ...camera, ...view, zoom })),
+ resize: vi.fn(),
+ snapshot: vi.fn(() => ({ width: 400, height: 300 })),
+ containerPointToLatLng: vi.fn(({ x, y }) => ({ lat: y, lon: x })),
+ latLngToContainerPoint: vi.fn(({ lat, lon }) => ({ x: lon, y: lat })),
+ panBy: vi.fn(),
+ on: vi.fn((name, handler) => {
+ // MapLibre has already moved when it emits these notifications. Mirror
+ // that in the façade double so the component's camera-alignment guard
+ // sees the same state a real surface would expose.
+ handlers[name] = (next) => {
+ if (name === 'rotate' || name === 'view-change' || name === 'view-settled') {
+ camera = { ...camera, ...next };
+ }
+ handler(next);
+ };
+ return () => delete handlers[name];
+ }),
+ destroy: vi.fn(),
+ };
+ engines.push(engine);
+ return engine;
+}
+
+vi.mock('../lib/map/engine.js', () => ({
+ createMapEngine: vi.fn(async (element, { view }) => fakeEngine(view, element)),
+}));
+vi.mock('../lib/map/basemap.js', () => ({
+ OVERLAY_IDS: [],
+ createBasemaps: vi.fn(() => ({
+ show: vi.fn(),
+ setOverlay: vi.fn(),
+ setZoomCeiling: vi.fn(),
+ dispose: vi.fn(),
+ })),
+}));
+
+const { default: Compare } = await import('./Compare.svelte');
+
+let live;
+let target;
+
+async function settle() {
+ for (let index = 0; index < 60; index += 1) await Promise.resolve();
+ flushSync();
+}
+
+async function open() {
+ target = document.createElement('div');
+ document.body.append(target);
+ live = mount(Compare, { target });
+ flushSync();
+ await settle();
+}
+
+function button(label, root = document) {
+ return [...root.querySelectorAll('button')].find((entry) => entry.textContent.trim().includes(label));
+}
+
+async function add(slot, provider = 'Esri World Imagery') {
+ const empty = [...target.querySelectorAll('.empty-slot')].find(
+ (entry) => entry.querySelector('.slot-letter').textContent === slot
+ );
+ empty.click();
+ flushSync();
+ [...document.querySelectorAll('.provider-card')]
+ .find((entry) => entry.textContent.includes(provider))
+ .click();
+ flushSync();
+ await settle();
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ engines.length = 0;
+});
+
+afterEach(() => {
+ if (live) unmount(live);
+ live = null;
+ target?.remove();
+ target = null;
+ document.body.innerHTML = '';
+});
+
+describe('Compare', () => {
+ it('opens empty and asks before any imagery is loaded', async () => {
+ await open();
+ 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');
+ });
+
+ it('adds two independent surfaces and then offers every comparison mode', async () => {
+ await open();
+ await add('A');
+ expect(engines).toHaveLength(1);
+ expect(target.querySelectorAll('.surface-shell')).toHaveLength(1);
+
+ await add('B', 'Esri Wayback');
+ expect(engines).toHaveLength(2);
+ expect(target.querySelectorAll('.surface-shell')).toHaveLength(2);
+ expect([...target.querySelectorAll('.mode-btn')].map((entry) => entry.textContent.trim())).toEqual([
+ 'Side by side',
+ 'Swipe',
+ '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());
+ expect(target.querySelectorAll('.source-card')).toHaveLength(2);
+ expect(target.querySelectorAll('.source-card button[aria-label="Imagery provider"]')).toHaveLength(2);
+ expect(
+ target.querySelector('.compare-bar').compareDocumentPosition(target.querySelector('.source-bar')) &
+ Node.DOCUMENT_POSITION_FOLLOWING
+ ).toBeTruthy();
+ // One camera, so one compass in the bar and none on either surface.
+ expect(target.querySelectorAll('button[aria-label="Reset to north"]')).toHaveLength(1);
+ expect(target.querySelector('.surface-shell button[aria-label="Reset to north"]')).toBeNull();
+ });
+
+ it('keeps the cameras together and exposes the swipe and opacity controls', async () => {
+ await open();
+ await add('A');
+ await add('B');
+
+ const next = { lat: 43.3, lon: 5.4, zoom: 18.37, bearing: 32 };
+ engines[0].handlers.rotate(next);
+ engines[0].handlers['view-settled'](next);
+ await settle();
+ expect(target.querySelector('.camera-readout').textContent).toContain('z18.4');
+ // The bar's compass reads the shared turn and puts it back to north.
+ expect(target.querySelector('button[aria-label="Reset to north"] + button').textContent.trim()).toBe('32°');
+ target.querySelector('button[aria-label="Reset to north"]').click();
+ flushSync();
+ expect(engines[0].setBearing).toHaveBeenCalledWith(0);
+
+ button('Swipe', target).click();
+ flushSync();
+ expect(target.querySelector('.compare-stage').classList.contains('swipe')).toBe(true);
+ expect(target.querySelector('input[aria-label="Swipe divider"]')).toBeNull();
+ const divider = target.querySelector('button[aria-label="Swipe divider on imagery"]');
+ divider.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowRight', bubbles: true }));
+ flushSync();
+ expect(target.querySelector('.compare-stage').style.getPropertyValue('--divider')).toBe('52%');
+
+ button('Fade', target).click();
+ flushSync();
+ expect(target.querySelector('.overlay-legend')).toBeNull();
+ const opacity = target.querySelector('input[aria-label="B opacity"]');
+ opacity.value = '25';
+ opacity.dispatchEvent(new Event('input', { bubbles: true }));
+ flushSync();
+ expect(target.querySelector('.compare-stage').style.getPropertyValue('--opacity')).toBe('0.25');
+ });
+
+ it('toggles only the difference overlay from its eye button', 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');
+ });
+
+ it('lays the difference over one image or over both, from the same switch', async () => {
+ await open();
+ await add('A');
+ await add('B', 'Esri Wayback');
+ button('Difference', target).click();
+ flushSync();
+ await settle();
+
+ const stage = () => target.querySelector('.compare-stage');
+ 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);
+
+ base('Both').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.');
+
+ base('A').click();
+ flushSync();
+ expect(stage().classList.contains('base-a')).toBe(true);
+ });
+
+ it('gives each computing mode the same column, and only one at a time', async () => {
+ await open();
+ await add('A');
+ await add('B', 'Esri Wayback');
+ expect(target.querySelector('.cmp-dock')).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();
+ });
+
+ it('pauses blink on the side that is currently shown', async () => {
+ vi.useFakeTimers();
+ try {
+ await open();
+ await add('A');
+ await add('B');
+ button('Blink', target).click();
+ flushSync();
+ await settle();
+ expect((target.querySelector('.secondary').classList.contains('blink-hidden') ? 'A' : 'B')).toBe('A');
+
+ vi.advanceTimersByTime(800);
+ flushSync();
+ expect((target.querySelector('.secondary').classList.contains('blink-hidden') ? 'A' : 'B')).toBe('B');
+
+ target.querySelector('[aria-label="Pause blink"]').click();
+ flushSync();
+ vi.advanceTimersByTime(1600);
+ flushSync();
+ expect((target.querySelector('.secondary').classList.contains('blink-hidden') ? 'A' : 'B')).toBe('B');
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('removes one surface without losing the other', async () => {
+ await open();
+ await add('A');
+ await add('B');
+ target.querySelector('button[aria-label="Remove imagery A"]').click();
+ flushSync();
+ expect(target.querySelectorAll('.surface-shell')).toHaveLength(1);
+ expect(target.querySelector('.surface-label strong').textContent).toBe('B');
+ expect(target.querySelectorAll('.mode-btn')).toHaveLength(0);
+ });
+
+ it('warns before discarding an unsaved comparison', async () => {
+ await open();
+ await add('A');
+ button('New', target).click();
+ flushSync();
+
+ const warning = document.querySelector('[role="alertdialog"]');
+ expect(warning.textContent).toContain('Discard unsaved changes?');
+ button('Cancel', warning).click();
+ flushSync();
+ expect(target.querySelectorAll('.surface-shell')).toHaveLength(1);
+
+ button('New', target).click();
+ flushSync();
+ button('Discard changes', document.querySelector('[role="alertdialog"]')).click();
+ flushSync();
+ expect(target.querySelectorAll('.empty-slot')).toHaveLength(2);
+ });
+
+ it('gives each source its own layers and keeps export choices in one modal', async () => {
+ await open();
+ await add('A');
+ await add('B');
+
+ target.querySelector('[aria-label="Layers on imagery A"]').click();
+ flushSync();
+ const layers = document.querySelector('[role="dialog"]');
+ expect(layers.getAttribute('aria-label')).toBe('Layers · A / B');
+ expect(layers.querySelectorAll('.layer-pane')).toHaveLength(2);
+ expect(layers.querySelectorAll('.layer-row')).toHaveLength(20);
+ expect(layers.textContent).toContain('Active fires');
+ expect(layers.textContent).toContain('Night lights');
+ expect(layers.textContent).toContain('Saved work');
+ const paneA = layers.querySelector('.layer-pane');
+ paneA.querySelector('button[aria-label="Show Roads on imagery A"]').click();
+ flushSync();
+ expect(target.querySelectorAll('.source-card .layers')[0].textContent).toContain('1');
+ paneA.querySelector('button[aria-label="Show Night lights on imagery A"]').click();
+ flushSync();
+ expect(target.querySelectorAll('.source-card .layers')[0].textContent).toContain('2');
+ expect(paneA.textContent).toContain('NOAA-20');
+ expect(paneA.querySelectorAll('.day-picker')).toHaveLength(1);
+ paneA.querySelector('button[aria-label="Show Active fires on imagery A"]').click();
+ flushSync();
+ expect(paneA.textContent).toContain('VIIRS');
+ expect(paneA.textContent).toContain('24 h');
+ const dates = [...paneA.querySelectorAll('.chips button')].find((entry) => entry.textContent.trim() === 'Custom');
+ dates.click();
+ flushSync();
+ expect(paneA.querySelectorAll('.day-picker')).toHaveLength(3);
+
+ button('Export', target).click();
+ await settle();
+ const output = document.querySelector('[role="dialog"]');
+ expect(output.getAttribute('aria-label')).toBe('Export a copy');
+ expect([...output.querySelectorAll('.output-choice strong')].map((entry) => entry.textContent)).toEqual([
+ 'PNG',
+ 'GIF · Blink',
+ 'GIF · Slide',
+ ]);
+ expect(output.textContent).not.toContain('Save to this case');
+ expect(output.textContent).toContain('Export copy');
+ });
+
+ it('adds a note over the comparison and keeps it in the editable state', async () => {
+ await open();
+ await add('A');
+ await add('B');
+ const canvas = target.querySelector('[aria-label="Annotations on imagery A"]');
+ canvas.getBoundingClientRect = () => ({ left: 0, top: 0, width: 1000, height: 600 });
+ target.querySelector('button[title^="Note"]').click();
+ flushSync();
+ canvas.dispatchEvent(
+ new MouseEvent('pointerdown', { bubbles: true, clientX: 16, clientY: 12 })
+ );
+ flushSync();
+ const text = target.querySelector('input[aria-label="Annotation text"]');
+ text.value = 'Before';
+ text.dispatchEvent(new Event('input', { bubbles: true }));
+ button('Apply', target).click();
+ flushSync();
+ expect(target.querySelector('.mark text').textContent).toContain('Before');
+ expect(target.querySelector('.annotation-toolbar')).not.toBeNull();
+ expect(target.querySelector('.badge').textContent).toBe('unsaved');
+ button('Save comparison', target).click();
+ flushSync();
+ button('Save comparison', document.querySelector('[role="dialog"]')).click();
+ await settle();
+ expect(post).toHaveBeenCalledWith(
+ '/api/cases/case-a/compare/sessions',
+ expect.objectContaining({
+ spec: expect.objectContaining({
+ annotations: [expect.objectContaining({ kind: 'text', text: 'Before' })],
+ }),
+ })
+ );
+ });
+
+ it('saves a reopenable session and restores sources, layers, mode and camera', async () => {
+ await open();
+ await add('A');
+ await add('B');
+ button('Save comparison', target).click();
+ flushSync();
+ expect(document.querySelector('[role="dialog"]')).not.toBeNull();
+ button('Save comparison', document.querySelector('[role="dialog"]')).click();
+ await settle();
+ expect(post).toHaveBeenCalledWith(
+ '/api/cases/case-a/compare/sessions',
+ expect.objectContaining({
+ rename_from: null,
+ spec: expect.objectContaining({
+ a: expect.objectContaining({ present: true }),
+ b: expect.objectContaining({ present: true }),
+ }),
+ })
+ );
+
+ button('New', target).click();
+ flushSync();
+ expect(target.querySelectorAll('.empty-slot')).toHaveLength(2);
+ button('Open', target).click();
+ await settle();
+ button('Harbour change', document.querySelector('[role="dialog"]')).click();
+ await settle();
+ expect(target.querySelector('input[aria-label="Comparison name"]').value).toBe('Harbour change');
+ expect(target.querySelector('.compare-stage').classList.contains('swipe')).toBe(true);
+ expect(target.querySelector('.compare-stage').style.getPropertyValue('--divider')).toBe('61%');
+ expect(target.querySelectorAll('.surface-shell')).toHaveLength(2);
+ 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 () => {
+ 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();
+ 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: world
+ // imagery on A and Wayback on B is no pair, so the step takes the wheel.
+ expect(target.querySelector('.source-bar')).toBeNull();
+ expect(dock().textContent).toContain('so they now show the one below');
+ 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 }));
+ 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');
+
+ button('Side by side', target).click();
+ flushSync();
+ expect(stage().classList.contains('solo')).toBe(false);
+ expect(target.querySelector('.source-bar')).not.toBeNull();
+ });
+
+ it('discards edits back to the saved version, where New would start over', async () => {
+ await open();
+ button('Open', target).click();
+ await settle();
+ button('Harbour change', document.querySelector('[role="dialog"]')).click();
+ await settle();
+ expect(target.querySelector('.badge')).toBeNull();
+ expect(button('Discard', target).disabled).toBe(true);
+
+ button('Fade', target).click();
+ flushSync();
+ expect(target.querySelector('.badge').textContent).toBe('unsaved');
+ expect(button('Discard', target).disabled).toBe(false);
+
+ button('Discard', target).click();
+ flushSync();
+ const dialog = document.querySelector('[role="alertdialog"]');
+ expect(dialog.textContent).toContain('Harbour change');
+ button('Discard changes', dialog).click();
+ await settle();
+ // Back to the saved swipe, with both sources still on the stage.
+ expect(target.querySelector('.compare-stage').classList.contains('swipe')).toBe(true);
+ expect(target.querySelectorAll('.surface-shell')).toHaveLength(2);
+ expect(target.querySelector('.badge')).toBeNull();
+ });
+});
diff --git a/frontend/src/tools/Compare.svelte b/frontend/src/tools/Compare.svelte
new file mode 100644
index 0000000..61bc4e7
--- /dev/null
+++ b/frontend/src/tools/Compare.svelte
@@ -0,0 +1,2314 @@
+<script>
+ /**
+ * 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
+ * MapSurface; the camera is the one shared fact.
+ */
+ import { onMount, tick, untrack } from 'svelte';
+ import { api } from '../lib/api.js';
+ import {
+ caseState,
+ ensureCase,
+ prefs,
+ prefsReady,
+ reloadCase,
+ toast,
+ uiState,
+ } from '../lib/state.svelte.js';
+ import {
+ COMPARE_LAYERS,
+ COMPARE_MODES,
+ FIND_MODES,
+ DEFAULT_DIVIDER,
+ DEFAULT_OPACITY,
+ comparisonLayers,
+ percentage,
+ availablePresets,
+ PROVIDER_KINDS,
+ providerKind,
+ } from '../lib/map/compare.js';
+ import {
+ blobBase64,
+ canvasBlob,
+ comparisonFilename,
+ composeComparison,
+ } from '../lib/map/compareExport.js';
+ import {
+ changeCompatibility,
+ changeSettings,
+ } from '../lib/map/changeAssist.js';
+ import {
+ ANNOTATION_COLOURS,
+ canFill,
+ comparisonAnnotations,
+ } from '../lib/map/compareAnnotations.js';
+ import { captureTab, extensionVersion } from '../lib/extBridge.js';
+ import {
+ CASE_FOLDER_LABEL,
+ destinationLabel,
+ readDestinations,
+ } from '../lib/exportDest.js';
+ import { startRotateDrag } from '../lib/map/gestures.js';
+ import {
+ askable as firmsAskable,
+ tileParams as firmsTileParams,
+ } from '../lib/map/firms.js';
+ import {
+ askable as nightAskable,
+ lastNight,
+ tileParams as nightTileParams,
+ } from '../lib/map/nightlights.js';
+ 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 Icon from '../components/Icon.svelte';
+ import Compass from '../components/Compass.svelte';
+ import ConfirmDialog from '../components/ConfirmDialog.svelte';
+ import ExportFolderPicker from '../components/ExportFolderPicker.svelte';
+ import Modal from '../components/Modal.svelte';
+ 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 { 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 MapSurface from './satellite/MapSurface.svelte';
+ import SavedOverlay from './satellite/SavedOverlay.svelte';
+ import LayerPane from './compare/LayerPane.svelte';
+ import AnnotationCanvas from './compare/AnnotationCanvas.svelte';
+ import AnnotationToolbar from './compare/AnnotationToolbar.svelte';
+ import { createSavedState } from './satellite/state/saved.svelte.js';
+ import PlaceSearch from './satellite/PlaceSearch.svelte';
+ 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';
+
+ const imagery = createImageryState({ api });
+ let home = $state(null);
+ let catalogueError = $state('');
+ let firesKeyed = $state(false);
+ let picking = $state(null); // 'a' | 'b' | null
+ let mode = $state('side');
+ let divider = $state(DEFAULT_DIVIDER);
+ let opacity = $state(DEFAULT_OPACITY);
+ let blinkB = $state(false);
+ let blinkInterval = $state(800);
+ let annotationSide = $state('both');
+ let blinkPaused = $state(false);
+ let coordsText = $state('');
+ let searching = $state(false);
+ let swiping = $state(false);
+ let stageEl = $state(null);
+ let rotating = $state(null); // { which, x, y } | null
+ let outputBusy = $state(''); // 'capture' | 'png' | 'gif' | 'copy' | ''
+ let rightPanel = $state(null); // 'export' | 'layers' | null
+ let grabbing = $state(false);
+ let captureSide = $state(null); // surface visible during an extension frame
+ let exportKind = $state('png'); // 'png' | 'blink' | 'slide'
+ let exportDestination = $state(null);
+ let exportPicker = $state(false);
+ let sessionName = $state('Comparison');
+ let openedSession = $state(null); // { name, title } | null
+ let savedSignature = $state(null);
+ let saveDialog = $state(false);
+ let sessionDialog = $state(false);
+ let sessionBusy = $state(false);
+ let sessionList = $state([]);
+ let discardTarget = $state(null); // { kind: 'new' | 'open' | 'revert', name? } | null
+ let annotations = $state([]);
+ let annotationTool = $state('select');
+ let selectedAnnotationId = $state(null);
+ let annotationColour = $state(ANNOTATION_COLOURS[0]);
+ let annotationStroke = $state(4);
+ let annotationFill = $state(0);
+ let annotationUndo = $state([]);
+ 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.
+ */
+ function applyAnalysisSources(next) {
+ let missing = null;
+ for (const [letter, target, sentinel, wayback] of [['a', a, s2a, wba], ['b', b, s2b, wbb]]) {
+ const source = next?.[letter];
+ if (!source) continue;
+ if (!imagery.find(source.provider)) {
+ missing = source.provider;
+ continue;
+ }
+ target.providerId = source.provider;
+ target.present = true;
+ if (source.provider === 'sentinel2') {
+ sentinel.layer = source.layer || sentinel.layer;
+ sentinel.date = source.date || '';
+ sentinel.setMaxcc(source.maxcc ?? 100);
+ } else {
+ wayback.pick(source.release ?? null);
+ }
+ }
+ if (missing) {
+ toast(`${missing === 'sentinel2' ? 'Copernicus Sentinel-2' : missing} is not configured, so the maps still show the previous imagery`, 'warn', 6000);
+ }
+ invalidateChangeAssist();
+ }
+
+ /** 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);
+ let changeUrl = $state('');
+ /** One transform per surface: the mask is ground, and each map frames it. */
+ let changeTransform = $state({ a: '', b: '' });
+ const changeVisible = $derived(changeOptions.visible);
+ const changeBase = $derived(changeOptions.base);
+ const changeOpacity = $derived(changeOptions.opacity);
+ const changePalette = $derived(changeOptions.palette);
+ const changeCounts = $derived(changeResult?.counts);
+ let changeRequest = 0;
+ let previousCaseId = null;
+ $effect(() => {
+ const id = caseState.current?.id ?? null;
+ if (previousCaseId && id !== previousCaseId) {
+ untrack(() => {
+ newComparison();
+ sessionDialog = false;
+ saveDialog = false;
+ discardTarget = null;
+ sessionList = [];
+ });
+ }
+ previousCaseId = id;
+ });
+ // The one thing A and B share. The parent owns this camera; each surface
+ // reports gestures here and receives the resulting value one way.
+ let view = $state({ lat: 0, lon: 0, zoom: 2 });
+ let bearing = $state(0);
+ const savedWork = createSavedState({ api, notify: toast, assignFolder, reloadCase });
+
+ function freshFirms() {
+ return { sensor: 'viirs', window: '24h', first: '', last: '' };
+ }
+
+ function freshNight() {
+ return { source: 'noaa20', day: lastNight() };
+ }
+
+ const a = $state({
+ present: false,
+ providerId: FALLBACK_PROVIDER,
+ engine: null,
+ element: null,
+ surface: null,
+ dated: null,
+ ready: false,
+ refused: false,
+ overlays: [],
+ firms: freshFirms(),
+ night: freshNight(),
+ });
+ const b = $state({
+ present: false,
+ providerId: FALLBACK_PROVIDER,
+ engine: null,
+ element: null,
+ surface: null,
+ dated: null,
+ ready: false,
+ refused: false,
+ overlays: [],
+ firms: freshFirms(),
+ night: freshNight(),
+ });
+
+ const s2a = createSentinelState({
+ place: () => ({ lat: view.lat, lon: view.lon }),
+ onBilled: () => imagery.refreshUsage(),
+ notify: toast,
+ api,
+ });
+ const s2b = createSentinelState({
+ place: () => ({ lat: view.lat, lon: view.lon }),
+ onBilled: () => imagery.refreshUsage(),
+ notify: toast,
+ api,
+ });
+ const wba = createWaybackState({
+ api,
+ place: () => ({ lat: view.lat, lon: view.lon, zoom: view.zoom }),
+ });
+ const wbb = createWaybackState({
+ api,
+ place: () => ({ lat: view.lat, lon: view.lon, zoom: view.zoom }),
+ });
+
+ $effect(() => {
+ const caseId = caseState.current?.id;
+ caseState.rev;
+ return savedWork.load(caseId);
+ });
+
+ 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 })
+ );
+ const shownB = $derived(
+ imagery.displayed(b.providerId, view.zoom, { ...s2b.variant, release: wbb.release })
+ );
+ const labelA = $derived(imagery.find(a.providerId)?.label ?? 'Imagery A');
+ const labelB = $derived(imagery.find(b.providerId)?.label ?? 'Imagery B');
+ const hasWidget = $derived(Boolean(shownA.provider?.widget || shownB.provider?.widget));
+ const sessionDirty = $derived(
+ (a.present || b.present) && sessionSignature() !== savedSignature
+ );
+ let firmsSensors = $state([]);
+
+ function changeSide(target, sentinel, wayback, shown) {
+ return {
+ present: target.present,
+ provider: shown.provider?.id ?? target.providerId,
+ widget: Boolean(shown.provider?.widget),
+ overlays: comparisonLayers(target.overlays),
+ firms: { ...target.firms },
+ nightlights: { ...target.night },
+ sentinel: {
+ layer: sentinel.layer,
+ date: sentinel.date,
+ effectiveDate: sentinel.date || sentinel.latest,
+ maxcc: sentinel.maxcc,
+ },
+ waybackRelease: wayback.release,
+ };
+ }
+
+ const changeStatus = $derived(
+ changeCompatibility(changeSide(a, s2a, wba, shownA), changeSide(b, s2b, wbb, shownB))
+ );
+
+ function surfaceOverlays(target) {
+ return target.overlays
+ .map((id) => {
+ if (id === 'firms') {
+ if (!firesKeyed || !firmsAskable(target.firms)) return null;
+ return { id, params: firmsTileParams(target.firms) };
+ }
+ if (id === 'nightlights') {
+ if (!nightAskable(target.night)) return null;
+ return { id, params: nightTileParams(target.night) };
+ }
+ if (id === 'saved') return null;
+ return id;
+ })
+ .filter(Boolean);
+ }
+
+ onMount(() => {
+ let gone = false;
+ void (async () => {
+ imagery.refreshUsage();
+ await prefsReady;
+ if (gone) return;
+ home = { ...prefs.homeView };
+ view = { ...home };
+ await loadProviders();
+ await loadFireCatalogue();
+ })();
+ return () => {
+ gone = true;
+ };
+ });
+
+ async function loadProviders() {
+ try {
+ await imagery.loadProviders();
+ catalogueError = '';
+ } catch (error) {
+ catalogueError = error?.message ?? 'Could not read imagery providers';
+ }
+ }
+
+ async function loadFireCatalogue() {
+ try {
+ const answer = await api.get('/api/firms/sensors');
+ firmsSensors = answer.sensors ?? [];
+ firesKeyed = Boolean(answer.keyed);
+ } catch {
+ firmsSensors = [];
+ firesKeyed = false;
+ }
+ }
+
+ function side(which) {
+ return which === 'a' ? a : b;
+ }
+
+ function savedCoords(at) {
+ return `${Number(at.lat).toFixed(5)}, ${Number(at.lon).toFixed(5)}`;
+ }
+
+ function openSaved(row) {
+ if (!Number.isFinite(Number(row?.lat)) || !Number.isFinite(Number(row?.lon))) return;
+ const zoom = Number.isFinite(Number(row.zoom)) ? Number(row.zoom) : Math.max(view.zoom, 13);
+ (a.engine ?? b.engine)?.setView({ lat: Number(row.lat), lon: Number(row.lon) }, zoom);
+ }
+
+ let cameraLink = null;
+ const zoomCeiling = $derived(both
+ ? Math.min(imagery.find(a.providerId)?.max_zoom ?? 19, imagery.find(b.providerId)?.max_zoom ?? 19)
+ : null);
+
+ function surfaceFrame(target) {
+ const box = target.element?.getBoundingClientRect();
+ return { ...target.engine.frame(), width: box?.width || 1, height: box?.height || 1 };
+ }
+
+ /** Where the computed mask lands on each surface as it is framed right now. */
+ function placeChangeMap() {
+ if (!changeResult) return;
+ changeTransform = {
+ a: a.engine ? cssMatrix(frameToFrame(changeResult.frame, surfaceFrame(a))) : '',
+ b: b.engine ? cssMatrix(frameToFrame(changeResult.frame, surfaceFrame(b))) : '',
+ };
+ }
+
+ $effect(() => {
+ const engines = [a.engine, b.engine].filter(Boolean);
+ if (!engines.length) return;
+ cameraLink = linkCameras(engines);
+ untrack(() => cameraLink.align());
+ const release = engines.map((engine) => engine.on('view-move', () => {
+ if (engine.following()) return;
+ view = engine.camera();
+ bearing = view.bearing ?? bearing;
+ placeChangeMap();
+ }));
+ return () => { cameraLink?.dispose(); cameraLink = null; release.forEach((off) => off()); };
+ });
+
+ function onSurfaceSettled(which, next) {
+ view = { lat: next.lat, lon: next.lon, zoom: next.zoom };
+ bearing = next.bearing ?? bearing;
+ invalidateChangeAssist();
+ }
+
+ function onSurfaceBearing(which, next) {
+ bearing = next.bearing;
+ }
+
+ function swapSides() {
+ const left = sideSpec(a, s2a, wba);
+ const right = sideSpec(b, s2b, wbb);
+ applySide(a, s2a, wba, right);
+ applySide(b, s2b, wbb, left);
+ 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;
+ }
+
+ function visitZone(zone) {
+ if (!changeResult) return;
+ const frame = changeResult.frame;
+ const [lon, lat] = fromMercator(...apply(screenToMercator(frame),
+ zone.centre.x * frame.width, zone.centre.y * frame.height));
+ activeEngine()?.setView({ lat, lon }, view.zoom);
+ }
+
+ function chooseProvider(provider) {
+ if (!picking || provider.needs_key) return;
+ const target = side(picking);
+ target.providerId = provider.id;
+ target.refused = false;
+ target.present = true;
+ picking = null;
+ }
+
+ function remove(which) {
+ const target = side(which);
+ target.present = false;
+ target.providerId = FALLBACK_PROVIDER;
+ target.ready = false;
+ target.refused = false;
+ target.engine = null;
+ target.element = null;
+ target.overlays = [];
+ target.firms = freshFirms();
+ target.night = freshNight();
+ mode = 'side';
+ }
+
+ // Compare owns the same Google-Earth style gesture as Satellite. Either map
+ // can lead; its live camera is bound to the other surface immediately.
+ $effect(() => {
+ const pairs = [
+ { which: 'a', element: a.element, engine: a.engine },
+ { which: 'b', element: b.element, engine: b.engine },
+ ].filter((entry) => entry.element && entry.engine);
+ const listeners = pairs.map((entry) => {
+ const down = (event) => {
+ const shiftDrag = event.button === 0 && event.shiftKey;
+ if (event.button !== 1 && !shiftDrag) return;
+ startRotateDrag(entry.engine, event, {
+ onPivot: ({ x, y }) => (rotating = { which: entry.which, x, y }),
+ onEnd: () => (rotating = null),
+ });
+ };
+ entry.element.addEventListener('mousedown', down, true);
+ return () => entry.element.removeEventListener('mousedown', down, true);
+ });
+ return () => listeners.forEach((release) => release());
+ });
+
+ // A layout change changes both map containers. MapLibre must be told after
+ // 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(() => {
+ a.engine?.resize();
+ b.engine?.resize();
+ cameraLink?.align();
+ // New rectangles, so the mask has to be placed against them again before
+ // the next camera move would have done it.
+ placeChangeMap();
+ invalidateChangeAssist();
+ });
+ });
+
+ // Tools stay mounted while hidden so their work survives a tab switch.
+ $effect(() => {
+ if (uiState.tool !== 'compare') return;
+ imagery.refreshUsage();
+ loadProviders();
+ void tick().then(() => {
+ a.engine?.resize();
+ b.engine?.resize();
+ });
+ });
+
+ $effect(() => {
+ if (uiState.tool !== 'compare' || !uiState.openCompare || !imagery.providers.length) return;
+ const name = uiState.openCompare;
+ uiState.openCompare = null;
+ requestOpenSession(name);
+ });
+
+ $effect(() => {
+ if (imagery.providers.length && !imagery.find(a.providerId)) a.providerId = FALLBACK_PROVIDER;
+ if (imagery.providers.length && !imagery.find(b.providerId)) b.providerId = FALLBACK_PROVIDER;
+ });
+
+ // Blink is an inspection aid, not an animation assembled from in-between
+ // frames: it shows A or B whole, and pauses on A whenever the mode closes.
+ $effect(() => {
+ if (mode !== 'blink' || !both || uiState.tool !== 'compare') {
+ blinkB = false;
+ return;
+ }
+ if (blinkPaused) return;
+ const timer = setInterval(() => (blinkB = !blinkB), blinkInterval);
+ return () => clearInterval(timer);
+ });
+
+ let s2aPassTimer;
+ let s2bPassTimer;
+ let s2aLatestTimer;
+ let s2bLatestTimer;
+ let wbaChangesTimer;
+ let wbbChangesTimer;
+
+ $effect(() => {
+ if (!a.present || !s2a.menuOpen || shownA.provider?.id !== SENTINEL_ID) return;
+ s2a.month;
+ s2a.placeKey;
+ clearTimeout(s2aPassTimer);
+ s2aPassTimer = setTimeout(() => s2a.loadPasses(), 600);
+ return () => clearTimeout(s2aPassTimer);
+ });
+ $effect(() => {
+ if (!b.present || !s2b.menuOpen || shownB.provider?.id !== SENTINEL_ID) return;
+ s2b.month;
+ s2b.placeKey;
+ clearTimeout(s2bPassTimer);
+ s2bPassTimer = setTimeout(() => s2b.loadPasses(), 600);
+ return () => clearTimeout(s2bPassTimer);
+ });
+ $effect(() => {
+ if (!a.ready || shownA.provider?.id !== SENTINEL_ID) return;
+ view.lat;
+ view.lon;
+ s2a.maxcc;
+ clearTimeout(s2aLatestTimer);
+ s2aLatestTimer = setTimeout(() => s2a.resolveLatest().catch(() => {}), 900);
+ return () => clearTimeout(s2aLatestTimer);
+ });
+ $effect(() => {
+ if (!b.ready || shownB.provider?.id !== SENTINEL_ID) return;
+ view.lat;
+ view.lon;
+ s2b.maxcc;
+ clearTimeout(s2bLatestTimer);
+ s2bLatestTimer = setTimeout(() => s2b.resolveLatest().catch(() => {}), 900);
+ return () => clearTimeout(s2bLatestTimer);
+ });
+ $effect(() => {
+ if (a.ready && shownA.provider?.id === WAYBACK_ID) wba.loadReleases();
+ });
+ $effect(() => {
+ if (b.ready && shownB.provider?.id === WAYBACK_ID) wbb.loadReleases();
+ });
+ $effect(() => {
+ if (!wba.menuOpen || shownA.provider?.id !== WAYBACK_ID || !wba.stale) return;
+ clearTimeout(wbaChangesTimer);
+ wbaChangesTimer = setTimeout(() => wba.loadChanges(), 900);
+ return () => clearTimeout(wbaChangesTimer);
+ });
+ $effect(() => {
+ if (!wbb.menuOpen || shownB.provider?.id !== WAYBACK_ID || !wbb.stale) return;
+ clearTimeout(wbbChangesTimer);
+ wbbChangesTimer = setTimeout(() => wbb.loadChanges(), 900);
+ return () => clearTimeout(wbbChangesTimer);
+ });
+
+ function activeEngine() {
+ return a.engine ?? b.engine;
+ }
+
+ async function goTo() {
+ const text = coordsText.trim();
+ const engine = activeEngine();
+ 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;
+ }
+ }
+
+ function goToSuggestion(item) {
+ const engine = activeEngine();
+ if (!engine || !Number.isFinite(item.lat) || !Number.isFinite(item.lon)) return;
+ engine.setView(item, item.zoom ?? Math.max(engine.getZoom(), 13));
+ }
+
+ async function onWidgetAuthFailure(provider) {
+ try {
+ await api.post(`/api/settings/keys/${provider.meter}/status`, {
+ ok: false,
+ detail: 'Google rejected the Maps JavaScript key (gm_authFailure)',
+ });
+ } catch {
+ /* the toast still gives the result */
+ }
+ toast('Google rejected the key. Basemap disabled; see Settings', 'danger', 8000);
+ await loadProviders();
+ }
+
+ function onWidgetFailed(which, provider, error) {
+ toast(`Google Maps failed to load: ${error.message}`, 'danger', 6000);
+ side(which).providerId = FALLBACK_PROVIDER;
+ }
+
+ 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];
+ if (changeOptions.method !== 'index' && changeOptions.live) void refreshChangeAssist();
+ }
+ }
+
+ function setDividerAt(clientX) {
+ const box = stageEl?.getBoundingClientRect();
+ if (!box?.width) return;
+ divider = percentage(((clientX - box.left) / box.width) * 100);
+ }
+
+ function startSwipe(event) {
+ swiping = true;
+ event.currentTarget.setPointerCapture?.(event.pointerId);
+ setDividerAt(event.clientX);
+ }
+
+ function moveSwipe(event) {
+ if (swiping) setDividerAt(event.clientX);
+ }
+
+ function stopSwipe(event) {
+ swiping = false;
+ event.currentTarget.releasePointerCapture?.(event.pointerId);
+ }
+
+ function keySwipe(event) {
+ if (event.key === 'ArrowLeft') divider = percentage(divider - 2);
+ else if (event.key === 'ArrowRight') divider = percentage(divider + 2);
+ else if (event.key === 'Home') divider = 0;
+ else if (event.key === 'End') divider = 100;
+ else return;
+ event.preventDefault();
+ }
+
+ function sideSpec(target, sentinel, wayback) {
+ return {
+ present: target.present,
+ provider: target.providerId,
+ overlays: comparisonLayers(target.overlays),
+ firms: { ...target.firms },
+ nightlights: { ...target.night },
+ sentinel: {
+ layer: sentinel.layer,
+ // Change assist 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,
+ maxcc: sentinel.maxcc,
+ },
+ wayback_release: wayback.release,
+ };
+ }
+
+ function sessionSpec() {
+ 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,
+ divider,
+ opacity,
+ blink: { interval: blinkInterval },
+ change_assist: changeSettings(changeOptions),
+ annotations: comparisonAnnotations(annotations),
+ a: sideSpec(a, s2a, wba),
+ b: sideSpec(b, s2b, wbb),
+ };
+ }
+
+ function sessionSignature() {
+ return JSON.stringify([sessionName.trim(), sessionSpec()]);
+ }
+
+ function requestSaveSession() {
+ if (!both) return;
+ if (openedSession) void performSessionSave();
+ else saveDialog = true;
+ }
+
+ async function performSessionSave() {
+ const title = sessionName.trim();
+ if (!title || sessionBusy || !both) return;
+ sessionBusy = true;
+ try {
+ const owner = await ensureCase();
+ const savedSpec = sessionSpec();
+ const result = await api.post(`/api/cases/${owner.id}/compare/sessions`, {
+ rename_from: openedSession?.name ?? null,
+ title,
+ spec: savedSpec,
+ });
+ if (caseState.current?.id !== owner.id) return;
+ sessionName = result.title;
+ openedSession = { name: result.name, title: result.title };
+ savedSignature = JSON.stringify([result.title, savedSpec]);
+ saveDialog = false;
+ let previewError = null;
+ try {
+ await saveWorkingPreview(owner.id, result.name);
+ } catch (error) {
+ previewError = error;
+ }
+ await reloadCase();
+ if (previewError) {
+ toast(`Comparison saved, but its preview could not update: ${previewError.message}`, 'warn', 7000);
+ } else {
+ toast(mode === 'blink'
+ ? 'Comparison and animated preview saved to My work'
+ : 'Comparison and preview saved to My work', 'ok');
+ }
+ } catch (error) {
+ toast(`Could not save the comparison: ${error.message}`, 'danger', 6500);
+ } finally {
+ sessionBusy = false;
+ }
+ }
+
+ async function openSessionList() {
+ sessionDialog = true;
+ sessionBusy = true;
+ try {
+ sessionList = caseState.current
+ ? await api.get(`/api/cases/${caseState.current.id}/compare/sessions`)
+ : [];
+ } catch (error) {
+ toast(`Could not read comparisons: ${error.message}`, 'danger');
+ } finally {
+ sessionBusy = false;
+ }
+ }
+
+ function applySide(target, sentinel, wayback, saved) {
+ 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');
+ }
+ target.providerId = provider;
+ target.overlays = comparisonLayers(saved?.overlays);
+ target.firms = {
+ ...freshFirms(),
+ ...(saved?.firms ?? {}),
+ };
+ target.night = {
+ ...freshNight(),
+ ...(saved?.nightlights ?? {}),
+ };
+ sentinel.layer = saved?.sentinel?.layer || sentinel.layer;
+ sentinel.date = saved?.sentinel?.date || '';
+ sentinel.setMaxcc(saved?.sentinel?.maxcc ?? 100);
+ wayback.pick(saved?.wayback_release ?? null);
+ target.present = Boolean(saved?.present);
+ target.refused = false;
+ }
+
+ async function openSession(name) {
+ if (!caseState.current || sessionBusy) return;
+ const caseId = caseState.current.id;
+ sessionBusy = true;
+ sessionDialog = false;
+ try {
+ const saved = await api.get(
+ `/api/cases/${caseId}/compare/sessions/${encodeURIComponent(name)}`
+ );
+ if (caseState.current?.id !== caseId) return;
+ const spec = saved.spec ?? saved;
+ view = {
+ lat: spec.camera.lat,
+ lon: spec.camera.lon,
+ zoom: spec.camera.zoom,
+ };
+ bearing = spec.camera?.bearing ?? 0;
+ mode = COMPARE_MODES.some((entry) => entry.id === spec.mode) ? spec.mode : 'side';
+ divider = percentage(spec.divider, DEFAULT_DIVIDER);
+ opacity = percentage(spec.opacity, DEFAULT_OPACITY);
+ changeOptions = changeSettings(spec.change_assist);
+ blinkInterval = spec.blink?.interval ?? 800;
+ annotations = comparisonAnnotations(spec.annotations);
+ resetAnnotationHistory();
+ applySide(a, s2a, wba, spec.a);
+ applySide(b, s2b, wbb, spec.b);
+ sessionName = saved.title || name;
+ openedSession = { name, title: sessionName };
+ await tick();
+ // Existing surfaces do not rebuild when a session changes the shared
+ // camera, so restore the saved view explicitly. Newly mounted surfaces
+ // already receive this view as their opening camera.
+ for (const target of [a, b]) {
+ target.engine?.setView(view, view.zoom);
+ target.engine?.setBearing(bearing);
+ }
+ a.engine?.resize();
+ b.engine?.resize();
+ savedSignature = sessionSignature();
+ if (mode === 'change' && changeOptions.method !== 'index' && changeOptions.live) void refreshChangeAssist();
+ toast(`Opened ${sessionName}`, 'ok');
+ } catch (error) {
+ toast(`Could not open the comparison: ${error.message}`, 'danger');
+ } finally {
+ sessionBusy = false;
+ }
+ }
+
+ function requestOpenSession(name) {
+ if (sessionDirty) {
+ discardTarget = { kind: 'open', name };
+ return;
+ }
+ void openSession(name);
+ }
+
+ async function deleteSession(name) {
+ if (!caseState.current || sessionBusy) return;
+ sessionBusy = true;
+ try {
+ const result = await api.del(
+ `/api/cases/${caseState.current.id}/compare/sessions/${encodeURIComponent(name)}`
+ );
+ sessionList = sessionList.filter((entry) => entry.name !== name);
+ if (openedSession?.name === name) {
+ openedSession = null;
+ savedSignature = null;
+ }
+ await reloadCase();
+ deletedToast(caseState.current.id, result, name);
+ } catch (error) {
+ toast(`Could not delete the comparison: ${error.message}`, 'danger');
+ } finally {
+ sessionBusy = false;
+ }
+ }
+
+ function newComparison() {
+ a.present = false;
+ b.present = false;
+ a.overlays = [];
+ b.overlays = [];
+ a.firms = freshFirms();
+ b.firms = freshFirms();
+ a.night = freshNight();
+ b.night = freshNight();
+ mode = 'side';
+ divider = DEFAULT_DIVIDER;
+ opacity = DEFAULT_OPACITY;
+ changeOptions = changeSettings();
+ blinkInterval = 800;
+ 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();
+ sessionName = 'Comparison';
+ openedSession = null;
+ savedSignature = null;
+ rightPanel = null;
+ }
+
+ function requestNewComparison() {
+ if (sessionDirty) {
+ discardTarget = { kind: 'new' };
+ return;
+ }
+ newComparison();
+ }
+
+ /**
+ * 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".
+ */
+ function requestDiscardChanges() {
+ if (!sessionDirty || sessionBusy) return;
+ discardTarget = openedSession
+ ? { kind: 'revert', name: openedSession.name }
+ : { kind: 'new' };
+ }
+
+ function confirmDiscard() {
+ const target = discardTarget;
+ discardTarget = null;
+ if (target?.kind === 'new') newComparison();
+ else if (target) void openSession(target.name);
+ }
+
+ function toggleLayer(target, layer) {
+ if (!target.present) return;
+ if (layer === 'firms' && !firesKeyed) return;
+ if (layer === 'saved' && !savedWork.rows.length) return;
+ target.overlays = target.overlays.includes(layer)
+ ? target.overlays.filter((id) => id !== layer)
+ : comparisonLayers([...target.overlays, layer]);
+ invalidateChangeAssist();
+ }
+
+ function copyLayers(source, target) {
+ if (!source.present || !target.present) return;
+ target.overlays = [...source.overlays];
+ target.firms = { ...source.firms };
+ target.night = { ...source.night };
+ invalidateChangeAssist();
+ }
+
+ function patchLayer(target, key, patch) {
+ target[key] = { ...target[key], ...patch };
+ invalidateChangeAssist();
+ }
+
+ async function toggleRightPanel(panel) {
+ rightPanel = rightPanel === panel ? null : panel;
+ if (rightPanel !== 'export') return;
+ try {
+ exportDestination = (await readDestinations()).views;
+ } catch {
+ exportDestination = '';
+ }
+ }
+
+ const twoPaints = () =>
+ new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)));
+
+ let changeTimer;
+ let changeRenderedKey = $state('');
+ const detectionKey = $derived(changeKey());
+
+ function changeKey() {
+ const { opacity, base, visible, zones, live, ...analysis } = changeSettings(changeOptions);
+ return JSON.stringify([
+ changeSide(a, s2a, wba, shownA),
+ changeSide(b, s2b, wbb, shownB),
+ view,
+ bearing,
+ analysis,
+ ]);
+ }
+
+ function invalidateChangeAssist() {
+ changeRenderedKey = '';
+ if (mode !== 'change' || changeOptions.method === 'index' || !changeOptions.live) return;
+ clearTimeout(changeTimer);
+ changeTimer = setTimeout(() => void refreshChangeAssist(), 180);
+ }
+
+ async function refreshChangeAssist() {
+ if (mode !== 'change' || !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 request = ++changeRequest;
+ changeBusy = true;
+ changeError = '';
+ try {
+ await tick();
+ await twoPaints();
+ if (request !== changeRequest || key !== changeKey()) return;
+ const sources = await sourceCanvases();
+ if (request !== changeRequest || key !== changeKey()) return;
+ const result = await detectCaptures(sources, settings, sides);
+ if (request !== changeRequest || mode !== 'change' || key !== changeKey()) return;
+ changeResult = result;
+ placeChangeMap();
+ changeUrl = result.canvas.toDataURL('image/png');
+ changeRenderedKey = key;
+ } catch (error) {
+ if (request !== changeRequest) return;
+ changeResult = null;
+ changeUrl = '';
+ changeError = error?.message ?? 'Could not compare these pixels';
+ } finally {
+ if (request === changeRequest) changeBusy = false;
+ }
+ }
+
+ $effect(() => {
+ if (mode !== 'change' || uiState.tool !== 'compare') { changeRequest++; return; }
+ if (!changeStatus.ok) {
+ changeRequest += 1;
+ changeResult = null;
+ changeUrl = '';
+ changeError = changeStatus.reason;
+ changeBusy = false;
+ return;
+ }
+ detectionKey;
+ changeRequest++;
+ changeBusy = false;
+ if (changeOptions.method === 'index' || !changeOptions.live) return;
+ clearTimeout(changeTimer);
+ changeTimer = setTimeout(() => void refreshChangeAssist(), 180);
+ return () => clearTimeout(changeTimer);
+ });
+
+ const selectedAnnotation = $derived(
+ annotations.find((mark) => mark.id === selectedAnnotationId) ?? null
+ );
+
+ function setAnnotations(next, commit = true) {
+ if (next.length > 200) { toast('A comparison can hold up to 200 annotations', 'warn'); return; }
+ const normal = comparisonAnnotations(next);
+ if (!commit && annotationPreviewBase === null) {
+ annotationPreviewBase = JSON.stringify(annotations);
+ }
+ if (commit) {
+ const before = annotationPreviewBase ?? JSON.stringify(annotations);
+ const after = JSON.stringify(normal);
+ if (before !== after) {
+ annotationUndo = [...annotationUndo.slice(-59), before];
+ annotationRedo = [];
+ }
+ annotationPreviewBase = null;
+ }
+ annotations = normal;
+ }
+
+ function undoAnnotation() {
+ const snapshot = annotationUndo.at(-1);
+ if (snapshot == null) return;
+ annotationRedo = [...annotationRedo, JSON.stringify(annotations)];
+ annotationUndo = annotationUndo.slice(0, -1);
+ annotations = comparisonAnnotations(JSON.parse(snapshot));
+ selectedAnnotationId = null;
+ }
+
+ function redoAnnotation() {
+ const snapshot = annotationRedo.at(-1);
+ if (snapshot == null) return;
+ annotationUndo = [...annotationUndo, JSON.stringify(annotations)];
+ annotationRedo = annotationRedo.slice(0, -1);
+ annotations = comparisonAnnotations(JSON.parse(snapshot));
+ selectedAnnotationId = null;
+ }
+
+ function patchSelectedAnnotation(patch) {
+ if (!selectedAnnotation) return;
+ setAnnotations(annotations.map((mark) =>
+ mark.id === selectedAnnotation.id ? { ...mark, ...patch } : mark
+ ));
+ }
+
+ function setAnnotationColour(value) {
+ annotationColour = value;
+ if (selectedAnnotation) patchSelectedAnnotation({ colour: value });
+ }
+
+ function setAnnotationStroke(value) {
+ if (selectedAnnotation?.kind === 'text') {
+ patchSelectedAnnotation({ font_size: value });
+ } else if (selectedAnnotation) {
+ patchSelectedAnnotation({ stroke_width: value });
+ } else {
+ annotationStroke = value;
+ }
+ }
+
+ function setAnnotationFill(value) {
+ annotationFill = value;
+ if (selectedAnnotation && canFill(selectedAnnotation.kind)) {
+ patchSelectedAnnotation({ fill_opacity: value });
+ }
+ }
+
+ function resetAnnotationHistory() {
+ annotationUndo = [];
+ annotationRedo = [];
+ annotationPreviewBase = null;
+ selectedAnnotationId = null;
+ }
+
+ $effect(() => {
+ if (!both || uiState.tool !== 'compare') return;
+ const shortcuts = { v: 'select', r: 'rect', e: 'ellipse', a: 'arrow', l: 'line', d: 'freehand', t: 'text', p: 'polygon', m: 'measure' };
+ const onKey = (event) => {
+ if (event.target?.closest?.('input, textarea, select, [contenteditable="true"]')) return;
+ const key = event.key.toLowerCase();
+ if (!event.ctrlKey && !event.metaKey && !event.altKey) {
+ const reading = COMPARE_MODES.find((entry) => entry.key === key);
+ if (reading) { setMode(reading.id); return; }
+ if (key === ' ' && mode === 'blink') { event.preventDefault(); blinkPaused = !blinkPaused; return; }
+ }
+ if ((event.ctrlKey || event.metaKey) && key === 'z') {
+ event.preventDefault();
+ if (event.shiftKey) redoAnnotation();
+ else undoAnnotation();
+ return;
+ }
+ if ((event.ctrlKey || event.metaKey) && key === 'y') {
+ event.preventDefault();
+ redoAnnotation();
+ return;
+ }
+ if ((event.key === 'Delete' || event.key === 'Backspace') && selectedAnnotationId) {
+ event.preventDefault();
+ setAnnotations(annotations.filter((mark) => mark.id !== selectedAnnotationId));
+ selectedAnnotationId = null;
+ return;
+ }
+ if (!event.ctrlKey && !event.metaKey && !event.altKey && shortcuts[key]) {
+ annotationTool = shortcuts[key];
+ }
+ };
+ document.addEventListener('keydown', onKey);
+ return () => document.removeEventListener('keydown', onKey);
+ });
+
+ function changeShare(counts) {
+ if (!counts) return 0;
+ const changed = counts.gained + counts.lost + counts.changed;
+ const total = changed + counts.quiet;
+ return total ? Math.round((changed / total) * 100) : 0;
+ }
+
+ async function capturedSurface(which) {
+ captureSide = which;
+ await twoPaints();
+ await new Promise((resolve) => setTimeout(resolve, 60));
+ const dataUrl = await captureTab();
+ const image = new window.Image();
+ await new Promise((resolve, reject) => {
+ image.onload = resolve;
+ image.onerror = () => reject(new Error('the extension returned an unreadable frame'));
+ image.src = dataUrl;
+ });
+ if (!isRegistered(
+ image.naturalWidth,
+ image.naturalHeight,
+ window.innerWidth,
+ window.innerHeight
+ )) {
+ throw new Error('the captured frame does not match this browser view. Try again');
+ }
+ const rect = side(which).element?.getBoundingClientRect();
+ const crop = rect && sourceRect(
+ { x: 0, y: 0, w: rect.width, h: rect.height },
+ {
+ mapRect: rect,
+ viewportWidth: window.innerWidth,
+ videoWidth: image.naturalWidth,
+ videoHeight: image.naturalHeight,
+ }
+ );
+ if (!crop) throw new Error('the map runs outside the captured browser area');
+ const canvas = document.createElement('canvas');
+ canvas.width = Math.round(crop.sw);
+ canvas.height = Math.round(crop.sh);
+ const context = canvas.getContext('2d');
+ context.imageSmoothingQuality = 'high';
+ context.drawImage(
+ image,
+ crop.sx,
+ crop.sy,
+ crop.sw,
+ crop.sh,
+ 0,
+ 0,
+ canvas.width,
+ canvas.height
+ );
+ return canvas;
+ }
+
+ async function sourceCanvases() {
+ if (!both || !a.ready || !b.ready) {
+ throw new Error('both maps must be ready before they can be exported');
+ }
+ if (!hasWidget) {
+ const frames = [surfaceFrame(a), surfaceFrame(b)];
+ const captures = await Promise.all([a.engine.snapshot(), b.engine.snapshot()]);
+ if (captures.some((capture) => !capture.complete)) throw new Error('Some tiles are still loading. Try again');
+ if ([a, b].some((target, index) => JSON.stringify(surfaceFrame(target)) !== JSON.stringify(frames[index]))) {
+ throw new Error('The map moved during capture. Settle it and try again');
+ }
+ return { a: { canvas: captures[0].canvas, frame: frames[0] }, b: { canvas: captures[1].canvas, frame: frames[1] } };
+ }
+ if (!extensionVersion()) {
+ throw new Error('Google imagery needs the Azimut Capture extension. Install it in Settings');
+ }
+ grabbing = true;
+ try {
+ return { a: { canvas: await capturedSurface('a'), frame: surfaceFrame(a) },
+ b: { canvas: await capturedSurface('b'), frame: surfaceFrame(b) } };
+ } finally {
+ captureSide = null;
+ grabbing = false;
+ }
+ }
+
+ function compose(
+ sources,
+ { renderMode = captureMode, renderBlinkB = blinkB, renderChangeMap = changeResult } = {}
+ ) {
+ const provenanceA = a.surface?.provenance?.() ?? {};
+ const provenanceB = b.surface?.provenance?.() ?? {};
+ const dated = (label, date) => (date ? `${label} · ${date}` : label);
+ return composeComparison({
+ a: sources.a,
+ b: sources.b,
+ mode: renderMode,
+ divider,
+ opacity,
+ change: renderChangeMap ? { ...renderChangeMap, ...changeSettings(changeOptions) } : null,
+ title: sessionName,
+ units: prefs.units,
+ blinkB: renderBlinkB,
+ annotations,
+ labelA: dated(labelA, provenanceA.imageryDate),
+ labelB: dated(labelB, provenanceB.imageryDate),
+ attributionA: shownA.provider?.attribution,
+ attributionB: shownB.provider?.attribution,
+ view,
+ bearing,
+ });
+ }
+
+ async function comparisonBlob() {
+ if (mode === 'change' && !changeStatus.ok) throw new Error(changeStatus.reason);
+ if (mode === 'change' && changeOptions.method !== 'index' && changeOptions.live && (changeRenderedKey !== changeKey() || !changeResult)) {
+ clearTimeout(changeTimer);
+ await refreshChangeAssist();
+ }
+ const sources = await sourceCanvases();
+ if (mode === 'change' && (changeRenderedKey !== changeKey() || !changeResult)) {
+ throw new Error('Run Change assist for this view before exporting');
+ }
+ const renderChangeMap = mode === 'change' ? changeResult : null;
+ return canvasBlob(compose(sources, { renderChangeMap }));
+ }
+
+ async function saveWorkingPreview(caseId, name) {
+ const form = new FormData();
+ if (mode === 'blink') {
+ const sources = await sourceCanvases();
+ const frameA = await canvasBlob(compose(sources, { renderMode: 'blink', renderBlinkB: false }));
+ const frameB = await canvasBlob(compose(sources, { renderMode: 'blink', renderBlinkB: true }));
+ form.append('image_a', frameA, 'comparison-a.png');
+ form.append('image_b', frameB, 'comparison-b.png');
+ form.append('format', 'blink');
+ form.append('interval', String(blinkInterval));
+ } else {
+ form.append('image_a', await comparisonBlob(), 'comparison.png');
+ form.append('format', 'png');
+ }
+ return api.post(
+ `/api/cases/${caseId}/compare/sessions/${encodeURIComponent(name)}/preview`,
+ form,
+ );
+ }
+
+ function outputError(action, error) {
+ if (error?.needsActivation) {
+ toast(
+ 'One-time step: click the Azimut Capture icon or press Alt+Shift+A, then try again',
+ 'warn',
+ 10000
+ );
+ return;
+ }
+ toast(`${action}: ${error.message}`, 'danger', 7000);
+ }
+
+ async function exportPng() {
+ if (outputBusy) return;
+ outputBusy = 'png';
+ try {
+ const owner = await ensureCase();
+ const blob = await comparisonBlob();
+ const result = await api.post(`/api/cases/${owner.id}/plates`, {
+ filename: comparisonFilename(),
+ format: 'png',
+ png: await blobBase64(blob),
+ });
+ rightPanel = null;
+ toast(`${result.file} written to ${destinationLabel(result.path)}`, 'ok', 5200, {
+ label: 'Show',
+ onClick: () => showExports(),
+ });
+ } catch (error) {
+ outputError('PNG export failed', error);
+ } finally {
+ outputBusy = '';
+ }
+ }
+
+ async function exportGif(animation) {
+ if (outputBusy) return;
+ outputBusy = 'gif';
+ try {
+ const owner = await ensureCase();
+ const sources = await sourceCanvases();
+ const frameA = await canvasBlob(compose(sources, { renderMode: 'blink', renderBlinkB: false }));
+ const frameB = await canvasBlob(compose(sources, { renderMode: 'blink', renderBlinkB: true }));
+ const form = new FormData();
+ form.append('image_a', frameA, 'comparison-a.png');
+ form.append('image_b', frameB, 'comparison-b.png');
+ form.append('animation', animation);
+ form.append('interval', String(blinkInterval));
+ form.append('filename', comparisonFilename());
+ const result = await api.post(`/api/cases/${owner.id}/compare/gif`, form);
+ rightPanel = null;
+ toast(`${result.file} written to ${destinationLabel(result.path)}`, 'ok', 5200, {
+ label: 'Show',
+ onClick: () => showExports(),
+ });
+ } catch (error) {
+ outputError('GIF export failed', error);
+ } finally {
+ outputBusy = '';
+ }
+ }
+
+ async function runExport() {
+ if (exportKind === 'png') await exportPng();
+ else await exportGif(exportKind);
+ }
+
+ async function showExports() {
+ if (!caseState.current) return;
+ try {
+ await api.post(`/api/cases/${caseState.current.id}/plates/reveal`);
+ } catch (error) {
+ toast(`Could not open the export folder: ${error.message}`, 'warn');
+ }
+ }
+
+ async function copyComparison() {
+ if (outputBusy) return;
+ outputBusy = 'copy';
+ try {
+ if (!navigator.clipboard?.write || typeof ClipboardItem === 'undefined') {
+ throw new Error('this browser cannot copy an image');
+ }
+ const blob = await comparisonBlob();
+ await navigator.clipboard.write([new ClipboardItem({ 'image/png': blob })]);
+ toast('Comparison copied as an image', 'ok');
+ } catch (error) {
+ outputError('Could not copy the comparison', error);
+ } finally {
+ outputBusy = '';
+ }
+ }
+</script>
+
+<div class="tool compare-tool" inert={sessionBusy}>
+ <div class="tool-header">
+ <h2>Compare</h2>
+ {#if a.present || b.present}
+ <input
+ class="input session-title"
+ bind:value={sessionName}
+ maxlength="200"
+ aria-label="Comparison name"
+ onkeydown={(event) => event.key === 'Enter' && requestSaveSession()}
+ />
+ {#if sessionDirty}<span class="badge">unsaved</span>{/if}
+ {:else}
+ <span class="sub">Two imagery views, one shared camera</span>
+ {/if}
+ <div class="spacer"></div>
+ {#if a.present || b.present}
+ <PlaceSearch
+ bind:value={coordsText}
+ savedRows={[]}
+ centre={activeView}
+ units={prefs.units}
+ {searching}
+ listId="compare-suggestions"
+ onpick={goToSuggestion}
+ onsubmit={goTo}
+ />
+ {/if}
+ <button class="btn btn-sm" onclick={openSessionList} disabled={!caseState.current || sessionBusy} title="Open a saved comparison">
+ <Icon name="folderOpen" size={13} /> Open
+ </button>
+ {#if a.present || b.present}
+ <button
+ class="btn btn-sm"
+ onclick={requestDiscardChanges}
+ disabled={!sessionDirty || 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>
+ {/if}
+ <button
+ class="btn btn-primary btn-sm"
+ onclick={requestSaveSession}
+ disabled={!both || sessionBusy || !sessionDirty}
+ title="Keep this editable comparison in My work"
+ >
+ <Icon name="save" size={13} /> {sessionBusy ? 'Saving…' : 'Save comparison'}
+ </button>
+ </div>
+
+ {#if both}
+ <div class="compare-bar">
+ <ModeDock {mode} change={changeStatus} onmode={setMode} onswap={swapSides} />
+ <div class="spacer"></div>
+ <span class="camera-readout mono">z{Number(view.zoom).toFixed(1)}</span>
+ <!-- One camera, so one compass: it turns both maps and resets them. -->
+ <Compass {bearing} onbearing={(deg) => primeEngine?.setBearing(deg)} />
+ <button class="btn btn-sm" onclick={() => toggleRightPanel('export')} disabled={!a.ready || !b.ready || !!outputBusy}>
+ <Icon name="download" size={13} /> Export
+ </button>
+ </div>
+ {/if}
+ {#if !a.present && !b.present}
+ <div class="presets">
+ {#each availablePresets(imagery.providers) as preset}
+ <button class="btn btn-sm" title={preset.hint} onclick={() => startPreset(preset)}>{preset.label}</button>
+ {/each}
+ </div>
+ {/if}
+ <!-- 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. -->
+ {#if (a.present || b.present) && !detecting}
+ <div class="source-bar" aria-label="Compared imagery">
+ {#if a.present}
+ <SourceCard letter="A" {imagery} bind:providerId={a.providerId} s2={s2a} wayback={wba}
+ 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}
+ shown={shownB} dated={b.dated} align="right" layerCount={b.overlays.length} layersOpen={rightPanel === 'layers'}
+ onlayers={() => toggleRightPanel('layers')} onremove={() => remove('b')} />
+ {:else}<button class="source-add" onclick={() => (picking = 'b')}>B · Add imagery</button>{/if}
+ </div>
+ {/if}
+
+ <div class="compare-workspace">
+ {#if both && !detecting}
+ <AnnotationToolbar
+ bind:tool={annotationTool}
+ selected={selectedAnnotation}
+ canUndo={annotationUndo.length > 0}
+ canRedo={annotationRedo.length > 0}
+ undo={undoAnnotation}
+ redo={redoAnnotation}
+ palette={ANNOTATION_COLOURS}
+ colour={annotationColour}
+ strokeWidth={annotationStroke}
+ fillOpacity={annotationFill}
+ setColour={setAnnotationColour}
+ setStroke={setAnnotationStroke}
+ setFill={setAnnotationFill}
+ bind:side={annotationSide}
+ setSide={(value) => { annotationSide = value; if (selectedAnnotation) patchSelectedAnnotation({ side: value }); }}
+ removeSelected={() => {
+ if (selectedAnnotationId) setAnnotations(annotations.filter((mark) => mark.id !== selectedAnnotationId));
+ selectedAnnotationId = null;
+ }}
+ clear={() => { setAnnotations([]); selectedAnnotationId = null; }}
+ count={annotations.length}
+ />
+ {/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:capturing={grabbing}
+ class:capture-a={captureSide === 'a'}
+ class:capture-b={captureSide === 'b'}
+ style:--divider={`${divider}%`}
+ style:--opacity={opacity / 100}
+ style:--change-opacity={changeOpacity / 100}
+ bind:this={stageEl}
+ >
+ {#if a.present && home}
+ <div class="surface-shell primary">
+ <div class="surface-label"><strong>A</strong></div>
+ <MapSurface
+ bind:this={a.surface}
+ bind:engine={a.engine}
+ bind:element={a.element}
+ {view}
+ {bearing}
+ bind:ready={a.ready}
+ bind:refused={a.refused}
+ bind:dated={a.dated}
+ bind:providerId={a.providerId}
+ {imagery}
+ s2={s2a}
+ wayback={wba}
+ {home}
+ resetToHome={false}
+ imperial={prefs.units === 'imperial'}
+ controlsTop={54}
+ chrome={false}
+ {zoomCeiling}
+ {grabbing}
+ overlays={surfaceOverlays(a)}
+ onusage={() => imagery.refreshUsage()}
+ onwidgetload={(meter) => imagery.countLoad(meter)}
+ onwidgetauthfailure={onWidgetAuthFailure}
+ onwidgetfailed={(provider, error) => onWidgetFailed('a', provider, error)}
+ onviewsettled={(next) => onSurfaceSettled('a', next)}
+ onbearingchange={(next) => onSurfaceBearing('a', next)}
+ >
+ {#if a.overlays.includes('saved')}
+ <SavedOverlay
+ engine={a.engine}
+ items={savedWork.shown}
+ caseId={caseState.current?.id}
+ coords={savedCoords}
+ onopen={openSaved}
+ onedit={openSaved}
+ onshowproofs={() => toast('Open Satellite to browse proofs', 'info')}
+ onrefresh={reloadCase}
+ />
+ {/if}
+ </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}
+ <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}
+ {#if both && !grabbing && !detecting}
+ <AnnotationCanvas {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}
+ {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}
+ bind:tool={analyzerDrawing} bind:selectedId={analyzerSelectedZone} colour="#38bdf8"
+ fillOpacity={0.08} onchange={setAnalyzerMarks} />
+ {/if}
+ {#if rotating?.which === 'a'}
+ <div class="rotate-pivot" style:left={`${rotating.x}px`} style:top={`${rotating.y}px`} aria-hidden="true"></div>
+ {/if}
+ </div>
+ {:else}
+ <button class="empty-slot" onclick={() => (picking = 'a')} disabled={!home}>
+ <span class="slot-letter">A</span>
+ <Icon name="plus" size={22} />
+ <strong>Add imagery</strong>
+ <span>Choose a provider, then its date.</span>
+ </button>
+ {/if}
+
+ {#if b.present && home}
+ <div
+ class="surface-shell secondary"
+ class:blink-hidden={mode === 'blink' && !blinkB}
+ >
+ <div class="surface-label"><strong>B</strong></div>
+ <MapSurface
+ bind:this={b.surface}
+ bind:engine={b.engine}
+ bind:element={b.element}
+ {view}
+ {bearing}
+ bind:ready={b.ready}
+ bind:refused={b.refused}
+ bind:dated={b.dated}
+ bind:providerId={b.providerId}
+ {imagery}
+ s2={s2b}
+ wayback={wbb}
+ {home}
+ resetToHome={false}
+ imperial={prefs.units === 'imperial'}
+ controlsTop={54}
+ chrome={false}
+ {zoomCeiling}
+ {grabbing}
+ overlays={surfaceOverlays(b)}
+ onusage={() => imagery.refreshUsage()}
+ onwidgetload={(meter) => imagery.countLoad(meter)}
+ onwidgetauthfailure={onWidgetAuthFailure}
+ onwidgetfailed={(provider, error) => onWidgetFailed('b', provider, error)}
+ onviewsettled={(next) => onSurfaceSettled('b', next)}
+ onbearingchange={(next) => onSurfaceBearing('b', next)}
+ >
+ {#if b.overlays.includes('saved')}
+ <SavedOverlay
+ engine={b.engine}
+ items={savedWork.shown}
+ caseId={caseState.current?.id}
+ coords={savedCoords}
+ onopen={openSaved}
+ onedit={openSaved}
+ onshowproofs={() => toast('Open Satellite to browse proofs', 'info')}
+ onrefresh={reloadCase}
+ />
+ {/if}
+ </MapSurface>
+ {#if both && mode === 'change' && 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}
+ <AnnotationCanvas {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}
+ {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}
+ bind:tool={analyzerDrawing} bind:selectedId={analyzerSelectedZone} colour="#38bdf8"
+ fillOpacity={0.08} onchange={setAnalyzerMarks} />
+ {/if}
+ {#if rotating?.which === 'b'}
+ <div class="rotate-pivot" style:left={`${rotating.x}px`} style:top={`${rotating.y}px`} aria-hidden="true"></div>
+ {/if}
+ </div>
+ {:else}
+ <button class="empty-slot" onclick={() => (picking = 'b')} disabled={!home}>
+ <span class="slot-letter">B</span>
+ <Icon name="plus" size={22} />
+ <strong>Add imagery</strong>
+ <span>Choose a provider, then its date.</span>
+ </button>
+ {/if}
+
+ {#if both && mode === 'swipe'}
+ <button
+ type="button"
+ class="swipe-line"
+ role="slider"
+ aria-label="Swipe divider on imagery"
+ aria-valuemin="0"
+ aria-valuemax="100"
+ aria-valuenow={divider}
+ tabindex="0"
+ onpointerdown={startSwipe}
+ onpointermove={moveSwipe}
+ onpointerup={stopSwipe}
+ onpointercancel={stopSwipe}
+ onkeydown={keySwipe}
+ ><span>↔</span></button>
+ {/if}
+
+ {#if both && mode === 'change'}
+ <div class="change-legend" class:colourblind={changePalette === 'colourblind'} class:hidden={!changeVisible}>
+ <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}
+ </div>
+ {/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), wayback_release: wba.release ?? wba.releases[0]?.release },
+ b: { ...sideSpec(b, s2b, wbb), wayback_release: wbb.release ?? wbb.releases[0]?.release } }}
+ releases={wba.releases.length ? wba.releases : wbb.releases}
+ 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}
+ onsources={applyAnalysisSources} onclose={() => setMode('side')} />
+ {/if}
+ </div>
+
+ {#if both && !FIND_MODES.includes(mode) && mode !== 'side'}
+ <div class="mode-footer">
+ <ModeControl {mode} bind:divider bind:opacity bind:blinkB bind:blinkPaused bind:blinkInterval />
+ </div>
+ {/if}
+ {#if rightPanel === 'export'}
+ <Modal title="Export a copy" onclose={() => (rightPanel = null)} width="540px">
+ <div class="export-dialog">
+ <div class="output-list">
+ <label class="output-choice" class:selected={exportKind === 'png'}>
+ <input type="radio" bind:group={exportKind} value="png" />
+ <Icon name="image" size={17} />
+ <span><strong>PNG</strong><small>The comparison exactly as it reads now.</small></span>
+ </label>
+ <label class="output-choice" class:selected={exportKind === 'blink'}>
+ <input type="radio" bind:group={exportKind} value="blink" />
+ <Icon name="play" size={17} />
+ <span><strong>GIF · Blink</strong><small>Alternates the two complete views.</small></span>
+ </label>
+ <label class="output-choice" class:selected={exportKind === 'slide'}>
+ <input type="radio" bind:group={exportKind} value="slide" />
+ <Icon name="panelRight" size={17} />
+ <span><strong>GIF · Slide</strong><small>Sweeps the divider across the image.</small></span>
+ </label>
+ </div>
+
+ <div class="destination">
+ <span class="field-label">Destination</span>
+ <strong title={exportDestination || CASE_FOLDER_LABEL}>
+ {exportDestination === null ? 'Reading…' : destinationLabel(exportDestination)}
+ </strong>
+ <button class="link" onclick={() => (exportPicker = true)}>Change…</button>
+ </div>
+
+ {#if hasWidget}
+ <p class="panel-note"><Icon name="info" size={13} /> Google pixels are captured through the Azimut Capture extension.</p>
+ {/if}
+
+ <div class="panel-actions">
+ <button class="btn" disabled={!!outputBusy} onclick={copyComparison}>
+ <Icon name="copy" size={13} /> {outputBusy === 'copy' ? 'Copying…' : 'Copy current PNG'}
+ </button>
+ <button class="btn btn-primary" disabled={!!outputBusy} onclick={runExport}>
+ <Icon name="download" size={13} /> {outputBusy === 'png' || outputBusy === 'gif' ? 'Exporting…' : 'Export copy'}
+ </button>
+ </div>
+
+ <button class="folder-open" onclick={showExports} disabled={!caseState.current}>
+ <Icon name="folderOpen" size={13} /> Show export folder
+ </button>
+ </div>
+ </Modal>
+ {/if}
+
+ {#if rightPanel === 'layers'}
+ <Modal title="Layers · A / B" onclose={() => (rightPanel = null)} width="900px">
+ <p class="panel-intro">Each side keeps its own layers. Use the eye to show one, or copy a complete stack across.</p>
+ <div class="layer-columns">
+ <LayerPane
+ letter="A"
+ present={a.present}
+ layers={COMPARE_LAYERS}
+ overlays={a.overlays}
+ firms={a.firms}
+ night={a.night}
+ {firmsSensors}
+ {firesKeyed}
+ savedCount={savedWork.rows.length}
+ ontoggle={(layer) => toggleLayer(a, layer)}
+ onfirms={(patch) => patchLayer(a, 'firms', patch)}
+ onnight={(patch) => patchLayer(a, 'night', patch)}
+ oncopy={() => copyLayers(a, b)}
+ onclear={() => { a.overlays = []; invalidateChangeAssist(); }}
+ />
+ <LayerPane
+ letter="B"
+ present={b.present}
+ layers={COMPARE_LAYERS}
+ overlays={b.overlays}
+ firms={b.firms}
+ night={b.night}
+ {firmsSensors}
+ {firesKeyed}
+ savedCount={savedWork.rows.length}
+ ontoggle={(layer) => toggleLayer(b, layer)}
+ onfirms={(patch) => patchLayer(b, 'firms', patch)}
+ onnight={(patch) => patchLayer(b, 'night', patch)}
+ oncopy={() => copyLayers(b, a)}
+ onclear={() => { b.overlays = []; invalidateChangeAssist(); }}
+ />
+ </div>
+ </Modal>
+ {/if}
+</div>
+
+{#if picking}
+ <Modal title={`Add imagery ${picking.toUpperCase()}`} onclose={() => (picking = null)} width="520px">
+ <p class="picker-lead">The first view sets the ground. Every view added after it opens on the same camera.</p>
+ {#if catalogueError}
+ <div class="picker-error">
+ <span>{catalogueError}</span>
+ <button class="btn btn-sm" onclick={loadProviders}>Retry</button>
+ </div>
+ {:else if !imagery.providers.length}
+ <p class="picker-loading">Reading imagery providers…</p>
+ {:else}
+ {#each PROVIDER_KINDS as kind (kind.id)}
+ {#if imagery.providers.some((entry) => providerKind(entry) === kind.id)}
+ <h3 class="provider-kind">{kind.label}</h3>
+ <div class="provider-grid">
+ {#each imagery.providers.filter((entry) => providerKind(entry) === kind.id) as provider (provider.id)}
+ <button
+ class="provider-card"
+ disabled={provider.needs_key}
+ onclick={() => chooseProvider(provider)}
+ title={provider.needs_key ? 'Add this provider’s API key in Settings' : undefined}
+ >
+ <Icon name={provider.imagery === false ? 'globe' : 'satellite'} size={18} />
+ <span class="provider-copy">
+ <strong>{provider.label}</strong>
+ <small>{provider.needs_key ? 'Needs a key' : provider.imagery === false ? 'Reference map' : 'Imagery'}</small>
+ </span>
+ </button>
+ {/each}
+ </div>
+ {/if}
+ {/each}
+ {/if}
+ </Modal>
+{/if}
+
+{#if saveDialog}
+ <Modal title="Save comparison" onclose={() => (saveDialog = false)} width="440px">
+ <div class="save-form">
+ <label>Name
+ <!-- svelte-ignore a11y_autofocus -->
+ <input class="input" bind:value={sessionName} maxlength="200" autofocus onkeydown={(event) => event.key === 'Enter' && performSessionSave()} />
+ </label>
+ <p>Saves every control needed to reopen this view.</p>
+ <div class="modal-actions">
+ <button class="btn" onclick={() => (saveDialog = false)}>Cancel</button>
+ <button class="btn btn-primary" disabled={!sessionName.trim() || sessionBusy} onclick={performSessionSave}>
+ {sessionBusy ? 'Saving…' : 'Save comparison'}
+ </button>
+ </div>
+ </div>
+ </Modal>
+{/if}
+
+{#if sessionDialog}
+ <Modal title="Open comparison" onclose={() => (sessionDialog = false)} width="540px">
+ {#if sessionBusy}
+ <p class="picker-loading">Reading saved comparisons…</p>
+ {:else if !sessionList.length}
+ <div class="session-empty"><Icon name="layers" size={24} /><strong>No saved comparisons yet.</strong></div>
+ {:else}
+ <div class="session-list">
+ {#each sessionList as saved (saved.name)}
+ <div class="session-row">
+ <button class="session-open" onclick={() => requestOpenSession(saved.name)}>
+ <strong>{saved.title}</strong>
+ <span>{imagery.find(saved.provider_a)?.label ?? saved.provider_a} / {imagery.find(saved.provider_b)?.label ?? saved.provider_b}</span>
+ <small>{COMPARE_MODES.find((entry) => entry.id === saved.mode)?.label ?? saved.mode}{saved.updated_at ? ` · ${saved.updated_at.replace('T', ' ').replace('Z', '')}` : ''}</small>
+ </button>
+ <button class="btn btn-ghost btn-xs" onclick={() => deleteSession(saved.name)} aria-label={`Delete ${saved.title}`}><Icon name="trash" size={14} /></button>
+ </div>
+ {/each}
+ </div>
+ {/if}
+ </Modal>
+{/if}
+
+{#if discardTarget}
+ <ConfirmDialog
+ title="Discard unsaved changes?"
+ message={discardTarget.kind === 'revert'
+ ? `This comparison goes back to the version saved as “${discardTarget.name}”.`
+ : 'The current comparison has not been saved.'}
+ detail="Saving keeps the sources, layers and camera together."
+ confirmLabel="Discard changes"
+ icon="compare"
+ onconfirm={confirmDiscard}
+ oncancel={() => (discardTarget = null)}
+ />
+{/if}
+
+{#if exportPicker}
+ <ExportFolderPicker
+ kind="views"
+ current={exportDestination ?? ''}
+ confirmLabel="Export here"
+ onclose={() => (exportPicker = false)}
+ onchosen={(path) => (exportDestination = path)}
+ />
+{/if}
+
+<style>
+ .tool { position: relative; }
+ .spacer { flex: 1; }
+ .tool-header { min-height: 55px; }
+ .tool-header :global(.place-search) { width: min(440px, 40vw); }
+ .session-title {
+ width: min(250px, 22vw);
+ height: 30px;
+ padding: 4px 8px;
+ font-weight: 650;
+ }
+ .badge {
+ padding: 2px 6px;
+ border-radius: 99px;
+ color: var(--warn);
+ background: color-mix(in srgb, var(--warn) 12%, transparent);
+ font-size: 10px;
+ text-transform: uppercase;
+ letter-spacing: .05em;
+ }
+ .source-bar {
+ display: grid;
+ grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
+ gap: 1px;
+ padding: 1px;
+ border-bottom: 1px solid var(--border);
+ background: var(--border-strong);
+ }
+ .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); }
+ .presets { display: flex; justify-content: center; gap: 8px; padding: 8px; }
+ .compare-workspace { display: flex; min-height: 0; flex: 1; }
+ .compare-stage {
+ position: relative;
+ flex: 1;
+ min-height: 0;
+ display: flex;
+ gap: 1px;
+ padding: 1px;
+ background: var(--border-strong);
+ overflow: hidden;
+ }
+ .surface-shell, .empty-slot {
+ position: relative;
+ flex: 1 1 50%;
+ min-width: 0;
+ min-height: 0;
+ }
+ .surface-shell { display: flex; overflow: hidden; background: var(--bg-0); }
+ .surface-label {
+ position: absolute;
+ top: 11px;
+ left: 11px;
+ z-index: 520;
+ display: flex;
+ align-items: center;
+ height: 29px;
+ border: 1px solid rgba(255,255,255,.18);
+ border-radius: var(--r-sm);
+ color: #f2f2f2;
+ background: rgba(24,24,24,.88);
+ backdrop-filter: blur(6px);
+ box-shadow: var(--shadow-1);
+ }
+ .surface-label strong { padding: 0 9px; font-size: var(--fs-xs); color: var(--accent); }
+ .empty-slot {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ gap: 8px;
+ border: 1px dashed var(--border-strong);
+ color: var(--text-3);
+ background: var(--bg-0);
+ cursor: pointer;
+ }
+ .empty-slot:hover:not(:disabled) { color: var(--text-1); background: var(--bg-1); border-color: var(--accent); }
+ .empty-slot:disabled { cursor: wait; }
+ .empty-slot strong { font-size: var(--fs-md); color: var(--text-1); }
+ .empty-slot span:last-child { font-size: var(--fs-sm); }
+ .slot-letter {
+ position: absolute;
+ top: 16px;
+ left: 18px;
+ font-size: var(--fs-xs);
+ font-weight: 700;
+ color: var(--accent);
+ }
+ .compare-stage.overlay { display: block; padding: 0; background: var(--bg-0); }
+ .compare-stage.overlay .surface-shell { position: absolute; inset: 0; }
+ /* A transparent B surface must reveal A at 0%, rather than its own empty
+ shell background painting a gray rectangle over the image underneath. */
+ .compare-stage.overlay .surface-shell { background: transparent; }
+ .compare-stage.overlay .primary { z-index: 1; }
+ .compare-stage.overlay .secondary { z-index: 2; }
+ .compare-stage.overlay .surface-label { display: none; }
+ /* 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;
+ inset: 0;
+ width: 100%;
+ height: 100%;
+ object-fit: fill;
+ transform-origin: 0 0;
+ opacity: var(--change-opacity);
+ pointer-events: none;
+ }
+ .change-legend {
+ position: absolute;
+ z-index: 555;
+ right: 12px;
+ bottom: 12px;
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ padding: 7px 9px;
+ border: 1px solid rgba(255,255,255,.16);
+ border-radius: var(--r-sm);
+ color: #e9edf1;
+ background: rgba(18,21,25,.88);
+ box-shadow: var(--shadow-1);
+ 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); }
+ .change-legend .loss { background: rgb(239,68,68); }
+ .change-legend .changed { background: rgb(250,204,21); }
+ .change-legend.colourblind .gain { background: rgb(0,114,178); }
+ .change-legend.colourblind .loss { background: rgb(230,159,0); }
+ .change-legend.colourblind .changed { background: rgb(204,121,167); }
+ .change-legend 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; }
+ .compare-stage.capture-a .secondary,
+ .compare-stage.capture-b .primary { visibility: hidden; }
+ .compare-stage.capturing.swipe .secondary { clip-path: none; }
+ .compare-stage.capturing.blended .secondary :global(.map),
+ .compare-stage.capturing.blended .secondary :global(.map-glass) { opacity: 1; }
+ .compare-stage.capturing.overlay .secondary.blink-hidden { opacity: 1; pointer-events: auto; }
+ .swipe-line {
+ position: absolute;
+ z-index: 540;
+ top: 0;
+ bottom: 0;
+ left: var(--divider);
+ width: 2px;
+ transform: translateX(-1px);
+ background: rgba(255,255,255,.92);
+ cursor: ew-resize;
+ touch-action: none;
+ box-shadow: 0 0 5px rgba(0,0,0,.75);
+ }
+ .swipe-line::before {
+ content: '';
+ position: absolute;
+ inset: 0 -12px;
+ }
+ .swipe-line:focus-visible span { outline: 2px solid var(--accent); outline-offset: 2px; }
+ .swipe-line span {
+ position: absolute;
+ top: 50%;
+ left: 50%;
+ display: grid;
+ place-items: center;
+ width: 32px;
+ height: 32px;
+ transform: translate(-50%, -50%);
+ border-radius: 50%;
+ color: #181818;
+ background: #f2f2f2;
+ box-shadow: var(--shadow-2);
+ }
+ .rotate-pivot {
+ position: absolute;
+ z-index: 570;
+ width: 34px;
+ height: 34px;
+ transform: translate(-50%, -50%);
+ border: 1px solid rgba(255,255,255,.92);
+ border-radius: 50%;
+ pointer-events: none;
+ box-shadow: 0 0 0 1px rgba(0,0,0,.7), inset 0 0 0 8px rgba(0,0,0,.25);
+ }
+ .rotate-pivot::before,
+ .rotate-pivot::after {
+ content: '';
+ position: absolute;
+ background: rgba(255,255,255,.92);
+ }
+ .rotate-pivot::before { left: 50%; top: 5px; bottom: 5px; width: 1px; }
+ .rotate-pivot::after { top: 50%; left: 5px; right: 5px; height: 1px; }
+ .picker-lead { margin-bottom: 13px; color: var(--text-2); font-size: var(--fs-sm); }
+ .provider-kind { font-size: 12px; margin: 12px 0 6px; color: var(--text-3); }
+ .provider-grid { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 8px; min-width: 0; }
+ .provider-card {
+ display: flex;
+ align-items: center;
+ gap: 11px;
+ min-height: 58px;
+ min-width: 0;
+ width: 100%;
+ padding: 10px 12px;
+ border: 1px solid var(--border);
+ border-radius: var(--r-md);
+ color: var(--text-2);
+ background: var(--bg-2);
+ text-align: left;
+ cursor: pointer;
+ }
+ .provider-card:hover:not(:disabled) { color: var(--accent); border-color: var(--border-strong); background: var(--bg-3); }
+ .provider-card:disabled { opacity: .52; cursor: not-allowed; }
+ .provider-copy { display: flex; flex-direction: column; gap: 2px; min-width: 0; }
+ .provider-copy strong { color: var(--text-1); overflow-wrap: anywhere; }
+ .provider-copy small { color: var(--text-3); font-size: var(--fs-xs); }
+ .picker-error { display: flex; align-items: center; justify-content: space-between; gap: 14px; color: var(--danger); }
+ .picker-loading { padding: 16px 0; color: var(--text-3); text-align: center; }
+
+ .field-label {
+ color: var(--text-3);
+ font-size: 10px;
+ font-weight: 700;
+ letter-spacing: .08em;
+ text-transform: uppercase;
+ }
+ .export-dialog { display: grid; gap: 15px; }
+ .output-list { display: grid; gap: 8px; }
+ .output-choice {
+ display: grid;
+ grid-template-columns: auto auto minmax(0, 1fr);
+ align-items: flex-start;
+ gap: 9px;
+ padding: 10px;
+ border: 1px solid var(--border);
+ border-radius: var(--r-md);
+ color: var(--text-3);
+ cursor: pointer;
+ }
+ .output-choice:hover,
+ .output-choice.selected { border-color: var(--border-strong); color: var(--accent); background: var(--bg-2); }
+ .output-choice span,
+ .output-choice small { display: block; }
+ .output-choice strong { color: var(--text-1); font-size: var(--fs-sm); }
+ .output-choice small { margin-top: 2px; color: var(--text-3); font-size: var(--fs-xs); line-height: 1.35; }
+ .destination { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 5px 10px; align-items: center; padding-top: 13px; border-top: 1px solid var(--border); }
+ .destination .field-label { grid-column: 1 / -1; }
+ .destination strong { overflow: hidden; color: var(--text-2); font-size: var(--fs-xs); text-overflow: ellipsis; white-space: nowrap; }
+ .link { color: var(--accent); font-size: var(--fs-xs); }
+ .panel-note,
+ .panel-intro { margin: 0; color: var(--text-3); font-size: var(--fs-xs); line-height: 1.45; }
+ .panel-intro { padding: 0 0 12px; }
+ .panel-note { display: flex; gap: 7px; align-items: flex-start; }
+ .panel-actions { display: flex; gap: 8px; }
+ .panel-actions .btn { flex: 1; justify-content: center; }
+ .folder-open { display: flex; align-items: center; gap: 7px; color: var(--text-3); font-size: var(--fs-xs); }
+ .folder-open:hover:not(:disabled) { color: var(--text-1); }
+ .layer-columns {
+ height: min(68vh, 690px);
+ display: grid;
+ grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
+ gap: 10px;
+ }
+ .save-form { display: grid; gap: 13px; }
+ .save-form label { display: grid; gap: 6px; color: var(--text-2); font-size: var(--fs-sm); }
+ .save-form p { margin: 0; color: var(--text-3); font-size: var(--fs-xs); }
+ .modal-actions { display: flex; justify-content: flex-end; gap: 8px; }
+ .session-empty { display: grid; place-items: center; gap: 8px; min-height: 150px; color: var(--text-3); }
+ .session-list { display: grid; max-height: min(56vh, 480px); overflow: auto; border: 1px solid var(--border); border-radius: var(--r-md); }
+ .session-row { display: flex; align-items: center; gap: 6px; min-width: 0; }
+ .session-row + .session-row { border-top: 1px solid var(--border); }
+ .session-open { display: grid; gap: 2px; min-width: 0; flex: 1; padding: 10px 12px; text-align: left; }
+ .session-open:hover { background: var(--bg-2); }
+ .session-open strong,
+ .session-open span,
+ .session-open small { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+ .session-open strong { color: var(--text-1); }
+ .session-open span { color: var(--text-2); font-size: var(--fs-xs); }
+ .session-open small { color: var(--text-3); font-size: 10px; }
+ @media (max-width: 900px) {
+ .tool-header .sub { display: none; }
+ .compare-stage:not(.overlay) { flex-direction: column; }
+ .provider-grid { grid-template-columns: 1fr; }
+ .source-bar { grid-template-columns: 1fr; }
+ .compare-bar { flex-wrap: wrap; }
+ .session-title { width: 150px; }
+ .camera-readout { display: none; }
+ .layer-columns { height: min(72vh, 720px); grid-template-columns: 1fr; overflow: auto; }
+ }
+</style>
diff --git a/frontend/src/tools/Files.svelte b/frontend/src/tools/Files.svelte
index 547f350..959b858 100644
--- a/frontend/src/tools/Files.svelte
+++ b/frontend/src/tools/Files.svelte
@@ -14,7 +14,7 @@
import { buildTree, subtreeCount, folderOf, flattenPaths, isInFolderSubtree } from '../lib/folderTree.js';
import { assignFolder, assignFolderBatch } from '../lib/filing.js';
import { createNote } from '../lib/notes.js';
- import { openNotebook } from '../lib/navigate.js';
+ import { openEntity, openNotebook } from '../lib/navigate.js';
import { createBookmark } from '../lib/bookmarks.js';
import { listenForPaste, pasteImage, resolvePaste } from '../lib/clipboardPaste.js';
import { marqueeRect, marqueeHits, toggleSelection } from '../lib/gridSelect.js';
@@ -42,7 +42,7 @@
const TYPE_ICON = {
media: 'image', capture: 'satellite', note: 'note', proof: 'proof',
- post: 'post', place: 'pin', 'inspect-session': 'inspect', bookmark: 'link',
+ post: 'post', place: 'pin', 'inspect-session': 'inspect', 'compare-session': 'compare', bookmark: 'link',
};
const VIDEO_EXTS = new Set(['mp4', 'mov', 'webm', 'mkv', 'avi', 'm4v']);
@@ -127,6 +127,7 @@
const tileThumb = (e) => {
const path = e.attrs?.path;
if (e.type === 'proof' && typeof path === 'string' && /\.png$/i.test(path)) return path;
+ if (e.type === 'compare-session' && typeof path === 'string' && /\.(png|gif)$/i.test(path)) return path;
return pathInfo.get(path)?.thumbnail ?? null;
};
@@ -619,6 +620,10 @@
openNotebook(entity.id);
return;
}
+ if (['compare-session', 'analysis-zones', 'analysis-follow-up', 'analysis-run'].includes(entity.type)) {
+ openEntity(entity);
+ return;
+ }
infoEntityId = entity.id;
}
function ctxMoveToUnfiled() {
diff --git a/frontend/src/tools/Overview.render.test.js b/frontend/src/tools/Overview.render.test.js
index 9d5e3b9..4c170c9 100644
--- a/frontend/src/tools/Overview.render.test.js
+++ b/frontend/src/tools/Overview.render.test.js
@@ -68,8 +68,13 @@ const answers = async (url) => {
if (url.includes('/catalog/entities')) return { items: RECENT, total: 30, next_cursor: null };
return {};
};
+const checklist = { revision: 0, lists: [{ id: 'default', name: 'Tasks', tasks: [] }] };
const get = vi.fn(answers);
-vi.mock('../lib/api.js', () => ({ api: { get, post: vi.fn(), del: vi.fn(), patch: vi.fn(), put: vi.fn() }, ApiError: Error }));
+const read = async (url, ...args) => {
+ const result = await get(url, ...args);
+ return url.endsWith('/todos') ? checklist : result;
+};
+vi.mock('../lib/api.js', () => ({ api: { get: read, post: vi.fn(), del: vi.fn(), patch: vi.fn(), put: vi.fn() }, ApiError: Error }));
const createCase = vi.fn(async () => ({ id: 'new' }));
const openCase = vi.fn(async () => {});
@@ -171,11 +176,12 @@ describe('with a case open', () => {
]);
});
- it('reads the case with five bounded requests and no more', async () => {
+ it('reads the case with five dashboard requests and its checklists', async () => {
await open();
const asked = get.mock.calls.map(([url]) => url);
const paths = asked.filter((url) => url.startsWith('/api/cases/'));
- expect(paths).toHaveLength(5);
+ expect(paths).toHaveLength(6);
+ expect(paths).toContain('/api/cases/case-a/todos');
// every one of them capped, counting, or the compact index the map panel already
// opens on — never a whole-graph read
expect(paths.filter((url) => url.includes('limit=')).length).toBe(3);
diff --git a/frontend/src/tools/Overview.svelte b/frontend/src/tools/Overview.svelte
index 3a50791..a645c39 100644
--- a/frontend/src/tools/Overview.svelte
+++ b/frontend/src/tools/Overview.svelte
@@ -1,26 +1,8 @@
<script>
- /**
- * Where the app opens: what this case is waiting on, what it looks like, and what
- * was worked on last.
- *
- * Two surfaces in one, chosen by whether a case is open. With a case it is a
- * reading — four outstanding counts as tiles, the case's points on a map, the last
- * things filed, and the case by family. Without one it is the front door, because a
- * fresh install lands in an empty workspace and nothing here could be summarised.
- *
- * **It asks the case nothing new.** The waiting counts come from the catalog summary
- * and one timeline page, both of which the Board and the Timeline already read; the
- * plate comes from the saved index the Satellite panel opens on. Pressing a row hands
- * the *question* to the surface that answers it rather than the rows it counted, so
- * the number here and the count there are one predicate asked twice, and no route,
- * table or migration was added to put a landing page in front of the app.
- *
- * Bounded like every other list (docs/STORAGE_AND_PERFORMANCE.md): five small reads
- * against the **open** case only. Nothing here opens a second case to count it, and
- * the only thing that reaches the network is the map of the case, which fetches the
- * free imagery under its points (`overview/PlaceMap.svelte`). The release card is
- * not an exception: it shows what the startup check already found, and says nothing
- * when that check is switched off.
+ /** Case dashboard, or a workspace entry page when no case is open.
+ * Five bounded reads supply the dashboard; CaseTodos owns its metadata read.
+ * The map uses imagery for the saved points. Release notices reuse the startup
+ * check, and do not initiate another network request.
*/
import { api } from '../lib/api.js';
import {
@@ -54,6 +36,7 @@
import Icon from '../components/Icon.svelte';
import Logo from '../components/Logo.svelte';
import PlaceMap from './overview/PlaceMap.svelte';
+ import CaseTodos from './overview/CaseTodos.svelte';
const RECENT = 6;
@@ -253,8 +236,14 @@
</button>
{/if}
+ <div class="grid" class:flat={!plate.pins.length} class:empty-case={empty}>
+ <div class="area-todos">
+ {#key caseState.current.id}
+ <CaseTodos caseId={caseState.current.id} />
+ {/key}
+ </div>
{#if empty}
- <section>
+ <section class="area-start">
<h2 class="label">Nothing in this case yet</h2>
<ul class="steps">
{#each FIRST_STEPS as step (step.tool)}
@@ -269,7 +258,6 @@
</ul>
</section>
{:else}
- <div class="grid" class:flat={!plate.pins.length}>
<section class="area-waiting">
<h2 class="label">What is waiting</h2>
{#if !summary}
@@ -360,8 +348,8 @@
</ul>
</section>
{/if}
- </div>
{/if}
+ </div>
<footer class="foot">
<button class="aside" onclick={() => (uiState.tool = 'guide')}>
@@ -584,7 +572,8 @@
grid-template-columns: minmax(0, 1.05fr) minmax(0, 0.95fr);
grid-template-areas:
'waiting places'
- 'recent figures';
+ 'todos figures'
+ 'recent recent';
gap: 30px 40px;
align-items: start;
padding-top: 4px;
@@ -594,8 +583,20 @@
.grid.flat {
grid-template-areas:
'waiting figures'
+ 'todos .'
'recent recent';
}
+ .grid.empty-case {
+ grid-template-areas: 'todos start';
+ }
+ .area-todos {
+ grid-area: todos;
+ min-width: 0;
+ }
+ .area-start {
+ grid-area: start;
+ min-width: 0;
+ }
.area-waiting {
grid-area: waiting;
}
@@ -610,11 +611,15 @@
}
@media (max-width: 980px) {
.grid,
- .grid.flat {
+ .grid.flat,
+ .grid.empty-case {
grid-template-columns: minmax(0, 1fr);
- grid-template-areas: 'waiting' 'places' 'recent' 'figures';
+ grid-template-areas: 'waiting' 'todos' 'places' 'recent' 'figures';
gap: 30px;
}
+ .grid.empty-case {
+ grid-template-areas: 'todos' 'start';
+ }
}
.label {
diff --git a/frontend/src/tools/PostComposer.svelte b/frontend/src/tools/PostComposer.svelte
index 58c207e..8571e87 100644
--- a/frontend/src/tools/PostComposer.svelte
+++ b/frontend/src/tools/PostComposer.svelte
@@ -221,7 +221,12 @@
}
function applyProof(p) {
- description = isDefaultName(p.title, 'proof') ? '' : (p.title ?? '');
+ // The proof's own sentence is what this field is for. A title is a filename,
+ // and most of them are the number the composer handed out, so it only stands
+ // in when the analyst renamed the proof and wrote no description.
+ description = p.description?.trim()
+ ? p.description.trim()
+ : (isDefaultName(p.title, 'proof') ? '' : (p.title ?? ''));
const proofSourceUrl = p.source ?? p.sources?.[0] ?? '';
source = proofSourceUrl;
setProof(p.png ?? null);
@@ -596,12 +601,16 @@
async function pickProof(item) {
setProof(item.png);
proofPickerOpen = false;
- if (!description.trim() && item.title && !isDefaultName(item.title, 'proof')) {
+ const blank = !description.trim();
+ if (blank && item.title && !isDefaultName(item.title, 'proof')) {
description = item.title;
}
// Pull the proof's coordinates + source into the post so the fields fill in.
try {
const spec = await api.get(`/api/cases/${caseState.current.id}/proofs/${item.name}`);
+ // Its sentence, once the spec is here. The picker row carries a filename
+ // and a thumbnail, so the title above was only ever a stand-in for this.
+ if (blank && spec.description?.trim()) description = spec.description.trim();
const src = proofSource(spec);
if (src) source = src;
await preloadProofMedia(item.png, src);
diff --git a/frontend/src/tools/PostComposer.test.js b/frontend/src/tools/PostComposer.test.js
index 2fed555..059dee1 100644
--- a/frontend/src/tools/PostComposer.test.js
+++ b/frontend/src/tools/PostComposer.test.js
@@ -191,3 +191,15 @@ describe('when the extension does not take the thread', () => {
expect(source).toContain('if (excuse) toast(excuse, \'warn\', 6000);');
});
});
+
+describe('Post Composer — the sentence the proof carries', () => {
+ it('writes the post from the description, and falls back to a renamed title', () => {
+ expect(source).toContain('description = p.description?.trim()');
+ expect(source).toContain("? p.description.trim()\n : (isDefaultName(p.title, 'proof') ? '' : (p.title ?? ''));");
+ });
+
+ it('prefers it over the filename the picker row showed', () => {
+ expect(source).toContain('const blank = !description.trim();');
+ expect(source).toContain("if (blank && spec.description?.trim()) description = spec.description.trim();");
+ });
+});
diff --git a/frontend/src/tools/ProofComposer.svelte b/frontend/src/tools/ProofComposer.svelte
index 88f4f18..fcf1d15 100644
--- a/frontend/src/tools/ProofComposer.svelte
+++ b/frontend/src/tools/ProofComposer.svelte
@@ -7,10 +7,14 @@
import { matchesTerms } from '../lib/folderBrowse.js';
import { isSatelliteMedia, sortItems } from '../lib/mediaFilter.js';
import { deletedToast, RESTORABLE } from '../lib/trash.js';
+ // Reading a typed pair back into a point: the one parser the app has, and the
+ // one a coordinate row is written in (decimal, hemispheres, or DMS).
+ import { parseLatLon } from '../lib/sheetRoles.js';
import { caseState, uiState, ensureCase, reloadCase, toast, prefs, fmtCoords } from '../lib/state.svelte.js';
import { templatesState } from '../lib/state.svelte.js';
import Icon from '../components/Icon.svelte';
import Modal from '../components/Modal.svelte';
+ import TemporalInput from '../components/TemporalInput.svelte';
import SearchInput from '../components/SearchInput.svelte';
import FolderBrowser from '../components/FolderBrowser.svelte';
import ConfirmDialog from '../components/ConfirmDialog.svelte';
@@ -21,6 +25,7 @@
import ProofLayersPanel from './proof/ProofLayersPanel.svelte';
import NewProofDialog from './proof/NewProofDialog.svelte';
import ImportProofDialog from './proof/ImportProofDialog.svelte';
+ import PointMapDialog from './proof/PointMapDialog.svelte';
import PanelCategories from './proof/PanelCategories.svelte';
import { bindPanelPointerLifecycle, createCanvasRenderGate,
discardDraft,
@@ -33,7 +38,7 @@
layoutPanels, panelsBottom, freeNormalizeDelta, legendLineHeight, footerBand,
attributionLine, docSize, offsetShape, autoLayoutRows,
autoCoords, formatCoords, autoSourceUrls, proofSource, statedSources,
- specPoints, footerLines, coordsPostLines, proofCoordsLines, MAX_POINTS,
+ specPoints, statePanelPoint, footerLines, coordsPostLines, proofCoordsLines, MAX_POINTS,
normalizeMaterial, resolveSourceUrls,
toSpec, newId, loadImage, orderedFeatureColors, notesFromShapes,
templateFromProof, applyProofStyle, normalizeProofStyle, newSignatureText,
@@ -98,6 +103,13 @@
// give it, which is what the field has always shown.
points: [{ coords: '', label: '', pov: false }],
sources: null, // null → traced from the panels; a list → what the analyst states
+ // When the material was taken, in the case's temporal profile, and the
+ // sentence the proof carries. Both optional, neither printed on the plate:
+ // the date is what puts the proof on the Timeline, the description is what a
+ // post is written from. '' → the panels answer for the date, nothing for the
+ // sentence.
+ when: '',
+ description: '',
// Case files the proof rests on without composing them, brought in from a stated
// source address. They join the chain on save, and the point with it.
material: [],
@@ -225,6 +237,8 @@
// the only thing this screen owns is the door — and that door is in the New
// proof dialog rather than the toolbar, which has no room left for a button.
let importOpen = $state(false);
+ // `{ row, view }` while one point is being moved on the map, else null.
+ let pointMap = $state(null);
let newProofTemplateId = $state('');
let newProofPanelPaths = $state([]);
let newProofQuery = $state('');
@@ -317,6 +331,8 @@
proof.footerCoords = spec.footerCoords === true;
proof.footerText = spec.footerText !== false;
proof.sources = statedSources(spec.sources ?? spec.source ?? null);
+ proof.when = typeof spec.when === 'string' ? spec.when : '';
+ proof.description = typeof spec.description === 'string' ? spec.description : '';
proof.material = normalizeMaterial(spec.material);
proof.captionSize = style.captionSize;
proof.legendSize = style.legendSize;
@@ -601,6 +617,8 @@
proof.templateId = null;
proof.points = [blankPoint()];
proof.sources = null;
+ proof.when = '';
+ proof.description = '';
proof.material = [];
proof.captionSize = CAPTION_SIZE;
proof.legendSize = LEGEND_SIZE;
@@ -975,9 +993,13 @@
meta: item.meta ?? {},
img,
};
+ // what the proof answers with today, read before the panel can change it
+ const answered = displayedCoords;
// grid: append (rightmost / bottom row); free: a new panel lands in front
if (proof.layout === 'free') proof.panels.unshift(panel);
else proof.panels.push(panel);
+ // a panel that carries a place states it, under the point already there
+ proof.points = statePanelPoint(proof.points, panel, answered, prefs.coordFormat);
dirty = true;
requestAnimationFrame(fit);
} catch (e) {
@@ -2956,6 +2978,14 @@
return `Saved ${places.length} points as places`;
}
+ /** And what it says about the date it stated for the footage. Counted past one,
+ * for the same reason. */
+ function datedLabel(files) {
+ const dated = files ?? [];
+ if (dated.length === 1) return `Dated the material: ${dated[0]}`;
+ return `Dated ${dated.length} files this proof rests on`;
+ }
+
/** Say yes to dropping the point the proof moved off. Deleted like any entity,
* so it lands in the trash and comes back from there. */
async function deleteOrphanPlaces() {
@@ -3026,6 +3056,9 @@
// answers with nothing at all when the case already holds them, so
// re-saving never asks twice.
if (result.place?.filed?.length) toast(placedLabel(result.place.filed), 'ok', 2600);
+ // The date went onto the footage as a statement of its own. Never asked —
+ // dating a proof is dating what it rests on — but never silent either.
+ if (result.dated?.length) toast(datedLabel(result.dated), 'ok', 2600);
if (result.place?.asking?.length) {
placeOffer = { name: result.name, points: result.place.asking };
}
@@ -3035,6 +3068,8 @@
if (andPost) {
uiState.postProof = {
title: result.title,
+ // What the post is written from, when the proof carries one.
+ description: proof.description,
// every point, one per line: the post cites the first and carries the rest
coordsText: coordsPostLines(proofCoordsLines(proof, prefs.coordFormat)).join('\n'),
source: displayedSource,
@@ -3141,6 +3176,11 @@
proof.footerCoords = spec.footerCoords === true;
proof.footerText = spec.footerText !== false;
proof.sources = statedSources(spec.sources ?? spec.source ?? null);
+ // Both are completed off the entity on the way out of the API, so a date or a
+ // sentence edited from Details opens here as the case's answer rather than as
+ // the copy this file was written with.
+ proof.when = typeof spec.when === 'string' ? spec.when : '';
+ proof.description = typeof spec.description === 'string' ? spec.description : '';
proof.material = normalizeMaterial(spec.material);
proof.captionSize = style.captionSize;
proof.legendSize = style.legendSize;
@@ -3174,7 +3214,11 @@
for (const p of spec.pastes ?? []) {
try {
const img = await loadImage(
- fileUrl(caseState.current.id, `proofs/${entry.name}.assets/${p.asset}`)
+ // Mirrors `layout.proof_assets_rel`: pasted images live beside the spec,
+ // under `proofs/.meta/`, and not beside the exported picture. Asking one
+ // folder up found nothing and read as an overlay the case had lost, on a
+ // proof whose file was there the whole time.
+ fileUrl(caseState.current.id, `proofs/.meta/${entry.name}.assets/${p.asset}`)
);
if (run !== openRun) return;
pasteAssets.set(p.asset, { img, data: null, pending: false });
@@ -3312,6 +3356,34 @@
dirty = true;
}
+ /** How deep the map opens on a point. A building fits in the frame, which is
+ * what a proof's point is usually on. */
+ const POINT_ZOOM = 17;
+
+ /**
+ * Where the map opens for one row: the point it already states, else the one
+ * above it, else what the panels answer with, else wherever Settings opens the
+ * map. A row added with `+` is empty by definition, and the point it was added
+ * under is the only thing that says which ground it belongs on.
+ */
+ function pointMapView(i) {
+ const above = proof.points.slice(0, i).map((one) => one.coords).reverse();
+ for (const text of [i === 0 ? displayedCoords : proof.points[i].coords, ...above]) {
+ const read = parseLatLon(text);
+ if (read && !read.outOfBounds) return { lat: read.lat, lon: read.lon, zoom: POINT_ZOOM };
+ }
+ // The panels answer in numbers rather than in text, so this one reads in
+ // whichever format the rows above were written in — MGRS included.
+ const auto = autoCoords(proof.panels);
+ return auto ? { ...auto, zoom: POINT_ZOOM } : { ...prefs.homeView };
+ }
+
+ /** The point the map handed back, written where the row reads it. */
+ function movePoint(i, point) {
+ proof.points[i].coords = formatCoords(point, prefs.coordFormat);
+ dirty = true;
+ }
+
/** Name a point. The first row's coordinates are written down with it, or the
* name is typed onto a row the save drops (see statePoint0). */
function namePoint(i, value) {
@@ -3701,6 +3773,15 @@
value={i === 0 ? displayedCoords : point.coords}
oninput={(e) => { proof.points[i].coords = e.target.value; dirty = true; }}
/>
+ <!-- Six decimals is a tenth of a metre, and nobody moves a corner
+ of a building by editing digits. -->
+ <button
+ class="point-map"
+ title="Move this point on the map"
+ onclick={() => (pointMap = { row: i, view: pointMapView(i) })}
+ >
+ <Icon name="pin" size={13} />
+ </button>
<input
class="input point-label"
placeholder="label"
@@ -3789,6 +3870,59 @@
{/each}
</div>
+ <!-- One sentence about what the proof shows. It is the proof's notes, so
+ the graph shows it and case search finds it, and it is what a post is
+ written from instead of a filename. -->
+ <div class="meta-field">
+ <div class="meta-head">
+ <Icon name="note" size={13} />
+ <span>Description</span>
+ <span class="meta-optional">optional</span>
+ </div>
+ <textarea
+ class="input meta-input desc-input"
+ rows="2"
+ maxlength="2000"
+ placeholder="A formation of 13 helicopters heading east"
+ value={proof.description}
+ oninput={(e) => { proof.description = e.target.value; dirty = true; }}
+ ></textarea>
+ </div>
+
+ <!-- When the material was taken. Not the day it was published and not the
+ day it was filed — the case already holds both of those, read off the
+ file. This is the analyst's answer, and it is what the Timeline shows
+ the proof at. Nothing of it reaches the plate. -->
+ <div class="meta-field">
+ <div class="meta-head">
+ <Icon name="clock" size={13} />
+ <span>Date</span>
+ <span class="meta-optional">optional</span>
+ <!-- Unlike the coordinates and the source, nothing fills this in and
+ nothing marks it missing. Both would be the same mistake: the date
+ a file carries is when it was uploaded or when a camera clock said
+ it was, and neither is when the thing happened. Offered, it would
+ be accepted without being read, and this date is stated for the
+ footage itself. So it is typed on purpose, or it stays unknown —
+ and the bin empties it back to unknown in one press. -->
+ {#if proof.when.trim()}
+ <button
+ class="meta-clear"
+ title="Clear the date"
+ onclick={() => { proof.when = ''; dirty = true; }}
+ >
+ <Icon name="trash" size={12} />
+ </button>
+ {/if}
+ </div>
+ <TemporalInput
+ id="proof-when"
+ compact
+ value={proof.when}
+ onchange={(value) => { proof.when = value; dirty = true; }}
+ />
+ </div>
+
<ProofLayersPanel
{proof}
{collapsed}
@@ -4023,6 +4157,14 @@
/>
{/if}
+{#if pointMap}
+ <PointMapDialog
+ view={pointMap.view}
+ onpick={(point) => movePoint(pointMap.row, point)}
+ onclose={() => (pointMap = null)}
+ />
+{/if}
+
{#if importOpen && caseState.current}
<ImportProofDialog
caseId={caseState.current.id}
@@ -4401,6 +4543,17 @@
color: var(--text-2);
}
.meta-warn { color: var(--warn, #e8a33d); display: inline-flex; }
+ /* Said outright, because the panel's other headers carry a `!` when they are
+ empty and a reader works the rule out from what is on screen: everything
+ here is a blank waiting to be filled. These two are not. */
+ .meta-optional {
+ margin-left: -2px;
+ font-size: var(--fs-xs);
+ font-weight: 400;
+ text-transform: none;
+ letter-spacing: 0;
+ color: var(--text-3);
+ }
.meta-reset {
margin-left: auto;
display: inline-flex;
@@ -4409,6 +4562,16 @@
border-radius: var(--r-sm);
}
.meta-reset:hover { color: var(--text-1); background: var(--bg-2); }
+ /* Empties an optional field rather than handing it back to what the panels say:
+ nothing ever filled this one in. */
+ .meta-clear {
+ margin-left: auto;
+ display: inline-flex;
+ color: var(--text-3);
+ padding: 1px;
+ border-radius: var(--r-sm);
+ }
+ .meta-clear:hover { color: var(--danger, #e05c5c); background: var(--bg-2); }
.meta-add {
display: inline-flex;
color: var(--text-3);
@@ -4477,16 +4640,17 @@
.point-row + .point-row { margin-top: 4px; }
.point-row .meta-input { flex: 1; min-width: 0; }
.point-label { width: 84px; flex: none; font-size: var(--fs-xs); padding: 5px 8px; }
- .point-pov, .point-move, .point-drop {
+ .point-map, .point-pov, .point-move, .point-drop {
display: inline-flex;
color: var(--text-3);
padding: 2px;
border-radius: var(--r-sm);
}
- .point-pov:hover, .point-move:hover { color: var(--text-1); background: var(--bg-2); }
+ .point-map:hover, .point-pov:hover, .point-move:hover { color: var(--text-1); background: var(--bg-2); }
.point-pov.on { color: var(--accent, #6ea8fe); background: var(--bg-2); }
.point-drop:hover { color: var(--danger, #e05c5c); background: var(--bg-2); }
.point-hint { margin-top: 5px; font-size: var(--fs-xs); color: var(--text-3); }
+ .desc-input { resize: vertical; min-height: 44px; line-height: 1.35; }
.adv-toggle {
display: flex;
align-items: center;
diff --git a/frontend/src/tools/ProofComposer.test.js b/frontend/src/tools/ProofComposer.test.js
index 71e9188..6715132 100644
--- a/frontend/src/tools/ProofComposer.test.js
+++ b/frontend/src/tools/ProofComposer.test.js
@@ -472,7 +472,11 @@ describe('Proof Composer pasted images', () => {
});
it('reads pasted images back from the proof folder on open', () => {
- expect(source).toContain('proofs/${entry.name}.assets/${p.asset}');
+ // Beside the spec, under `.meta/`, which is where the save put them. This
+ // assertion held the folder one level up for as long as the code did, and an
+ // overlay nothing had lost reopened as missing. What the two sides agree on is
+ // checked against `layout.proof_assets_rel` itself, in the backend suite.
+ expect(source).toContain('proofs/.meta/${entry.name}.assets/${p.asset}');
expect(source).toContain("pasteAssets.set(p.asset, { img, data: null, pending: false })");
// annotations bound to a paste survive the reload with it
expect(source).toContain('const validSurfaces = new Set([...proof.panels, ...proof.pastes]');
@@ -590,6 +594,31 @@ describe('the points a proof states', () => {
expect(source).not.toContain('class="point-add"');
});
+ it('states a panel’s place under the answer already on screen', () => {
+ // In free layout a new panel lands in *front*, so the auto answer used to
+ // change under the analyst as soon as a second capture was dropped on the
+ // canvas; in grid layout the second place was simply never heard.
+ const body = bodyOfFn('addPanel');
+ expect(body).toContain('const answered = displayedCoords;');
+ expect(body.indexOf('const answered')).toBeLessThan(body.indexOf('proof.panels.unshift(panel)'));
+ expect(body).toContain(
+ 'proof.points = statePanelPoint(proof.points, panel, answered, prefs.coordFormat);'
+ );
+ });
+
+ it('opens a row on the ground it names, or on the point above it', () => {
+ // six decimals is a tenth of a metre: the pin is the instrument, not the digits
+ expect(source).toContain('title="Move this point on the map"');
+ expect(source).toContain('onclick={() => (pointMap = { row: i, view: pointMapView(i) })}');
+ const view = bodyOfFn('pointMapView');
+ expect(view).toContain('proof.points.slice(0, i).map((one) => one.coords).reverse()');
+ expect(view).toContain('autoCoords(proof.panels)');
+ expect(view).toContain('{ ...prefs.homeView }');
+ expect(bodyOfFn('movePoint')).toContain(
+ 'proof.points[i].coords = formatCoords(point, prefs.coordFormat);'
+ );
+ });
+
it('redraws the plate when a point or the footer switch changes', () => {
// both feed the footer, and the footer decides the picture's height: a
// rebuild that does not read them leaves the export a line behind
@@ -1075,3 +1104,65 @@ describe('the unsaved badge', () => {
expect(reset).toContain('savedSnapshot = null;');
});
});
+
+describe('Proof Composer — what the proof says about itself', () => {
+ const side = source.slice(source.indexOf('<span>Source</span>'), source.indexOf('<ProofLayersPanel'));
+
+ it('puts the description and the date under Source, the sentence first', () => {
+ expect(side.indexOf('<span>Description</span>')).toBeGreaterThan(-1);
+ expect(side.indexOf('<span>Date</span>')).toBeGreaterThan(side.indexOf('<span>Description</span>'));
+ });
+
+ it('says both are optional, rather than leaving the `!` above to imply it', () => {
+ expect(side.match(/class="meta-optional">optional</g)).toHaveLength(2);
+ });
+
+ it('edits the date with the one temporal editor the app has, compact', () => {
+ expect(side).toContain('<TemporalInput');
+ expect(side).toContain('compact');
+ expect(side).toContain('onchange={(value) => { proof.when = value; dirty = true; }}');
+ });
+
+ it('never marks an empty date as missing, the way a coordinate is', () => {
+ expect(side.slice(side.indexOf('<span>Date</span>'))).not.toContain('meta-warn');
+ });
+
+ it('never fills the date in, from a panel or from anything else', () => {
+ // Coordinates and sources are answered by the panels; a date is not. The
+ // composer must state it because somebody decided it, not because a file
+ // carried a number.
+ expect(source).not.toContain('offeredWhen');
+ expect(source).not.toContain('autoWhen');
+ });
+
+ it('empties it in one press, rather than handing it back to the panels', () => {
+ expect(side).toContain('title="Clear the date"');
+ expect(side).toContain("onclick={() => { proof.when = ''; dirty = true; }}");
+ expect(side).toContain('<Icon name="trash" size={12} />');
+ });
+
+ it('opens on both, and blanks both on a fresh proof', () => {
+ expect(source).toContain("proof.when = typeof spec.when === 'string' ? spec.when : '';");
+ expect(source).toContain(
+ "proof.description = typeof spec.description === 'string' ? spec.description : '';",
+ );
+ expect(bodyOfFn('resetDoc')).toContain("proof.when = '';");
+ expect(bodyOfFn('resetDoc')).toContain("proof.description = '';");
+ });
+
+ it('hands the description to the post it opens', () => {
+ expect(source).toContain('description: proof.description,');
+ });
+});
+
+describe('Proof Composer — dating the material', () => {
+ it('says what the save stated, without asking first', () => {
+ expect(source).toContain("if (result.dated?.length) toast(datedLabel(result.dated), 'ok', 2600);");
+ });
+
+ it('names one file and counts past one, like the places beside it', () => {
+ const body = bodyOfFn('datedLabel');
+ expect(body).toContain('`Dated the material: ${dated[0]}`');
+ expect(body).toContain('`Dated ${dated.length} files this proof rests on`');
+ });
+});
diff --git a/frontend/src/tools/Satellite.svelte b/frontend/src/tools/Satellite.svelte
index aea4ab1..69069e3 100644
--- a/frontend/src/tools/Satellite.svelte
+++ b/frontend/src/tools/Satellite.svelte
@@ -1,5 +1,5 @@
<script>
- import { onMount, tick } from 'svelte';
+ import { onMount, tick, untrack } from 'svelte';
// The map is lib/map's: the engine, its layers, what is drawn on them and the
// drag gestures. Nothing in this file knows which engine that is — and the
// map itself is a surface (satellite/MapSurface.svelte), which is what lets a
@@ -25,6 +25,7 @@
import { temporalMapQuery } from '../lib/temporalMap.js';
import { windowWords } from '../lib/timeline.js';
import { isMode, KINDS } from '../lib/geoTree.js';
+ import { stackOf } from '../lib/mediaViewer.js';
import {
caseState, uiState, ensureCase, reloadCase, toast, prefs, fmtCoords, prefsReady,
} from '../lib/state.svelte.js';
@@ -97,6 +98,7 @@
import SavedTree from './satellite/SavedTree.svelte';
import SavedSearch from './satellite/SavedSearch.svelte';
import SavedOverlay from './satellite/SavedOverlay.svelte';
+ import MediaViewer from './satellite/MediaViewer.svelte';
import SheetPointsOverlay from './satellite/SheetPointsOverlay.svelte';
import TemporalMapOverlay from './satellite/TemporalMapOverlay.svelte';
@@ -144,7 +146,18 @@
// pass — is its own store (state/saved.svelte.js).
const savedWork = createSavedState({ api, notify: toast, assignFolder, reloadCase });
let savedSearchOpen = $state(false);
- let savedOverlay = $state(false); // map layer: off by default, session only
+ // Map layer: on from the start, on the Media position, so a case opens on its
+ // footage already placed. Session-only: the tool stays mounted across tabs, so a
+ // switch pressed off stays off until the app reloads, and nothing is saved.
+ let savedOverlay = $state(true);
+ /**
+ * The located files the panel is playing, or null for the saved-work list.
+ *
+ * `items` is the stack one mark holds, `index` the file on screen. It takes the
+ * panel rather than a window over the map, because the footage is read beside
+ * the imagery it is being matched against.
+ */
+ let mediaView = $state(null);
let temporalMap = $state(null); // Timeline handoff, session-only
let temporalShown = $state(true); // …and whether its marks are drawn
let temporalMapLoading = $state(false);
@@ -181,11 +194,12 @@
/**
* The other key-less reference layers, each simply on or off: Esri's borders
* and roads, Open Infrastructure Map's power lines, OpenSeaMap's sea marks
- * and OSM's raw GPS traces. Off by default, so none of them fetches a tile
- * until its switch is pressed.
+ * and OSM's raw GPS traces. Borders start on, because every read of imagery
+ * starts with which side of a line it is on; they are map tiles, the network
+ * a map is opened to use. The rest fetch no tile until their switch is pressed.
*/
const refLayers = $state({
- boundaries: false,
+ boundaries: true,
roads: false,
power: false,
seamarks: false,
@@ -1094,7 +1108,7 @@
disabled: !savedWork.rows.length,
detail: savedWork.shown.length ? String(savedWork.shown.length) : '',
title: savedWork.rows.length
- ? "This case's saved places and captures"
+ ? "This case's saved work, or its located photos and videos"
: 'Nothing is saved in this case yet',
toggle: () => (savedOverlay = !savedOverlay),
// Which of them are drawn. The same two answers the Saved panel is asking
@@ -1157,7 +1171,24 @@
// fly the map to a capture's recorded point (item 7)
/** Open one saved item: fly the map to it, or — for a screenshot of a site we
* cannot embed, filed without coordinates — reopen the page it came from. */
+ /** Play a stack of located files in the panel, opening the panel if it is shut. */
+ async function openMedia(items, index = 0) {
+ if (!items?.length) return;
+ mediaView = { items, index };
+ if (capturesCollapsed) {
+ capturesCollapsed = false;
+ await tick();
+ engine?.resize();
+ }
+ }
+
function openSaved(row) {
+ // a file flies the map to where it stands and plays beside it, with every
+ // other file on that metre a press of the arrows away
+ if (row.kind === 'media') {
+ const { items, index } = stackOf(savedWork.shown, row);
+ openMedia(items, index);
+ }
if (row.lat == null || row.lon == null) {
if (row.source_url && !fullscreen) window.open(row.source_url, '_blank', 'noopener,noreferrer');
return;
@@ -1225,13 +1256,30 @@
temporalMapError = '';
// The points came out of another case's sheet, so they go with it.
sheetPoints = null;
+ mediaView = null;
footprint.cancel();
}
return savedWork.load(id);
});
- // The proofs index, read the first time the Proofs position is opened.
- $effect(() => savedWork.loadProofs(caseState.current?.id, caseState.rev));
+ // The proofs and media indexes, each read the first time its position is opened.
+ $effect(() => savedWork.loadMode(caseState.current?.id, caseState.rev));
+
+ // A reloaded media index re-reads the stack being played: a file deleted or
+ // unplaced elsewhere leaves it, and the viewer closes once nothing is left.
+ $effect(() => {
+ const fresh = savedWork.media;
+ const open = untrack(() => mediaView);
+ if (!open) return;
+ const byKey = new Map(fresh.map((row) => [row.key, row]));
+ const current = open.items[open.index]?.key;
+ const items = open.items.map((row) => byKey.get(row.key)).filter(Boolean);
+ if (!items.length) {
+ mediaView = null;
+ return;
+ }
+ mediaView = { items, index: Math.max(0, items.findIndex((row) => row.key === current)) };
+ });
// another workspace asked to show one capture: clear whatever filter is on so
// it can't be hidden, then let the tree open its branch and scroll to it
@@ -1696,6 +1744,12 @@
uiState.tool = 'proof';
}
+ function openProofByName(proof) {
+ if (!proof?.name) return;
+ uiState.openProof = proof.name;
+ uiState.tool = 'proof';
+ }
+
function openLinkedPost(post) {
if (!post.name) return;
uiState.openDraft = post.name;
@@ -1988,6 +2042,7 @@
coords={coordsLabel}
{fullscreen}
bind:hoveredId={hoveredSavedId}
+ activeKey={mediaView ? mediaView.items[mediaView.index]?.key : null}
onopen={openSaved}
onedit={editSaved}
onproof={sendToComposer}
@@ -1995,6 +2050,7 @@
onshowproofs={() => (savedWork.kind = 'proofs')}
onrefresh={reloadCase}
ontrace={startTrace}
+ onmedia={openMedia}
/>
{/if}
@@ -2278,12 +2334,29 @@
>
<Icon name={capturesCollapsed ? 'chevronLeft' : 'chevronRight'} size={15} />
<span class="label" style="margin:0">Saved</span>
- <span class="count">{savedWork.rows.length}</span>
+ <!-- what the panel is listing, which is what its position says: the
+ count on a header that reads Media must not be the places index -->
+ <span class="count">{savedWork.shownRows.length}</span>
</button>
{#if capturesCollapsed}
<!-- collapsed: header acts as the toggle back to the list -->
{:else}
<div class="panel-scroll">
+ {#if mediaView}
+ <!-- A located file, played in place of the list rather than over the
+ map it is being compared with. Closing it brings the list back as
+ it was left. -->
+ <MediaViewer
+ items={mediaView.items}
+ bind:index={mediaView.index}
+ caseId={caseState.current?.id}
+ coords={coordsLabel}
+ {fullscreen}
+ onclose={() => (mediaView = null)}
+ onmedia={(row) => openEntity({ id: row.id, type: 'media', attrs: { path: row.path } })}
+ onproof={openProofByName}
+ />
+ {:else}
<!-- What is drawn over the imagery. One list, above the case's own
work: the labels and the saved pins used to be buttons in the
toolbox, and the handoffs floating cards over the map. -->
@@ -2353,6 +2426,7 @@
onlocate={runLocate}
oncancelLocate={savedWork.stopLocate}
/>
+ {/if}
</div>
{/if}
</aside>
diff --git a/frontend/src/tools/Satellite.test.js b/frontend/src/tools/Satellite.test.js
index 9265cd4..30fefa7 100644
--- a/frontend/src/tools/Satellite.test.js
+++ b/frontend/src/tools/Satellite.test.js
@@ -51,9 +51,9 @@ describe('Satellite saved work', () => {
}
});
- it('loads and drops both indexes with the case, through the store', () => {
+ it('loads and drops every index with the case, through the store', () => {
expect(source).toContain('return savedWork.load(id);');
- expect(source).toContain('savedWork.loadProofs(caseState.current?.id, caseState.rev)');
+ expect(source).toContain('savedWork.loadMode(caseState.current?.id, caseState.rev)');
});
it('closes over this case for every row action', () => {
@@ -77,8 +77,9 @@ describe('Satellite saved work', () => {
expect(effect).toContain('sheetPoints = null');
});
- it('keeps the map overlay off by default and out of the case file', () => {
- expect(source).toContain('let savedOverlay = $state(false)');
+ it('opens with the map overlay on, and keeps it out of the case file', () => {
+ // a case is opened to be read, and its located work is what a map is read for
+ expect(source).toContain('let savedOverlay = $state(true)');
expect(source).toContain('{#if savedOverlay}');
// it is a layer, listed with the other layers rather than sitting in the
// toolbox: nothing about it changes what the pointer does
@@ -678,10 +679,16 @@ describe('a map in more than one window', () => {
});
describe('the key-less reference layers', () => {
- it('fetches no tile from any of them until its switch is pressed', () => {
- // local-first: a map not showing borders asks Esri nothing about borders
- const state = source.slice(source.indexOf('const refLayers = $state({'));
- expect(state.slice(0, 200)).not.toContain('true');
+ it('fetches no tile from any of them until its switch is pressed, borders apart', () => {
+ // local-first: a map not showing power lines asks nobody about power lines.
+ // Borders are the exception and are on from the start — they are map tiles,
+ // which is the network a map is opened to use.
+ const state = source.slice(
+ source.indexOf('const refLayers = $state({'),
+ source.indexOf('const night = $state(')
+ );
+ expect(state).toContain('boundaries: true');
+ expect(state.replace('boundaries: true', '')).not.toContain('true');
expect(source).toContain("const night = $state({ on: false, source: 'noaa20', day: lastNight() });");
});
diff --git a/frontend/src/tools/Settings.render.test.js b/frontend/src/tools/Settings.render.test.js
index 49f26bb..ebaef2f 100644
--- a/frontend/src/tools/Settings.render.test.js
+++ b/frontend/src/tools/Settings.render.test.js
@@ -146,6 +146,21 @@ describe('each section', () => {
expect(pane().querySelector('a[href="/api/ingest/extension.zip"]')).not.toBeNull();
});
+ it('Extension links the XPI on the release that carries it, not the newest one', () => {
+ // The signed add-on is attached to the release that last moved the extension,
+ // so it is the extension's own version that names the tag and the file. Link
+ // `releases/latest` instead and every release that left `extension/` alone
+ // sends Firefox users to a page with no XPI on it at all.
+ const text = show('extension');
+ expect(text).toContain('azimut-capture-1.0.xpi');
+ const link = pane().querySelector('a[href*="azimut-capture-1.0.xpi"]');
+ expect(link).not.toBeNull();
+ expect(link.getAttribute('href')).toBe(
+ 'https://github.com/OsintMeThat/azimut/releases/download/v1.0/azimut-capture-1.0.xpi',
+ );
+ expect(pane().querySelector('a[href$="/releases/latest"]')).toBeNull();
+ });
+
it('Storage manages all three export folders and the backup', () => {
const text = show('storage');
expect(text).toContain('Note PDFs');
diff --git a/frontend/src/tools/Settings.svelte b/frontend/src/tools/Settings.svelte
index ab8afe3..4688c61 100644
--- a/frontend/src/tools/Settings.svelte
+++ b/frontend/src/tools/Settings.svelte
@@ -193,6 +193,10 @@
// icon, so a tab can never disagree with the rail that led the user to it.
let badges = $derived(updateBadges(updatesState, prefs.updateDismissedVersion));
let extOutdated = $derived(badges.extensionOutdated);
+ // Which extension version the app ships, which is also the release tag whose
+ // assets carry the signed XPI. The probe verdict is the sharper source, but it
+ // is null until the probes answer, so the settings value backs it.
+ let extBundled = $derived(extState?.bundledVersion ?? updatesState.extensionBundled);
async function copyToken() {
try {
@@ -354,7 +358,7 @@
{ id: 'notes', label: 'Note PDFs' },
{ id: 'media', label: 'Media copies' },
{ id: 'proofs', label: 'Proof PNGs' },
- { id: 'views', label: 'Analysis plates' },
+ { id: 'views', label: 'Views and comparisons' },
{ id: 'sheets', label: 'Sheet CSVs' },
];
@@ -891,6 +895,7 @@
{extDetected}
{extOutdated}
{extState}
+ {extBundled}
{extBusy}
{installExtension}
{updateExtension}
diff --git a/frontend/src/tools/compare/AcquisitionPicker.svelte b/frontend/src/tools/compare/AcquisitionPicker.svelte
new file mode 100644
index 0000000..0f14793
--- /dev/null
+++ b/frontend/src/tools/compare/AcquisitionPicker.svelte
@@ -0,0 +1,194 @@
+<script>
+ /**
+ * The Sentinel-2 passes the drawn areas actually have, to pick a run's dates from.
+ *
+ * It replaces two bare date fields, which offered every day since 2015 and
+ * knew nothing: a sweep pinned to a day without a pass reads nodata, and the
+ * user finds that out after paying for the tiles. A calendar is the wrong
+ * shape for the answer, too — Sentinel-2 revisits every five days, so four
+ * cells in five are dead. So this lists what exists, newest first, with the
+ * two facts that decide between them: how much of the areas the pass reaches,
+ * and how much of it was cloud.
+ */
+ import Icon from '../../components/Icon.svelte';
+ import { LOOKBACK_WINDOWS, coverClass, coverLabel } from '../../lib/map/acquisitions.js';
+ import { cloudClass, cloudLabel } from '../../lib/sentinel.js';
+
+ let {
+ list = [],
+ days,
+ busy = false,
+ error = '',
+ truncated = false,
+ searched = false,
+ areas = 0,
+ single = false,
+ wantsReference = true,
+ wantsCompare = true,
+ a = '',
+ b = '',
+ ondays,
+ onlook,
+ onpick,
+ } = $props();
+</script>
+
+<div class="passes" aria-label="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)}
+ <button
+ type="button"
+ class:on={days === option.id}
+ disabled={busy}
+ onclick={() => ondays(option.id)}
+ >{option.label}</button>
+ {/each}
+ </div>
+ <button class="btn btn-sm" disabled={busy || !areas} onclick={onlook}>
+ {busy ? 'Looking…' : searched ? 'Look again' : 'Find passes'}
+ </button>
+ </div>
+
+ {#if !areas}
+ <p class="hint">Draw an area in step 1, then look up the passes it has.</p>
+ {:else if error}
+ <p class="warn" role="alert">{error}</p>
+ {:else if busy}
+ <p class="hint">Reading the catalogue over your areas…</p>
+ {:else if !searched}
+ <p class="hint">One lookup, billed as one Copernicus request.</p>
+ {:else if !list.length}
+ <p class="warn">No pass reaches these areas in this window. Try a longer one.</p>
+ {:else}
+ {#if truncated}
+ <p class="warn">The catalogue stopped at 100 passes, so older ones are missing. 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}>
+ <div class="facts">
+ <strong class="cmp-mono">{entry.date}</strong>
+ <span class="badge {coverClass(entry.coverage)}">{coverLabel(entry.coverage)}</span>
+ <span class="badge {cloudClass(entry.cloud)}">{cloudLabel(entry.cloud) || 'cloud unknown'}</span>
+ </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"
+ 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'}
+ onclick={() => onpick('b', entry)}
+ >{single ? 'Use' : 'B'}</button>
+ {/if}
+ </div>
+ </li>
+ {/each}
+ </ul>
+ <p class="hint">
+ <Icon name="info" size={11} />
+ A pass covers what its swath reached that day, not the whole map.
+ </p>
+ {/if}
+</div>
+
+<style>
+ .passes {
+ display: grid;
+ gap: 7px;
+ padding: 8px;
+ border: 1px solid var(--border);
+ border-radius: var(--r-sm);
+ background: var(--bg-2);
+ }
+ .head {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 8px;
+ flex-wrap: wrap;
+ }
+ .hint {
+ display: flex;
+ align-items: center;
+ gap: 5px;
+ margin: 0;
+ color: var(--text-3);
+ font-size: 10px;
+ line-height: 1.35;
+ }
+ .warn {
+ margin: 0;
+ color: var(--warn, #e2a03f);
+ font-size: 10.5px;
+ line-height: 1.35;
+ }
+ .list {
+ display: grid;
+ gap: 3px;
+ max-height: 208px;
+ margin: 0;
+ padding: 0;
+ overflow-y: auto;
+ list-style: none;
+ }
+ li {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 8px;
+ padding: 5px 6px;
+ border: 1px solid transparent;
+ border-radius: var(--r-sm);
+ }
+ li:hover {
+ background: var(--bg-3);
+ }
+ li.chosen {
+ border-color: var(--accent);
+ background: var(--accent-soft);
+ }
+ .facts {
+ min-width: 0;
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ flex-wrap: wrap;
+ }
+ .facts strong {
+ color: var(--text-1);
+ font-size: var(--fs-xs);
+ }
+ .badge {
+ padding: 1px 5px;
+ border: 1px solid var(--border);
+ border-radius: var(--r-sm);
+ color: var(--text-3);
+ font-size: 9.5px;
+ white-space: nowrap;
+ }
+ .badge.full,
+ .badge.clear {
+ border-color: color-mix(in srgb, var(--ok, #46a758) 60%, transparent);
+ color: var(--ok, #46a758);
+ }
+ .badge.part {
+ border-color: color-mix(in srgb, var(--warn, #e2a03f) 55%, transparent);
+ color: var(--warn, #e2a03f);
+ }
+ .badge.thin,
+ .badge.cloudy {
+ border-color: color-mix(in srgb, var(--danger, #e5484d) 50%, transparent);
+ color: var(--danger, #e5484d);
+ }
+</style>
diff --git a/frontend/src/tools/compare/AcquisitionPicker.test.js b/frontend/src/tools/compare/AcquisitionPicker.test.js
new file mode 100644
index 0000000..cb5a82a
--- /dev/null
+++ b/frontend/src/tools/compare/AcquisitionPicker.test.js
@@ -0,0 +1,98 @@
+// @vitest-environment happy-dom
+import { describe, expect, it, vi } from 'vitest';
+import { flushSync, mount, unmount } from 'svelte';
+import AcquisitionPicker from './AcquisitionPicker.svelte';
+
+const passes = [
+ { date: '2026-05-11', cloud: 3, granules: 2, coverage: 1 },
+ { date: '2026-05-08', cloud: 41, granules: 1, coverage: 0.62 },
+];
+
+function render(props = {}) {
+ const target = document.createElement('div');
+ document.body.append(target);
+ const live = mount(AcquisitionPicker, {
+ target,
+ props: {
+ list: passes, days: 30, searched: true, areas: 1,
+ ondays: () => {}, onlook: () => {}, onpick: () => {}, ...props,
+ },
+ });
+ flushSync();
+ return { target, done: () => { unmount(live); target.remove(); } };
+}
+
+const rows = (target) => [...target.querySelectorAll('li')];
+const button = (target, name) =>
+ [...target.querySelectorAll('button')].find((node) => node.textContent.trim() === name);
+
+describe('the acquisition picker', () => {
+ it('lists what exists rather than every day on the calendar', () => {
+ const { target, done } = render();
+ expect(rows(target)).toHaveLength(2);
+ expect(target.querySelector('input[type="date"]')).toBe(null);
+ done();
+ });
+
+ it('shows how much of the areas each pass reaches, beside its cloud', () => {
+ const { target, done } = render();
+ expect(rows(target)[0].textContent).toContain('Full cover');
+ expect(rows(target)[0].textContent).toContain('3% cloud');
+ // the fact a crosshair lookup cannot give, and a sweep cannot do without
+ expect(rows(target)[1].textContent).toContain('62% of the areas');
+ done();
+ });
+
+ it('asks for an area before it asks Copernicus anything', () => {
+ const onlook = vi.fn();
+ const { target, done } = render({ areas: 0, list: [], searched: false });
+ expect(target.textContent).toContain('Draw an area in step 1');
+ expect(button(target, 'Find passes').disabled).toBe(true);
+ done();
+ });
+
+ it('does not reach the network until it is asked to', () => {
+ const onlook = vi.fn();
+ const { target, done } = render({ list: [], searched: false, onlook });
+ // local-first: mounting the panel must never spend a request
+ expect(onlook).not.toHaveBeenCalled();
+ expect(target.textContent).toContain('billed as one Copernicus request');
+ button(target, 'Find passes').click();
+ expect(onlook).toHaveBeenCalledOnce();
+ done();
+ });
+
+ it('hands a chosen pass back for the slot it was chosen for', () => {
+ const onpick = vi.fn();
+ const { target, done } = render({ onpick });
+ button(target, 'A').click();
+ expect(onpick).toHaveBeenCalledWith('a', passes[0]);
+ done();
+ });
+
+ it('offers one slot for a method that reads a single image', () => {
+ const { target, done } = render({ single: true });
+ expect(button(target, 'A')).toBeUndefined();
+ expect(button(target, 'Use')).toBeDefined();
+ done();
+ });
+
+ it('hides the compare slot when a rule will resolve it at run time', () => {
+ const { target, done } = render({ wantsCompare: false });
+ expect(button(target, 'B')).toBeUndefined();
+ expect(button(target, 'A')).toBeDefined();
+ done();
+ });
+
+ it('says when the catalogue stopped short instead of implying a full list', () => {
+ const { target, done } = render({ truncated: true });
+ expect(target.textContent).toContain('stopped at 100 passes');
+ done();
+ });
+
+ it('suggests a longer window when nothing reaches the areas', () => {
+ const { target, done } = render({ list: [] });
+ expect(target.textContent).toContain('No pass reaches these areas');
+ done();
+ });
+});
diff --git a/frontend/src/tools/compare/AnalysisOverlay.svelte b/frontend/src/tools/compare/AnalysisOverlay.svelte
new file mode 100644
index 0000000..4e0dde7
--- /dev/null
+++ b/frontend/src/tools/compare/AnalysisOverlay.svelte
@@ -0,0 +1,68 @@
+<script>
+ import { displayGroups } from '../../lib/map/analyzers.js';
+ let { engine, layers = [], selected = null, onpick = () => {}, active = true } = $props();
+ let revision = $state(0);
+ $effect(() => {
+ if (!engine) return;
+ return engine.on('view-move', () => revision++);
+ });
+ // Reading the camera's revision here keeps every projected shape on its
+ // ground, boxes included, however the map is panned or turned.
+ const project = ([lon, lat]) => {
+ revision;
+ return engine?.latLngToContainerPoint({ lon, lat }) ?? { x: 0, y: 0 };
+ };
+ const visible = (rows) => rows.filter((row) => row.review !== 'dismissed');
+ 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) })),
+ groups: displayGroups(visible(layer.results), project),
+ }));
+ });
+ function box(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(' ');
+ }
+ function pick(layer, group) {
+ if (group.rows.length > 1 && engine) {
+ const [lon, lat] = group.rows[0].coordinates;
+ engine.setView({ lon, lat }, engine.getZoom() + 2);
+ } else onpick(layer.id, group.rows[0].id);
+ }
+</script>
+
+<svg class="analysis-overlay" aria-label="Analysis candidates">
+ {#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" />
+ {/each}
+ {/if}
+ {#each layer.groups as group, i (i)}
+ {@const kept = group.rows.every((row) => row.review === 'kept')}
+ <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); }}>
+ <!-- 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)}
+ <circle cx={group.x} cy={group.y} r={group.rows.length > 1 ? 18 : 11}
+ 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" />
+ {#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>
+ {/each}
+ {/each}
+</svg>
+
+<style>
+ .analysis-overlay { position: absolute; inset: 0; width: 100%; height: 100%; z-index: 545; pointer-events: none; }
+ g { pointer-events: auto; cursor: pointer; }
+ text { fill: #111; text-anchor: middle; font: bold 11px system-ui; pointer-events: none; }
+</style>
diff --git a/frontend/src/tools/compare/AnalyzerPanel.svelte b/frontend/src/tools/compare/AnalyzerPanel.svelte
new file mode 100644
index 0000000..41c0f24
--- /dev/null
+++ b/frontend/src/tools/compare/AnalyzerPanel.svelte
@@ -0,0 +1,957 @@
+<script>
+ /**
+ * Detect mode's own column: sweep a drawn area 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,
+ clone,
+ coverage,
+ framesPerTile,
+ mapSource,
+ readableDuration,
+ 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 = {},
+ releases = [],
+ 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 = () => {},
+ } = $props();
+
+ let catalogue = $state(null);
+ let recipe = $state(null);
+ let chosen = $state('');
+ let title = $state('');
+ let a = $state({ provider: 'esri-wayback', date: '', release: null, layer: 'TRUE_COLOR', maxcc: 30 });
+ let b = $state({ provider: 'esri-wayback', date: '', release: null, layer: 'TRUE_COLOR', maxcc: 30 });
+ 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 part = $state(0);
+ let busy = $state(false);
+ let error = $state('');
+ let view = $state('setup');
+ let showImagery = $state(false);
+ let showDetection = $state(false);
+ let showRecipe = $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`
+ );
+ const compatible = $derived(!recipe || recipe.providers.includes(b.provider));
+ /** 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));
+ /** 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 grid = $derived(catalogue?.grids?.[b.provider] ?? null);
+ const cost = $derived(coverage(zones, grid));
+ 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.provider === right.provider ? { left, right } : null;
+ });
+ const tileCount = $derived(Number.isFinite(cost.tiles) ? String(cost.tiles) : 'over the limit');
+ const frames = $derived(cost.tiles * framesPerTile({ single, bands: !!capability.sentinel_only }));
+ 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.`)
+ : !compatible ? 'This analyzer does not support the chosen imagery source.'
+ // Said here rather than discovered when the run comes back failed.
+ : dateRule === 'manual' && !isDated(b) ? `Choose the ${single ? 'image' : 'image to compare'}.`
+ : !single && !isDated(a) && !(dateRule === 'latest_previous' && followupId)
+ ? 'Choose the reference image.'
+ : pending ? 'A run is already working in this case.'
+ : ''
+ );
+
+ /** Named enough to run: a Sentinel day, or a Wayback release. */
+ const isDated = (source) =>
+ source.provider === 'sentinel2' ? !!source.date : source.release != null;
+ 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));
+
+ /**
+ * One chip, two stores behind it. Sentinel-2's classification and a guess off
+ * the picture are not the same claim, so they are not the same field: the
+ * classification is trusted by default, the guess is never turned on for
+ * anyone. The chip hides that, the catalogue decides which applies.
+ */
+ const weatherOn = $derived(
+ capability.cloud_filter === 'classes'
+ ? recipe?.parameters?.ignore_clouds ?? false
+ : recipe?.parameters?.guess_clouds ?? false
+ );
+
+ function setWeather(on) {
+ if (!recipe) return;
+ recipe.parameters = capability.cloud_filter === 'classes'
+ ? { ...recipe.parameters, ignore_clouds: on, ignore_shadows: on }
+ : { ...recipe.parameters, guess_clouds: on };
+ }
+
+ /** 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(
+ b.provider === 'sentinel2'
+ ? [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 this cannot read — 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;
+ if (methodOf(recipe.method).sentinel_only && b.provider !== 'sentinel2') setProvider('sentinel2');
+ }
+
+ function setProvider(provider) {
+ pinned = true;
+ b = { ...b, provider };
+ a = { ...a, provider };
+ }
+
+ 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 };
+ }
+
+ function hydrate(body) {
+ title = body.title; zones = clone(body.zones); recipe = clone(body.recipe); chosen = recipe.id;
+ a = clone(body.a); b = clone(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'; part = 0; }
+ }
+
+ 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; part = 0; 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; part = 0; focus(row.coordinates); }
+ }
+
+ export function pick(runId, resultId) {
+ const run = layers.find((r) => r.id === runId);
+ if (run) { current = run; candidateId = resultId; part = 0; 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>
+ <p class="cmp-dock-lead">
+ Sweeps the areas you draw at full resolution. What it finds is a list of candidates to check
+ one by one: only the ones you keep become pins in the case.
+ </p>
+
+ <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 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>
+ {/if}
+ {#if !zones.length}
+ <p class="hint">Draw on either map, take the current view, or open a saved set from Saved.</p>
+ {:else}
+ {#each zones as zone (zone.id)}
+ <div class="row area-row">
+ <button class="cmp-icon" aria-label={`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}`} 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² · {tileCount} tiles of {cost.size}px
+ </p>
+ {#if !tooMany}
+ <p class="hint">{frames} frames to fetch, about {duration}. You can cancel a run once it starts.</p>
+ {/if}
+ <p class="hint">Drag an area by its edge to move it, or click the edge to edit its corners. Inside it, the map pans as usual.</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={compatible && (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">The maps were not showing a source this can analyze, so they now show the one below.</p>
+ {/if}
+ <p class="pair">
+ {#if !single}{sourceLabel(a)} <Icon name="arrowRight" size={11} />{/if} {sourceLabel(b)}
+ </p>
+ {#if !compatible}<p class="warn">This analyzer supports {recipe.providers.map((p) => p === 'sentinel2' ? 'Sentinel-2' : 'Wayback').join(' and ')}.</p>{/if}
+ {#if capability.sentinel_only}
+ <p class="hint">
+ This analyzer measures Sentinel-2 bands as well as showing the picture, so a run fetches
+ {single ? 'two frames' : 'four frames'} per tile. All of them count toward your Copernicus usage.
+ </p>
+ {/if}
+ <div class="row">
+ <button class="link" onclick={() => (showImagery = !showImagery)} aria-expanded={showImagery}>
+ {showImagery ? 'Hide imagery settings' : 'Change imagery, 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="Analyze Wayback or Copernicus Sentinel-2, with one provider for both dates.">Source
+ <select aria-label="Analyzer source" value={b.provider} onchange={(e) => setProvider(e.currentTarget.value)}>
+ <option value="esri-wayback">Wayback</option><option value="sentinel2">Copernicus Sentinel-2</option>
+ </select>
+ </label>
+ <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 b.provider === 'sentinel2'}
+ {#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="Both dates must use the same rendering, or style differences read as change.">Layer
+ <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>
+ {:else}
+ {#each ['a', 'b'] as letter}
+ {#if (letter === 'b' && dateRule === 'manual') || (letter === 'a' && !single)}
+ <label>Release {letter.toUpperCase()}
+ {#if releases.length}
+ <select aria-label={`Release ${letter.toUpperCase()}`} value={letter === 'a' ? a.release : b.release}
+ onchange={(e) => {
+ pinned = true;
+ const release = Number(e.currentTarget.value);
+ if (letter === 'a') a = { ...a, release };
+ else { b = { ...b, release }; if (single) a = { ...a, release }; }
+ }}>
+ <option value="">Choose a release</option>
+ {#each releases as r}<option value={r.release}>{r.date} · {r.release}</option>{/each}
+ </select>
+ {:else}
+ <input type="number" aria-label={`Release ${letter.toUpperCase()}`} min="1" value={letter === 'a' ? a.release : b.release}
+ oninput={(e) => {
+ pinned = true;
+ const release = Number(e.currentTarget.value);
+ if (letter === 'a') a = { ...a, release };
+ else { b = { ...b, release }; if (single) a = { ...a, release }; }
+ }} />
+ {/if}
+ </label>
+ {/if}
+ {/each}
+ <p class="hint">Wayback release dates are publication dates, not exact acquisition dates.</p>
+ {/if}
+ {#if dateRule !== 'manual'}
+ <p class="hint">Run looks for recent imagery at that moment. Nothing downloads on its own; save a watch to reuse the previous run as the reference.</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 offline}
+ <p class="hint">A finished run only keeps the tiles that found something, so a rerun offline covers what the cache still holds.</p>
+ {/if}
+ {/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>
+ <label>
+ <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="My analyzers">{#each catalogue.custom as r}<option value={r.id}>{r.name}</option>{/each}</optgroup>
+ {/if}
+ {#if ![...(catalogue?.builtins ?? []), ...(catalogue?.custom ?? [])].some((r) => r.id === chosen)}
+ <option value={chosen}>{recipe.name} (from a saved run)</option>
+ {/if}
+ </select>
+ </label>
+ <p class="hint">{recipe.description}</p>
+ <CloudFilter
+ kind={capability.cloud_filter ?? ''}
+ clouds={weatherOn}
+ shadows={capability.cloud_filter === 'classes' && recipe.parameters.ignore_shadows}
+ split={capability.cloud_filter === 'classes'}
+ ontoggle={setWeather}
+ />
+ <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 analyzer' : 'Edit or duplicate…'}
+ </button>
+ </div>
+ {#if showDetection}
+ <label title="Higher values retain weaker differences and usually produce more noise.">Sensitivity · {recipe.parameters.sensitivity}
+ <input aria-label="Analyzer sensitivity" type="range" min="0" max="100" bind:value={recipe.parameters.sensitivity} />
+ </label>
+ <label title="Drop candidate regions smaller than this ground area after grouping.">Minimum area (m²)
+ <input type="number" min="0" max="100000000" bind:value={recipe.parameters.min_area} />
+ </label>
+ <label title="Filter on visual signal strength. This is not the probability that an object was identified.">Minimum signal score · {recipe.parameters.min_score}
+ <input type="range" min="0" max="1" step="0.01" bind:value={recipe.parameters.min_score} />
+ </label>
+ {#if recipe.method === 'index'}
+ <label title="NDVI: vegetation; NDWI: water; NBR: burn scars; NDBI: built-up or bare ground.">Index
+ <select bind:value={recipe.parameters.index}>{#each ['ndvi', 'ndwi', 'nbr', 'ndbi'] as index}<option value={index}>{index.toUpperCase()}</option>{/each}</select>
+ </label>
+ {/if}
+ {#if capability.cloud_filter === 'classes'}
+ <label class="check"><input type="checkbox" bind:checked={recipe.parameters.ignore_clouds} /> Exclude cloud and snow pixels</label>
+ <label class="check"><input type="checkbox" bind:checked={recipe.parameters.ignore_shadows} /> Exclude shadow pixels</label>
+ {/if}
+ {#if capability.cloud_filter}
+ <label title="Grow the cloud and shadow mask, to take the soft edge a mask leaves behind.">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 small speckles; stronger cleanup 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 difference before detecting regions; zero preserves small details.">Smoothing · {recipe.parameters.smoothing}px<input type="range" min="0" max="3" bind:value={recipe.parameters.smoothing} /></label>
+ <label title="Merge nearby candidate boxes; zero joins only overlapping or touching boxes.">Group within (m)<input type="number" min="0" max="500" bind:value={recipe.parameters.merge_metres} /></label>
+ {#if !single}
+ <label title="Keep strengthening, weakening or both directions of the signal.">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.sentinel_only}
+ <label class="check" title="Reduce lighting differences; this can also suppress broad real changes."><input type="checkbox" bind:checked={recipe.parameters.normalize} /> Correct overall brightness differences</label>
+ {/if}
+ </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 the method can detect.">Candidate label<input bind:value={recipe.phenomenon} maxlength="120" /></label>
+ <label title="The local image-processing method. These analyzers measure signal; they do not recognize object identities.">Method
+ <select aria-label="Analyzer method" bind:value={recipe.method}
+ onchange={() => { if (methodOf(recipe.method).sentinel_only) { recipe.providers = ['sentinel2']; setProvider('sentinel2'); } }}>
+ {#each catalogue?.methods ?? [] as method}<option value={method.id}>{method.label}</option>{/each}
+ </select>
+ </label>
+ <label class="check"><input type="checkbox" value="esri-wayback" bind:group={recipe.providers} disabled={capability.sentinel_only} /> Works on Wayback</label>
+ <label class="check"><input type="checkbox" value="sentinel2" bind:group={recipe.providers} /> Works on Copernicus Sentinel-2</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">
+ <button class="btn btn-sm" disabled={busy} onclick={() => act(() => saveRecipe())}>Save analyzer</button>
+ <button class="btn btn-sm" disabled={busy} onclick={() => act(() => saveRecipe(true))}>Duplicate</button>
+ </div>
+ <p class="hint">Analyzers are shared by every case and travel in Settings backup.</p>
+ {/if}
+ </section>
+ {/if}
+
+ {#if view === 'results'}
+ {#if current}
+ <section class="run">
+ <strong>{current.title}</strong>
+ <p class="hint">{statusLabel(current.status)} · {current.progress}/{current.total} tiles</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'}
+ <p class="hint">
+ {#if methodOf(current.input.recipe.method).single}{sourceLabel(current.input.b)}
+ {:else}{sourceLabel(current.input.a)} → {sourceLabel(current.input.b)}{/if}
+ </p>
+ <p class="hint">{current.input.recipe.name} · {current.input.recipe.method} · engine {current.engine_version}</p>
+ <button class="btn btn-sm" onclick={() => { hydrate(current.input); view = 'setup'; }}>Edit settings and run again</button>
+ {#if !candidates.length}<p class="hint">Nothing passed these filters. That is not evidence that nothing changed.</p>{/if}
+ {/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" onclick={() => step(-1)}><Icon name="chevronLeft" size={14} /></button>
+ <span class="grow centre">Candidate {candidates.findIndex((r) => r.id === candidateId) + 1} of {candidates.length}</span>
+ <button class="cmp-icon" aria-label="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?part=${part}`}
+ alt={single ? 'Candidate evidence' : 'Candidate evidence: A on the left, B on the right'} />
+ {#if candidate.parts.length > 1}
+ <label>Evidence part<select bind:value={part}>{#each candidate.parts as _, i}<option value={i}>{i + 1} of {candidate.parts.length}</option>{/each}</select></label>
+ {/if}
+ <p class="facts">{Math.round(candidate.area)} m² · {Math.round(candidate.width)} × {Math.round(candidate.height)} m</p>
+ <p class="hint">Signal score {Math.round(candidate.signal_score * 100)}% · not a calibrated confidence</p>
+ <button class="link" onclick={() => focus(candidate.coordinates)}>
+ {candidate.coordinates[1].toFixed(6)}, {candidate.coordinates[0].toFixed(6)}
+ </button>
+
+ <!-- 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 · in this case as a pin</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>
+ <p class="hint">Keeping files this one candidate and its evidence in the case. Nothing else here reaches it.</p>
+ {/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}`} 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; part = 0; }}>
+ {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, kept together. Run it again whenever you want a fresh pass; 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}`} 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}`} 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>
+ .views { margin: 10px 12px 0; }
+ .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: 8px; }
+ section.run, section.candidate { border-top: 1px solid var(--border); padding-top: 10px; }
+ section > 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; }
+ .centre { text-align: center; }
+ .nav { justify-content: space-between; }
+ .facts { margin: 0; font-size: var(--fs-xs); }
+ .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
new file mode 100644
index 0000000..427f12b
--- /dev/null
+++ b/frontend/src/tools/compare/AnalyzerPanel.test.js
@@ -0,0 +1,220 @@
+// @vitest-environment happy-dom
+import { beforeEach, afterEach, expect, it, vi } from 'vitest';
+import { flushSync, mount, unmount } from 'svelte';
+
+const recipe = { id: 'large-change', name: 'Large surface change', description: 'Candidate changes',
+ phenomenon: 'Change', method: 'colour', providers: ['esri-wayback', 'sentinel2'], zones: [],
+ colour: '#f6a81a', style: 'both', parameters: { sensitivity: 55, min_area: 20, min_score: 0,
+ cleanup: 1, smoothing: 0, normalize: false, index: 'ndvi', direction: 'both',
+ ignore_clouds: true, ignore_shadows: true, merge_metres: 0 } };
+const get = vi.fn();
+const post = vi.fn();
+const patch = vi.fn();
+vi.mock('../../lib/api.js', () => ({ api: { get, post, patch, put: vi.fn(), del: vi.fn() } }));
+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 wayback = { a: { provider: 'esri-wayback', wayback_release: 1 },
+ b: { provider: 'esri-wayback', wayback_release: 2 } };
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ get.mockImplementation(async (path) => path === '/api/compare/analyzers'
+ ? { builtins: [structuredClone(recipe)], custom: [], methods: [{ id: 'colour', label: 'Colour' }],
+ max_tiles: 256, max_results: 2000, grids: { sentinel2: [13, 512], 'esri-wayback': [19, 256] } }
+ : []);
+ 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 () => {
+ const zones = [{ id: 'area', name: 'Area', kind: 'rect', points: [[2, 48], [2.001, 48.001]] }];
+ 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, sources: wayback } });
+ await settle();
+ // No click on an imagery control: the maps above the stage already said it.
+ expect(target.textContent).toContain('From the maps');
+ expect(post).not.toHaveBeenCalled();
+ button('Run on 1 area').click(); await settle();
+ expect(post).toHaveBeenCalledWith('/api/cases/case-a/analysis/runs', expect.objectContaining({
+ zones, a: expect.objectContaining({ release: 1 }), b: expect.objectContaining({ release: 2 }),
+ }));
+ expect(target.textContent).toContain('Offline fixture');
+});
+
+it('prices an area in tiles and refuses one the engine would reject', async () => {
+ const zones = [{ id: 'big', name: 'Whole region', kind: 'rect', points: [[2, 48], [3, 49]] }];
+ live = mount(Panel, { target, props: { caseId: 'case-a', zones, sources: wayback } });
+ await settle();
+ expect(target.textContent).toContain('tiles of 256px');
+ expect(button('Run on 1 area').disabled).toBe(true);
+ expect(target.textContent).toContain('256-tile limit');
+ expect(post).not.toHaveBeenCalled();
+});
+
+it('duplicates a built-in analyzer under a name of its own', async () => {
+ post.mockImplementation(async (_, body) => ({ ...body, id: 'custom-copy' }));
+ live = mount(Panel, { target, props: { caseId: 'case-a' } }); await settle();
+ button('Edit or duplicate…').click(); await settle();
+ const name = target.querySelector('[aria-label="Analyzer name"]');
+ name.value = 'Weekly harbour'; name.dispatchEvent(new Event('input', { bubbles: true }));
+ button('Duplicate').click(); await settle();
+ expect(post).toHaveBeenCalledWith('/api/compare/analyzers', expect.objectContaining({ id: 'custom', name: 'Weekly harbour' }));
+});
+
+it('reviews candidates one at a time, and only keeping reaches the case', async () => {
+ const zones = [{ id: 'area', name: 'Area', kind: 'rect', points: [[2, 48], [2.001, 48.001]] }];
+ const row = (id, lon) => ({ id, coordinates: [lon, 48], bbox: [lon, 48, lon + 0.001, 48.001],
+ area: 90, width: 15, height: 6, signal_score: 0.8, confidence: null, review: 'new',
+ phenomenon: 'Surface change', parts: [{ frames: ['a', 'b'], box: [0, 0, 4, 4] }] });
+ const saved = { id: '123456789abc', title: 'Harbour sweep', status: 'ready', progress: 1, total: 1,
+ count: 2, engine_version: 1, results: [row('0-1', 2), row('0-2', 2.002)],
+ input: { title: 'Harbour sweep', zones, recipe: structuredClone(recipe),
+ 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 { builtins: [structuredClone(recipe)], custom: [], methods: [{ id: 'colour', label: 'Colour' }],
+ max_tiles: 4096, max_results: 2000, grids: { 'esri-wayback': [19, 256] } };
+ }
+ 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('Candidate 1 of 2');
+ expect(target.textContent).toContain('2 still to review · 0 kept, 0 dismissed');
+
+ // 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('Candidate 2 of 2');
+
+ // 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 · in this case as a pin');
+ expect(target.textContent).toContain('All 2 reviewed · 1 kept, 1 dismissed');
+});
+
+const sentinelCatalogue = (methods) => ({
+ builtins: [structuredClone(recipe)], custom: [], methods,
+ max_tiles: 4096, max_results: 2000, grids: { sentinel2: [13, 512], 'esri-wayback': [19, 256] },
+});
+const sentinelMaps = {
+ 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 } },
+};
+
+it('picks Copernicus dates from passes the areas have, not from a calendar', async () => {
+ const zones = [{ id: 'area', name: 'Area', kind: 'rect', points: [[2, 48], [2.001, 48.001]] }];
+ get.mockImplementation(async (path) => path === '/api/compare/analyzers'
+ ? sentinelCatalogue([{ id: 'colour', label: 'Colour', cloud_filter: 'picture' }]) : []);
+ 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, sources: sentinelMaps } });
+ await settle();
+ button('Change imagery, 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 }));
+ 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 () => {
+ const zones = [{ id: 'area', name: 'Area', kind: 'rect', points: [[2, 48], [2.001, 48.001]] }];
+ get.mockImplementation(async (path) => path === '/api/compare/analyzers'
+ ? sentinelCatalogue([{ id: 'colour', label: 'Colour', cloud_filter: 'picture' }]) : []);
+ 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, sources: sentinelMaps } });
+ await settle();
+ button('Change imagery, 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('offers the cloud guess off, and says it is a guess', async () => {
+ get.mockImplementation(async (path) => path === '/api/compare/analyzers'
+ ? sentinelCatalogue([{ id: 'colour', label: 'Colour', cloud_filter: 'picture' }]) : []);
+ live = mount(Panel, { target, props: { caseId: 'case-a', sources: wayback } });
+ await settle();
+ const chip = [...target.querySelectorAll('button')].find((b) => b.textContent.includes('Clouds & shadows'));
+ // a test that cannot tell cloud from a white roof is never on by default
+ expect(chip.getAttribute('aria-pressed')).toBe('false');
+ expect(target.textContent).toContain('A guess from the picture');
+ chip.click(); await settle();
+ expect(chip.getAttribute('aria-pressed')).toBe('true');
+});
+
+it('offers no cloud switch where masking cloud would mask the subject', async () => {
+ get.mockImplementation(async (path) => path === '/api/compare/analyzers'
+ ? sentinelCatalogue([{ id: 'colour', label: 'Smoke', cloud_filter: '' }]) : []);
+ live = mount(Panel, { target, props: { caseId: 'case-a', sources: wayback } });
+ await settle();
+ expect(target.textContent).not.toContain('Clouds & shadows');
+});
+
+it('runs a saved watch again without asking for its settings twice', async () => {
+ const zones = [{ id: 'area', name: 'Area', kind: 'rect', points: [[2, 48], [2.001, 48.001]] }];
+ const watch = { id: 'abcdef123456', title: 'Harbour weekly', created_at: '2026-09-01T00:00:00Z',
+ zones, recipe: structuredClone(recipe), a: { provider: 'esri-wayback', release: 1 },
+ b: { provider: 'esri-wayback', release: 2 }, offline: false, date_rule: 'latest_previous',
+ followup_id: 'abcdef123456' };
+ get.mockImplementation(async (path) => {
+ if (path === '/api/compare/analyzers') {
+ return { builtins: [structuredClone(recipe)], custom: [], methods: [], max_tiles: 256,
+ grids: { 'esri-wayback': [19, 256] } };
+ }
+ 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, date_rule: 'latest_previous', followup_id: watch.id,
+ }));
+});
diff --git a/frontend/src/tools/compare/AnnotationCanvas.svelte b/frontend/src/tools/compare/AnnotationCanvas.svelte
new file mode 100644
index 0000000..9240eb2
--- /dev/null
+++ b/frontend/src/tools/compare/AnnotationCanvas.svelte
@@ -0,0 +1,234 @@
+<script>
+ import { onMount } from 'svelte';
+ import { markLabel, movedMark, onSide, projectMark } from '../../lib/map/compareAnnotations.js';
+
+ let { annotations = [], engine, letter = 'a', units = 'metric', active = true,
+ tool = $bindable('select'), selectedId = $bindable(null), colour = '#f6a81a',
+ strokeWidth = 4, fillOpacity = 0, annotationSide = 'both', editVertices = false, onchange = () => {} } = $props();
+ let svg = $state();
+ let revision = $state(0);
+ let draft = $state(null);
+ let editor = $state(null);
+ let gesture = null;
+
+ /** Below this, a pointer press is a click: a shape is picked, never nudged. */
+ const DRAG_SLOP = 4;
+
+ $effect(() => {
+ if (!engine) return;
+ const refresh = () => revision++;
+ const release = engine.on('view-move', refresh);
+ const observer = new ResizeObserver(refresh);
+ if (svg) observer.observe(svg);
+ return () => { release(); observer.disconnect(); };
+ });
+
+ // Every screen position in this component goes through here, and reading the
+ // camera's revision *inside* it is what pins them all to the ground: a handle
+ // or a popup computed outside the projected shapes would otherwise stay where
+ // the last pan left it.
+ const project = ([lon, lat]) => {
+ revision;
+ const at = engine?.latLngToContainerPoint({ lon, lat });
+ return [at?.x ?? 0, at?.y ?? 0];
+ };
+ const marks = $derived.by(() =>
+ [...annotations.filter((mark) => onSide(mark, letter)), ...(draft ? [draft] : [])]
+ .map((mark) => ({ mark, shape: projectMark(mark, project), label: markLabel(mark, units),
+ vertices: editVertices ? mark.points.map(project) : [] }))
+ );
+ const pathOf = (shape) => shape.path.map(([x, y], i) => `${i ? 'L' : 'M'}${x},${y}`).join(' ') + (shape.closed ? ' Z' : '');
+ function point(event) {
+ const box = svg?.getBoundingClientRect();
+ if (!box?.width || !engine) return null;
+ const at = engine.containerPointToLatLng({ x: event.clientX - box.left, y: event.clientY - box.top });
+ return [Math.max(-180, Math.min(180, at.lon)), Math.max(-90, Math.min(90, at.lat))];
+ }
+ function makeMark(points) {
+ return { id: crypto.randomUUID(), kind: tool, side: annotationSide, colour, points,
+ stroke_width: strokeWidth, fill_opacity: fillOpacity, font_size: 16, text: '' };
+ }
+ function begin(event) {
+ if (!active || tool === 'select' || event.button > 0) return;
+ const at = point(event);
+ if (!at) return;
+ event.preventDefault();
+ if (tool === 'text') {
+ editor = { mark: makeMark([at]), value: '' };
+ return;
+ }
+ if (tool === 'polygon') {
+ if (!draft) draft = makeMark([at, at, at]);
+ else draft = { ...draft, points: [...draft.points.slice(0, -1), at, at].slice(0, 200) };
+ return;
+ }
+ draft = makeMark([at, at]);
+ gesture = { kind: 'draw', start: at };
+ svg.setPointerCapture?.(event.pointerId);
+ }
+ /** True once a press has travelled far enough to mean "drag", not "click". */
+ function dragging(event) {
+ if (!gesture?.from) return true;
+ if (gesture.live) return true;
+ if (Math.hypot(event.clientX - gesture.from.x, event.clientY - gesture.from.y) < DRAG_SLOP) return false;
+ gesture.live = true;
+ return true;
+ }
+
+ function move(event) {
+ const at = point(event);
+ if (!at) return;
+ if (gesture && !dragging(event)) return;
+ 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') {
+ const moved = movedMark(gesture.mark, at[0] - gesture.start[0], at[1] - gesture.start[1]);
+ onchange(annotations.map((mark) => mark.id === moved.id ? moved : mark), false);
+ } else if (draft && tool === 'polygon') {
+ draft = { ...draft, points: [...draft.points.slice(0, -1), at] };
+ } else if (gesture?.kind === 'draw' && draft) {
+ draft = { ...draft, points: draft.kind === 'freehand'
+ ? [...draft.points, at].slice(0, 400) : [draft.points[0], at] };
+ }
+ }
+ function finish(event) {
+ if (!gesture) return;
+ move(event);
+ svg.releasePointerCapture?.(event.pointerId);
+ if (gesture.kind === 'move' || gesture.kind === 'vertex') {
+ // 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);
+ } else if (draft) {
+ const first = project(draft.points[0]);
+ const last = project(draft.points.at(-1));
+ if (Math.hypot(last[0] - first[0], last[1] - first[1]) >= 3) {
+ onchange([...annotations, draft], true);
+ selectedId = draft.id;
+ }
+ draft = null;
+ tool = 'select';
+ }
+ gesture = null;
+ }
+ function finishPolygon(event) {
+ event?.preventDefault();
+ if (!draft || draft.kind !== 'polygon') return;
+ const points = draft.points.filter((p, i, all) => i === 0 || p[0] !== all[i - 1][0] || p[1] !== all[i - 1][1]);
+ if (points.length >= 3) {
+ onchange([...annotations, { ...draft, points }], true);
+ selectedId = draft.id;
+ }
+ draft = null;
+ tool = 'select';
+ }
+ function select(event, mark) {
+ if (!active || tool !== 'select' || event.button > 0) return;
+ event.preventDefault();
+ event.stopPropagation();
+ selectedId = mark.id;
+ gesture = { kind: 'move', start: point(event), mark: JSON.parse(JSON.stringify(mark)),
+ from: { x: event.clientX, y: event.clientY }, live: false };
+ svg.setPointerCapture?.(event.pointerId);
+ }
+ function vertex(event, mark, index) {
+ if (!active || !editVertices || event.button > 0) return;
+ event.preventDefault(); event.stopPropagation();
+ selectedId = mark.id;
+ gesture = { kind: 'vertex', mark: JSON.parse(JSON.stringify(mark)), index,
+ from: { x: event.clientX, y: event.clientY }, live: false };
+ svg.setPointerCapture?.(event.pointerId);
+ }
+ function edit(event, mark) {
+ if (mark.kind !== 'text') return;
+ event.stopPropagation();
+ editor = { mark, value: mark.text };
+ }
+ function saveText() {
+ if (!editor) return;
+ const mark = { ...editor.mark, text: editor.value.trim() };
+ if (mark.text) {
+ onchange(annotations.some((item) => item.id === mark.id)
+ ? annotations.map((item) => item.id === mark.id ? mark : item)
+ : [...annotations, mark], true);
+ selectedId = mark.id;
+ }
+ editor = null;
+ tool = 'select';
+ }
+ onMount(() => {
+ const key = (event) => {
+ if (!active || event.target?.closest?.('input, textarea, select')) return;
+ if (event.key === 'Escape') { draft = null; editor = null; gesture = null; tool = 'select'; }
+ if (event.key === 'Enter') finishPolygon(event);
+ };
+ document.addEventListener('keydown', key);
+ return () => document.removeEventListener('keydown', key);
+ });
+</script>
+
+<!-- svelte-ignore a11y_no_static_element_interactions -->
+<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}>
+ {#each marks as { mark, shape, label, vertices } (mark.id)}
+ <!-- svelte-ignore a11y_no_static_element_interactions -->
+ <g class="mark" class:area={editVertices} class:selected={selectedId === mark.id} style:color={mark.colour}
+ onpointerdown={(event) => select(event, mark)} ondblclick={(event) => edit(event, mark)}>
+ {#if mark.kind !== 'text'}
+ <path d={pathOf(shape)} stroke={mark.colour} stroke-width={mark.stroke_width}
+ fill={shape.closed ? mark.colour : 'none'} fill-opacity={mark.fill_opacity}
+ stroke-dasharray={mark.kind === 'measure' ? '8 6' : undefined} />
+ {#if editVertices}
+ <!-- An area is grabbed by its edge. Its middle belongs to the map, so
+ dragging inside one pans as it would anywhere else. -->
+ <path class="edge" d={pathOf(shape)} fill="none" stroke="transparent"
+ stroke-width={Math.max(16, mark.stroke_width * 4)} />
+ {/if}
+ {#if shape.head}<polygon points={shape.head.map((p) => p.join(',')).join(' ')} fill={mark.colour} />{/if}
+ {/if}
+ {#if label}
+ <text x={shape.anchor[0] + 6} y={shape.anchor[1] - 8} font-size={mark.font_size}>{label}</text>
+ {/if}
+ </g>
+ {#if editVertices && active && selectedId === mark.id && tool === 'select'}
+ {#each vertices as at, i}
+ <!-- svelte-ignore a11y_no_static_element_interactions -->
+ <g class="vertex" onpointerdown={(e) => vertex(e, mark, i)}>
+ <rect class="grip" x={at[0] - 11} y={at[1] - 11} width="22" height="22" fill="transparent" />
+ <rect x={at[0] - 5} y={at[1] - 5} width="10" height="10"
+ fill="#fff" stroke={mark.colour} stroke-width="2" />
+ </g>
+ {/each}
+ {/if}
+ {/each}
+</svg>
+{#if editor}
+ {@const anchor = project(editor.mark.points[0])}
+ <form class="text-editor cmp-glass" style:left={`${anchor[0]}px`} style:top={`${anchor[1]}px`}
+ onsubmit={(event) => { event.preventDefault(); saveText(); }}>
+ <input class="compare-text-editor input" aria-label="Annotation text" value={editor.value}
+ oninput={(event) => { if (editor) editor.value = event.currentTarget.value; }}
+ maxlength="240" onkeydown={(event) => { if (event.key === 'Escape') editor = null; }} />
+ <button class="btn btn-sm" type="submit">Apply</button>
+ <button class="btn btn-sm" type="button" onclick={() => (editor = null)}>Cancel</button>
+ </form>
+{/if}
+
+<style>
+ .annotation-canvas { position: absolute; inset: 0; width: 100%; height: 100%; z-index: 550; pointer-events: none; overflow: hidden; }
+ .annotation-canvas.drawing { pointer-events: auto; cursor: crosshair; touch-action: none; }
+ .mark { pointer-events: visiblePainted; cursor: move; }
+ .mark.area { pointer-events: none; }
+ .mark.area .edge { pointer-events: stroke; cursor: move; }
+ .drawing .mark { pointer-events: none; }
+ .vertex { pointer-events: auto; cursor: crosshair; }
+ .vertex .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; }
+ .text-editor { position: absolute; z-index: 620; display: flex; gap: 5px; padding: 8px; max-width: 90%; transform: translateY(-100%); }
+ .text-editor input { min-width: 100px; width: 220px; }
+</style>
diff --git a/frontend/src/tools/compare/AnnotationCanvas.test.js b/frontend/src/tools/compare/AnnotationCanvas.test.js
new file mode 100644
index 0000000..8dbfa5d
--- /dev/null
+++ b/frontend/src/tools/compare/AnnotationCanvas.test.js
@@ -0,0 +1,78 @@
+// @vitest-environment happy-dom
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { flushSync, mount, unmount } from 'svelte';
+
+const { default: Canvas } = await import('./AnnotationCanvas.svelte');
+
+globalThis.ResizeObserver = class { observe() {} disconnect() {} };
+
+let live, target, handlers, origin;
+
+/** Ten pixels to the degree, shifted by wherever the camera has been panned. */
+function fakeEngine() {
+ handlers = {};
+ origin = { x: 0, y: 0 };
+ return {
+ on: (name, handler) => { handlers[name] = handler; return () => delete handlers[name]; },
+ latLngToContainerPoint: ({ lon, lat }) => ({ x: lon * 10 - origin.x, y: lat * 10 - origin.y }),
+ containerPointToLatLng: ({ x, y }) => ({ lon: (x + origin.x) / 10, lat: (y + origin.y) / 10 }),
+ };
+}
+
+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 }));
+ flushSync();
+}
+
+function stage(props) {
+ live = mount(Canvas, { target, props: { engine: fakeEngine(), ...props } });
+ flushSync();
+ const svg = target.querySelector('svg');
+ svg.getBoundingClientRect = () => ({ left: 0, top: 0, width: 400, height: 300 });
+ return svg;
+}
+
+beforeEach(() => { target = document.createElement('div'); document.body.append(target); });
+afterEach(() => { if (live) unmount(live); target.remove(); });
+
+it('keeps the corner handles on their ground when the camera moves', () => {
+ stage({ annotations: [area()], editVertices: true, selectedId: 'z1', tool: 'select' });
+ const handle = () => target.querySelectorAll('.vertex rect:last-child')[0];
+ expect(handle().getAttribute('x')).toBe('5'); // 1° → 10px, less half the handle
+
+ origin.x = 40;
+ handlers['view-move']();
+ flushSync();
+ expect(handle().getAttribute('x')).toBe('-35'); // panned with the imagery, not left behind
+});
+
+it('treats a press that does not travel as a selection, never as a move', () => {
+ const onchange = vi.fn();
+ const svg = stage({ annotations: [area()], editVertices: true, tool: 'select', onchange });
+ const edge = target.querySelector('.edge');
+
+ press(edge, 'pointerdown', 20, 20);
+ press(svg, 'pointermove', 22, 21);
+ press(svg, 'pointerup', 22, 21);
+ expect(onchange).not.toHaveBeenCalled();
+
+ press(edge, 'pointerdown', 20, 20);
+ press(svg, 'pointermove', 60, 20);
+ press(svg, 'pointerup', 60, 20);
+ const dragged = onchange.mock.calls.filter(([, commit]) => !commit).at(-1)[0];
+ expect(dragged[0].points[0][0]).toBeCloseTo(5); // four degrees east, and only east
+ expect(dragged[0].points[0][1]).toBeCloseTo(1);
+ expect(onchange.mock.calls.at(-1)[1]).toBe(true); // one entry to undo, at the end
+});
+
+it('gives an area an edge to grab, so its middle still belongs to the map', () => {
+ stage({ annotations: [area()], editVertices: true, tool: 'select' });
+ expect(target.querySelectorAll('.edge')).toHaveLength(1);
+ unmount(live);
+
+ stage({ annotations: [area()], tool: 'select' });
+ expect(target.querySelectorAll('.edge')).toHaveLength(0);
+});
diff --git a/frontend/src/tools/compare/AnnotationToolbar.svelte b/frontend/src/tools/compare/AnnotationToolbar.svelte
new file mode 100644
index 0000000..0b3d312
--- /dev/null
+++ b/frontend/src/tools/compare/AnnotationToolbar.svelte
@@ -0,0 +1,193 @@
+<script>
+ import Icon from '../../components/Icon.svelte';
+ import { canFill, ANNOTATION_TOOLS } from '../../lib/map/compareAnnotations.js';
+
+ let {
+ tool = $bindable(),
+ selected = null,
+ canUndo = false,
+ canRedo = false,
+ undo = () => {},
+ redo = () => {},
+ palette = [],
+ colour,
+ strokeWidth,
+ fillOpacity,
+ setColour = () => {},
+ setStroke = () => {},
+ setFill = () => {},
+ removeSelected = () => {},
+ clear = () => {},
+ count = 0,
+ side = $bindable('both'),
+ setSide = () => {},
+ } = $props();
+
+ const contextual = $derived(tool !== 'select' || Boolean(selected));
+ const fillable = $derived(canFill(selected?.kind ?? tool));
+ const sizeValue = $derived(selected?.kind === 'text'
+ ? (selected.font_size ?? 20)
+ : (selected?.stroke_width ?? strokeWidth));
+ let open = $state('');
+ let flyout = $state({});
+
+ function toggle(name, event) {
+ open = open === name ? '' : name;
+ if (!open) return;
+ const box = event.currentTarget.getBoundingClientRect();
+ flyout = box.top > window.innerHeight / 2
+ ? { left: `${box.right + 6}px`, bottom: `${window.innerHeight - box.bottom}px` }
+ : { left: `${box.right + 6}px`, top: `${box.top}px` };
+ }
+
+ $effect(() => {
+ if (!open) return;
+ const close = (event) => {
+ if (event.key === 'Escape') open = '';
+ };
+ document.addEventListener('keydown', close);
+ return () => document.removeEventListener('keydown', close);
+ });
+</script>
+
+<aside class="annotation-toolbar" aria-label="Comparison annotation tools">
+ <button class="tool-button" title="Undo (Ctrl+Z)" disabled={!canUndo} onclick={undo}><Icon name="undo" size={18} /></button>
+ <button class="tool-button" title="Redo (Ctrl+Shift+Z)" disabled={!canRedo} onclick={redo}><Icon name="redo" size={18} /></button>
+ <div class="separator"></div>
+ {#each ANNOTATION_TOOLS as entry (entry.id)}
+ <button
+ class="tool-button"
+ class:active={tool === entry.id}
+ aria-pressed={tool === entry.id}
+ title={`${entry.label} (${entry.shortcut})`}
+ onclick={() => (tool = entry.id)}
+ ><Icon name={entry.icon} size={18} /></button>
+ {/each}
+
+ {#if contextual}
+ <div class="separator"></div>
+ <select aria-label="Annotation side" value={selected?.side ?? side} onchange={(event) => setSide(event.currentTarget.value)}>
+ <option value="both">A/B</option><option value="a">A</option><option value="b">B</option>
+ </select>
+ <button class="tool-button" title="Annotation colour" onclick={(event) => toggle('colour', event)}>
+ <span class="swatch" style:background={selected?.colour ?? colour}></span>
+ </button>
+ <button class="tool-button sized" title={selected?.kind === 'text' ? 'Font size' : 'Stroke width'} onclick={(event) => toggle('size', event)}>
+ <Icon name="sliders" size={17} /><small>{sizeValue}</small>
+ </button>
+ {#if fillable}
+ <button class="tool-button sized" title="Fill opacity" onclick={(event) => toggle('fill', event)}>
+ <span class="fill-sample" style:opacity={selected?.fill_opacity ?? fillOpacity}></span>
+ <small>{Math.round((selected?.fill_opacity ?? fillOpacity) * 100)}</small>
+ </button>
+ {/if}
+ {/if}
+
+ {#if selected}
+ <div class="separator"></div>
+ <button class="tool-button danger" title="Delete selected annotation" onclick={removeSelected}><Icon name="trash" size={18} /></button>
+ {/if}
+ {#if count}
+ <button class="tool-button" title="Clear all annotations" onclick={clear}><Icon name="reset" size={18} /></button>
+ {/if}
+</aside>
+
+{#if open === 'colour'}
+ <div class="flyout colours" style:left={flyout.left} style:top={flyout.top} style:bottom={flyout.bottom}>
+ {#each palette as entry (entry)}
+ <button
+ class="colour-button"
+ class:active={(selected?.colour ?? colour) === entry}
+ style:background={entry}
+ aria-label={`Colour ${entry}`}
+ onclick={() => { setColour(entry); open = ''; }}
+ ></button>
+ {/each}
+ <label class="colour-button custom" style:background={selected?.colour ?? colour} title="Custom colour">
+ <Icon name="plus" size={12} />
+ <input type="color" value={selected?.colour ?? colour} oninput={(event) => setColour(event.currentTarget.value)} />
+ </label>
+ </div>
+{:else if open === 'size'}
+ <div class="flyout slider" style:left={flyout.left} style:top={flyout.top} style:bottom={flyout.bottom}>
+ <input
+ type="range"
+ min="1"
+ max={selected?.kind === 'text' ? 72 : 24}
+ value={sizeValue}
+ aria-label={selected?.kind === 'text' ? 'Font size' : 'Stroke width'}
+ oninput={(event) => setStroke(Number(event.currentTarget.value))}
+ />
+ </div>
+{:else if open === 'fill'}
+ <div class="flyout slider" style:left={flyout.left} style:top={flyout.top} style:bottom={flyout.bottom}>
+ <input
+ type="range"
+ min="0"
+ max="100"
+ step="5"
+ value={Math.round((selected?.fill_opacity ?? fillOpacity) * 100)}
+ aria-label="Fill opacity"
+ oninput={(event) => setFill(Number(event.currentTarget.value) / 100)}
+ />
+ </div>
+{/if}
+
+<style>
+ .annotation-toolbar {
+ position: relative;
+ z-index: 610;
+ width: 52px;
+ flex: 0 0 52px;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 3px;
+ padding: 7px 6px;
+ overflow-y: auto;
+ border-right: 1px solid var(--border);
+ background: var(--bg-1);
+ }
+ .tool-button {
+ width: 38px;
+ height: 38px;
+ flex: 0 0 38px;
+ display: grid;
+ place-items: center;
+ border-radius: var(--r-sm);
+ color: var(--text-3);
+ }
+ .tool-button:hover:not(:disabled), .tool-button.active { color: var(--accent); background: var(--bg-3); }
+ .tool-button:disabled { opacity: .3; }
+ .tool-button.danger:hover { color: var(--danger); }
+ .tool-button.sized { position: relative; }
+ .tool-button.sized small {
+ position: absolute;
+ right: 2px;
+ bottom: 1px;
+ min-width: 14px;
+ color: var(--text-3);
+ font-size: 8px;
+ line-height: 1;
+ }
+ .separator { width: 28px; height: 1px; flex: 0 0 1px; margin: 3px 0; background: var(--border); }
+ .swatch { width: 19px; height: 19px; border: 2px solid rgba(255,255,255,.68); border-radius: 50%; box-shadow: 0 0 0 1px rgba(0,0,0,.5); }
+ .fill-sample { width: 20px; height: 17px; border: 2px solid currentColor; border-radius: 2px; background: currentColor; }
+ .flyout {
+ position: fixed;
+ z-index: 1200;
+ padding: 8px;
+ border: 1px solid var(--border-strong);
+ border-radius: var(--r-md);
+ background: var(--bg-2);
+ box-shadow: var(--shadow-2);
+ }
+ .colours { display: grid; grid-template-columns: repeat(3, 28px); gap: 7px; }
+ .colour-button { width: 28px; height: 28px; border: 2px solid transparent; border-radius: 50%; }
+ .colour-button.active { border-color: #fff; box-shadow: 0 0 0 1px var(--accent); }
+ .colour-button.custom { position: relative; display: grid; place-items: center; color: white; cursor: pointer; }
+ .colour-button input { position: absolute; width: 1px; height: 1px; opacity: 0; }
+ .slider { width: 180px; }
+ .slider input { width: 100%; accent-color: var(--accent); }
+ select { width: 42px; color: var(--text-1); background: var(--bg-2); font-size: 10px; }
+</style>
diff --git a/frontend/src/tools/compare/ChangePanel.svelte b/frontend/src/tools/compare/ChangePanel.svelte
new file mode 100644
index 0000000..aef6aea
--- /dev/null
+++ b/frontend/src/tools/compare/ChangePanel.svelte
@@ -0,0 +1,192 @@
+<script>
+ /**
+ * Difference mode's own column. It reads the pixels the two maps are showing
+ * right now, so everything here is about *this view*: the reading follows the
+ * camera and is never saved. Detect mode, next to it in the dock, is the one
+ * that freezes an area and keeps what it found.
+ */
+ import { CHANGE_BASES, CHANGE_METHODS, CHANGE_INDICES, CHANGE_DISPLAYS, CHANGE_CLASSES, changeSettings } 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));
+</script>
+
+<aside class="cmp-dock" aria-label="Difference">
+ <header>
+ <strong>Difference</strong>
+ <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 the pixels on screen. Panning or zooming changes what it reads, and nothing here is saved.
+ Use Detect for 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">The view moved. Run again to match it.</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>
+
+ <CloudFilter
+ kind={settings.method === 'index' ? 'classes' : 'picture'}
+ clouds={settings.ignore_clouds}
+ shadows={settings.ignore_shadows}
+ ontoggle={(on) => (settings = { ...settings, ignore_clouds: on, ignore_shadows: on })}
+ />
+
+ <label class="check" title="Turn off to hold the current reading until Run; spectral analysis is always explicit.">
+ <input type="checkbox" bind:checked={settings.live} /> Follow the map automatically
+ </label>
+
+ <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 index}<option value={index.id}>{index.label} · {index.hint}</option>{/each}</select>
+ </label>
+ <p class="hint">Run fetches two Sentinel-2 frames and counts toward your usage.</p>
+ {/if}
+ <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>
+ <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>
+ <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="none">None</option><option value="mean">Mean brightness</option><option value="histogram">Histogram</option></select>
+ </label>
+ <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>
+ <label class="check" title="Exclude cloud; on a picture this is a guess at what cloud looks like."><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}px<input aria-label="Cloud mask margin" type="range" min="0" max="10" bind:value={settings.cloud_margin} /></label>
+ <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)}>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>{/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); }
+ .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
new file mode 100644
index 0000000..c8e63f5
--- /dev/null
+++ b/frontend/src/tools/compare/ChangePanel.test.js
@@ -0,0 +1,59 @@
+// @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: [] };
+
+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();
+ });
+});
diff --git a/frontend/src/tools/compare/CloudFilter.svelte b/frontend/src/tools/compare/CloudFilter.svelte
new file mode 100644
index 0000000..93f4967
--- /dev/null
+++ b/frontend/src/tools/compare/CloudFilter.svelte
@@ -0,0 +1,99 @@
+<script>
+ /**
+ * Cloud and the shadow it casts, as one thing to click.
+ *
+ * It sits at the top of both computing panels rather than inside a settings
+ * tab, 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 in the panel's own detail
+ * area: this is the one decision, and the rest is tuning.
+ *
+ * `kind` comes from the method catalogue, never from a list kept here — a
+ * method that cannot separate cloud from what it looks for offers nothing.
+ */
+ import Icon from '../../components/Icon.svelte';
+
+ let { kind = '', clouds = false, shadows = false, split = true, ontoggle } = $props();
+
+ const on = $derived(split ? clouds || shadows : clouds);
+ const name = $derived(
+ !split || !on || (clouds && shadows)
+ ? 'Clouds & shadows'
+ : clouds
+ ? 'Clouds only'
+ : 'Shadows only'
+ );
+ // Said every time it is on, because the two answers are not equally good and
+ // the panel must not let a guess pass for a measurement.
+ const how = $derived(
+ kind === 'classes'
+ ? "Sentinel-2's own scene classification."
+ : 'A guess from the picture: bright and colourless, or near-black.'
+ );
+</script>
+
+{#if kind}
+ <div class="cloud-filter">
+ <button
+ type="button"
+ class="chip"
+ class:on
+ aria-pressed={on}
+ onclick={() => ontoggle(!on)}
+ title={on ? 'Stop excluding cloud and shadow' : 'Exclude cloud and the shadow it casts'}
+ >
+ <Icon name={on ? 'eyeOff' : 'eye'} size={13} />
+ {name}
+ <span class="state">{on ? 'on' : 'off'}</span>
+ </button>
+ <p class="how" class:dim={!on}>{how}</p>
+ </div>
+{/if}
+
+<style>
+ .cloud-filter {
+ display: grid;
+ gap: 3px;
+ }
+ .chip {
+ display: flex;
+ align-items: center;
+ gap: 7px;
+ width: 100%;
+ padding: 7px 9px;
+ border: 1px solid var(--border);
+ border-radius: var(--r-sm);
+ background: var(--bg-2);
+ color: var(--text-2);
+ font-size: var(--fs-xs);
+ font-weight: 600;
+ text-align: left;
+ cursor: pointer;
+ transition: border-color 0.12s, color 0.12s, background 0.12s;
+ }
+ .chip:hover {
+ border-color: var(--border-strong);
+ color: var(--text-1);
+ }
+ .chip.on {
+ border-color: var(--accent);
+ background: var(--accent-soft);
+ color: var(--accent);
+ }
+ .state {
+ margin-left: auto;
+ font-family: var(--font-mono);
+ font-size: 10px;
+ font-weight: 500;
+ opacity: 0.8;
+ }
+ .how {
+ margin: 0;
+ color: var(--text-3);
+ font-size: 10px;
+ line-height: 1.35;
+ }
+ .how.dim {
+ opacity: 0.75;
+ }
+</style>
diff --git a/frontend/src/tools/compare/CloudFilter.test.js b/frontend/src/tools/compare/CloudFilter.test.js
new file mode 100644
index 0000000..a4cd2cd
--- /dev/null
+++ b/frontend/src/tools/compare/CloudFilter.test.js
@@ -0,0 +1,73 @@
+// @vitest-environment happy-dom
+import { describe, expect, it, vi } from 'vitest';
+import { flushSync, mount, unmount } from 'svelte';
+import CloudFilter from './CloudFilter.svelte';
+
+function render(props = {}) {
+ const target = document.createElement('div');
+ document.body.append(target);
+ const live = mount(CloudFilter, { target, props: { kind: 'classes', ontoggle: () => {}, ...props } });
+ flushSync();
+ return { target, done: () => { unmount(live); target.remove(); } };
+}
+
+const chip = (target) => target.querySelector('button');
+
+describe('the cloud and shadow filter', () => {
+ it('offers nothing for a method that cannot separate cloud from its subject', () => {
+ // smoke, bright shapes on water and a hotspot: masking cloud would mask
+ // the very thing they look for, so there is no switch to mislead with
+ const { target, done } = render({ kind: '' });
+ expect(chip(target)).toBe(null);
+ done();
+ });
+
+ it('turns both cloud and shadow on with one click', () => {
+ const ontoggle = vi.fn();
+ const { target, done } = render({ clouds: false, shadows: false, ontoggle });
+ expect(chip(target).getAttribute('aria-pressed')).toBe('false');
+ chip(target).click();
+ expect(ontoggle).toHaveBeenCalledWith(true);
+ done();
+ });
+
+ it('turns a filter that is on back off', () => {
+ const ontoggle = vi.fn();
+ const { target, done } = render({ clouds: true, shadows: true, ontoggle });
+ expect(chip(target).getAttribute('aria-pressed')).toBe('true');
+ chip(target).click();
+ expect(ontoggle).toHaveBeenCalledWith(false);
+ done();
+ });
+
+ it('names a half-set filter rather than reading as both', () => {
+ const { target, done } = render({ clouds: true, shadows: false });
+ expect(chip(target).textContent).toContain('Clouds only');
+ done();
+ const shadow = render({ clouds: false, shadows: true });
+ expect(chip(shadow.target).textContent).toContain('Shadows only');
+ shadow.done();
+ });
+
+ it('says a guess is a guess, and a classification a classification', () => {
+ // the panel must never let a brightness test pass for a measurement
+ const { target, done } = render({ kind: 'classes', clouds: true });
+ expect(target.textContent).toContain('scene classification');
+ expect(target.textContent).not.toContain('guess');
+ done();
+
+ const guess = render({ kind: 'picture', clouds: true });
+ expect(guess.target.textContent).toContain('A guess from the picture');
+ guess.done();
+ });
+
+ it('follows one switch when cloud and shadow cannot be split', () => {
+ const ontoggle = vi.fn();
+ const { target, done } = render({ kind: 'picture', split: false, clouds: true, ontoggle });
+ expect(chip(target).getAttribute('aria-pressed')).toBe('true');
+ expect(chip(target).textContent).toContain('Clouds & shadows');
+ chip(target).click();
+ expect(ontoggle).toHaveBeenCalledWith(false);
+ done();
+ });
+});
diff --git a/frontend/src/tools/compare/LayerPane.svelte b/frontend/src/tools/compare/LayerPane.svelte
new file mode 100644
index 0000000..f2ac4ae
--- /dev/null
+++ b/frontend/src/tools/compare/LayerPane.svelte
@@ -0,0 +1,300 @@
+<script>
+ /** One half of Compare's shared A/B layer sheet. */
+ import DayPicker from '../../components/DayPicker.svelte';
+ import Icon from '../../components/Icon.svelte';
+ import {
+ DATED as FIRMS_DATED,
+ lastDayOf,
+ today as firmsToday,
+ WINDOWS as FIRMS_WINDOWS,
+ } from '../../lib/map/firms.js';
+ import {
+ COMPOSITE as NIGHT_COMPOSITE,
+ firstNight,
+ lastNight,
+ SENSORS as NIGHT_SENSORS,
+ } from '../../lib/map/nightlights.js';
+
+ let {
+ letter,
+ present,
+ layers,
+ overlays,
+ firms,
+ night,
+ firmsSensors,
+ firesKeyed,
+ savedCount,
+ ontoggle,
+ onfirms,
+ onnight,
+ oncopy,
+ onclear,
+ } = $props();
+
+ const disabled = (id) =>
+ !present || (id === 'firms' && !firesKeyed) || (id === 'saved' && !savedCount);
+ const on = (id) => overlays.includes(id);
+ const disabledReason = (id) =>
+ id === 'firms' && !firesKeyed
+ ? 'Add a FIRMS key in Settings'
+ : id === 'saved' && !savedCount
+ ? 'No saved work in this case'
+ : '';
+</script>
+
+<section class="layer-pane" aria-label={`Imagery ${letter} layers`}>
+ <header>
+ <span class="letter">{letter}</span>
+ <div>
+ <strong>Imagery {letter}</strong>
+ <small>{present ? `${overlays.length} visible` : 'No imagery selected'}</small>
+ </div>
+ <button class="copy" disabled={!present} onclick={oncopy} title={`Copy imagery ${letter} layers to the other side`}>
+ <Icon name="copy" size={13} /> Copy
+ </button>
+ </header>
+
+ <div class="layer-list">
+ {#each layers as layer (layer.id)}
+ <div class="layer-block" class:active={on(layer.id)} class:disabled={disabled(layer.id)}>
+ <div class="layer-row">
+ <button
+ type="button"
+ class="eye"
+ class:on={on(layer.id)}
+ disabled={disabled(layer.id)}
+ aria-label={`${on(layer.id) ? 'Hide' : 'Show'} ${layer.label} on imagery ${letter}`}
+ aria-pressed={on(layer.id)}
+ title={disabledReason(layer.id) || layer.hint}
+ onclick={() => ontoggle(layer.id)}
+ >
+ <Icon name={on(layer.id) ? 'eye' : 'eyeOff'} size={14} />
+ </button>
+ <button
+ type="button"
+ class="layer-name"
+ disabled={disabled(layer.id)}
+ title={disabledReason(layer.id) || layer.hint}
+ onclick={() => ontoggle(layer.id)}
+ >
+ <strong>{layer.label}</strong>
+ <small>{disabledReason(layer.id) || layer.hint}</small>
+ </button>
+ </div>
+
+ {#if layer.id === 'firms' && on('firms') && firesKeyed}
+ <div class="settings" aria-label={`Active fires settings for imagery ${letter}`}>
+ <label>
+ <span>Sensor</span>
+ <select
+ class="select"
+ value={firms.sensor}
+ onchange={(event) => onfirms({ sensor: event.currentTarget.value })}
+ >
+ {#each firmsSensors as sensor (sensor.id)}
+ <option value={sensor.id}>{sensor.label}</option>
+ {/each}
+ </select>
+ </label>
+ <div class="setting">
+ <span>Period</span>
+ <div class="chips">
+ {#each FIRMS_WINDOWS as option (option.id)}
+ <button
+ type="button"
+ class:on={firms.window === option.id}
+ onclick={() => onfirms({ window: option.id })}
+ >{option.label}</button>
+ {/each}
+ <button
+ type="button"
+ class:on={firms.window === FIRMS_DATED}
+ onclick={() => onfirms({
+ window: FIRMS_DATED,
+ ...(!firms.first ? { first: firmsToday() } : {}),
+ })}
+ >Custom</button>
+ </div>
+ </div>
+ {#if firms.window === FIRMS_DATED}
+ <div class="date-grid">
+ <label>
+ <span>From</span>
+ <DayPicker
+ value={firms.first}
+ max={firmsToday()}
+ label="First day of detections to draw"
+ placeholder="Pick a day"
+ onpick={(day) => onfirms({ first: day })}
+ />
+ </label>
+ <label>
+ <span>To</span>
+ <DayPicker
+ value={firms.last}
+ min={firms.first}
+ max={lastDayOf(firms.first)}
+ label="Last day; blank draws the first day alone"
+ placeholder="Same day"
+ clearable
+ onpick={(day) => onfirms({ last: day })}
+ />
+ </label>
+ </div>
+ {/if}
+ </div>
+ {/if}
+
+ {#if layer.id === 'nightlights' && on('nightlights')}
+ <div class="settings" aria-label={`Night lights settings for imagery ${letter}`}>
+ <label>
+ <span>Product</span>
+ <select
+ class="select"
+ value={night.source}
+ onchange={(event) => onnight({ source: event.currentTarget.value })}
+ >
+ {#each NIGHT_SENSORS as sensor (sensor.id)}
+ <option value={sensor.id}>{sensor.label} nightly</option>
+ {/each}
+ <option value={NIGHT_COMPOSITE.id}>{NIGHT_COMPOSITE.label} composite</option>
+ </select>
+ </label>
+ {#if night.source !== NIGHT_COMPOSITE.id}
+ <label class="night-date">
+ <span>Night</span>
+ <DayPicker
+ value={night.day}
+ min={firstNight(night.source)}
+ max={lastNight()}
+ label="Night of the pass, around 01:30 local time"
+ placeholder="Pick a night"
+ onpick={(day) => onnight({ day })}
+ />
+ </label>
+ {:else}
+ <p class="baseline">Cloud-free 2016 baseline</p>
+ {/if}
+ </div>
+ {/if}
+ </div>
+ {/each}
+ </div>
+
+ <footer>
+ <button class="btn btn-ghost btn-sm" disabled={!present || !overlays.length} onclick={onclear}>Clear {letter}</button>
+ </footer>
+</section>
+
+<style>
+ .layer-pane {
+ min-width: 0;
+ display: flex;
+ flex-direction: column;
+ border: 1px solid var(--border);
+ border-radius: var(--r-md);
+ background: var(--bg-1);
+ overflow: hidden;
+ }
+ header {
+ min-height: 54px;
+ display: flex;
+ align-items: center;
+ gap: 9px;
+ padding: 9px 11px;
+ border-bottom: 1px solid var(--border);
+ background: var(--bg-2);
+ }
+ header > div { min-width: 0; flex: 1; }
+ header strong, header small { display: block; }
+ header strong { color: var(--text-1); font-size: var(--fs-sm); }
+ header small { margin-top: 1px; color: var(--text-3); font-size: 10px; }
+ .letter {
+ display: grid;
+ place-items: center;
+ width: 25px;
+ height: 25px;
+ border: 1px solid var(--border-strong);
+ border-radius: var(--r-sm);
+ color: var(--accent);
+ background: var(--bg-0);
+ font-size: var(--fs-xs);
+ font-weight: 700;
+ }
+ .copy {
+ display: flex;
+ align-items: center;
+ gap: 5px;
+ padding: 5px 7px;
+ border-radius: var(--r-sm);
+ color: var(--text-3);
+ font-size: 10px;
+ }
+ .copy:hover:not(:disabled) { color: var(--text-1); background: var(--bg-3); }
+ .copy:disabled { opacity: .45; }
+ .layer-list { min-height: 0; overflow: auto; padding: 5px 8px; }
+ .layer-block { border-bottom: 1px solid var(--border); }
+ .layer-block:last-child { border-bottom: 0; }
+ .layer-block.disabled { opacity: .52; }
+ .layer-row { min-height: 43px; display: flex; align-items: center; gap: 6px; }
+ .eye {
+ display: grid;
+ place-items: center;
+ flex: 0 0 27px;
+ width: 27px;
+ height: 27px;
+ border-radius: var(--r-sm);
+ color: var(--text-3);
+ }
+ .eye:hover:not(:disabled) { color: var(--text-1); background: var(--bg-3); }
+ .eye.on { color: var(--accent); }
+ .layer-name { min-width: 0; flex: 1; padding: 5px 0; text-align: left; }
+ .layer-name strong, .layer-name small { display: block; }
+ .layer-name strong { color: var(--text-2); font-size: var(--fs-sm); }
+ .layer-name small {
+ margin-top: 1px;
+ overflow: hidden;
+ color: var(--text-3);
+ font-size: 10px;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ .active .layer-name strong { color: var(--text-1); }
+ .settings {
+ display: grid;
+ gap: 8px;
+ margin: 0 0 8px 33px;
+ padding: 9px;
+ border: 1px solid var(--border);
+ border-radius: var(--r-sm);
+ background: var(--bg-2);
+ }
+ .settings label, .setting { min-width: 0; display: grid; gap: 4px; }
+ .settings label > span, .setting > span {
+ color: var(--text-3);
+ font-size: 10px;
+ font-weight: 650;
+ letter-spacing: .03em;
+ }
+ .settings .select { width: 100%; min-width: 0; padding: 5px 7px; font: inherit; font-size: 11px; }
+ .chips { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 4px; }
+ .chips button {
+ min-width: 0;
+ padding: 4px 3px;
+ border: 1px solid var(--border);
+ border-radius: var(--r-sm);
+ color: var(--text-2);
+ background: var(--bg-1);
+ font-size: 10px;
+ }
+ .chips button:hover { border-color: var(--border-strong); color: var(--text-1); }
+ .chips button.on { border-color: var(--accent); color: var(--accent); background: var(--accent-soft); }
+ .date-grid { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 7px; }
+ .night-date { max-width: 220px; }
+ .baseline { margin: 0; color: var(--text-3); font-size: 10px; }
+ footer { display: flex; justify-content: flex-end; margin-top: auto; padding: 7px 9px; border-top: 1px solid var(--border); }
+ @media (max-width: 720px) {
+ .date-grid { grid-template-columns: 1fr; }
+ }
+</style>
diff --git a/frontend/src/tools/compare/ModeControl.svelte b/frontend/src/tools/compare/ModeControl.svelte
new file mode 100644
index 0000000..9e44925
--- /dev/null
+++ b/frontend/src/tools/compare/ModeControl.svelte
@@ -0,0 +1,124 @@
+<script>
+ /**
+ * 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.
+ */
+ import Icon from '../../components/Icon.svelte';
+ import { BLINK_SPEEDS, percentage } from '../../lib/map/compare.js';
+
+ let {
+ mode,
+ divider = $bindable(50),
+ opacity = $bindable(50),
+ blinkB = $bindable(false),
+ blinkPaused = $bindable(false),
+ blinkInterval = $bindable(800),
+ } = $props();
+</script>
+
+{#if mode === 'swipe'}
+ <div class="mode-control cmp-glass" aria-label="Swipe">
+ <span class="cmp-letter a">A</span>
+ <input
+ class="cmp-range"
+ type="range"
+ min="0"
+ max="100"
+ value={divider}
+ style:--fill={`${divider}%`}
+ oninput={(event) => (divider = percentage(event.currentTarget.value))}
+ aria-label="Swipe position"
+ />
+ <span class="cmp-letter b">B</span>
+ <button class="text-btn" onclick={() => (divider = 50)} disabled={divider === 50}>Centre</button>
+ </div>
+{:else if mode === 'opacity'}
+ <div class="mode-control cmp-glass" aria-label="Fade">
+ <span class="cmp-letter a">A</span>
+ <input
+ class="cmp-range"
+ type="range"
+ min="0"
+ max="100"
+ value={opacity}
+ style:--fill={`${opacity}%`}
+ oninput={(event) => (opacity = percentage(event.currentTarget.value))}
+ aria-label="B opacity"
+ />
+ <span class="cmp-letter b">B</span>
+ <span class="value cmp-mono">{opacity}%</span>
+ </div>
+{:else if mode === 'blink'}
+ <div class="mode-control cmp-glass" aria-label="Blink">
+ <button
+ class="cmp-icon"
+ onclick={() => (blinkPaused = !blinkPaused)}
+ aria-label={blinkPaused ? 'Play blink' : 'Pause blink'}
+ title={blinkPaused ? 'Play (Space)' : 'Pause (Space)'}
+ >
+ <Icon name={blinkPaused ? 'play' : 'pause'} size={15} />
+ </button>
+ <div class="cmp-seg" aria-label="Side shown">
+ <button class:on={!blinkB} onclick={() => { blinkPaused = true; blinkB = false; }}>
+ <span class="cmp-letter a small">A</span>
+ </button>
+ <button class:on={blinkB} onclick={() => { blinkPaused = true; blinkB = true; }}>
+ <span class="cmp-letter b small">B</span>
+ </button>
+ </div>
+ <span class="rule" aria-hidden="true"></span>
+ <div class="cmp-seg" aria-label="Blink speed">
+ {#each BLINK_SPEEDS as speed (speed.id)}
+ <button class:on={blinkInterval === speed.id} onclick={() => (blinkInterval = speed.id)}>{speed.label}</button>
+ {/each}
+ </div>
+ </div>
+{/if}
+
+<style>
+ .mode-control {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ min-height: 42px;
+ padding: 5px 10px;
+ }
+ .mode-control .cmp-range {
+ width: min(320px, 34vw);
+ }
+ .cmp-letter.small {
+ width: 18px;
+ height: 18px;
+ font-size: 10px;
+ }
+ .cmp-seg > button:has(.cmp-letter) {
+ padding: 0 5px;
+ }
+ .value {
+ min-width: 36px;
+ color: var(--glass-muted);
+ font-size: 11px;
+ text-align: right;
+ }
+ .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;
+ }
+ .rule {
+ width: 1px;
+ height: 18px;
+ background: var(--glass-line);
+ }
+</style>
diff --git a/frontend/src/tools/compare/ModeControl.test.js b/frontend/src/tools/compare/ModeControl.test.js
new file mode 100644
index 0000000..d78ddf8
--- /dev/null
+++ b/frontend/src/tools/compare/ModeControl.test.js
@@ -0,0 +1,33 @@
+// @vitest-environment happy-dom
+import { describe, expect, it } from 'vitest';
+import { flushSync, mount, unmount } from 'svelte';
+import ModeControl from './ModeControl.svelte';
+
+function render(props) {
+ const target = document.createElement('div');
+ document.body.append(target);
+ const live = mount(ModeControl, { target, props });
+ flushSync();
+ return { target, done: () => { unmount(live); target.remove(); } };
+}
+
+describe('Compare mode footer', () => {
+ it('carries the one control each reading mode needs', () => {
+ for (const [mode, label] of [['swipe', 'Swipe position'], ['opacity', 'B opacity']]) {
+ const { target, done } = render({ mode });
+ expect(target.querySelector(`[aria-label="${label}"]`)).not.toBe(null);
+ done();
+ }
+ const { target, done } = render({ mode: 'blink' });
+ expect(target.querySelector('[aria-label="Blink speed"]')).not.toBe(null);
+ 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();
+ }
+ });
+});
diff --git a/frontend/src/tools/compare/ModeDock.svelte b/frontend/src/tools/compare/ModeDock.svelte
new file mode 100644
index 0000000..6474a5b
--- /dev/null
+++ b/frontend/src/tools/compare/ModeDock.svelte
@@ -0,0 +1,64 @@
+<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';
+
+ let { mode, change, onmode = () => {}, onswap = () => {} } = $props();
+</script>
+
+<div class="mode-dock cmp-glass" role="toolbar" aria-label="Comparison view">
+ <div class="cmp-seg">
+ {#each COMPARE_MODES as entry, index (entry.id)}
+ {@const blocked = entry.id === 'change' && !change.ok}
+ {#if index > 0 && entry.group !== COMPARE_MODES[index - 1].group}
+ <!-- Left of the rule: how the pair is shown. Right of it: what gets
+ computed over the pair, which is a different kind of choice. -->
+ <span class="group-rule" aria-hidden="true"></span>
+ {/if}
+ <button
+ class="mode-btn"
+ class:on={mode === entry.id}
+ class:blocked
+ class:find={entry.group === 'find'}
+ aria-pressed={mode === entry.id}
+ title={blocked ? change.reason : `${entry.label} (${entry.key})`}
+ onclick={() => onmode(entry.id)}
+ >
+ <Icon name={entry.icon} size={14} />
+ <span>{entry.label}</span>
+ </button>
+ {/each}
+ </div>
+ <button class="cmp-icon" onclick={onswap} title="Swap A and B" aria-label="Swap A and B">
+ <Icon name="swap" size={15} />
+ </button>
+</div>
+
+<style>
+ .mode-dock {
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ padding: 4px;
+ }
+ .mode-btn.blocked:not(.on) {
+ color: var(--glass-dim);
+ }
+ .group-rule {
+ align-self: center;
+ width: 1px;
+ height: 18px;
+ margin: 0 4px;
+ background: var(--glass-line);
+ }
+ /* 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 {
+ display: none;
+ }
+ }
+</style>
diff --git a/frontend/src/tools/compare/SourceCard.svelte b/frontend/src/tools/compare/SourceCard.svelte
new file mode 100644
index 0000000..49fb1b7
--- /dev/null
+++ b/frontend/src/tools/compare/SourceCard.svelte
@@ -0,0 +1,140 @@
+<script>
+ /**
+ * What one side is showing, over its own picture: the side's letter, its
+ * provider and date pickers, the acquisition date under the crosshair, and
+ * the two acts that belong to one side only (its layers, taking it away).
+ */
+ import Icon from '../../components/Icon.svelte';
+ import ImageryChip from '../satellite/ImageryChip.svelte';
+
+ let {
+ letter,
+ imagery,
+ providerId = $bindable(),
+ s2,
+ wayback,
+ shown,
+ dated = null,
+ layerCount = 0,
+ layersOpen = false,
+ align = 'left',
+ onlayers = () => {},
+ onremove = () => {},
+ } = $props();
+
+ const lower = $derived(letter.toLowerCase());
+ const showsDate = $derived(
+ dated?.date && shown.provider?.id !== 'sentinel2' && shown.provider?.id !== 'esri-wayback'
+ );
+</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} />
+ </div>
+ {#if showsDate}
+ <span class="dated cmp-mono" title={dated.source ? `Acquired around this date (${dated.source})` : 'Acquired around this date'}>
+ <Icon name="clock" size={11} />{dated.date}
+ </span>
+ {/if}
+ <span class="rule" aria-hidden="true"></span>
+ <button
+ class="cmp-icon layers"
+ class:active={layersOpen}
+ onclick={onlayers}
+ aria-label={`Layers on imagery ${letter}`}
+ aria-expanded={layersOpen}
+ title="Layers"
+ >
+ <Icon name="layers" size={15} />
+ {#if layerCount}<span class="count">{layerCount}</span>{/if}
+ </button>
+ <button class="cmp-icon" onclick={onremove} aria-label={`Remove imagery ${letter}`} title="Remove this side">
+ <Icon name="x" size={14} />
+ </button>
+</div>
+
+<style>
+ .source-card {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ max-width: 100%;
+ padding: 4px 4px 4px 6px;
+ }
+ .chips {
+ min-width: 0;
+ }
+ /* The shared chips were made for a map corner; inside a card they lose their
+ own box and open their menus towards the middle of the stage. */
+ .chips :global(.chip-row) {
+ flex-wrap: nowrap;
+ justify-content: flex-start;
+ gap: 2px;
+ }
+ .chips :global(.chip) {
+ height: 28px;
+ border-radius: 7px;
+ color: var(--glass-ink);
+ background: transparent;
+ box-shadow: none;
+ backdrop-filter: none;
+ font-weight: 600;
+ }
+ .chips :global(.chip:hover),
+ .chips :global(.chip.on) {
+ color: var(--glass-ink);
+ background: var(--glass-hover);
+ }
+ .chips :global(.chip .name) {
+ max-width: 190px;
+ }
+ .chips :global(.pill) {
+ background: rgba(255, 255, 255, 0.06);
+ box-shadow: none;
+ backdrop-filter: none;
+ }
+ .source-card:not(.right) :global(.menu),
+ .source-card:not(.right) :global(.wb-menu),
+ .source-card:not(.right) :global(.s2-menu) {
+ left: 0;
+ right: auto;
+ }
+ .dated {
+ display: inline-flex;
+ align-items: center;
+ gap: 5px;
+ padding: 0 6px;
+ color: var(--glass-muted);
+ font-size: 11px;
+ white-space: nowrap;
+ }
+ .rule {
+ width: 1px;
+ height: 18px;
+ background: var(--glass-line);
+ }
+ .layers {
+ position: relative;
+ width: auto;
+ min-width: 30px;
+ gap: 4px;
+ padding: 0 6px;
+ display: inline-flex;
+ }
+ .layers.active {
+ color: var(--glass-ink);
+ background: var(--glass-press);
+ }
+ .count {
+ min-width: 16px;
+ padding: 1px 4px;
+ border-radius: 99px;
+ color: #111317;
+ background: var(--glass-ink);
+ font-size: 10px;
+ font-weight: 700;
+ line-height: 14px;
+ }
+</style>
diff --git a/frontend/src/tools/compare/compare.css b/frontend/src/tools/compare/compare.css
new file mode 100644
index 0000000..667af9f
--- /dev/null
+++ b/frontend/src/tools/compare/compare.css
@@ -0,0 +1,277 @@
+/* Compare uses the same theme tokens as the other tools. */
+.compare-tool {
+ --cmp-a: var(--info);
+ --cmp-b: var(--accent);
+ --glass: var(--bg-1);
+ --glass-strong: var(--bg-2);
+ --glass-line: var(--border);
+ --glass-line-strong: var(--border-strong);
+ --glass-hover: var(--bg-2);
+ --glass-press: var(--bg-3);
+ --glass-ink: var(--text-1);
+ --glass-muted: var(--text-2);
+ --glass-dim: var(--text-3);
+ --glass-radius: var(--r-sm);
+ --glass-shadow: none;
+}
+
+.cmp-glass {
+ color: var(--glass-ink);
+ background: var(--glass);
+ border: 1px solid var(--glass-line);
+ border-radius: var(--glass-radius);
+ box-shadow: var(--glass-shadow);
+}
+
+.cmp-glass.strong {
+ background: var(--glass-strong);
+}
+
+.cmp-letter {
+ display: inline-grid;
+ place-items: center;
+ flex: 0 0 auto;
+ width: 22px;
+ height: 22px;
+ border-radius: var(--r-sm);
+ color: var(--bg-0);
+ font: 800 11px/1 var(--font-sans);
+ letter-spacing: 0;
+}
+.cmp-letter.a { background: var(--cmp-a); }
+.cmp-letter.b { background: var(--cmp-b); }
+.cmp-letter.both {
+ background: linear-gradient(135deg, var(--cmp-a) 50%, var(--cmp-b) 50%);
+}
+
+.cmp-icon {
+ display: inline-grid;
+ place-items: center;
+ flex: 0 0 auto;
+ width: 30px;
+ height: 30px;
+ border-radius: var(--r-sm);
+ color: var(--glass-muted);
+ transition: background 0.12s var(--ease), color 0.12s var(--ease);
+}
+.cmp-icon:hover:not(:disabled) { color: var(--glass-ink); background: var(--glass-hover); }
+.cmp-icon.on { color: var(--accent); background: var(--accent-soft); }
+.cmp-icon:disabled { opacity: 0.38; cursor: not-allowed; }
+
+.cmp-seg {
+ display: inline-flex;
+ gap: 2px;
+ padding: 2px;
+ border-radius: var(--r-sm);
+ background: var(--bg-0);
+ box-shadow: inset 0 0 0 1px var(--glass-line);
+}
+.cmp-seg > button {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ gap: 6px;
+ min-height: 26px;
+ padding: 0 10px;
+ border-radius: var(--r-sm);
+ color: var(--glass-muted);
+ font-size: 11.5px;
+ font-weight: 600;
+ white-space: nowrap;
+ transition: background 0.12s var(--ease), color 0.12s var(--ease);
+}
+.cmp-seg > button:hover:not(:disabled) { color: var(--glass-ink); background: var(--glass-hover); }
+.cmp-seg > button.on { color: var(--accent); background: var(--accent-soft); }
+.cmp-seg > button:disabled { opacity: 0.4; cursor: not-allowed; }
+.cmp-seg.fill { display: flex; }
+.cmp-seg.fill > button { flex: 1; }
+
+.cmp-range {
+ -webkit-appearance: none;
+ appearance: none;
+ width: 100%;
+ height: 18px;
+ background: transparent;
+ cursor: pointer;
+}
+.cmp-range::-webkit-slider-runnable-track {
+ height: 4px;
+ border-radius: 99px;
+ background: linear-gradient(90deg, var(--accent) var(--fill, 50%), var(--border-strong) var(--fill, 50%));
+}
+.cmp-range::-moz-range-track {
+ height: 4px;
+ border-radius: 99px;
+ background: var(--border-strong);
+}
+.cmp-range::-moz-range-progress {
+ height: 4px;
+ border-radius: 99px;
+ background: var(--accent);
+}
+.cmp-range::-webkit-slider-thumb {
+ -webkit-appearance: none;
+ width: 14px;
+ height: 14px;
+ margin-top: -5px;
+ border: 2px solid #111317;
+ border-radius: 50%;
+ background: var(--glass-ink);
+ box-shadow: 0 1px 4px rgba(0, 0, 0, 0.5);
+}
+.cmp-range::-moz-range-thumb {
+ width: 12px;
+ height: 12px;
+ border: 2px solid #111317;
+ border-radius: 50%;
+ background: var(--glass-ink);
+}
+.cmp-range:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; border-radius: 4px; }
+
+.cmp-switch {
+ position: relative;
+ flex: 0 0 auto;
+ width: 30px;
+ height: 17px;
+ border-radius: 99px;
+ background: rgba(255, 255, 255, 0.18);
+ transition: background 0.15s var(--ease);
+}
+.cmp-switch::after {
+ content: '';
+ position: absolute;
+ top: 2px;
+ left: 2px;
+ width: 13px;
+ height: 13px;
+ border-radius: 50%;
+ background: #f5f6f7;
+ box-shadow: 0 1px 2px rgba(0, 0, 0, 0.4);
+ transition: transform 0.15s var(--ease);
+}
+.cmp-switch.on { background: var(--accent); }
+.cmp-switch.on::after { transform: translateX(13px); }
+
+.cmp-kicker {
+ color: var(--glass-dim);
+ font-size: 10px;
+ font-weight: 700;
+ letter-spacing: 0.08em;
+ text-transform: uppercase;
+}
+
+.cmp-mono {
+ font-family: var(--font-mono);
+ font-variant-numeric: tabular-nums;
+}
+
+/* The column beside the stage. Both computing modes use it, so setting up a
+ difference and setting up a detection have the same shape: a header that
+ names the mode and says in one line what it reads, a scrolling body, and
+ one action pinned at the foot that never scrolls out of reach. It takes
+ width from the maps rather than covering them — the map stays the thing
+ you are working on. */
+.cmp-dock {
+ display: flex;
+ flex: 0 0 clamp(300px, 26vw, 380px);
+ flex-direction: column;
+ min-height: 0;
+ border-left: 1px solid var(--border);
+ background: var(--bg-1);
+}
+.cmp-dock > header {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 9px 8px 9px 12px;
+ border-bottom: 1px solid var(--border);
+}
+.cmp-dock > header strong { flex: 1; font-size: var(--fs-sm); }
+.cmp-dock-lead {
+ padding: 9px 12px;
+ border-bottom: 1px solid var(--border);
+ color: var(--text-2);
+ font-size: var(--fs-xs);
+ line-height: 1.45;
+}
+.cmp-dock-body {
+ display: grid;
+ flex: 1;
+ align-content: start;
+ gap: 14px;
+ min-height: 0;
+ overflow-y: auto;
+ padding: 12px;
+}
+.cmp-dock-foot {
+ display: grid;
+ gap: 7px;
+ padding: 10px 12px;
+ border-top: 1px solid var(--border);
+ background: var(--bg-1);
+}
+.cmp-dock-foot .reason {
+ color: var(--text-3);
+ font-size: var(--fs-xs);
+ text-align: center;
+}
+
+/* One numbered step. The number is the whole instruction about order. */
+.cmp-step { display: grid; gap: 8px; }
+.cmp-step > header {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ min-height: 24px;
+}
+.cmp-step > header > strong {
+ flex: 1;
+ font-size: var(--fs-xs);
+ font-weight: 700;
+ letter-spacing: 0.06em;
+ text-transform: uppercase;
+}
+.cmp-step-n {
+ display: grid;
+ place-items: center;
+ width: 19px;
+ height: 19px;
+ border-radius: 50%;
+ color: var(--text-3);
+ background: var(--bg-3);
+ font: 700 10px/1 var(--font-sans);
+}
+.cmp-step.done .cmp-step-n { color: var(--bg-0); background: var(--accent); }
+.cmp-step .hint { color: var(--text-3); font-size: var(--fs-xs); line-height: 1.45; margin: 0; }
+.cmp-step .warn { color: var(--warn); font-size: var(--fs-xs); line-height: 1.45; margin: 0; }
+
+/* Inputs inside a dock: label above, control below, never side by side —
+ the column is too narrow for a two-column form to stay readable. */
+.cmp-dock label {
+ display: grid;
+ gap: 4px;
+ font-size: var(--fs-xs);
+ color: var(--text-2);
+}
+.cmp-dock label.check {
+ display: flex;
+ align-items: center;
+ gap: 7px;
+}
+.cmp-dock input,
+.cmp-dock select,
+.cmp-dock textarea {
+ min-width: 0;
+ padding: 5px 6px;
+ border: 1px solid var(--border);
+ border-radius: var(--r-sm);
+ color: var(--text-1);
+ background: var(--bg-2);
+ font-size: var(--fs-xs);
+ accent-color: var(--accent);
+}
+.cmp-dock input[type='range'] { width: 100%; padding: 0; border: none; background: none; }
+.cmp-dock input[type='checkbox'] { width: auto; padding: 0; }
+.cmp-dock input[type='color'] { height: 26px; padding: 2px; }
+.cmp-dock .row { display: flex; align-items: center; gap: 7px; }
+.cmp-dock .row > .grow { flex: 1; min-width: 0; }
diff --git a/frontend/src/tools/overview/CaseTodos.svelte b/frontend/src/tools/overview/CaseTodos.svelte
new file mode 100644
index 0000000..fbbed31
--- /dev/null
+++ b/frontend/src/tools/overview/CaseTodos.svelte
@@ -0,0 +1,199 @@
+<script>
+ import { onMount, tick } from 'svelte';
+ import { api } from '../../lib/api.js';
+ import Icon from '../../components/Icon.svelte';
+ import ConfirmDialog from '../../components/ConfirmDialog.svelte';
+
+ let { caseId } = $props();
+ let data = $state(null);
+ let active = $state('');
+ let busy = $state(false);
+ let error = $state('');
+ let conflict = $state(false);
+ let taskText = $state('');
+ let naming = $state(null);
+ let listName = $state('');
+ let nameInput = $state(null);
+ let taskInput = $state(null);
+ let deleting = $state(null);
+ let menu = $state(false);
+ const selected = $derived(data?.lists.find((list) => list.id === active));
+ const endpoint = $derived(`/api/cases/${encodeURIComponent(caseId)}/todos`);
+
+ onMount(() => { void load(); });
+
+ async function load() {
+ busy = true;
+ error = '';
+ try {
+ data = await api.get(endpoint);
+ active = data.lists.some((list) => list.id === active) ? active : (data.lists[0]?.id ?? '');
+ conflict = false;
+ } catch (e) { error = e.message; }
+ finally { busy = false; }
+ }
+
+ async function save(lists) {
+ if (busy || conflict) return false;
+ busy = true;
+ error = '';
+ try {
+ data = await api.put(endpoint, { revision: data.revision, lists });
+ return true;
+ } catch (e) {
+ error = e.message;
+ conflict = e.status === 409;
+ return false;
+ } finally { busy = false; }
+ }
+
+ function copy() { return JSON.parse(JSON.stringify(data.lists)); }
+
+ async function nameList(id = '') {
+ naming = id;
+ listName = data.lists.find((list) => list.id === id)?.name ?? '';
+ menu = false;
+ await tick();
+ nameInput?.focus();
+ }
+
+ async function submitName(event) {
+ event.preventDefault();
+ const name = listName.trim();
+ if (!name) return;
+ const lists = copy();
+ const id = naming || crypto.randomUUID();
+ if (naming) lists.find((list) => list.id === id).name = name;
+ else lists.push({ id, name, tasks: [] });
+ if (await save(lists)) { active = id; naming = null; }
+ }
+
+ async function addTask(event) {
+ event.preventDefault();
+ const text = taskText.trim();
+ if (!text || !selected) return;
+ const lists = copy();
+ lists.find((list) => list.id === active).tasks.push({ id: crypto.randomUUID(), text, done: false });
+ if (await save(lists)) {
+ taskText = '';
+ await tick();
+ taskInput?.focus();
+ }
+ }
+
+ async function updateTask(id, patch, input) {
+ const lists = copy();
+ const task = lists.find((list) => list.id === active).tasks.find((task) => task.id === id);
+ const previous = { ...task };
+ Object.assign(task, patch);
+ if (!task.text.trim() || !await save(lists)) {
+ if (input.type === 'checkbox') input.checked = previous.done;
+ else input.value = previous.text;
+ }
+ }
+
+ async function deleteTask(id) {
+ const lists = copy();
+ const list = lists.find((list) => list.id === active);
+ list.tasks = list.tasks.filter((task) => task.id !== id);
+ await save(lists);
+ }
+
+ async function deleteList(id) {
+ if (await save(copy().filter((list) => list.id !== id))) {
+ active = data.lists[0]?.id ?? '';
+ deleting = null;
+ menu = false;
+ }
+ }
+</script>
+
+<section class="todos" aria-label="To-do">
+ <header><h2 class="label">To-do</h2><span aria-live="polite">{busy && data ? 'Saving…' : ''}</span></header>
+ {#if error}
+ <p role="alert">{error} <button class="btn btn-sm" onclick={load} disabled={busy}>Reload lists</button></p>
+ {/if}
+ {#if data}
+ <fieldset disabled={busy || conflict}>
+ <div class="tabs" aria-label="Task lists">
+ {#each data.lists as list (list.id)}
+ <button class="tab" class:active={active === list.id} aria-pressed={active === list.id}
+ onclick={() => { active = list.id; taskText = ''; menu = false; naming = null; }}>
+ {list.name} <span>{list.tasks.filter((task) => task.done).length}/{list.tasks.length}</span>
+ </button>
+ {/each}
+ <button class="btn btn-ghost btn-sm" aria-label="Add list" title="Add list" disabled={data.lists.length >= 50} onclick={() => nameList()}><Icon name="plus" size={15} /></button>
+ {#if selected}
+ <button class="btn btn-ghost btn-sm" aria-label="List options" aria-expanded={menu} onclick={() => (menu = !menu)}>•••</button>
+ {/if}
+ </div>
+ {#if menu && selected}
+ <div class="options">
+ <button class="btn btn-sm" onclick={() => nameList(active)}>Rename list</button>
+ <button class="btn btn-sm" onclick={() => selected.tasks.length ? (deleting = selected) : deleteList(active)}>Delete list</button>
+ </div>
+ {/if}
+ {#if naming !== null}
+ <form onsubmit={submitName} class="entry">
+ <input class="input" aria-label="List name" placeholder="List name" maxlength="120" bind:value={listName} bind:this={nameInput} onkeydown={(e) => { if (e.key === 'Escape') naming = null; }} />
+ <button class="btn btn-sm" disabled={!listName.trim()}>Save</button>
+ <button type="button" class="btn btn-ghost btn-sm" onclick={() => (naming = null)}>Cancel</button>
+ </form>
+ {/if}
+ {#if selected}
+ <ul aria-label={selected.name}>
+ {#each selected.tasks as task (task.id)}
+ <li>
+ <input type="checkbox" aria-label={`Complete ${task.text}`} checked={task.done} onchange={(e) => updateTask(task.id, { done: e.currentTarget.checked }, e.currentTarget)} />
+ <input class="task" class:done={task.done} aria-label="Task text" value={task.text} maxlength="2000" onchange={(e) => updateTask(task.id, { text: e.currentTarget.value.trim() }, e.currentTarget)} onkeydown={(e) => { if (e.key === 'Enter') e.currentTarget.blur(); }} />
+ <button class="btn btn-ghost btn-sm" aria-label={`Delete ${task.text}`} onclick={() => deleteTask(task.id)}><Icon name="trash" size={14} /></button>
+ </li>
+ {/each}
+ </ul>
+ <form class="entry" onsubmit={addTask}>
+ <input class="input" aria-label="New task" placeholder="Add a task…" maxlength="2000" bind:value={taskText} bind:this={taskInput} disabled={selected.tasks.length >= 200} />
+ <button class="btn btn-sm" aria-label="Add task" disabled={!taskText.trim() || selected.tasks.length >= 200}><Icon name="plus" size={15} /></button>
+ </form>
+ {:else}
+ <p class="quiet">Add a list to start.</p>
+ {/if}
+ </fieldset>
+ {:else if busy}
+ <p class="quiet">Loading lists…</p>
+ {/if}
+</section>
+
+{#if deleting}
+ <ConfirmDialog title="Delete list?" message={`Delete “${deleting.name}” and its ${deleting.tasks.length} tasks?`} detail="This cannot be undone." confirmLabel="Delete list" tone="danger" {busy} onconfirm={() => deleteList(deleting.id)} oncancel={() => { if (!busy) deleting = null; }} />
+{/if}
+
+<style>
+ /* Written in the Home dashboard's vocabulary: a small-caps label over flat rows,
+ no panel of its own, tabs drawn like the workspace tab strip. */
+ header { display: flex; align-items: baseline; justify-content: space-between; gap: 12px; margin-bottom: 10px; }
+ header .label { margin: 0; }
+ header span, .tab span { color: var(--text-3); font-size: var(--fs-xs); }
+ fieldset { border: 0; padding: 0; margin: 0; min-width: 0; }
+ .tabs { display: flex; align-items: center; gap: 2px; overflow-x: auto; border-bottom: 1px solid var(--border); }
+ .tab { padding: 7px 12px; white-space: nowrap; font-size: var(--fs-sm); font-weight: 500; color: var(--text-3); }
+ .tab:hover { color: var(--text-1); }
+ .tab.active { color: var(--text-1); box-shadow: inset 0 -2px 0 var(--accent); }
+ .tab span { margin-left: 6px; font-weight: 400; font-variant-numeric: tabular-nums; }
+ .entry, li, .options { display: flex; align-items: center; gap: 8px; }
+ .entry, .options { margin-top: 10px; }
+ .entry .input { flex: 1; min-width: 0; }
+ ul { list-style: none; margin: 0; padding: 0; max-height: 300px; overflow-y: auto; }
+ /* The Recent work row: a hairline between rows, the amber edge under the pointer. */
+ li { padding: 2px 4px 2px 8px; border-bottom: 1px solid var(--border); border-left: 2px solid transparent; transition: background 0.14s var(--ease), border-color 0.14s var(--ease); }
+ li:hover, li:focus-within { background: var(--bg-1); border-left-color: var(--accent); }
+ input[type='checkbox'] { accent-color: var(--accent); flex-shrink: 0; }
+ .task { flex: 1; min-width: 0; background: transparent; border: 1px solid transparent; border-radius: var(--r-sm); padding: 6px; color: var(--text-1); font: inherit; font-size: var(--fs-md); }
+ .task:focus { border-color: var(--accent); outline: none; }
+ .task.done { text-decoration: line-through; color: var(--text-3); }
+ li .btn { color: var(--text-3); opacity: 0; }
+ li:hover .btn, li:focus-within .btn { opacity: 1; }
+ li .btn:hover { color: var(--text-1); }
+ @media (hover: none) { li .btn { opacity: 1; } }
+ .quiet { padding: 12px 8px; font-size: var(--fs-sm); color: var(--text-3); }
+ p[role='alert'] { margin-bottom: 10px; color: var(--danger); font-size: var(--fs-sm); }
+</style>
diff --git a/frontend/src/tools/overview/CaseTodos.test.js b/frontend/src/tools/overview/CaseTodos.test.js
new file mode 100644
index 0000000..c9d0351
--- /dev/null
+++ b/frontend/src/tools/overview/CaseTodos.test.js
@@ -0,0 +1,115 @@
+// @vitest-environment happy-dom
+import { afterEach, expect, it, vi } from 'vitest';
+import { flushSync, mount, unmount } from 'svelte';
+
+const { get, put } = vi.hoisted(() => ({ get: vi.fn(), put: vi.fn() }));
+vi.mock('../../lib/api.js', () => ({ api: { get, put } }));
+import CaseTodos from './CaseTodos.svelte';
+let component;
+let target;
+const initial = () => ({ revision: 0, lists: [{ id: 'default', name: 'Tasks', tasks: [] }] });
+async function settle() {
+ for (let i = 0; i < 20; i++) await Promise.resolve();
+ flushSync();
+}
+async function open(data = initial()) {
+ get.mockResolvedValue(data);
+ put.mockImplementation(async (_url, body) => ({ ...body, revision: body.revision + 1 }));
+ target = document.createElement('div');
+ document.body.append(target);
+ component = mount(CaseTodos, { target, props: { caseId: 'case-a' } });
+ flushSync();
+ await settle();
+}
+const input = (label) => target.querySelector(`input[aria-label="${label}"]`);
+const button = (label) => target.querySelector(`button[aria-label="${label}"]`);
+async function type(label, value) {
+ input(label).value = value;
+ input(label).dispatchEvent(new Event('input', { bubbles: true }));
+ await settle();
+}
+async function submit(label) {
+ input(label).closest('form').dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }));
+ await settle();
+}
+afterEach(async () => { if (component) await unmount(component); target?.remove(); vi.clearAllMocks(); });
+
+it('adds, edits, checks, unchecks and deletes a task with persisted counters', async () => {
+ await open();
+ await type('New task', 'Check image');
+ await submit('New task');
+ expect(target.textContent).toContain('0/1');
+ expect(input('New task').value).toBe('');
+ input('Task text').value = 'Check source';
+ input('Task text').dispatchEvent(new Event('change', { bubbles: true }));
+ await settle();
+ const checkbox = () => target.querySelector('input[type="checkbox"]');
+ checkbox().click(); await settle();
+ expect(target.textContent).toContain('1/1');
+ expect(input('Task text').classList.contains('done')).toBe(true);
+ checkbox().click(); await settle();
+ expect(target.textContent).toContain('0/1');
+ button('Delete Check source').click(); await settle();
+ expect(target.textContent).toContain('0/0');
+ expect(put).toHaveBeenLastCalledWith('/api/cases/case-a/todos', expect.objectContaining({ lists: [{ id: 'default', name: 'Tasks', tasks: [] }] }));
+});
+
+it('creates and renames separate lists and confirms deleting a populated list', async () => {
+ await open();
+ button('Add list').click(); await settle();
+ await type('List name', 'Sources'); await submit('List name');
+ await type('New task', 'Contact source'); await submit('New task');
+ button('List options').click(); await settle();
+ [...target.querySelectorAll('button')].find((b) => b.textContent === 'Rename list').click(); await settle();
+ await type('List name', 'Contacts'); await submit('List name');
+ expect(target.textContent).toContain('Contacts');
+ button('List options').click(); await settle();
+ [...target.querySelectorAll('button')].find((b) => b.textContent === 'Delete list').click(); await settle();
+ expect(document.querySelector('[role="alertdialog"]')).not.toBeNull();
+ [...document.querySelectorAll('[role="alertdialog"] button')].find((b) => b.textContent.trim() === 'Cancel').click(); await settle();
+ expect(input('Task text').value).toBe('Contact source');
+ [...target.querySelectorAll('button')].find((b) => b.textContent === 'Delete list').click(); await settle();
+ [...document.querySelectorAll('[role="alertdialog"] button')].find((b) => b.textContent.trim() === 'Delete list').click(); await settle();
+ expect(target.textContent).not.toContain('Contacts');
+ expect(target.textContent).toContain('Tasks');
+});
+
+it('retains the draft on save failure and blocks stale writes until reload', async () => {
+ await open();
+ put.mockRejectedValueOnce(Object.assign(new Error('Changed in another tab'), { status: 409 }));
+ await type('New task', 'Keep draft'); await submit('New task');
+ expect(input('New task').value).toBe('Keep draft');
+ expect(target.querySelector('fieldset').disabled).toBe(true);
+ expect(target.querySelector('[role="alert"]').textContent).toContain('Changed in another tab');
+ [...target.querySelectorAll('button')].find((b) => b.textContent === 'Reload lists').click(); await settle();
+ expect(target.querySelector('fieldset').disabled).toBe(false);
+ await submit('New task');
+ expect(input('Task text').value).toBe('Keep draft');
+});
+
+it('does not write a default list on mount', async () => {
+ await open();
+ expect(put).not.toHaveBeenCalled();
+ expect(get).toHaveBeenCalledWith('/api/cases/case-a/todos');
+});
+
+it('offers a reload when the first read fails', async () => {
+ get.mockRejectedValueOnce(new Error('Case unavailable'));
+ target = document.createElement('div');
+ document.body.append(target);
+ component = mount(CaseTodos, { target, props: { caseId: 'case-a' } });
+ flushSync();
+ await settle();
+ expect(target.querySelector('[role="alert"]').textContent).toContain('Case unavailable');
+ get.mockResolvedValueOnce(initial());
+ [...target.querySelectorAll('button')].find((b) => b.textContent === 'Reload lists').click(); await settle();
+ expect(target.querySelector('[role="alert"]')).toBeNull();
+ expect(input('New task')).not.toBeNull();
+});
+
+it('titles the block like the other Home sections and avoids the global empty state', async () => {
+ await open({ revision: 0, lists: [] });
+ expect(target.querySelector('h2').classList.contains('label')).toBe(true);
+ expect(target.textContent).toContain('Add a list to start.');
+ expect(target.querySelector('.empty')).toBeNull();
+});
diff --git a/frontend/src/tools/proof/PointMapDialog.render.test.js b/frontend/src/tools/proof/PointMapDialog.render.test.js
new file mode 100644
index 0000000..5a554c0
--- /dev/null
+++ b/frontend/src/tools/proof/PointMapDialog.render.test.js
@@ -0,0 +1,196 @@
+// @vitest-environment happy-dom
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { flushSync, mount, unmount } from 'svelte';
+
+/**
+ * Moving a proof's point on the ground rather than in digits.
+ *
+ * The map itself is drawn by the engine and cannot be asserted here, so what is
+ * pinned is the contract around it: where it opens, that the pin follows a
+ * click, what the dialog hands back, and that it writes nothing — a coordinate
+ * row is the only thing this dialog is allowed to change.
+ */
+
+const PROVIDERS = [
+ {
+ id: 'esri-world-imagery',
+ label: 'Esri World Imagery',
+ imagery: true,
+ max_zoom: 19,
+ tile_size: 256,
+ oversample: 1,
+ },
+];
+
+const get = vi.fn(async (path) => {
+ if (path === '/api/satellite/providers') return PROVIDERS;
+ if (path === '/api/settings') return { usage: {}, month: '2026-09' };
+ if (path.includes('/imagery-date')) return { supported: false };
+ 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() } }));
+
+vi.mock('../../lib/state.svelte.js', () => ({
+ prefs: { coordFormat: 'dd', units: 'metric', homeView: { lat: 43, lon: 25, zoom: 3 } },
+}));
+
+const engines = [];
+function fakeEngine(opening, container) {
+ const handlers = {};
+ const engine = {
+ handlers,
+ impl: { on: vi.fn(), off: vi.fn() },
+ container,
+ camera: vi.fn(() => ({ ...opening, bearing: 0 })),
+ getZoom: vi.fn(() => opening.zoom),
+ setBearing: vi.fn(),
+ resize: vi.fn(),
+ on: vi.fn((name, handler) => {
+ handlers[name] = handler;
+ return () => delete handlers[name];
+ }),
+ destroy: vi.fn(),
+ };
+ engines.push(engine);
+ return engine;
+}
+vi.mock('../../lib/map/engine.js', () => ({
+ createMapEngine: vi.fn(async (element, { view }) => fakeEngine(view, element)),
+}));
+
+const setOverlay = vi.fn();
+vi.mock('../../lib/map/basemap.js', () => ({
+ OVERLAY_IDS: ['labels', 'roads', 'boundaries', 'railway', 'power', 'seamarks', 'gpstraces'],
+ createBasemaps: vi.fn(() => ({
+ show: vi.fn(),
+ setOverlay,
+ setZoomCeiling: vi.fn(),
+ dispose: vi.fn(),
+ })),
+}));
+
+const set = vi.fn();
+const patch = vi.fn();
+const destroy = vi.fn();
+vi.mock('../../lib/map/surface.js', () => ({
+ createSurface: vi.fn(() => ({ set, patch, destroy })),
+}));
+
+const { default: PointMapDialog } = await import('./PointMapDialog.svelte');
+
+const VIEW = { lat: 48.8584, lon: 2.2945, zoom: 17 };
+
+let live;
+const onpick = vi.fn();
+const onclose = vi.fn();
+
+async function settle() {
+ for (let index = 0; index < 40; index += 1) await Promise.resolve();
+ flushSync();
+}
+
+async function open(view = VIEW) {
+ const target = document.createElement('div');
+ document.body.append(target);
+ live = mount(PointMapDialog, { target, props: { view, onpick, onclose } });
+ flushSync();
+ await settle();
+}
+
+const button = (label) =>
+ [...document.querySelectorAll('button')].find((entry) => entry.textContent.trim() === label);
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ engines.length = 0;
+});
+
+afterEach(() => {
+ if (live) unmount(live);
+ live = null;
+ document.body.innerHTML = '';
+});
+
+describe('moving a proof point on the map', () => {
+ it('opens on the view it was handed, with the pin on it', async () => {
+ await open();
+
+ const [{ view }] = (await import('../../lib/map/engine.js')).createMapEngine.mock.calls.map(
+ ([, options]) => options
+ );
+ expect(view).toMatchObject(VIEW);
+ const [[shapes]] = set.mock.calls;
+ expect(shapes).toHaveLength(1);
+ expect(shapes[0]).toMatchObject({ kind: 'marker', at: { lat: 48.8584, lon: 2.2945 } });
+ expect(shapes[0].draggable).toBe(true);
+ expect(document.body.textContent).toContain('Click the map to move the pin.');
+ expect(document.body.textContent).toContain('48.858400, 2.294500');
+ });
+
+ it('follows a click, without rebuilding the layer under the pin', async () => {
+ await open();
+ set.mockClear();
+
+ engines[0].handlers.click({ lat: 48.873792, lon: 2.295028 });
+ flushSync();
+
+ expect(set).not.toHaveBeenCalled();
+ expect(patch).toHaveBeenLastCalledWith('point', { at: { lat: 48.873792, lon: 2.295028 } });
+ expect(document.body.textContent).toContain('48.873792, 2.295028');
+ });
+
+ it('hands the point back and closes, or closes with nothing said', async () => {
+ await open();
+ engines[0].handlers.click({ lat: 1.5, lon: -2.25 });
+ flushSync();
+
+ button('Use this point').click();
+ expect(onpick).toHaveBeenCalledWith({ lat: 1.5, lon: -2.25 });
+ expect(onclose).toHaveBeenCalled();
+
+ onpick.mockClear();
+ button('Cancel').click();
+ expect(onpick).not.toHaveBeenCalled();
+ });
+
+ it('offers the reference layers, labels first and already on', async () => {
+ await open();
+
+ expect(setOverlay).toHaveBeenCalledWith('labels', true, null);
+ expect(setOverlay).toHaveBeenCalledWith('railway', false, undefined);
+
+ button('Layers').click();
+ flushSync();
+ const names = [...document.querySelectorAll('.layers .name')].map((entry) =>
+ entry.textContent.trim()
+ );
+ expect(names).toEqual([
+ 'Labels',
+ 'Borders',
+ 'Roads',
+ 'Railways',
+ 'Power lines',
+ 'Sea marks',
+ 'GPS traces',
+ ]);
+
+ setOverlay.mockClear();
+ [...document.querySelectorAll('.layers button')]
+ .find((entry) => entry.getAttribute('aria-label') === 'Railways')
+ .click();
+ await settle();
+ expect(setOverlay).toHaveBeenCalledWith('railway', true, null);
+ });
+
+ it('writes nothing: the dialog answers one question and files nothing', async () => {
+ await open();
+ engines[0].handlers.click({ lat: 1, lon: 2 });
+ flushSync();
+ button('Use this point').click();
+
+ expect(post).not.toHaveBeenCalled();
+ expect(put).not.toHaveBeenCalled();
+ });
+});
diff --git a/frontend/src/tools/proof/PointMapDialog.svelte b/frontend/src/tools/proof/PointMapDialog.svelte
new file mode 100644
index 0000000..20ec65e
--- /dev/null
+++ b/frontend/src/tools/proof/PointMapDialog.svelte
@@ -0,0 +1,214 @@
+<script>
+ /**
+ * A point, moved on the map instead of typed.
+ *
+ * Typing a coordinate is the one act in the composer that has no picture under
+ * it: six decimals is a tenth of a metre, and nobody edits a building's corner
+ * by counting digits. So the row opens the ground it names — the same map the
+ * rest of the app draws (`MapSurface`), the same basemaps, the same reference
+ * layers — with the pin on what the row already says, and hands the point back.
+ *
+ * Read-only about everything else. No capture, no save, no place: the dialog
+ * exists to answer one question, and the map that owns those acts is the Map
+ * tool. The camera opens where the caller says (the row's own point, else the
+ * one above it) so a row added with `+` starts beside the point it belongs with
+ * rather than on the empty Atlantic.
+ */
+ import { onMount, untrack } from 'svelte';
+ import Modal from '../../components/Modal.svelte';
+ import Icon from '../../components/Icon.svelte';
+ import MapSurface from '../satellite/MapSurface.svelte';
+ import MapLayers from '../satellite/MapLayers.svelte';
+ import { createImageryState, FALLBACK_PROVIDER } from '../satellite/state/imagery.svelte.js';
+ import { createSurface } from '../../lib/map/surface.js';
+ import { markerGeometry, markerSvg } from '../../lib/mapMarkers.js';
+ // The reference layers, named where they are already named for a reader
+ // (`lib/map/compare.js`): the same seven key-less overlays, the same words.
+ import { COMPARE_LAYERS } from '../../lib/map/compare.js';
+ import { api } from '../../lib/api.js';
+ import { formatCoords } from '../../lib/coords.js';
+ import { prefs } from '../../lib/state.svelte.js';
+
+ let {
+ /** Where the map opens, `{ lat, lon, zoom }`. The pin starts on it. */
+ view,
+ /** The point chosen, `{ lat, lon }`. The dialog closes itself after. */
+ onpick,
+ onclose,
+ } = $props();
+
+ const PIN = 'point';
+ /** Only these two read wrongly over a street basemap, which draws its own. */
+ const IMAGERY_ONLY = new Set(['labels', 'roads']);
+ const REFERENCE = COMPARE_LAYERS.filter((layer) => layer.group === 'reference');
+
+ const imagery = createImageryState({ api });
+ let providerId = $state(FALLBACK_PROVIDER);
+ let engine = $state(null);
+ let ready = $state(false);
+ // Where the pin starts: the opening camera, read once. The dialog is opened on
+ // one row and closed on it, so a later view would be a different question.
+ let at = $state(untrack(() => ({ lat: view.lat, lon: view.lon })));
+ let on = $state(['labels']);
+ let layersOpen = $state(false);
+ let surface = null;
+
+ const baseIsImagery = $derived(imagery.find(providerId)?.imagery ?? true);
+ const usable = $derived(on.filter((id) => baseIsImagery || !IMAGERY_ONLY.has(id)));
+ const reading = $derived(formatCoords(at.lat, at.lon, prefs.coordFormat));
+ const layerRows = $derived(
+ REFERENCE.map((layer) => ({
+ id: layer.id,
+ label: layer.label,
+ title: IMAGERY_ONLY.has(layer.id) && !baseIsImagery
+ ? 'Only useful over satellite imagery'
+ : layer.hint,
+ on: on.includes(layer.id),
+ disabled: IMAGERY_ONLY.has(layer.id) && !baseIsImagery,
+ toggle: () =>
+ (on = on.includes(layer.id) ? on.filter((id) => id !== layer.id) : [...on, layer.id]),
+ }))
+ );
+
+ onMount(() => {
+ imagery.loadProviders().catch(() => {
+ /* the free basemap still draws; the chip simply has nothing to offer */
+ });
+ imagery.refreshUsage();
+ });
+
+ // The pin is drawn once the map is up, then moved in place: rebuilt on every
+ // drag frame it would be dropped and re-added mid-gesture, which is why its
+ // opening position is read untracked.
+ $effect(() => {
+ if (!ready || !engine) return;
+ const layer = createSurface(engine);
+ const { size, anchor } = markerGeometry('pin');
+ layer.set([
+ {
+ id: PIN,
+ kind: 'marker',
+ at: untrack(() => at),
+ className: 'point-mark',
+ html: markerSvg('pin'),
+ size,
+ anchor,
+ draggable: true,
+ zIndex: 1000,
+ onDrag: (moved) => (at = moved),
+ },
+ ]);
+ surface = layer;
+ return () => {
+ layer.destroy();
+ surface = null;
+ };
+ });
+
+ // Read before the guard: behind `surface?.` the position would never be read
+ // at all while the map is still being built, and the pin would then stop
+ // following anything.
+ $effect(() => {
+ const moved = at;
+ surface?.patch(PIN, { at: moved });
+ });
+</script>
+
+<Modal title="Move the point" {onclose} width="900px">
+ <div class="stage">
+ <MapSurface
+ bind:engine
+ bind:ready
+ bind:providerId
+ {imagery}
+ home={view}
+ overlays={usable}
+ imperial={prefs.units === 'imperial'}
+ controlsTop={8}
+ onclick={(clicked) => (at = clicked)}
+ />
+ <div class="layers" class:open={layersOpen}>
+ {#if layersOpen}
+ <MapLayers rows={layerRows} bind:open={layersOpen} />
+ {:else}
+ <button type="button" class="layers-btn" onclick={() => (layersOpen = true)}>
+ <Icon name="stack" size={13} />
+ <span>Layers</span>
+ </button>
+ {/if}
+ </div>
+ </div>
+
+ <div class="foot">
+ <span class="hint">Click the map to move the pin.</span>
+ <span class="reading mono">{reading}</span>
+ <button class="btn btn-ghost btn-sm" onclick={onclose}>Cancel</button>
+ <button
+ class="btn btn-ok btn-sm"
+ onclick={() => {
+ onpick(at);
+ onclose();
+ }}>Use this point</button
+ >
+ </div>
+</Modal>
+
+<style>
+ .stage {
+ position: relative;
+ display: flex;
+ height: min(62vh, 520px);
+ border: 1px solid var(--border);
+ border-radius: var(--r-sm);
+ overflow: hidden;
+ }
+ /* Under the zoom buttons, aligned with them. The right-hand corner is the
+ surface's own: it stacks the basemap, the imagery date and the compass
+ there, and a control of ours over that column hides whichever of them the
+ map happens to be showing. */
+ .layers {
+ position: absolute;
+ top: 76px;
+ left: 12px;
+ z-index: 500;
+ max-height: calc(100% - 92px);
+ overflow: auto;
+ }
+ .layers.open {
+ width: 208px;
+ padding: 6px 8px 8px;
+ background: var(--bg-1);
+ border: 1px solid var(--border);
+ border-radius: var(--r-sm);
+ }
+ .layers-btn {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ padding: 5px 9px;
+ font-size: var(--fs-xs);
+ color: var(--text-1);
+ background: var(--bg-1);
+ border: 1px solid var(--border);
+ border-radius: var(--r-sm);
+ cursor: pointer;
+ }
+ .foot {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ padding-top: 10px;
+ }
+ .hint {
+ font-size: var(--fs-sm);
+ color: var(--text-3);
+ }
+ .reading {
+ margin-left: auto;
+ font-size: var(--fs-sm);
+ color: var(--text-1);
+ }
+ :global(.point-mark) {
+ filter: drop-shadow(0 1px 2px rgba(0, 0, 0, 0.5));
+ }
+</style>
diff --git a/frontend/src/tools/proof/ProofToolbar.svelte b/frontend/src/tools/proof/ProofToolbar.svelte
index 240509d..755cc11 100644
--- a/frontend/src/tools/proof/ProofToolbar.svelte
+++ b/frontend/src/tools/proof/ProofToolbar.svelte
@@ -201,6 +201,62 @@
<button class="tb-btn" title="Fit view (f)" onclick={fit}>
<Icon name="eye" size={18} />
</button>
+ <!-- Layout, tweet crops and repack live in one overflow flyout. -->
+ <div class="tb-group" bind:this={overflowEl}>
+ <button
+ class="tb-btn"
+ class:active={overflowOpen || layout === 'free' || !!guide}
+ title="Layout, tweet crops & repack"
+ onclick={() => toggle('overflow')}
+ bind:this={overflowBtn}
+ >
+ <Icon name="grid" size={18} />
+ </button>
+ <div
+ class="flyout flyout-overflow"
+ class:open={overflowOpen}
+ style:left={overflowPos.left}
+ style:top={overflowPos.top}
+ style:bottom={overflowPos.bottom}
+ >
+ <div class="flyout-row">
+ <button
+ class="tb-btn"
+ class:active={layout !== 'free'}
+ title="Grid layout: panels flow in rows"
+ onclick={() => setLayoutMode('grid')}
+ >
+ <Icon name="grid" size={18} />
+ </button>
+ <button
+ class="tb-btn"
+ class:active={layout === 'free'}
+ title="Free layout: drag panels anywhere"
+ onclick={() => setLayoutMode('free')}
+ >
+ <Icon name="layers" size={18} />
+ </button>
+ </div>
+ <div class="flyout-row">
+ {#each Object.keys(tweetGuides) as entry (entry)}
+ <button
+ class="tb-btn tb-guide"
+ class:active={guide === entry}
+ title={`Preview the ${entry} tweet crop. Everything outside is cut off`}
+ onclick={() => (guide = guide === entry ? null : entry)}
+ >{entry}</button>
+ {/each}
+ <button
+ class="tb-btn tb-magic"
+ title={`Repack panels toward ${guide ?? '16:9'} and reset panel sizes`}
+ disabled={!panelCount}
+ onclick={applyMagic}
+ >
+ <Icon name="wand" size={18} />
+ </button>
+ </div>
+ </div>
+ </div>
{#if showContextTools}
<div class="tb-sep"></div>
@@ -323,83 +379,39 @@
{/if}
{/if}
- <div class="tb-sep"></div>
-
- <!-- Layout, tweet crops and repack live in one overflow flyout. -->
- <div class="tb-group" bind:this={overflowEl}>
- <button
- class="tb-btn"
- class:active={overflowOpen || layout === 'free' || !!guide}
- title="Layout, tweet crops & repack"
- onclick={() => toggle('overflow')}
- bind:this={overflowBtn}
- >
- <Icon name="grid" size={18} />
- </button>
- <div
- class="flyout flyout-overflow"
- class:open={overflowOpen}
- style:left={overflowPos.left}
- style:top={overflowPos.top}
- style:bottom={overflowPos.bottom}
- >
- <div class="flyout-row">
- <button
- class="tb-btn"
- class:active={layout !== 'free'}
- title="Grid layout: panels flow in rows"
- onclick={() => setLayoutMode('grid')}
- >
- <Icon name="grid" size={18} />
- </button>
- <button
- class="tb-btn"
- class:active={layout === 'free'}
- title="Free layout: drag panels anywhere"
- onclick={() => setLayoutMode('free')}
- >
- <Icon name="layers" size={18} />
- </button>
- </div>
- <div class="flyout-row">
- {#each Object.keys(tweetGuides) as entry (entry)}
- <button
- class="tb-btn tb-guide"
- class:active={guide === entry}
- title={`Preview the ${entry} tweet crop. Everything outside is cut off`}
- onclick={() => (guide = guide === entry ? null : entry)}
- >{entry}</button>
- {/each}
- <button
- class="tb-btn tb-magic"
- title={`Repack panels toward ${guide ?? '16:9'} and reset panel sizes`}
- disabled={!panelCount}
- onclick={applyMagic}
- >
- <Icon name="wand" size={18} />
- </button>
- </div>
- </div>
- </div>
</div>
<style>
+ /* Two columns, always. In one column the rail stood around 750px tall, which
+ is past the bottom of a laptop window once the topbar and the tab strip have
+ taken their share — the colour, the width and the layout controls sat under
+ the fold behind a scrollbar nobody looks for. Fixed rather than responsive: a
+ toolbar that changes shape with the window is one nobody learns.
+ The second column is paid for out of the buttons rather than the canvas: at
+ the size they were, the rail read as a slab beside the picture it serves. A
+ 32px box still holds an 18px icon with room around it, and the whole rail
+ ends up 26px wider than the single column it replaces, against some 400px of
+ height it gives back.
+ The groups the separators mark are kept by the grid itself — a separator
+ spans both columns, so the buttons between two of them fill their own rows
+ and read left to right, then down. */
.toolbar {
- width: 52px;
+ width: 76px;
flex-shrink: 0;
- display: flex;
- flex-direction: column;
- align-items: center;
- gap: 6px;
- padding: 12px 0;
+ display: grid;
+ grid-template-columns: repeat(2, 32px);
+ justify-content: center;
+ align-content: start;
+ gap: 4px;
+ padding: 8px 0;
border-right: 1px solid var(--border);
background: var(--bg-1);
overflow-y: auto;
overflow-x: hidden;
}
.tb-btn {
- width: 38px;
- height: 38px;
+ width: 32px;
+ height: 32px;
display: flex;
align-items: center;
justify-content: center;
@@ -408,17 +420,22 @@
flex-shrink: 0;
}
.tb-btn:hover { color: var(--text-1); background: var(--bg-2); }
- .tb-btn.active { color: var(--text-1); background: var(--bg-3); }
+ /* The tool in hand is a selection, which is what the amber is for elsewhere in
+ the app. Grey on grey said "pressed" and left the rail's own state to be
+ worked out from the cursor. */
+ .tb-btn.active { color: var(--accent); background: var(--accent-soft); }
.tb-guide { font-size: 11px; font-weight: 700; }
.tb-magic:not(:disabled) { color: var(--accent); }
.tb-magic:not(:disabled):hover { background: var(--accent-soft); }
.tb-magic:disabled { opacity: 0.4; cursor: default; }
+ /* A hairline across the rail rather than a stub under one column: it is the
+ only thing marking the groups, so it reads as a rule and not as a stray mark. */
.tb-sep {
- width: 26px;
+ grid-column: 1 / -1;
+ justify-self: stretch;
+ margin: 3px 4px;
height: 1px;
background: var(--border);
- margin: 4px 0;
- flex-shrink: 0;
}
.tb-size { position: relative; }
.tb-size-val {
diff --git a/frontend/src/tools/satellite/MapSurface.svelte b/frontend/src/tools/satellite/MapSurface.svelte
index 0a7bad7..5b4058f 100644
--- a/frontend/src/tools/satellite/MapSurface.svelte
+++ b/frontend/src/tools/satellite/MapSurface.svelte
@@ -15,8 +15,9 @@
* The camera reports out rather than being driven in: the engine settles a
* pan on a whole zoom level and wraps a longitude back inside ±180, and a
* parent that assumed otherwise would fight it. `engine` and `element` are
- * handed back for the acts a tool owns — flying to a saved point, and the
- * drag gestures it arms over the map.
+ * handed back for the acts a tool owns — flying to a saved point, the drag
+ * gestures it arms over the map, and linking two surfaces on one camera
+ * (`lib/map/cameraLink.js`).
*
* The catalogue and the month's tally are shared (state/imagery.svelte.js):
* a tile counted against the month is counted once, however many surfaces
@@ -27,6 +28,7 @@
import { createBasemaps, OVERLAY_IDS } from '../../lib/map/basemap.js';
import { DEFAULT_LAYER, DEFAULT_MAXCC, SENTINEL_ID } from '../../lib/sentinel.js';
import Icon from '../../components/Icon.svelte';
+ import Compass from '../../components/Compass.svelte';
import ImageryChip from './ImageryChip.svelte';
let {
@@ -47,6 +49,8 @@
imperial = false,
/** The view the map opens on. Read once, at build. */
home,
+ /** Satellite starts at home; linked Compare surfaces keep their bound view. */
+ resetToHome = true,
/** Where the camera is now. Reported out; the engine is what moves it. */
view = $bindable({ lat: 0, lon: 0, zoom: 2 }),
bearing = $bindable(0),
@@ -61,6 +65,15 @@
armed = null,
/** Hide this surface's own chrome for a screen capture. */
grabbing = false,
+ /** False hides this surface's own corner (provider, date, compass) for a
+ * tool that shows them itself, as Compare does over its two maps. */
+ chrome = true,
+ /** When the pixels under the crosshair were taken, reported out:
+ * `{ date, exact, source }`, or null when nothing can say. */
+ dated = $bindable(null),
+ /** A view zoom this surface stops at below its provider's own ceiling, so
+ * two linked surfaces stop together. Null leaves the provider in charge. */
+ zoomCeiling = null,
/** How far down the engine's zoom buttons start, so they stack under
* whatever the tool floats in the same corner (see `engine.css`). */
controlsTop = 58,
@@ -75,18 +88,18 @@
onwidgetload = () => {},
onwidgetauthfailure = () => {},
onwidgetfailed = () => {},
+ /** The settled camera and the turn, for a parent that shares them. */
+ onviewsettled = () => {},
+ onbearingchange = () => {},
children,
} = $props();
let mapEl = $state();
let basemaps = null;
- let editingBearing = $state(false);
- let bearingInput = $state('');
// Acquisition date of the imagery under the crosshair — Esri only.
let imageryDate = $state(null); // { supported, date, source } | null
let dateRequest = 0;
let dateTimer;
-
/**
* What this surface actually shows, which is not always what it was asked
* for: a billed basemap steps aside when the month is nearly spent or the
@@ -106,6 +119,16 @@
shown.provider?.id === SENTINEL_ID && s2?.window.from ? s2.window.from : null
);
+ $effect(() => {
+ dated = pinnedDay
+ ? { date: pinnedDay, exact: true, source: 'Sentinel-2' }
+ : shown.provider?.id === SENTINEL_ID
+ ? s2?.latest ? { date: s2.latest, exact: false, source: 'Sentinel-2' } : null
+ : imageryDate?.supported && imageryDate.date
+ ? { date: imageryDate.date, exact: false, source: imageryDate.source ?? null }
+ : null;
+ });
+
export function resize() {
engine?.resize();
}
@@ -132,7 +155,7 @@
});
async function build() {
- view = { ...home };
+ if (resetToHome) view = { ...home };
try {
engine = await createMapEngine(mapEl, { view, imperial });
} catch (e) {
@@ -146,6 +169,7 @@
return null;
}
element = mapEl;
+ engine.setBearing(bearing);
basemaps = createBasemaps(engine, {
onMeteredTiles: onusage,
// one billed map load, counted where it happens (the proxy can't see it)
@@ -153,15 +177,18 @@
onWidgetAuthFailure: onwidgetauthfailure,
onWidgetFailed: onwidgetfailed,
});
+ basemaps.setZoomCeiling(zoomCeiling);
showBasemap();
showOverlays();
// the façade wraps the centre back inside ±180 for us, which is what every
// route a capture reaches enforces
const offSettled = engine.on('view-settled', (settled) => {
view = { lat: settled.lat, lon: settled.lon, zoom: settled.zoom };
+ onviewsettled(settled);
});
const offRotate = engine.on('rotate', (turned) => {
bearing = Math.round(turned.bearing);
+ onbearingchange(turned);
});
const offClick = engine.on('click', (at) => onclick(at));
const offMenu = engine.on('contextmenu', (at) => oncontextmenu(at));
@@ -184,6 +211,11 @@
basemaps.show(shown.provider, shown.id, shown.cell);
}
+ $effect(() => {
+ const value = zoomCeiling;
+ if (ready) basemaps?.setZoomCeiling(value);
+ });
+
$effect(() => {
shown.id; // a new provider, a new eco/block fallback, a new Sentinel window
shown.cell; // …and the z17 detail-boost bracket
@@ -234,17 +266,6 @@
engine?.setBearing(deg); // the façade normalises whatever it is handed
}
- function startEditBearing() {
- bearingInput = String(bearing);
- editingBearing = true;
- }
-
- function commitBearing() {
- const deg = parseFloat(bearingInput);
- if (Number.isFinite(deg)) setBearing(deg);
- editingBearing = false;
- }
-
// the container resizes when a panel opens or the window changes, and
// reappears from display:none when the tool tab is re-selected
export async function remeasure() {
@@ -273,6 +294,7 @@
<!-- The picture this surface is showing, when it was taken, and the compass
reading how it is turned: all facts about this map and belonging to it,
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} />
@@ -319,51 +341,10 @@
</span>
{/if}
- <!-- Which way is up, as one reading: the needle resets north, the number
- opens for an exact angle. Middle-dragging the map is what turns it. -->
- <div class="rotate-ctl" class:turned={bearing !== 0}>
- <button
- class="compass"
- onclick={() => setBearing(0)}
- title={bearing ? 'Reset to north' : 'North up · middle-drag the map to rotate'}
- aria-label="Reset to north"
- >
- <svg width="15" height="15" viewBox="0 0 16 16" style="transform: rotate({bearing}deg)">
- <!-- A needle, not a rose: the outline is the whole instrument and the
- filled half is north. Two colours and a disc read as decoration. -->
- <path
- d="M8 1.6 11.7 14 8 10.9 4.3 14Z"
- fill="none"
- stroke="currentColor"
- stroke-width="1.3"
- stroke-linejoin="round"
- />
- <path d="M8 1.6 11.7 14 8 10.9Z" fill="currentColor" />
- </svg>
- </button>
- {#if editingBearing}
- <!-- svelte-ignore a11y_autofocus -->
- <input
- class="input deg-input mono"
- type="number"
- min="0"
- max="359"
- bind:value={bearingInput}
- autofocus
- onblur={commitBearing}
- onkeydown={(e) => {
- if (e.key === 'Enter') commitBearing();
- else if (e.key === 'Escape') editingBearing = false;
- }}
- aria-label="Set bearing in degrees"
- />
- {:else}
- <button class="deg mono" onclick={startEditBearing} title="Click to type an exact angle">
- {bearing}°
- </button>
- {/if}
- </div>
+ <!-- Which way is up. Middle-dragging the map is what turns it. -->
+ <Compass {bearing} onbearing={setBearing} />
</div>
+ {/if}
</div>
<style>
@@ -460,50 +441,4 @@
.surface-ctl > :global(*) {
pointer-events: auto;
}
- /* The needle and its angle are one reading, so they are one control, built
- like the chips above it: same fill, same 1px ring, same height. The disc
- and the two-tone rose it replaces read as an ornament on an instrument
- panel, and were the only round thing on the map. */
- .rotate-ctl {
- display: flex;
- align-items: stretch;
- height: 30px;
- border-radius: var(--radius-1);
- background: rgba(24, 24, 24, 0.88);
- backdrop-filter: blur(6px);
- box-shadow: 0 0 0 1px var(--border);
- }
- /* north-up is the resting state and says nothing; a turned map is a fact
- worth seeing from across the screen */
- .rotate-ctl.turned {
- box-shadow: 0 0 0 1px color-mix(in srgb, var(--accent) 50%, transparent);
- }
- .compass {
- display: grid;
- place-items: center;
- width: 30px;
- color: var(--text-2);
- cursor: pointer;
- }
- .compass:hover {
- color: var(--accent);
- }
- .deg {
- min-width: 42px;
- padding: 0 7px 0 5px;
- text-align: left;
- font-size: var(--fs-xs);
- color: var(--text-1);
- cursor: text;
- }
- .deg:hover {
- color: var(--accent);
- }
- .deg-input {
- width: 52px;
- padding: 0 4px;
- border: none;
- background: none;
- text-align: left;
- font-size: var(--fs-xs);
- }</style>
+</style>
diff --git a/frontend/src/tools/satellite/MarkerMenu.test.js b/frontend/src/tools/satellite/MarkerMenu.test.js
index 52c1952..b06c93c 100644
--- a/frontend/src/tools/satellite/MarkerMenu.test.js
+++ b/frontend/src/tools/satellite/MarkerMenu.test.js
@@ -41,7 +41,6 @@ describe('the point the map is reading', () => {
expect(source).toContain('aria-checked={style === entry.id}');
expect(source).not.toContain('class="chip"');
for (const name of ['noMark', 'centre', 'move', 'crosshair', 'pin']) expect(paths[name]).toBeTruthy();
- expect(paths.ghost).toBeUndefined();
});
it('opens upwards, because it sits at the foot of the map', () => {
diff --git a/frontend/src/tools/satellite/MediaViewer.render.test.js b/frontend/src/tools/satellite/MediaViewer.render.test.js
new file mode 100644
index 0000000..e48ffaa
--- /dev/null
+++ b/frontend/src/tools/satellite/MediaViewer.render.test.js
@@ -0,0 +1,156 @@
+// @vitest-environment happy-dom
+/**
+ * The player in the Saved panel, actually mounted.
+ *
+ * What it owes: the file on screen is the one the counter names, the arrows walk
+ * the stack in both directions and wrap, the keyboard reaches them without a
+ * click, and a focused video keeps its own arrows for seeking.
+ */
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { flushSync, mount, unmount } from 'svelte';
+
+const { default: MediaViewer } = await import('./MediaViewer.svelte');
+
+const live = [];
+
+const photo = {
+ id: 'e1',
+ key: '[email protected],2.1',
+ kind: 'media',
+ media_kind: 'image',
+ title: 'quay',
+ path: 'media/quay.png',
+ lat: 48.1,
+ lon: 2.1,
+ status: 'confirmed',
+ roads: [{ type: 'located-at', status: 'confirmed' }],
+ linked_proofs: [],
+};
+const clip = {
+ ...photo,
+ id: 'e2',
+ key: '[email protected],2.1',
+ media_kind: 'video',
+ title: 'rooftop',
+ path: 'media/rooftop.mp4',
+ status: 'suggested',
+ roads: [{ type: 'proof', id: 'p1', title: 'Roofline', status: 'confirmed' }],
+ linked_proofs: [{ id: 'p1', name: 'Roofline', title: 'Roofline' }],
+};
+
+function open(props = {}) {
+ const target = document.createElement('div');
+ document.body.append(target);
+ const app = mount(MediaViewer, {
+ target,
+ props: {
+ items: [photo, clip],
+ index: 0,
+ caseId: 'case-1',
+ coords: (row) => `${row.lat}, ${row.lon}`,
+ onclose: vi.fn(),
+ onmedia: vi.fn(),
+ onproof: vi.fn(),
+ ...props,
+ },
+ });
+ live.push(app);
+ flushSync();
+ return app;
+}
+
+const text = () => document.body.textContent.replace(/\s+/g, ' ');
+const button = (label) =>
+ [...document.querySelectorAll('button')].find((b) => b.getAttribute('aria-label') === label);
+
+afterEach(() => {
+ while (live.length) unmount(live.pop());
+ document.body.innerHTML = '';
+});
+
+describe('the file on screen', () => {
+ it('plays a photo as an image and footage as a player', () => {
+ open();
+ expect(document.querySelector('img').getAttribute('src')).toContain('media/quay.png');
+ expect(document.querySelector('video')).toBeNull();
+
+ button('Next').click();
+ flushSync();
+ expect(document.querySelector('video').getAttribute('src')).toContain('media/rooftop.mp4');
+ expect(document.querySelector('video').hasAttribute('controls')).toBe(true);
+ });
+
+ it('says why it stands here, and marks what only a tool has claimed', () => {
+ open({ index: 0 });
+ expect(text()).toContain('Recorded here');
+ expect(text()).not.toContain('suggested');
+
+ button('Next').click();
+ flushSync();
+ expect(text()).toContain('Via Roofline');
+ expect(text()).toContain('suggested');
+ });
+
+ it('offers the file in Media, and the proofs built on it', () => {
+ const onmedia = vi.fn();
+ const onproof = vi.fn();
+ open({ index: 1, onmedia, onproof });
+ const acts = [...document.querySelectorAll('.acts button')];
+ expect(acts.map((b) => b.textContent.trim())).toEqual(['Open in Media', 'Roofline']);
+ acts[0].click();
+ expect(onmedia).toHaveBeenCalledWith(clip);
+ acts[1].click();
+ expect(onproof).toHaveBeenCalledWith(clip.linked_proofs[0]);
+ });
+
+ it('leaves a lone file no arrows to press', () => {
+ open({ items: [photo] });
+ expect(button('Next')).toBeUndefined();
+ expect(text()).not.toContain('1 / 1');
+ });
+});
+
+describe('walking the stack', () => {
+ it('counts from one and wraps at the end', () => {
+ open();
+ expect(text()).toContain('1 / 2');
+ button('Next').click();
+ flushSync();
+ expect(text()).toContain('2 / 2');
+ button('Next').click();
+ flushSync();
+ expect(text()).toContain('1 / 2');
+ button('Previous').click();
+ flushSync();
+ expect(text()).toContain('2 / 2');
+ });
+
+ it('takes the keyboard when it opens, so the arrows work without a click', async () => {
+ open();
+ await Promise.resolve();
+ await Promise.resolve();
+ const viewer = document.querySelector('.viewer');
+ expect(document.activeElement).toBe(viewer);
+
+ viewer.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowRight', bubbles: true }));
+ flushSync();
+ expect(text()).toContain('2 / 2');
+ });
+
+ it('leaves the arrows to a focused video, which seeks with them', () => {
+ open({ index: 1 });
+ const video = document.querySelector('video');
+ video.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowRight', bubbles: true }));
+ flushSync();
+ expect(text()).toContain('2 / 2'); // still the same file
+ });
+
+ it('closes on Escape, the way every other overlay in the app does', () => {
+ const onclose = vi.fn();
+ open({ onclose });
+ document
+ .querySelector('.viewer')
+ .dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }));
+ expect(onclose).toHaveBeenCalled();
+ });
+});
diff --git a/frontend/src/tools/satellite/MediaViewer.svelte b/frontend/src/tools/satellite/MediaViewer.svelte
new file mode 100644
index 0000000..77c68b9
--- /dev/null
+++ b/frontend/src/tools/satellite/MediaViewer.svelte
@@ -0,0 +1,214 @@
+<script>
+ /**
+ * One located photo or video, read in the Saved panel beside the map.
+ *
+ * It takes the panel rather than a card over the map: the gesture it serves is
+ * holding the footage next to the imagery, and a window over the map would
+ * hide the half being compared. A mark holding several files opens all of them,
+ * and the arrows walk the stack.
+ *
+ * Nothing is edited here. It plays the file, says why the file stands on this
+ * point, and opens it in Media or in the proofs built on it.
+ */
+ import { tick } from 'svelte';
+ import Icon from '../../components/Icon.svelte';
+ import { fileUrl } from '../../lib/fileUrl.js';
+ import { roadWords, step } from '../../lib/mediaViewer.js';
+
+ let {
+ items = [],
+ index = $bindable(0),
+ caseId,
+ coords,
+ fullscreen = false,
+ onclose,
+ onmedia,
+ onproof,
+ } = $props();
+
+ const row = $derived(items[Math.min(index, items.length - 1)] ?? null);
+ const why = $derived(roadWords(row));
+ const proposed = $derived(row?.status === 'suggested');
+ const blocked = $derived(fullscreen ? 'Exit fullscreen first. This leaves the map' : null);
+
+ let el = $state();
+
+ function go(delta) {
+ index = step(index, delta, items.length);
+ }
+
+ // A stack opened from the map takes the keyboard, so the arrows walk it straight
+ // away without a click into the panel first.
+ $effect(() => {
+ void items; // a second mark pressed while the viewer is open takes it again
+ if (!el) return;
+ tick().then(() => el?.focus({ preventScroll: true }));
+ });
+
+ function onkeydown(event) {
+ // a focused video seeks with the arrows, and that is what the key means there
+ if (event.target instanceof HTMLMediaElement) return;
+ if (event.key === 'Escape') {
+ event.preventDefault();
+ onclose();
+ } else if (event.key === 'ArrowLeft' && items.length > 1) {
+ event.preventDefault();
+ go(-1);
+ } else if (event.key === 'ArrowRight' && items.length > 1) {
+ event.preventDefault();
+ go(1);
+ }
+ }
+</script>
+
+{#if row}
+ <!-- svelte-ignore a11y_no_noninteractive_element_interactions -->
+ <section class="viewer" bind:this={el} tabindex="-1" aria-label="Media viewer" {onkeydown}>
+ <header class="bar">
+ {#if items.length > 1}
+ <button class="btn btn-icon" title="Previous (←)" aria-label="Previous" onclick={() => go(-1)}>
+ <Icon name="chevronLeft" size={14} />
+ </button>
+ <span class="count">{index + 1} / {items.length}</span>
+ <button class="btn btn-icon" title="Next (→)" aria-label="Next" onclick={() => go(1)}>
+ <Icon name="chevronRight" size={14} />
+ </button>
+ {/if}
+ <button class="btn btn-icon close" title="Back to saved work (Esc)" aria-label="Close" onclick={onclose}>
+ <Icon name="x" size={14} />
+ </button>
+ </header>
+
+ <!-- keyed on the row, so stepping away stops the video that was playing -->
+ {#key row.key ?? row.id}
+ <div class="stage">
+ {#if row.media_kind === 'video'}
+ <!-- svelte-ignore a11y_media_has_caption -->
+ <video src={fileUrl(caseId, row.path)} controls preload="metadata"></video>
+ {:else}
+ <img src={fileUrl(caseId, row.path)} alt={row.title} />
+ {/if}
+ </div>
+ {/key}
+
+ <div class="about">
+ <h3 class="title" title={row.title}>{row.title || 'Untitled'}</h3>
+ <p class="sub">
+ <span class="mono">{coords(row)}</span>
+ {#if proposed}
+ <span class="proposed" title="Proposed by a tool, waiting for you">suggested</span>
+ {/if}
+ </p>
+ {#if why}<p class="why">{why}</p>{/if}
+ </div>
+
+ <nav class="acts" aria-label="Open elsewhere">
+ <button
+ class="btn btn-sm"
+ disabled={fullscreen}
+ title={blocked ?? 'Open this file in Media'}
+ onclick={() => onmedia(row)}
+ >
+ <Icon name={row.media_kind === 'video' ? 'video' : 'image'} size={13} />
+ <span>Open in Media</span>
+ </button>
+ {#each row.linked_proofs ?? [] as proof (proof.id)}
+ <button
+ class="btn btn-sm"
+ disabled={fullscreen}
+ title={blocked ?? 'Open this proof in Geo Proof'}
+ onclick={() => onproof(proof)}
+ >
+ <Icon name="proof" size={13} />
+ <span class="label">{proof.title || proof.name}</span>
+ </button>
+ {/each}
+ </nav>
+ </section>
+{/if}
+
+<style>
+ .viewer {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ outline: none;
+ }
+ .bar {
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ }
+ .count {
+ font-size: var(--fs-xs);
+ color: var(--text-2);
+ font-variant-numeric: tabular-nums;
+ }
+ .close {
+ margin-left: auto;
+ }
+ /* black behind the picture, so a portrait clip reads as a frame in the panel
+ rather than as a gap in it */
+ .stage {
+ display: grid;
+ place-items: center;
+ background: #000;
+ border-radius: var(--r-sm);
+ overflow: hidden;
+ }
+ .stage img,
+ .stage video {
+ display: block;
+ width: 100%;
+ max-height: 60vh;
+ object-fit: contain;
+ }
+ .about {
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+ min-width: 0;
+ }
+ .title {
+ margin: 0;
+ font-size: var(--fs-sm);
+ font-weight: 600;
+ color: var(--text-1);
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ .sub {
+ display: flex;
+ align-items: baseline;
+ gap: 6px;
+ margin: 0;
+ font-size: var(--fs-xs);
+ color: var(--text-3);
+ }
+ .why {
+ margin: 0;
+ font-size: var(--fs-xs);
+ color: var(--text-2);
+ }
+ .proposed {
+ padding: 0 4px;
+ border-radius: 999px;
+ background: color-mix(in srgb, var(--accent) 16%, transparent);
+ color: color-mix(in srgb, var(--accent) 85%, var(--text-2));
+ font-size: 9px;
+ }
+ .acts {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 6px;
+ }
+ .acts .btn {
+ max-width: 100%;
+ }
+ .acts .label {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+</style>
diff --git a/frontend/src/tools/satellite/PlaceSearch.svelte b/frontend/src/tools/satellite/PlaceSearch.svelte
index e202cf2..050067c 100644
--- a/frontend/src/tools/satellite/PlaceSearch.svelte
+++ b/frontend/src/tools/satellite/PlaceSearch.svelte
@@ -29,6 +29,7 @@
centre = null,
units = 'metric',
searching = false,
+ listId = 'sat-suggestions',
onpick,
onsubmit,
} = $props();
@@ -179,9 +180,9 @@
class="input"
role="combobox"
aria-expanded={open && rows.length > 0}
- aria-controls="sat-suggestions"
+ aria-controls={listId}
aria-autocomplete="list"
- aria-activedescendant={at >= 0 && rows[at] ? `sat-suggestion-${at}` : undefined}
+ aria-activedescendant={at >= 0 && rows[at] ? `${listId}-${at}` : undefined}
autocomplete="off"
aria-label="Search a place or coordinates"
placeholder={'A place, or 50.4501, 30.5234'}
@@ -203,7 +204,7 @@
</div>
{#if open && groups.length}
- <div class="menu card" id="sat-suggestions" role="listbox" aria-label="Matches">
+ <div class="menu card" id={listId} role="listbox" aria-label="Matches">
{#each groups as group (group.id)}
<p class="head">{group.label}</p>
{#each group.items as item (item.key)}
@@ -212,7 +213,7 @@
type="button"
class="row"
class:on={index === at}
- id={`sat-suggestion-${index}`}
+ id={`${listId}-${index}`}
role="option"
aria-selected={index === at}
onmouseenter={() => (at = index)}
diff --git a/frontend/src/tools/satellite/SavedOverlay.render.test.js b/frontend/src/tools/satellite/SavedOverlay.render.test.js
new file mode 100644
index 0000000..c3f99c7
--- /dev/null
+++ b/frontend/src/tools/satellite/SavedOverlay.render.test.js
@@ -0,0 +1,88 @@
+// @vitest-environment happy-dom
+/**
+ * What the saved layer asks the map to draw, for the one kind of mark that has
+ * no card: a located file.
+ *
+ * A photo is read by looking at it, so its mark plays the stack in the panel
+ * instead of opening a card over the map. Everything filed on a point keeps its
+ * card, which is what the rest of SavedPopup.test.js covers.
+ */
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { flushSync, mount, unmount } from 'svelte';
+
+const drawn = [];
+const surface = {
+ set: (shapes) => drawn.push(shapes),
+ element: () => document.createElement('div'),
+ closePopup: vi.fn(),
+ clear: vi.fn(),
+ destroy: vi.fn(),
+};
+vi.mock('../../lib/map/surface.js', () => ({ createSurface: () => surface }));
+
+const { default: SavedOverlay } = await import('./SavedOverlay.svelte');
+
+const engine = { getZoom: () => 16, on: () => () => {} };
+let held = null;
+
+const media = (key, kind = 'image') => ({
+ id: key,
+ key: `${key}@48.1,2.1`,
+ kind: 'media',
+ media_kind: kind,
+ title: key,
+ path: `media/${key}.png`,
+ lat: 48.1,
+ lon: 2.1,
+});
+const place = { id: 'p1', key: 'p1', kind: 'place', title: 'Quay', lat: 48.1, lon: 2.1 };
+
+function draw(items, props = {}) {
+ drawn.length = 0;
+ const target = document.createElement('div');
+ document.body.appendChild(target);
+ held = mount(SavedOverlay, {
+ target,
+ props: { engine, items, caseId: 'case-1', coords: () => '48.1, 2.1', ...props },
+ });
+ flushSync();
+ return (drawn.at(-1) ?? []).filter((shape) => shape.kind === 'marker');
+}
+
+afterEach(() => {
+ if (held) unmount(held);
+ held = null;
+ document.body.innerHTML = '';
+});
+
+describe('a mark of located files', () => {
+ it('answers its own click with the stack, and opens no card', () => {
+ const onmedia = vi.fn();
+ const [mark] = draw([media('quay'), media('roof')], { onmedia });
+ expect(mark.popup).toBeUndefined();
+ mark.onClick();
+ expect(onmedia).toHaveBeenCalledTimes(1);
+ expect(onmedia.mock.calls[0][0].map((row) => row.id)).toEqual(['quay', 'roof']);
+ });
+
+ it('draws footage as footage and photographs as photographs', () => {
+ const [clips] = draw([media('a', 'video'), media('b', 'video')]);
+ expect(clips.html).toContain('saved-mark-media');
+ const [mixed] = draw([media('a', 'video'), media('b', 'image')]);
+ // one glyph for the stack: it says "files here", and the panel says which
+ expect(mixed.html).not.toBe(clips.html);
+ });
+
+ it('leaves the card to everything filed on a point', () => {
+ const [mark] = draw([place]);
+ expect(mark.onClick).toBeUndefined();
+ expect(mark.popup.className).toBe('saved-popup');
+ });
+
+ it('keeps the card where a file shares a spot with saved work', () => {
+ // the mark is no longer only files, and the card is what lists a mixed stack
+ const [mark] = draw([place, media('quay')]);
+ expect(mark.onClick).toBeUndefined();
+ expect(mark.popup).toBeTruthy();
+ });
+});
diff --git a/frontend/src/tools/satellite/SavedOverlay.svelte b/frontend/src/tools/satellite/SavedOverlay.svelte
index e1d7e33..52abdea 100644
--- a/frontend/src/tools/satellite/SavedOverlay.svelte
+++ b/frontend/src/tools/satellite/SavedOverlay.svelte
@@ -18,6 +18,8 @@
coords,
fullscreen = false,
hoveredId = $bindable(null),
+ // the stack the media viewer is reading, lit until it closes
+ activeKey = null,
onopen,
onedit,
onproof,
@@ -25,10 +27,14 @@
onshowproofs,
onrefresh,
ontrace,
+ onmedia,
} = $props();
const GLYPH = { place: 'pin', capture: 'satellite', screenshot: 'screen', proof: 'proof' };
+ /** True when every item under a mark is a located file: it opens the viewer. */
+ const isMedia = (mark) => mark.kinds.every((kind) => kind === 'media');
+
let zoom = $state(null);
// Keep marker elements by item id for hover sync without a rebuild.
@@ -45,6 +51,12 @@
function icon(mark) {
// Mixed stacks use the shared place glyph.
const kind = mark.kinds.length > 1 ? 'place' : mark.kinds[0];
+ // a stack of files draws as footage only when all of it is footage
+ const name = isMedia(mark)
+ ? mark.items.every((row) => row.media_kind === 'video')
+ ? 'video'
+ : 'image'
+ : (GLYPH[kind] ?? 'pin');
const count =
mark.items.length > 1 ? `<i class="saved-mark-count">${mark.items.length}</i>` : '';
// A proof borrowing capture coordinates appears as a dot on that capture.
@@ -53,7 +65,7 @@
: '';
return {
className: 'saved-mark-wrap',
- html: `<span class="saved-mark saved-mark-${kind}">${glyph(GLYPH[kind] ?? 'pin', 13)}${count}${worked}</span>`,
+ html: `<span class="saved-mark saved-mark-${kind}">${glyph(name, 13)}${count}${worked}</span>`,
...TEARDROP,
};
}
@@ -186,15 +198,21 @@
keyboard: false,
onOver: () => (hoveredId = mark.items[0].key ?? mark.items[0].id),
onOut: () => (hoveredId = null),
- // every mark opens its card, one item or five: clicking a pin should
- // tell you what is there before it moves the map out from under you
- popup: {
- content: () => popupContent(mark),
- className: 'saved-popup',
- minWidth: 296,
- maxWidth: 330,
- offset: TEARDROP_CARD_OFFSET,
- },
+ // A file's mark plays it in the panel beside the map, stack and all:
+ // the card is for work filed on a point, and a photo is read by looking.
+ // Every other mark opens its card, one item or five: clicking a pin should
+ // tell you what is there before it moves the map out from under you.
+ ...(isMedia(mark)
+ ? { onClick: () => onmedia?.(mark.items) }
+ : {
+ popup: {
+ content: () => popupContent(mark),
+ className: 'saved-popup',
+ minWidth: 296,
+ maxWidth: 330,
+ offset: TEARDROP_CARD_OFFSET,
+ },
+ }),
},
])
);
@@ -217,6 +235,15 @@
lit = id ? (elements.get(id) ?? null) : null;
lit?.classList.add('is-hovered');
});
+
+ // the mark the viewer is reading, kept lit through hovers elsewhere
+ let reading = null;
+ $effect(() => {
+ const next = activeKey ? (elements.get(activeKey) ?? null) : null;
+ if (reading && reading !== next) reading.classList.remove('is-active');
+ reading = next;
+ reading?.classList.add('is-active');
+ });
</script>
<style>
@@ -276,6 +303,12 @@
background: #fff;
box-shadow: 0 0 0 1.5px rgba(0, 0, 0, 0.55);
}
+ /* a file is outlined in white, so footage reads apart from the imagery work
+ filed around it without leaving the layer's one colour family */
+ :global(.saved-mark-media) {
+ box-shadow: 0 0 0 1.5px #fff, 0 2px 5px rgba(0, 0, 0, 0.45);
+ }
+ :global(.saved-mark-wrap.is-active .saved-mark),
:global(.saved-mark-wrap.is-hovered .saved-mark),
:global(.saved-mark-wrap:hover .saved-mark) {
transform: rotate(-45deg) scale(1.25);
diff --git a/frontend/src/tools/satellite/SavedPopup.test.js b/frontend/src/tools/satellite/SavedPopup.test.js
index 6b2b00b..1cbcf05 100644
--- a/frontend/src/tools/satellite/SavedPopup.test.js
+++ b/frontend/src/tools/satellite/SavedPopup.test.js
@@ -161,10 +161,13 @@ describe('SavedOverlay popup wiring', () => {
expect(overlay).toContain('onpost: close(onpost)');
});
- it('opens a card for every mark, one item or a stack', () => {
+ it('opens a card for every mark of saved work, one item or a stack', () => {
expect(overlay).toContain('content: () => popupContent(mark)');
- // no shortcut path that flies straight there on a single-item mark
- expect(overlay).not.toContain('onClick');
+ // no shortcut path that flies straight there on a single-item mark. A mark of
+ // located files is the one that answers its own click, by playing them in the
+ // panel — there is no card for a photo to open.
+ expect(overlay).toContain('isMedia(mark)\n ? { onClick: () => onmedia?.(mark.items) }');
+ expect((overlay.match(/onClick/g) ?? []).length).toBe(1);
});
it('asks for the width its own rows need, and leaves the look to the map', () => {
diff --git a/frontend/src/tools/satellite/SavedRow.svelte b/frontend/src/tools/satellite/SavedRow.svelte
index fb33523..8cc0990 100644
--- a/frontend/src/tools/satellite/SavedRow.svelte
+++ b/frontend/src/tools/satellite/SavedRow.svelte
@@ -9,6 +9,7 @@
*/
import Icon from '../../components/Icon.svelte';
import { fileUrl } from '../../lib/fileUrl.js';
+ import { roadWords } from '../../lib/mediaViewer.js';
let {
row,
@@ -35,6 +36,11 @@
const isPlace = $derived(row.kind === 'place');
const isProof = $derived(row.kind === 'proof');
+ // a located file: pressing it plays it beside the map, and it is edited in Media
+ const isMedia = $derived(row.kind === 'media');
+ const glyphName = $derived(
+ isMedia ? (row.media_kind === 'video' ? 'video' : 'image') : (GLYPH[row.kind] ?? 'pin')
+ );
// A proof borrows the point of the capture it composes, so `All` marks that
// capture instead of stacking a second mark on it.
const worked = $derived(row.proofs > 0 ? `${row.proofs} proof${row.proofs > 1 ? 's' : ''} built here` : null);
@@ -44,9 +50,11 @@
// one string, ellipsized as a whole: truncating bit by bit leaves stubs like
// "· … ·" in a 300px panel
const meta = $derived(
- [row.zoom != null ? `z${Math.round(row.zoom)}` : null, row.provider ?? row.site, row.imagery_date]
- .filter(Boolean)
- .join(' · ')
+ isMedia
+ ? roadWords(row)
+ : [row.zoom != null ? `z${Math.round(row.zoom)}` : null, row.provider ?? row.site, row.imagery_date]
+ .filter(Boolean)
+ .join(' · ')
);
const blocked = $derived(fullscreen ? 'Exit fullscreen first. This leaves the map' : null);
const proposed = $derived(row.status === 'suggested');
@@ -71,19 +79,21 @@
disabled={!flyable && !opensSource}
title={opensSource
? `Open the source page (${row.site ?? 'external map'})`
- : flyable
- ? 'Fly the map to this point'
- : 'No coordinates recorded'}
+ : isMedia
+ ? 'Fly here and play it beside the map'
+ : flyable
+ ? 'Fly the map to this point'
+ : 'No coordinates recorded'}
onclick={() => onopen(row)}
>
<span class="thumb">
{#if row.thumbnail && caseId}
<img src={fileUrl(caseId, row.thumbnail)} alt="" loading="lazy" decoding="async" />
{:else}
- <Icon name={GLYPH[row.kind] ?? 'pin'} size={dense ? 16 : 14} />
+ <Icon name={glyphName} size={dense ? 16 : 14} />
{/if}
{#if row.thumbnail}
- <span class="badge"><Icon name={GLYPH[row.kind] ?? 'pin'} size={9} /></span>
+ <span class="badge"><Icon name={glyphName} size={9} /></span>
{/if}
{#if worked}<span class="worked" role="img" aria-label={worked} title={worked}></span>{/if}
</span>
@@ -106,6 +116,9 @@
</span>
</button>
+ <!-- A file is renamed, filed and deleted in Media. Here it is something to look
+ at, and the viewer the row opens carries the ways out. -->
+ {#if !isMedia}
<div class="actions">
<!-- Accepting is offered where the point is read, not only in the sidebar:
the analyst is looking at the map that decides whether the point is
@@ -153,6 +166,7 @@
</button>
{/if}
</div>
+ {/if}
</div>
<style>
diff --git a/frontend/src/tools/satellite/SavedTree.svelte b/frontend/src/tools/satellite/SavedTree.svelte
index 4fc6db8..1ccb891 100644
--- a/frontend/src/tools/satellite/SavedTree.svelte
+++ b/frontend/src/tools/satellite/SavedTree.svelte
@@ -218,7 +218,11 @@
<div class="tree">
{#if !rows.length}
- <p class="none">Save a place or capture a crop. Both land here, grouped by where they are.</p>
+ <p class="none">
+ {kind === 'media'
+ ? 'No photo or video is placed yet. Relate one to a place or build a proof on it.'
+ : 'Save a place or capture a crop. Both land here, grouped by where they are.'}
+ </p>
{:else if !shown}
<p class="none">Nothing saved matches that.</p>
{:else}
@@ -346,9 +350,9 @@
.kind:hover {
color: var(--text-1);
}
- /* Proofs is a mode, not a refinement of the three to its left: the rule says
- so without spending a word on it */
- .kind.mode {
+ /* Proofs and Media are modes, not refinements of the three to their left: one
+ rule before the first of them says so without spending a word on it */
+ .kind:not(.mode) + .kind.mode {
margin-left: 5px;
border-left: 1px solid var(--border);
padding-left: 5px;
diff --git a/frontend/src/tools/satellite/state/saved.svelte.js b/frontend/src/tools/satellite/state/saved.svelte.js
index d03242d..eb11cf5 100644
--- a/frontend/src/tools/satellite/state/saved.svelte.js
+++ b/frontend/src/tools/satellite/state/saved.svelte.js
@@ -1,11 +1,12 @@
/**
* The case's saved work, as the Map's panel reads it.
*
- * Two indexes, not one: places, captures and filed screenshots come back in one
- * compact index when a case opens, while proofs are read only once the Proofs
- * position is opened — a case must not pay for a view it may never show. Both
- * are keyed on the case *and its revision*, because filing a proof reloads the
- * case and a stale list would still show the folder the proof just left.
+ * Three indexes, not one: places, captures and filed screenshots come back in
+ * one compact index when a case opens, while proofs and located media are each
+ * read only once their position is opened — a case must not pay for a view it
+ * may never show. Both lazy ones are keyed on the case *and its revision*,
+ * because filing a proof reloads the case and a stale list would still show the
+ * folder the proof just left.
*
* `runLocate` is the one long act here: filling in the country of everything
* that still has none, one batch at a time because Nominatim allows one lookup
@@ -31,10 +32,19 @@ function loadGroup() {
}
}
+/** Where each mode's rows come from. */
+const MODE_INDEX = {
+ proofs: (caseId) => `/api/cases/${caseId}/proofs/index`,
+ media: (caseId) => `/api/cases/${caseId}/satellite/media`,
+};
+
export function createSavedState({ api, notify, assignFolder, reloadCase }) {
let rows = $state([]);
- let proofs = $state([]);
- let kind = $state('all');
+ // one list per mode, read the first time that position is opened
+ let modeRows = $state({ proofs: [], media: [] });
+ // Media first: a map opened on a case answers "what footage do I have, and
+ // where" before it lists every pin the analyst has dropped.
+ let kind = $state('media');
let query = $state('');
/**
* Which folder the map is drawing, or null for every one of them.
@@ -48,16 +58,16 @@ export function createSavedState({ api, notify, assignFolder, reloadCase }) {
let locating = $state(null); // { done, total } while a pass runs
let acceptingId = $state(null);
- let rowsFor = null; // the case id both indexes were loaded for
- let proofsFor = null; // the case id *and revision* the proofs index was read for
+ let rowsFor = null; // the case id every index was loaded for
+ let modeFor = { proofs: null, media: null }; // the case id *and revision* each was read for
let locateStopped = false;
let locateGeneration = 0;
/** Everything a different case must not inherit. */
function reset() {
rows = [];
- proofs = [];
- proofsFor = null;
+ modeRows = { proofs: [], media: [] };
+ modeFor = { proofs: null, media: null };
locateStopped = true;
locateGeneration += 1;
locating = null;
@@ -87,26 +97,28 @@ export function createSavedState({ api, notify, assignFolder, reloadCase }) {
};
}
- /** The proofs index, the first time the Proofs position is opened. */
- function loadProofs(caseId, rev) {
+ /**
+ * The index behind the open mode, the first time that position is opened.
+ *
+ * An answer lands only while its case and revision are still the ones asked
+ * about. Leaving the position before it arrives keeps it rather than throwing
+ * it away: that stamp is already spent, and coming back would find nothing.
+ */
+ function loadMode(caseId, rev) {
+ const mode = kind;
const stamp = `${caseId}:${rev}`;
- if (!caseId || !isMode(kind) || proofsFor === stamp) return () => {};
- proofsFor = stamp;
- let live = true;
+ if (!caseId || !isMode(mode) || modeFor[mode] === stamp) return;
+ modeFor = { ...modeFor, [mode]: stamp };
api
- .get(`/api/cases/${caseId}/proofs/index`)
+ .get(MODE_INDEX[mode](caseId))
.then((answer) => {
- if (live) proofs = answer;
+ if (modeFor[mode] === stamp) modeRows = { ...modeRows, [mode]: answer };
})
.catch(() => {
- if (live) {
- proofs = [];
- proofsFor = null;
- }
+ if (modeFor[mode] !== stamp) return;
+ modeRows = { ...modeRows, [mode]: [] };
+ modeFor = { ...modeFor, [mode]: null };
});
- return () => {
- live = false;
- };
}
async function runLocate(caseId) {
@@ -190,7 +202,7 @@ export function createSavedState({ api, notify, assignFolder, reloadCase }) {
// the sidecar of an image it is not.
const entity = {
id: row.id,
- type: row.kind === 'place' ? 'place' : row.kind === 'proof' ? 'proof' : 'capture',
+ type: ['place', 'proof', 'media'].includes(row.kind) ? row.kind : 'capture',
attrs: { path: row.path },
};
try {
@@ -217,7 +229,10 @@ export function createSavedState({ api, notify, assignFolder, reloadCase }) {
rows = value;
},
get proofs() {
- return proofs;
+ return modeRows.proofs;
+ },
+ get media() {
+ return modeRows.media;
},
get kind() {
return kind;
@@ -259,9 +274,9 @@ export function createSavedState({ api, notify, assignFolder, reloadCase }) {
return acceptingId;
},
- /** Proofs are their own position, and read their own index. */
+ /** Proofs and media are positions of their own, and read their own index. */
get shownRows() {
- return isMode(kind) ? proofs : rows;
+ return isMode(kind) ? modeRows[kind] : rows;
},
/** What the panel is showing, which is also what the map layer draws. */
get shown() {
@@ -273,7 +288,7 @@ export function createSavedState({ api, notify, assignFolder, reloadCase }) {
reset,
load,
- loadProofs,
+ loadMode,
runLocate,
stopLocate: () => (locateStopped = true),
accept,
diff --git a/frontend/src/tools/satellite/state/saved.svelte.test.js b/frontend/src/tools/satellite/state/saved.svelte.test.js
index 9c963e7..41e29c6 100644
--- a/frontend/src/tools/satellite/state/saved.svelte.test.js
+++ b/frontend/src/tools/satellite/state/saved.svelte.test.js
@@ -16,6 +16,10 @@ const ROWS = [
{ id: 'e3', kind: 'screenshot', path: 'media/b.png', title: 'b' },
];
const PROOFS = [{ id: 'p1', kind: 'proof', path: 'proofs/x.png', name: 'x', title: 'x' }];
+const MEDIA = [
+ { id: 'm1', key: 'm1@1,2', kind: 'media', media_kind: 'video', path: 'media/clip.mp4', title: 'clip', lat: 1, lon: 2 },
+ { id: 'm1', key: 'm1@3,4', kind: 'media', media_kind: 'video', path: 'media/clip.mp4', title: 'clip', lat: 3, lon: 4 },
+];
let api;
let notify;
@@ -37,6 +41,7 @@ beforeEach(() => {
get: vi.fn(async (path) => {
calls.push(path);
if (path.includes('/proofs/index')) return PROOFS;
+ if (path.includes('/satellite/media')) return MEDIA;
return ROWS;
}),
post: vi.fn(async () => ({ located: 0, failed: 0, remaining: 0 })),
@@ -53,43 +58,89 @@ describe('opening a case', () => {
expect(calls).toEqual(['/api/cases/case-1/satellite/index']);
});
+ it('opens on located media, the position a map is first read for', () => {
+ expect(store().kind).toBe('media');
+ });
+
it('pays nothing for the proofs index until that position is opened', async () => {
const saved = store();
+ saved.kind = 'all';
saved.load('case-1');
- saved.loadProofs('case-1', 3);
+ saved.loadMode('case-1', 3);
await vi.waitFor(() => expect(saved.rows).toHaveLength(3));
- expect(calls.some((path) => path.includes('/proofs/index'))).toBe(false);
+ expect(calls).toEqual(['/api/cases/case-1/satellite/index']);
saved.kind = 'proofs';
- saved.loadProofs('case-1', 3);
+ saved.loadMode('case-1', 3);
await vi.waitFor(() => expect(saved.proofs).toHaveLength(1));
// …and the proofs position reads its own rows, not the compact index
expect(saved.shownRows).toEqual(PROOFS);
+ expect(calls.some((path) => path.includes('/satellite/media'))).toBe(false);
+ });
+
+ it('reads the media index for the media position, one row per point', async () => {
+ const saved = store();
+ saved.loadMode('case-1', 3);
+ await vi.waitFor(() => expect(saved.media).toHaveLength(2));
+ expect(calls).toEqual(['/api/cases/case-1/satellite/media']);
+ expect(saved.shownRows).toEqual(MEDIA);
+ expect(saved.shown.map((row) => row.key)).toEqual(['m1@1,2', 'm1@3,4']);
});
- it('re-reads the proofs index when the case is reloaded, not only when it changes', async () => {
+ it('re-reads a mode index when the case is reloaded, not only when it changes', async () => {
// filing a proof reloads the case; keying only on the id would leave the
// panel showing the folder the proof just left
const saved = store();
saved.kind = 'proofs';
- saved.loadProofs('case-1', 3);
+ saved.loadMode('case-1', 3);
await vi.waitFor(() => expect(saved.proofs).toHaveLength(1));
const before = api.get.mock.calls.length;
- saved.loadProofs('case-1', 3);
+ saved.loadMode('case-1', 3);
expect(api.get).toHaveBeenCalledTimes(before); // same revision: nothing to re-read
- saved.loadProofs('case-1', 4);
+ saved.loadMode('case-1', 4);
await vi.waitFor(() => expect(api.get.mock.calls.length).toBe(before + 1));
});
- it('drops both indexes before loading a different case', async () => {
+ it('keeps an answer that arrives after the position was left', async () => {
+ // the stamp is spent when the request goes out, so dropping the answer would
+ // leave the position empty until the case happened to reload
+ let release;
+ api.get = vi.fn(() => new Promise((resolve) => (release = () => resolve(MEDIA))));
+ const saved = store();
+ saved.loadMode('case-1', 1);
+ saved.kind = 'all';
+ release();
+ await vi.waitFor(() => expect(saved.media).toHaveLength(2));
+ });
+
+ it('drops every index before loading a different case', async () => {
const saved = store();
saved.load('case-1');
+ saved.loadMode('case-1', 1);
saved.kind = 'proofs';
- saved.loadProofs('case-1', 1);
+ saved.loadMode('case-1', 1);
await vi.waitFor(() => expect(saved.proofs).toHaveLength(1));
+ await vi.waitFor(() => expect(saved.media).toHaveLength(2));
saved.load('case-2');
expect(saved.rows).toEqual([]);
expect(saved.proofs).toEqual([]);
+ expect(saved.media).toEqual([]);
+ });
+
+ it('lands no answer from a case that was left while it was on its way', async () => {
+ let release;
+ api.get = vi.fn(() => new Promise((resolve) => (release = () => resolve(MEDIA))));
+ const saved = store();
+ saved.load('case-1');
+ const first = release;
+ saved.loadMode('case-1', 1);
+ const media = release;
+ saved.load('case-2');
+ first();
+ media();
+ await Promise.resolve();
+ await Promise.resolve();
+ expect(saved.media).toEqual([]);
});
it('ignores an earlier case’s answer once the case has changed', async () => {
@@ -114,6 +165,7 @@ describe('what the panel is showing', () => {
const saved = store();
saved.load('case-1');
await vi.waitFor(() => expect(saved.rows).toHaveLength(3));
+ saved.kind = 'all';
expect(saved.shown).toHaveLength(3);
saved.kind = 'places';
expect(saved.shown.map((row) => row.id)).toEqual(['e1']);
@@ -255,8 +307,15 @@ describe('acting on a row', () => {
{ id: 'e3', type: 'capture', attrs: { path: 'media/b.png' } },
''
);
- expect(reloadCase).toHaveBeenCalledTimes(2);
- expect(notify).toHaveBeenLastCalledWith('Removed from My work', 'ok', 1600);
+ // a photo keeps its sidecar in step, through the media route
+ await saved.move('case-1', { id: 'm1', kind: 'media', path: 'media/clip.mp4' }, 'Quays');
+ expect(assignFolder).toHaveBeenLastCalledWith(
+ 'case-1',
+ { id: 'm1', type: 'media', attrs: { path: 'media/clip.mp4' } },
+ 'Quays'
+ );
+ expect(reloadCase).toHaveBeenCalledTimes(3);
+ expect(notify).toHaveBeenLastCalledWith('Filed in Quays', 'ok', 1600);
});
it('deletes a place as an entity and a capture as a file', async () => {
diff --git a/frontend/src/tools/satellite/state/sentinel.svelte.js b/frontend/src/tools/satellite/state/sentinel.svelte.js
index 9bd003b..0d9f1cf 100644
--- a/frontend/src/tools/satellite/state/sentinel.svelte.js
+++ b/frontend/src/tools/satellite/state/sentinel.svelte.js
@@ -315,6 +315,9 @@ export function createSentinelState({ place, onBilled, notify, api }) {
get date() {
return date;
},
+ set date(value) {
+ date = validDay(value) ? value : '';
+ },
get maxcc() {
return maxcc;
},
diff --git a/frontend/src/tools/settings/ExtensionTab.svelte b/frontend/src/tools/settings/ExtensionTab.svelte
index b0c2f7e..e362682 100644
--- a/frontend/src/tools/settings/ExtensionTab.svelte
+++ b/frontend/src/tools/settings/ExtensionTab.svelte
@@ -24,6 +24,7 @@
extDetected,
extOutdated,
extState,
+ extBundled,
extBusy,
installExtension,
updateExtension,
@@ -40,6 +41,17 @@
// one copy from another, so it only ever says "something is there".
let status = $derived(extState?.status ?? (extDetected ? 'probing' : 'absent'));
let version = $derived(extState?.detectedVersion ?? extDetected);
+
+ // The XPI is attached to the release that last moved the extension, which is
+ // the tag matching its own version — not the newest release. Naming the file
+ // is the difference between a download and a hunt through six assets on a page
+ // that may carry none of them.
+ let xpiName = $derived(extBundled ? `azimut-capture-${extBundled}.xpi` : null);
+ let xpiUrl = $derived(
+ xpiName
+ ? `https://github.com/OsintMeThat/azimut/releases/download/v${extBundled}/${xpiName}`
+ : 'https://github.com/OsintMeThat/azimut/releases/latest',
+ );
</script>
<section class="group">
@@ -169,17 +181,13 @@
paste the path. Then reload this tab.
</p>
<p class="note">
- Firefox: download the signed add-on below, then open
- <span class="mono">about:addons</span> and choose the gear menu → Install Add-on From File.
+ Firefox: download the <span class="mono">.xpi</span> below, then open
+ <span class="mono">about:addons</span> → the gear menu → Install Add-on From File.
</p>
<div class="scraper-actions">
- <a
- class="btn btn-sm dotted"
- href="https://github.com/OsintMeThat/azimut/releases/latest"
- target="_blank"
- rel="noreferrer"
- >
- <Icon name="download" size={13} /> Signed add-on for Firefox
+ <a class="btn btn-sm dotted" href={xpiUrl} target="_blank" rel="noreferrer">
+ <Icon name="download" size={13} />
+ {xpiName ?? 'Signed .xpi for Firefox'}
</a>
<a class="btn btn-sm dotted" href="/api/ingest/extension.zip" download>
<Icon name="download" size={13} /> Download as .zip instead
diff --git a/src/azimut/api/analyzers.py b/src/azimut/api/analyzers.py
new file mode 100644
index 0000000..da81766
--- /dev/null
+++ b/src/azimut/api/analyzers.py
@@ -0,0 +1,302 @@
+"""Compare recipes, saved areas, follow-ups and immutable analysis runs."""
+
+from __future__ import annotations
+
+import io
+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 .. 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 .cases import delete_by_path, delete_entity_deep, get_case
+
+router = APIRouter(prefix="/api", tags=["analyzers"])
+
+
[email protected]("/compare/analyzers")
+def recipes() -> dict[str, Any]:
+ custom = []
+ for raw in config.load_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,
+ "grids": {name: list(pair) for name, pair in engine.GRIDS.items()}}
+
+
[email protected]("/compare/analyzers")
+def save_recipe(body: Recipe) -> dict[str, Any]:
+ if body.id in {r.id for r in BUILTINS} or body.id == "custom":
+ body = body.model_copy(update={"id": f"custom-{secrets.token_hex(6)}"})
+
+ def update(settings: dict[str, Any]) -> None:
+ saved = [r for r in settings.get("analyzers", []) if r.get("id") != body.id]
+ if len(saved) >= 100:
+ raise HTTPException(409, "the analyzer library is full; remove an unused recipe")
+ settings["analyzers"] = [*saved, body.model_dump()]
+
+ config.update_settings(update)
+ return body.model_dump()
+
+
[email protected]("/compare/analyzers/{ident}")
+def delete_recipe(ident: str) -> dict[str, bool]:
+ def update(settings: dict[str, Any]) -> None:
+ settings["analyzers"] = [r for r in settings.get("analyzers", []) if r.get("id") != ident]
+ config.update_settings(update)
+ return {"deleted": True}
+
+
+Kind = Literal["zones", "followups", "runs"]
+
+
+def read(case: Any, kind: str, ident: str) -> dict[str, Any]:
+ try:
+ return engine.read(case, kind, ident)
+ except FileNotFoundError as exc:
+ raise HTTPException(404, "analysis item not found") from exc
+ except (ValueError, OSError) as exc:
+ raise HTTPException(422, "analysis item is unreadable") from exc
+
+
[email protected]("/cases/{case_id}/analysis/{kind}")
+def list_items(case_id: str, kind: Kind) -> list[dict[str, Any]]:
+ return engine.listing(get_case(case_id), kind)
+
+
[email protected]("/cases/{case_id}/analysis/{kind}/{ident}")
+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/zones")
+def save_zones(case_id: str, body: ZoneSet) -> dict[str, Any]:
+ return engine.save(get_case(case_id), "zones", body.model_dump())
+
+
[email protected]("/cases/{case_id}/analysis/zones/{ident}")
+def update_zones(case_id: str, ident: str, body: ZoneSet) -> dict[str, Any]:
+ case = get_case(case_id)
+ read(case, "zones", ident)
+ return engine.save(case, "zones", body.model_dump(), ident)
+
+
[email protected]("/cases/{case_id}/analysis/followups")
+def save_followup(case_id: str, body: RunInput) -> dict[str, Any]:
+ data = body.model_dump()
+ data["followup_id"] = None
+ return engine.save(get_case(case_id), "followups", data)
+
+
[email protected]("/cases/{case_id}/analysis/followups/{ident}")
+def update_followup(case_id: str, ident: str, body: RunInput) -> dict[str, Any]:
+ case = get_case(case_id)
+ read(case, "followups", ident)
+ 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)
+ 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")
+ if body.followup_id:
+ read(case, "followups", body.followup_id)
+ try:
+ planned = engine.plan(body)
+ 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),
+ "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/{ident}/cancel")
+def cancel_run(case_id: str, ident: str) -> dict[str, Any]:
+ case = get_case(case_id)
+ with engine.LOCK, case._lock:
+ saved = read(case, "runs", ident)
+ if saved["status"] in engine.ACTIVE:
+ saved.update(status="cancelled", updated_at=engine.now())
+ media.write_json_atomic(case.resolve_inside(engine.relpath("runs", ident)), saved)
+ return saved
+
+
[email protected]("/cases/{case_id}/analysis/{kind}/{ident}")
+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 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"]
+
+
+def result_of(saved: dict[str, Any], result_id: str) -> dict[str, Any]:
+ if saved.get("status") != "ready":
+ raise HTTPException(409, "results are available after the complete analysis")
+ found = next((r for r in saved["results"] if r["id"] == result_id), None)
+ if found is None:
+ raise HTTPException(404, "candidate not found")
+ return found
+
+
[email protected]("/cases/{case_id}/analysis/runs/{ident}/results/{result_id}")
+def review_result(case_id: str, ident: str, result_id: str, body: Review) -> dict[str, Any]:
+ case = get_case(case_id)
+ with engine.LOCK, case._lock:
+ saved = read(case, "runs", ident)
+ result = result_of(saved, result_id)
+ 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)
+ engine.persist_run(case, saved)
+ return result
+
+
+# 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
+# across the column and smear it. Nearest neighbour keeps every pixel square and
+# invents nothing, so what is on screen is still the sensor's own reading.
+PREVIEW_EDGE = 320
+PREVIEW_MARGIN = 20
+
+
+def source_label(source: dict[str, Any]) -> str:
+ if source.get("provider") == "sentinel2":
+ return str(source.get("date") or "Sentinel-2")
+ return f"Release {source.get('release')}"
+
+
+def kept_entity(case: Any, result: dict[str, Any]) -> dict[str, Any] | None:
+ """The pin a kept candidate put in the case, if it is still there."""
+ ident = result.get("entity_id")
+ return case.get_entity(ident) if ident else None
+
+
+def preview_bytes(case: Any, saved: dict[str, Any], result: dict[str, Any], part: int = 0) -> bytes:
+ if part >= len(result["parts"]):
+ raise HTTPException(404, "candidate evidence part not found")
+ evidence = result["parts"][part]
+ x, y, width, height = evidence["box"]
+ crops = []
+ for key in evidence["frames"]:
+ record = saved["frames"][key]
+ path = case.resolve_inside(record["path"])
+ with Image.open(path) as image:
+ if max(image.size) > 512:
+ raise HTTPException(422, "evidence frame has an unexpected size")
+ crops.append(image.convert("RGB").crop((
+ max(0, x - PREVIEW_MARGIN), max(0, y - PREVIEW_MARGIN),
+ min(image.width, x + width + PREVIEW_MARGIN),
+ min(image.height, y + height + PREVIEW_MARGIN))))
+ edge = max(max(crop.size) for crop in crops)
+ zoom = max(1, min(12, round(PREVIEW_EDGE / edge))) if edge else 1
+ if zoom > 1:
+ crops = [crop.resize((crop.width * zoom, crop.height * zoom), Image.Resampling.NEAREST)
+ for crop in crops]
+ elif edge > PREVIEW_EDGE:
+ for crop in crops:
+ crop.thumbnail((PREVIEW_EDGE, PREVIEW_EDGE))
+
+ gap = 8
+ 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"])]
+ 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))
+ drawing = ImageDraw.Draw(preview)
+ left = 0
+ for label, crop in zip(labels, crops):
+ preview.paste(crop, (left, band))
+ drawing.text((left + 4, 4), label, fill="white", font=font)
+ left += crop.width + gap
+ attribution = ("Copernicus Sentinel data / Sentinel Hub" if
+ saved["input"]["b"]["provider"] == "sentinel2" else "Esri World Imagery Wayback")
+ drawing.text((4, band + body + 5), attribution, fill="#c8ced6", font=small)
+ output = io.BytesIO()
+ preview.save(output, "PNG")
+ return output.getvalue()
+
+
[email protected]("/cases/{case_id}/analysis/runs/{ident}/results/{result_id}/preview")
+def preview(case_id: str, ident: str, result_id: str, part: int = 0) -> Response:
+ if part < 0:
+ raise HTTPException(422, "invalid evidence part")
+ case = get_case(case_id)
+ saved = read(case, "runs", ident)
+ result = result_of(saved, result_id)
+ return Response(preview_bytes(case, saved, result, part), media_type="image/png")
+
+
+class Promotion(Model):
+ title: str = Field(min_length=1, max_length=120)
+
+
[email protected]("/cases/{case_id}/analysis/runs/{ident}/results/{result_id}/promote")
+def promote(case_id: str, ident: str, result_id: str, body: Promotion) -> dict[str, Any]:
+ """Keep one candidate: the single act that puts it in the case.
+
+ Keeping *is* the review, so it records the verdict itself rather than
+ asking for a separate one. A sweep of a hundred candidates leaves nothing
+ behind but the ones an analyst chose here, one at a time.
+ """
+ case = get_case(case_id)
+ with engine.LOCK, case._lock:
+ saved = read(case, "runs", ident)
+ result = result_of(saved, result_id)
+ existing = kept_entity(case, result)
+ if existing:
+ return {"entity": existing, "result": result}
+ # The promoted copy carries its own before/after and provenance so
+ # 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),
+ body.title, ".png", source, by="compare")
+ lon, lat = result["coordinates"]
+ 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"],
+ "analysis_provenance": source}, by="compare")
+ result.update(entity_id=entity["id"], review="kept", reviewed_at=engine.now())
+ engine.persist_run(case, saved)
+ return {"entity": entity, "image": filed["item"]["path"], "result": result}
+
+
[email protected]("/cases/{case_id}/analysis/runs/{ident}/results/{result_id}/promote")
+def unpromote(case_id: str, ident: str, result_id: str) -> dict[str, Any]:
+ """Undo keeping: the pin and its evidence go to Trash, the candidate returns."""
+ case = get_case(case_id)
+ with engine.LOCK, case._lock:
+ saved = read(case, "runs", ident)
+ result = result_of(saved, result_id)
+ entity = kept_entity(case, result)
+ removed = delete_entity_deep(case, entity["id"]) if entity else None
+ result.update(entity_id=None, review="new", reviewed_at=engine.now())
+ engine.persist_run(case, saved)
+ return {"result": result, "deleted": removed}
diff --git a/src/azimut/api/cases/__init__.py b/src/azimut/api/cases/__init__.py
index 17a1b99..3fbdaa7 100644
--- a/src/azimut/api/cases/__init__.py
+++ b/src/azimut/api/cases/__init__.py
@@ -33,6 +33,7 @@ from .registry import router as _registry
from .timeline import router as _timeline
from .timeline import timeline
from .trash import router as _trash
+from .todos import router as _todos
router = APIRouter()
# Literal paths first — see the module docstring.
@@ -49,6 +50,7 @@ for _sub in (
_timeline,
_trash,
_folders,
+ _todos,
):
router.include_router(_sub)
diff --git a/src/azimut/api/cases/todos.py b/src/azimut/api/cases/todos.py
new file mode 100644
index 0000000..b7f00c7
--- /dev/null
+++ b/src/azimut/api/cases/todos.py
@@ -0,0 +1,55 @@
+"""Small case checklists, stored as manifest metadata and carried by bundles."""
+
+from typing import Annotated
+
+from fastapi import APIRouter, HTTPException
+from pydantic import BaseModel, Field, StringConstraints, model_validator
+
+from .common import get_case
+
+router = APIRouter(prefix="/api/cases", tags=["cases"])
+Name = Annotated[str, StringConstraints(strip_whitespace=True, min_length=1, max_length=120)]
+Text = Annotated[str, StringConstraints(strip_whitespace=True, min_length=1, max_length=2000)]
+Identifier = Annotated[str, StringConstraints(pattern=r"^[a-zA-Z0-9_-]{1,64}$")]
+
+
+class Task(BaseModel):
+ id: Identifier
+ text: Text
+ done: bool = False
+
+
+class TodoList(BaseModel):
+ id: Identifier
+ name: Name
+ tasks: list[Task] = Field(default_factory=list, max_length=200)
+
+
+class Todos(BaseModel):
+ revision: int = Field(ge=0)
+ lists: list[TodoList] = Field(max_length=50)
+
+ @model_validator(mode="after")
+ def unique_ids(self):
+ ids = [entry.id for entry in self.lists]
+ if len(set(ids)) != len(ids):
+ raise ValueError("duplicate list ids")
+ for entry in self.lists:
+ ids = [task.id for task in entry.tasks]
+ if len(set(ids)) != len(ids):
+ raise ValueError("duplicate task ids")
+ return self
+
+
[email protected]("/{case_id}/todos")
+def read_todos(case_id: str):
+ return get_case(case_id).read_todos()
+
+
[email protected]("/{case_id}/todos")
+def save_todos(case_id: str, body: Todos):
+ case = get_case(case_id)
+ with case.lock:
+ if case.read_todos()["revision"] != body.revision:
+ raise HTTPException(409, "This to-do list changed in another tab. Reload it before editing.")
+ return case.write_todos(body.model_dump())
diff --git a/src/azimut/api/compare.py b/src/azimut/api/compare.py
new file mode 100644
index 0000000..50ea88e
--- /dev/null
+++ b/src/azimut/api/compare.py
@@ -0,0 +1,649 @@
+"""Saved Compare sessions, their rendered image and animated exports.
+
+A session stores the reading, not its pixels: the two providers and their
+variants, independent reference layers, the shared camera, the comparison mode,
+Change assist settings and ground-anchored annotations. It lives under
+``.compare/``.
+
+Its rendered image is a media working file, filed through the media pipeline
+with ``source.type = "compare"`` so the Media Library holds it back with the
+other files the app produced. Saving the session again replaces that one file
+instead of adding another, unless something was already derived from it: a
+proof built on a comparison must keep the pixels it was built on, so the new
+render then becomes a new file and the session points at it.
+
+Finished copies go to the configured export destination and are not case state.
+"""
+
+from __future__ import annotations
+
+import io
+import json
+import warnings
+from datetime import datetime, timezone
+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 .. import config, layout
+from ..engine import artifacts as artifact_engine
+from ..engine import exportdir, sentinel, tiles
+from ..engine import links as link_engine
+from ..engine import media as media_engine
+from ..workspace import Case, CaseError
+from .cases import delete_by_path, get_case
+from .naming import read_created_at, slugify
+
+router = APIRouter(prefix="/api", tags=["compare"])
+
+OVERLAYS = frozenset({
+ "labels", "boundaries", "roads", "railway", "power", "seamarks", "gpstraces",
+ "firms", "nightlights", "saved",
+})
+MAX_FRAME_BYTES = 24_000_000
+MAX_GIF_PIXELS = 16_000_000
+MAX_GIF_EDGE = 1280
+#: Two PNGs plus multipart framing, enforced before uploads are materialised.
+MAX_GIF_BODY_BYTES = MAX_FRAME_BYTES * 2 + 1_000_000
+#: What a saved comparison's media sidecar records as its producer.
+SOURCE_TYPE = "compare"
+
+_DAY = r"^(|\d{4}-\d{2}-\d{2})$"
+
+
+class CompareCamera(BaseModel):
+ lat: float = Field(ge=-90, le=90)
+ lon: float = Field(ge=-180, le=180)
+ zoom: float = Field(ge=0, le=24)
+ bearing: float = Field(default=0, ge=0, lt=360)
+
+
+class CompareSentinel(BaseModel):
+ layer: str = Field(default="TRUE_COLOR", min_length=1, max_length=100)
+ date: str = Field(default="", pattern=_DAY)
+ maxcc: int = Field(default=100, ge=0, le=100)
+
+
+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)
+ first: str = Field(default="", pattern=_DAY)
+ last: str = Field(default="", pattern=_DAY)
+
+
+class CompareNightlights(BaseModel):
+ source: Literal["noaa20", "snpp", "composite"] = "noaa20"
+ day: str = Field(default="", pattern=_DAY)
+
+
+class CompareSide(BaseModel):
+ present: bool = False
+ provider: str = Field(default="esri-world-imagery", min_length=1, max_length=500)
+ 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)
+ firms: CompareFirms = Field(default_factory=CompareFirms)
+ nightlights: CompareNightlights = Field(default_factory=CompareNightlights)
+
+
+ChangeClass = Literal["gain", "loss", "changed"]
+
+
+def _change_classes() -> list[ChangeClass]:
+ return ["gain", "loss", "changed"]
+
+
+class CompareChangeAssist(BaseModel):
+ method: Literal["colour", "structure", "brightness", "index"] = "colour"
+ index: Literal["ndvi", "ndwi", "nbr", "ndbi"] = "ndvi"
+ threshold: Literal["auto", "manual"] = "auto"
+ sensitivity: int = Field(default=55, ge=0, le=100)
+ normalize: Literal["none", "mean", "histogram"] = "histogram"
+ smoothing: int = Field(default=1, ge=0, le=4)
+ alignment: int = Field(default=4, ge=0, le=8)
+ cleanup: int = Field(default=1, ge=0, le=3)
+ min_area: float = Field(default=0, ge=0, le=1_000_000)
+ ignore_clouds: bool = False
+ ignore_shadows: bool = False
+ # How far to grow the cloud and shadow mask, in working pixels.
+ cloud_margin: int = Field(default=2, ge=0, le=10)
+ classes: list[ChangeClass] = Field(
+ default_factory=_change_classes, max_length=3
+ )
+ display: Literal["heat", "classes", "outline"] = "classes"
+ 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
+ live: bool = True
+
+
+AnnotationKind = Literal[
+ "text", "arrow", "line", "rect", "ellipse", "freehand", "measure", "polygon"
+]
+#: How many ground points each kind holds: an exact count, or (minimum, maximum).
+_POINT_COUNTS: dict[str, tuple[int, int]] = {
+ "text": (1, 1),
+ "arrow": (2, 2),
+ "line": (2, 2),
+ "measure": (2, 2),
+ "rect": (2, 2),
+ "ellipse": (2, 2),
+ "freehand": (2, 400),
+ "polygon": (3, 200),
+}
+
+
+class CompareAnnotation(BaseModel):
+ """One mark pinned to the ground, so it follows the imagery under it."""
+
+ id: str = Field(min_length=1, max_length=80)
+ kind: AnnotationKind
+ side: Literal["both", "a", "b"] = "both"
+ colour: str = Field(pattern=r"^#[0-9A-Fa-f]{6}$")
+ #: ``[lon, lat]`` pairs.
+ points: list[tuple[float, float]] = Field(min_length=1, max_length=400)
+ stroke_width: int = Field(default=3, ge=1, le=24)
+ fill_opacity: float = Field(default=0, ge=0, le=1)
+ font_size: int = Field(default=16, ge=8, le=72)
+ text: str = Field(default="", max_length=240)
+
+ @model_validator(mode="after")
+ def _shape(self) -> "CompareAnnotation":
+ low, high = _POINT_COUNTS[self.kind]
+ if not low <= len(self.points) <= high:
+ raise ValueError(f"a {self.kind} annotation holds {low} to {high} points")
+ for lon, lat in self.points:
+ if not (-180 <= lon <= 180 and -90 <= lat <= 90):
+ raise ValueError("annotation points must be WGS84 longitude and latitude")
+ if self.kind == "text" and not self.text.strip():
+ raise ValueError("a text annotation needs text")
+ return self
+
+
+class CompareBlink(BaseModel):
+ interval: int = Field(default=800, ge=200, le=4000)
+
+
+class CompareSpec(BaseModel):
+ version: Literal[2] = 2
+ camera: CompareCamera
+ mode: Literal["side", "swipe", "opacity", "blink", "change"] = "side"
+ divider: int = Field(default=50, ge=0, le=100)
+ opacity: int = Field(default=50, ge=0, le=100)
+ blink: CompareBlink = Field(default_factory=CompareBlink)
+ change_assist: CompareChangeAssist = Field(default_factory=CompareChangeAssist)
+ annotations: list[CompareAnnotation] = Field(default_factory=list, max_length=200)
+ a: CompareSide
+ b: CompareSide
+
+
+class SessionIn(BaseModel):
+ rename_from: str | None = None
+ overwrite: bool = False
+ title: str = Field(min_length=1, max_length=200)
+ spec: CompareSpec
+
+
+def _now() -> str:
+ return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
+
+
+def _validated_spec(spec: CompareSpec) -> dict[str, Any]:
+ cleaned = spec.model_dump()
+ for key in ("a", "b"):
+ side = cleaned[key]
+ try:
+ tiles.get_provider(side["provider"])
+ except KeyError as exc:
+ raise HTTPException(status_code=422, detail=str(exc)) from exc
+ unknown = set(side["overlays"]) - OVERLAYS
+ if unknown:
+ raise HTTPException(
+ status_code=422,
+ detail=f"unknown comparison layer '{sorted(unknown)[0]}'",
+ )
+ # Repeating a layer has no visual meaning and makes session diffs noisy.
+ side["overlays"] = list(dict.fromkeys(side["overlays"]))
+ assist = cleaned["change_assist"]
+ assist["classes"] = list(dict.fromkeys(assist["classes"]))
+ for mark in cleaned["annotations"]:
+ mark["points"] = [list(point) for point in mark["points"]]
+ if cleaned["mode"] == "change":
+ reason = change_refusal(cleaned["a"], cleaned["b"], assist["method"])
+ if reason:
+ raise HTTPException(status_code=422, detail=reason)
+ return cleaned
+
+
+def _same_layers(a: dict[str, Any], b: dict[str, Any], *, skip: str | None = None) -> bool:
+ left = set(a["overlays"])
+ right = set(b["overlays"])
+ if skip:
+ left.discard(skip)
+ right.discard(skip)
+ if left != right:
+ return False
+ if "firms" in left and a["firms"] != b["firms"]:
+ return False
+ if "nightlights" in left and a["nightlights"] != b["nightlights"]:
+ return False
+ return True
+
+
+_ESRI_CHAIN = frozenset({"esri-world-imagery", "esri-wayback"})
+
+
+def change_refusal(a: dict[str, Any], b: dict[str, Any], method: str = "colour") -> str | None:
+ """Why a raw pixel reading of this pair would mislead, or None when it is fair.
+
+ Mirrors ``changeCompatibility`` in ``lib/map/changeAssist.js``, which also
+ grades a fair pair as matched or indicative. The server only refuses; the
+ grade is explanation, and the browser shows it.
+ """
+ if not a["present"] or not b["present"]:
+ return "Change assist needs imagery A and B"
+ if method == "index":
+ if a["provider"] != "sentinel2" or b["provider"] != "sentinel2":
+ return "Spectral indices need Sentinel-2 on both sides"
+ if not a["sentinel"]["date"] or not b["sentinel"]["date"]:
+ return "Spectral indices need a dated pass on both sides"
+ if a["sentinel"]["date"] == b["sentinel"]["date"]:
+ return "Choose two different Sentinel-2 passes"
+ return None
+ if a["provider"] == b["provider"] == "sentinel2":
+ if not a["sentinel"]["date"] or not b["sentinel"]["date"]:
+ return "Choose a dated Sentinel-2 pass on both sides"
+ if a["sentinel"]["date"] == b["sentinel"]["date"]:
+ return "Choose two different Sentinel-2 passes"
+ if a["sentinel"]["layer"] != b["sentinel"]["layer"]:
+ return "Sentinel-2 needs the same layer on both sides"
+ 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"]
+ and a["wayback_release"] == b["wayback_release"]
+ )
+ if same_picture:
+ return "Choose two different Esri releases"
+ if not _same_layers(a, b):
+ return "Match the reference layers on A and B"
+ return None
+ night_a = "nightlights" in a["overlays"]
+ night_b = "nightlights" in b["overlays"]
+ if night_a and night_b:
+ if a["provider"] != b["provider"]:
+ return "Night lights need the same background imagery on A and B"
+ if a["nightlights"]["source"] != b["nightlights"]["source"]:
+ return "Night lights need the same VIIRS product on A and B"
+ if a["nightlights"]["source"] == "composite":
+ return "The night-light composite has one date only"
+ if (
+ not a["nightlights"]["day"]
+ or not b["nightlights"]["day"]
+ or a["nightlights"]["day"] == b["nightlights"]["day"]
+ ):
+ return "Choose two different nights"
+ if a["sentinel"] != b["sentinel"] or a["wayback_release"] != b["wayback_release"]:
+ return "Match the background imagery on A and B"
+ if not _same_layers(a, b, skip="nightlights"):
+ return "Match every other layer on A and B"
+ return None
+ return "Change assist reads Sentinel-2, Esri imagery releases or VIIRS night-light pairs"
+
+
+def _read_session(case: Case, name: str) -> dict[str, Any] | None:
+ try:
+ path = case.resolve_inside(layout.compare_session_rel(name))
+ except CaseError:
+ return None
+ try:
+ saved = json.loads(path.read_text(encoding="utf-8"))
+ except (OSError, json.JSONDecodeError):
+ return None
+ return saved if saved.get("azimut_compare") == 1 else None
+
+
+def _preview_of(case: Case, spec_rel: str) -> str | None:
+ """The media working file a session renders into, if it still exists."""
+ entity = case.find_entity(attr="spec", value=spec_rel)
+ preview = (entity.get("attrs") or {}).get("preview") if entity else None
+ if not isinstance(preview, str) or not preview:
+ return None
+ try:
+ return preview if case.resolve_inside(preview).is_file() else None
+ except CaseError:
+ return None
+
+
[email protected]("/cases/{case_id}/compare/sessions")
+def list_sessions(case_id: str) -> list[dict[str, Any]]:
+ case = get_case(case_id)
+ out = []
+ folder = case.subdir(layout.COMPARE_DIR)
+ for path in sorted(folder.glob("*.json")):
+ saved = _read_session(case, path.stem)
+ if saved is None:
+ continue
+ spec = saved.get("spec") or {}
+ out.append({
+ "name": path.stem,
+ "title": saved.get("title", path.stem),
+ "updated_at": saved.get("updated_at"),
+ "provider_a": (spec.get("a") or {}).get("provider"),
+ "provider_b": (spec.get("b") or {}).get("provider"),
+ "mode": spec.get("mode", "side"),
+ "preview": _preview_of(case, layout.compare_session_rel(path.stem)),
+ })
+ out.sort(key=lambda item: item.get("updated_at") or "", reverse=True)
+ return out
+
+
[email protected]("/cases/{case_id}/compare/sessions/{name}")
+def load_session(case_id: str, name: str) -> dict[str, Any]:
+ case = get_case(case_id)
+ try:
+ path = case.resolve_inside(layout.compare_session_rel(name))
+ except CaseError as exc:
+ raise HTTPException(status_code=403, detail=str(exc)) from exc
+ if not path.exists():
+ raise HTTPException(status_code=404, detail="comparison session not found")
+ saved = _read_session(case, name)
+ if saved is None:
+ raise HTTPException(status_code=422, detail="that is not a readable comparison session")
+ return {**saved, "preview": _preview_of(case, layout.compare_session_rel(name))}
+
+
[email protected]("/cases/{case_id}/compare/sessions")
+def save_session(case_id: str, body: SessionIn) -> dict[str, Any]:
+ case = get_case(case_id)
+ case.subdir(layout.COMPARE_DIR).mkdir(parents=True, exist_ok=True)
+ name = slugify(body.title, "Comparison")
+ rel = layout.compare_session_rel(name)
+ path = case.resolve_inside(rel)
+ old = slugify(body.rename_from, "Comparison") if body.rename_from else None
+ old_rel = layout.compare_session_rel(old) if old and old != name else None
+ if old_rel and path.exists():
+ raise HTTPException(status_code=409, detail="another comparison already uses that name")
+ if body.rename_from is None and path.exists() and not body.overwrite:
+ raise HTTPException(status_code=409, detail="a comparison already uses that name")
+
+ previous = case.resolve_inside(layout.compare_session_rel(old or name))
+ saved = {
+ "azimut_compare": 1,
+ "title": name,
+ "created_at": read_created_at(previous) or _now(),
+ "updated_at": _now(),
+ "spec": _validated_spec(body.spec),
+ }
+ media_engine.write_json_atomic(path, saved)
+
+ existing = case.find_entity(attr="spec", value=old_rel or rel)
+ if existing:
+ patch: dict[str, Any] = {"label": name}
+ if old_rel:
+ patch["attrs"] = {"spec": rel}
+ case.update_entity(existing["id"], patch)
+ else:
+ case.add_entity("compare-session", name, attrs={"spec": rel}, by="compare")
+ if old_rel:
+ case.resolve_inside(old_rel).unlink(missing_ok=True)
+ return {"name": name, "title": name, "spec_path": rel}
+
+
+def _gif_bytes(a: Image.Image, b: Image.Image, animation: str, interval: int = 700) -> bytes:
+ frames = _gif_frames(a, b, animation)
+ palette = [
+ frame.quantize(colors=192, method=Image.Quantize.MEDIANCUT)
+ for frame in frames
+ ]
+ buf = io.BytesIO()
+ palette[0].save(
+ buf,
+ "GIF",
+ save_all=True,
+ append_images=palette[1:],
+ duration=interval if animation == "blink" else 90,
+ loop=0,
+ optimize=True,
+ disposal=2,
+ )
+ return buf.getvalue()
+
+
+def _in_use(case: Case, entity_id: str) -> bool:
+ """Whether anything in the case was derived from, or depends on, this file."""
+ for link in case.links_touching(
+ [entity_id], types=[link_engine.DERIVED_FROM, link_engine.DEPENDS_ON]
+ ):
+ if link.get("to") == entity_id:
+ return True
+ return False
+
+
[email protected]("/cases/{case_id}/compare/sessions/{name}/preview")
+async def save_session_preview(
+ case_id: str,
+ name: str,
+ image_a: UploadFile = File(),
+ image_b: UploadFile | None = File(default=None),
+ format_: Literal["png", "blink"] = Form(alias="format"),
+ interval: int = Form(default=800, ge=200, le=4000),
+) -> dict[str, Any]:
+ """File the rendered comparison as the session's media working file.
+
+ One file per session: a later save replaces its bytes in place, unless the
+ format changed or something was derived from it, in which case the render
+ becomes a new file (see the module docstring).
+ """
+ case = get_case(case_id)
+ canonical = slugify(name, "Comparison")
+ spec_rel = layout.compare_session_rel(canonical)
+ session = _read_session(case, canonical)
+ entity = case.find_entity(attr="spec", value=spec_rel)
+ if session is None or entity is None:
+ raise HTTPException(status_code=404, detail="comparison session not found")
+
+ a = await _read_png(image_a, "A")
+ if format_ == "blink":
+ if image_b is None:
+ raise HTTPException(status_code=422, detail="a blink preview needs image B")
+ b = await _read_png(image_b, "B")
+ data = _gif_bytes(a, b, "blink", interval)
+ suffix = ".gif"
+ else:
+ out = io.BytesIO()
+ a.save(out, "PNG", optimize=True)
+ data = out.getvalue()
+ suffix = ".png"
+
+ spec = session["spec"]
+ camera = spec["camera"]
+ source = {
+ "type": SOURCE_TYPE,
+ "session": spec_rel,
+ "mode": spec["mode"],
+ "providers": {"a": spec["a"]["provider"], "b": spec["b"]["provider"]},
+ "lat": camera["lat"],
+ "lon": camera["lon"],
+ "zoom": camera["zoom"],
+ "bearing": camera["bearing"],
+ "rendered_at": _now(),
+ # The composer writes both provider credits into the image footer.
+ "attribution_burned": True,
+ }
+ attrs = {"lat": camera["lat"], "lon": camera["lon"], "compare_session": spec_rel}
+
+ current = _preview_of(case, spec_rel)
+ current_entity = case.find_entity(attr="path", value=current) if current else None
+ replaced = False
+ try:
+ if (
+ current
+ and current_entity
+ and current.endswith(suffix)
+ and not _in_use(case, current_entity["id"])
+ ):
+ media_engine.replace_rendered_bytes(case, current, data, source, extra_attrs=attrs)
+ rel = current
+ if case.resolve_inside(current).stem != canonical:
+ rel = media_engine.rename_media(case, current, canonical)["path"]
+ replaced = True
+ else:
+ filed = media_engine.import_rendered_bytes(
+ case, data, canonical, suffix, source, by="compare", extra_attrs=attrs
+ )
+ rel = filed["item"]["path"]
+ # A render nothing was built on is the session's alone: the old
+ # format goes to the Trash rather than lingering beside the new one.
+ if current and current_entity and not _in_use(case, current_entity["id"]):
+ delete_by_path(case, current)
+ case.update_entity(entity["id"], {"attrs": {"preview": rel}})
+ except (OSError, ValueError, CaseError) as exc:
+ raise HTTPException(status_code=409, detail=f"could not save the image: {exc}") from exc
+ return {"path": rel, "format": format_, "replaced": replaced}
+
+
[email protected]("/cases/{case_id}/compare/sessions/{name}")
+def delete_session(case_id: str, name: str) -> dict[str, Any]:
+ """Delete the editable session. Its rendered image stays in Media."""
+ case = get_case(case_id)
+ rel = layout.compare_session_rel(slugify(name, "Comparison"))
+ try:
+ case.resolve_inside(rel)
+ except CaseError as exc:
+ raise HTTPException(status_code=403, detail=str(exc)) from exc
+ result = delete_by_path(case, rel)
+ if not result["deleted"]:
+ artifact_engine.delete(case, {"type": "compare-session", "attrs": {"spec": rel}})
+ return result
+
+
+async def _read_png(upload: UploadFile, side: str) -> Image.Image:
+ raw = await upload.read(MAX_FRAME_BYTES + 1)
+ if len(raw) > MAX_FRAME_BYTES:
+ raise HTTPException(status_code=413, detail=f"comparison frame {side} is too large")
+ try:
+ with warnings.catch_warnings():
+ warnings.simplefilter("error", Image.DecompressionBombWarning)
+ opened = Image.open(io.BytesIO(raw))
+ if opened.format != "PNG":
+ raise ValueError("not a PNG")
+ frame = opened.convert("RGB")
+ except (Image.DecompressionBombWarning, Image.DecompressionBombError) as exc:
+ raise HTTPException(status_code=413, detail=f"comparison frame {side} is too large") from exc
+ except Exception as exc:
+ raise HTTPException(status_code=422, detail=f"comparison frame {side} is unreadable") from exc
+ if frame.width * frame.height > MAX_GIF_PIXELS:
+ raise HTTPException(status_code=413, detail=f"comparison frame {side} has too many pixels")
+ return frame
+
+
+def _gif_frames(a: Image.Image, b: Image.Image, animation: str) -> list[Image.Image]:
+ if max(a.size) > MAX_GIF_EDGE:
+ scale = MAX_GIF_EDGE / max(a.size)
+ a = a.resize(
+ (max(1, round(a.width * scale)), max(1, round(a.height * scale))),
+ Image.Resampling.LANCZOS,
+ )
+ if b.size != a.size:
+ b = b.resize(a.size, Image.Resampling.LANCZOS)
+ if animation == "blink":
+ return [a, b]
+ positions = [0, 13, 25, 38, 50, 63, 75, 88, 100, 88, 75, 63, 50, 38, 25, 13]
+ frames = []
+ for percent in positions:
+ split = round(a.width * percent / 100)
+ frame = a.copy()
+ if split < a.width:
+ frame.paste(b.crop((split, 0, a.width, a.height)), (split, 0))
+ frames.append(frame)
+ return frames
+
+
[email protected]("/cases/{case_id}/compare/gif")
+async def export_gif(
+ case_id: str,
+ image_a: UploadFile,
+ image_b: UploadFile,
+ animation: Literal["blink", "slide"] = Form(),
+ interval: int = Form(default=800, ge=200, le=4000),
+ filename: str = Form(default="comparison", min_length=1, max_length=120),
+) -> dict[str, str]:
+ """Write a bounded animation to the configured export destination."""
+ case = get_case(case_id)
+ a = await _read_png(image_a, "A")
+ b = await _read_png(image_b, "B")
+ data = _gif_bytes(a, b, animation, interval)
+ name = f"{layout.slugify(filename, 'comparison')}-{animation}.gif"
+ try:
+ export_destination = exportdir.destination("views", case.path)
+ in_case = export_destination == layout.subdir(case.path, "exports")
+ if in_case:
+ path = export_destination / name
+ path.write_bytes(data)
+ else:
+ path = exportdir.write_out(data, export_destination, name)
+ except (OSError, exportdir.ExportDirError) as exc:
+ raise HTTPException(status_code=409, detail=f"could not write the GIF: {exc}") from exc
+ return {"file": path.name, "path": str(export_destination), "animation": animation}
+
+
+class IndexFrameIn(BaseModel):
+ """A Web Mercator box, its pixel size, and the pass to read an index from."""
+
+ west: float
+ south: float
+ east: float
+ north: float
+ width: int = Field(ge=1, le=sentinel.PRODUCT_MAX_EDGE)
+ height: int = Field(ge=1, le=sentinel.PRODUCT_MAX_EDGE)
+ day: str = Field(pattern=r"^\d{4}-\d{2}-\d{2}$")
+ index: Literal["ndvi", "ndwi", "nbr", "ndbi"]
+ maxcc: int = Field(default=100, ge=0, le=100)
+ layer: str = Field(default="TRUE_COLOR", min_length=1, max_length=40)
+
+
[email protected]("/compare/sentinel-index")
+def sentinel_index(body: IndexFrameIn) -> Response:
+ """Render one Sentinel-2 spectral index over the compared frame.
+
+ Asked only when the analyst runs Change assist in index mode. One metered
+ Sentinel Hub request per side, refused like the tiles once the monthly
+ free tier is nearly spent.
+ """
+ instance = (config.load_settings().get("api_keys") or {}).get("sentinelhub")
+ if not instance:
+ raise HTTPException(status_code=404, detail="no Sentinel Hub key saved")
+ 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:
+ data = sentinel.band_frame(
+ instance,
+ (body.west, body.south, body.east, body.north),
+ body.width,
+ body.height,
+ body.day,
+ body.index,
+ body.maxcc,
+ layer=body.layer,
+ )
+ except ValueError as exc:
+ # refused before anything was sent, so nothing is metered
+ raise HTTPException(status_code=422, detail=str(exc)) from exc
+ except Exception as exc:
+ config.record_usage("sentinelhub", 1)
+ raise HTTPException(status_code=502, detail=f"index request failed: {exc}") from exc
+ config.record_usage("sentinelhub", 1)
+ return Response(content=data, media_type="image/png", headers={"Cache-Control": "no-store"})
diff --git a/src/azimut/api/ingest.py b/src/azimut/api/ingest.py
index 8a64b7a..828a47d 100644
--- a/src/azimut/api/ingest.py
+++ b/src/azimut/api/ingest.py
@@ -733,17 +733,22 @@ def mark_grid(body: GridMarksIn) -> dict[str, Any]:
#: a settings file is not something the extension has any business asking for.
HANDOFF_DIRS = ("media", "proofs")
-#: Ceiling for one handed-over file. It crosses the extension's worker/page
-#: boundary as base64 in a message, so this is a real limit rather than a policy:
-#: 48 MB of file is ~64 MB of string, held on both sides while the page rebuilds
-#: the file. A clip refused here is a clip the analyst attaches by hand, which is
-#: what they did before.
-MAX_HANDOFF_BYTES = 48 * 1024 * 1024
+#: Ceiling for one handed-over file. The extension reads it back a chunk at a
+#: time (``Range``, which ``FileResponse`` answers), so what either side holds is
+#: one chunk and never the file — the number is about what is worth carrying into
+#: someone else's page at all, not about the message. A reference window on a
+#: foreign map is meant to reach the same clip the Satellite tab opens, and that
+#: tab streams from disk with no ceiling of its own.
+#:
+#: The composer keeps a smaller one of its own (``MAX_COMPOSER_BYTES`` in
+#: ``extension/background.js``): a thread's attachments are pushed into the page
+#: whole, in one injected payload, so there the string really is the limit.
+MAX_HANDOFF_BYTES = 512 * 1024 * 1024
@router.get("/file", dependencies=[Depends(require_token)])
def handoff_file(case_id: str, path: str) -> Response:
- """One case attachment, for the extension to put in a composer.
+ """One case attachment, for the extension to put in a composer or a window.
The extension holds the pairing token, so it can already file captures and list
cases; this lets it read back the two folders a post attaches from. Narrow on
@@ -753,6 +758,9 @@ def handoff_file(case_id: str, path: str) -> Response:
``resolve_inside`` refuses traversal out of the case, which leaves
``media/../case.json`` — inside the case, and not an attachment. Reading the
prefix off the request would have handed that over.
+
+ ``FileResponse`` serves a ``Range`` request itself, which is what lets a
+ reference window pull a long video across in pieces.
"""
case = get_case(case_id)
try:
diff --git a/src/azimut/api/proofs.py b/src/azimut/api/proofs.py
index b86dd49..1f25cf0 100644
--- a/src/azimut/api/proofs.py
+++ b/src/azimut/api/proofs.py
@@ -32,9 +32,11 @@ from ..engine import links as link_engine
from ..engine import media as media_engine
from ..engine import reveal as reveal_engine
from ..engine import satellite as satellite_engine
+from ..engine import temporal
from ..engine import thumbnails as thumbnail_engine
from ..workspace import Case, CaseError, ensure_dir
from .cases import delete_by_path, get_case
+from .cases.common import delete_entity_deep
from .drafts import list_drafts
from .naming import read_created_at, slugify
from .satellite import locate_on_save
@@ -106,6 +108,41 @@ def _write_spec(path: Path, spec: dict[str, Any]) -> None:
path.write_text(json.dumps(spec, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
+#: What a proof says about itself in words and in time, beside the composition.
+#: Both are optional — a proof with neither is the proof this app shipped with —
+#: and both are mirrored onto the entity, so the graph, the Timeline and search
+#: read them without opening one JSON file per proof.
+_STATED_TEXT_MAX = 2000
+
+
+def _stated_when(spec: dict[str, Any]) -> str:
+ """The date the proof states, checked against the profile the case stores.
+
+ Refused here rather than stored and puzzled over later: a value the temporal
+ parser cannot read would reach the Timeline as a parse error on a row nobody
+ asked for, and the composer has the same profile in front of the analyst.
+ """
+ raw = spec.get("when")
+ if raw in (None, ""):
+ return ""
+ if not isinstance(raw, str):
+ raise HTTPException(status_code=422, detail="a date must be text")
+ value = raw.strip()
+ if not value:
+ return ""
+ try:
+ temporal.parse_temporal(value)
+ except temporal.TemporalError as exc:
+ raise HTTPException(status_code=422, detail=f"unsupported date: {exc}") from exc
+ return value
+
+
+def _stated_description(spec: dict[str, Any]) -> str:
+ """The sentence the proof carries, which is the entity's own notes."""
+ raw = spec.get("description")
+ return raw.strip()[:_STATED_TEXT_MAX] if isinstance(raw, str) else ""
+
+
def _proof_thumb(case: Case, name: str, data: bytes | None = None) -> str | None:
"""Cached thumbnail for a proof's export, or None if it can't be produced.
@@ -264,6 +301,12 @@ def load_proof(case_id: str, name: str) -> dict[str, Any]:
alone showed one row for a proof the map drew twice, and the next save would
have written that missing point out of the composition for good. The list comes
back complete instead, and saving is what makes the spec agree with the map.
+
+ The date and the description are completed the same way, and for the same
+ reason: both are editable from the Details panel — one as an attribute, one as
+ the entity's notes — so opening on the spec alone would show the composer a
+ sentence the case had already replaced, and the next save would write the
+ edit back out.
"""
case = get_case(case_id)
try:
@@ -275,7 +318,13 @@ def load_proof(case_id: str, name: str) -> dict[str, Any]:
spec = json.loads(spec_path.read_text(encoding="utf-8"))
proof = case.find_entity(attr="spec", value=layout.proof_spec_rel(spec_path.stem))
if isinstance(spec, dict) and proof is not None:
- return satellite_engine.open_spec(case, proof["id"], spec)
+ opened = satellite_engine.open_spec(case, proof["id"], spec)
+ attrs = proof.get("attrs") or {}
+ for key, attr in (("when", "when"), ("description", "notes")):
+ stated = attrs.get(attr)
+ if isinstance(stated, str) and stated.strip():
+ opened[key] = stated.strip()
+ return opened
return spec
@@ -332,6 +381,10 @@ def save_proof(case_id: str, body: ProofIn) -> dict[str, Any]:
# Decoded up front: a bad batch must be refused before anything is written.
incoming = _decode_assets(body.assets)
+ # Read up front for the same reason: a date outside the profile is refused
+ # before the rename below moves this proof's export and its pasted images.
+ when = _stated_when(body.spec)
+ description = _stated_description(body.spec)
# The export too, and for a stronger reason — the rename below deletes the
# old PNG and moves the assets folder, so a payload refused after that point
# would leave the proof under its old name with both of them gone.
@@ -375,6 +428,8 @@ def save_proof(case_id: str, body: ProofIn) -> dict[str, Any]:
spec = dict(body.spec)
spec["azimut_proof"] = 1
spec["title"] = name
+ spec["when"] = when or None
+ spec["description"] = description or None
previous = case.resolve_inside(layout.proof_spec_rel(old or name))
spec.setdefault("created_at", read_created_at(previous) or _now())
spec["updated_at"] = _now()
@@ -406,6 +461,15 @@ def save_proof(case_id: str, body: ProofIn) -> dict[str, Any]:
# file per proof.
if thumb_rel and existing["attrs"].get("thumb") != thumb_rel:
attrs["thumb"] = thumb_rel
+ # What the proof states about itself travels the same way, and for one more
+ # reason than the thumbnail: `when` is what the Timeline projects the proof
+ # from, and the description is the entity's notes — the text the Details
+ # panel shows and case search finds. Written on every save, empty included,
+ # since clearing the field is the analyst taking the statement back.
+ if existing["attrs"].get("when", "") != when:
+ attrs["when"] = when
+ if existing["attrs"].get("notes", "") != description:
+ attrs["notes"] = description
if attrs:
patch["attrs"] = attrs
case.update_entity(existing["id"], patch)
@@ -418,6 +482,8 @@ def save_proof(case_id: str, body: ProofIn) -> dict[str, Any]:
"spec": rel,
**({"path": png_rel} if png_rel else {}),
**({"thumb": thumb_rel} if thumb_rel else {}),
+ **({"when": when} if when else {}),
+ **({"notes": description} if description else {}),
},
by="proof-composer",
)["id"]
@@ -442,6 +508,20 @@ def save_proof(case_id: str, body: ProofIn) -> dict[str, Any]:
by="proof-composer",
)
+ # The chain has to be filed before this: the footage behind a panel is reached
+ # by walking it, and a material address added in this same save is on it only
+ # once the sync above has run.
+ dated = _date_the_material(
+ case,
+ proof_id=entity_id,
+ name=name,
+ old=old,
+ rel=rel,
+ old_rel=old_rel,
+ when=when,
+ spec=spec,
+ )
+
place, released = _place_for(case, entity_id, spec)
return {
"name": name,
@@ -450,11 +530,129 @@ def save_proof(case_id: str, body: ProofIn) -> dict[str, Any]:
"thumb": thumb_rel,
"spec_path": rel,
"place": place,
+ # The files this save stated the date for, so the composer can say so. A
+ # save that writes into the graph announces it; it just does not ask.
+ "dated": dated,
# points this save moved off that nothing holds any more; the composer asks
"orphans": [{"id": e["id"], "label": e["label"]} for e in released],
}
+#: The attribute that binds the dating statement below to the proof that made it.
+#: Keyed by the spec path for the same reason the proof entity itself is found that
+#: way: it is the one value a proof owns, and a rename carries it.
+_STATED_BY = "proof"
+
+#: What the statement holds when nothing but this save has touched it. A Claim that
+#: has grown reasoning, a quote or a confidence is the analyst's own work by then,
+#: and clearing a date in the composer must not delete it.
+_OURS = {"when", "time_role", _STATED_BY}
+
+
+def _source_material(case: Case, spec: dict[str, Any]) -> list[dict[str, Any]]:
+ """The collected files a proof rests on, each read back to its own origin.
+
+ A proof composes a *frame*; the thing that was filmed is the video behind it, so
+ the chain is walked up to whatever nothing else in the case derives from. Captures
+ drop out at the end rather than at the start: a satellite screenshot is dated by
+ the provider's flyover, not by the event, and its own panel may still stand
+ between a crop and the imagery it came from.
+ """
+ paths = [p.get("src") for p in spec.get("panels", []) if p.get("src")]
+ found, _missing = link_engine.resolve(case, paths + _material_paths(spec))
+ roots: dict[str, dict[str, Any]] = {}
+ seen: set[str] = set()
+ frontier = list(found)
+ while frontier:
+ current = frontier.pop()
+ if current in seen:
+ continue
+ seen.add(current)
+ entity = case.get_entity(current)
+ if entity is None:
+ continue
+ parents = [
+ link["to"]
+ for link in case.links_of(current)
+ if link["type"] == link_engine.DERIVED_FROM and link["from"] == current
+ ]
+ collected = [
+ parent
+ for parent in parents
+ if (case.get_entity(parent) or {}).get("type") in {"media", "capture"}
+ ]
+ if collected:
+ frontier.extend(collected)
+ elif entity["type"] == "media":
+ roots[current] = entity
+ return list(roots.values())
+
+
+def _dating_label(name: str) -> str:
+ return f"Material of {name} was taken"
+
+
+def _date_the_material(
+ case: Case,
+ *,
+ proof_id: str,
+ name: str,
+ old: str | None,
+ rel: str,
+ old_rel: str | None,
+ when: str,
+ spec: dict[str, Any],
+) -> list[str]:
+ """State the proof's date for the footage it rests on, and answer with what it hit.
+
+ The date belongs to the material, not to the document arguing about it: a video
+ was shot when it was shot, whichever proof says so. It travels as a Claim — the
+ one shape this case has for *an analyst concluded this* — so it carries who said
+ it and what it rests on, and it never writes over the clock the file itself
+ reports. Both readings then sit side by side on that file's Time panel, the
+ statement above the file's own dates.
+
+ One statement per proof, about every source at once. A proof states one date, and
+ one statement about three files says exactly that, where three statements would
+ read as three findings and would have to be kept in step by hand.
+ """
+ standing = case.find_entity(attr=_STATED_BY, value=old_rel or rel)
+ if standing is not None and standing.get("type") != "claim":
+ standing = None
+ sources = _source_material(case, spec) if when else []
+ if not sources:
+ # The date is gone, or nothing collected is left under the proof. The
+ # statement goes with it — unless it has grown past what this save wrote,
+ # which makes it the analyst's and not ours to delete.
+ if standing is not None and set(standing.get("attrs") or {}) <= _OURS:
+ delete_entity_deep(case, standing["id"])
+ return []
+ # The wording is this save's only while nobody has rewritten it. A statement
+ # reworded by hand is the analyst's sentence, and restating the date is no
+ # reason to put our own back over it.
+ written = {_dating_label(name), _dating_label(old)} if old else {_dating_label(name)}
+ label = standing["label"] if standing and standing["label"] not in written else _dating_label(name)
+ case.save_temporal_claim(
+ entity_id=standing["id"] if standing else None,
+ label=label,
+ attrs={
+ **{
+ key: value
+ for key, value in ((standing or {}).get("attrs") or {}).items()
+ if key not in _OURS
+ },
+ "when": when,
+ # What the file shows, as read by whoever composed the proof. The same
+ # role the Timeline's own "this media was captured" correction uses.
+ "time_role": "observed",
+ _STATED_BY: rel,
+ },
+ connectors={"about": [e["id"] for e in sources], "at": [], "cites": [proof_id]},
+ by="proof-composer",
+ )
+ return [str(e.get("label") or "") for e in sources]
+
+
def _material_paths(spec: dict[str, Any]) -> list[str]:
"""The case files a proof states it rests on.
diff --git a/src/azimut/api/satellite.py b/src/azimut/api/satellite.py
index 8b3fec1..97c17bf 100644
--- a/src/azimut/api/satellite.py
+++ b/src/azimut/api/satellite.py
@@ -20,6 +20,7 @@ from PIL import Image
from pydantic import BaseModel, Field
from .. import config
+from ..engine.analysis_models import Zone
from ..engine import (
cities,
firms,
@@ -279,6 +280,45 @@ def sentinel_dates(lat: float, lon: float, start: str, end: str) -> dict[str, An
return {"dates": found, "start": start, "end": end}
+class AcquisitionQuery(BaseModel):
+ """The drawn areas a sweep would cover, and the window to look in."""
+
+ 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}$")
+
+
[email protected]("/satellite/sentinel/acquisitions")
+def sentinel_acquisitions(body: AcquisitionQuery) -> dict[str, Any]:
+ """Sentinel-2 passes over drawn areas, each with the share of them it covers.
+
+ The question a crosshair lookup cannot answer. An analysis sweep fixes an
+ area, and Sentinel-2's swath does not care where that area's centre is: a
+ day can reach two thirds of it and leave the rest nodata. Asked before the
+ run, that is a number on a row; discovered after it, it is a sweep paid for
+ in tiles that found nothing.
+
+ User-triggered only. Billed as one request on the sentinelhub meter.
+ """
+ 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:
+ found = sentinel.acquisitions(
+ instance, [list(zone.ring()) for zone in body.zones], body.start, body.end
+ )
+ except ValueError as exc:
+ raise HTTPException(status_code=422, detail=str(exc)) from exc
+ except Exception as exc:
+ raise HTTPException(status_code=502, detail=f"pass lookup failed: {exc}") from exc
+ config.record_usage("sentinelhub", 1)
+ return {**found, "start": body.start, "end": body.end}
+
+
@router.get("/satellite/sentinel/coverage")
def sentinel_coverage(
lat: float, lon: float, layer: str, date: str, maxcc: int = sentinel.DEFAULT_MAXCC
@@ -1158,6 +1198,16 @@ def saved_index(case_id: str) -> list[dict[str, Any]]:
return satellite_engine.saved_index(get_case(case_id))
[email protected]("/cases/{case_id}/satellite/media")
+def media_index(case_id: str) -> list[dict[str, Any]]:
+ """The case's located images and videos, one row per point, newest first.
+
+ Read when the Saved panel's Media position is opened, never on case open:
+ placing a file walks its derivation chain, which the saved index must not pay.
+ """
+ return satellite_engine.media_index(get_case(case_id))
+
+
@router.post("/cases/{case_id}/satellite/locate")
def locate_saved(
case_id: str, limit: int = Query(default=10, ge=1, le=25)
diff --git a/src/azimut/api/settings.py b/src/azimut/api/settings.py
index 4915dce..9b71728 100644
--- a/src/azimut/api/settings.py
+++ b/src/azimut/api/settings.py
@@ -33,6 +33,7 @@ from ..engine import (
workspacemove,
)
from .templates import MAX_PER_KIND as MAX_TEMPLATES_PER_KIND
+from ..engine.analysis_models import 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.
@@ -613,6 +614,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)
+
schema_version: int = Field(
default=config.SETTINGS_SCHEMA,
alias="schema",
diff --git a/src/azimut/caselayout.py b/src/azimut/caselayout.py
index 9a01edb..d12124c 100644
--- a/src/azimut/caselayout.py
+++ b/src/azimut/caselayout.py
@@ -358,7 +358,9 @@ def _align_visible_names(case: "Case") -> None:
media_engine.rename_media(case, path, desired, settle_worker=False)
for entity in list(case.list_entities()):
- if entity.get("type") in {"note", "proof", "inspect-session", "post"}:
+ if entity.get("type") in {
+ "note", "proof", "inspect-session", "compare-session", "post"
+ }:
case.update_entity(entity["id"], {"label": entity.get("label") or ""})
diff --git a/src/azimut/config.py b/src/azimut/config.py
index c3925b6..3e2a161 100644
--- a/src/azimut/config.py
+++ b/src/azimut/config.py
@@ -46,6 +46,7 @@ logger = logging.getLogger(__name__)
SETTINGS_SCHEMA = 1
DEFAULT_SETTINGS: dict[str, Any] = {
+ "analyzers": [], # portable custom recipes shared by all cases
# Schema version this build writes. Read back through _settings_schema() so
# a future breaking rename is migrated rather than silently dropped.
"schema": SETTINGS_SCHEMA,
diff --git a/src/azimut/engine/analysis_models.py b/src/azimut/engine/analysis_models.py
new file mode 100644
index 0000000..f12bf45
--- /dev/null
+++ b/src/azimut/engine/analysis_models.py
@@ -0,0 +1,244 @@
+"""Portable recipes and geographic inputs for Compare analyzers.
+
+Models describe capabilities by stable ids. A later model adapter can join the
+method registry without changing saved runs or accepting executable recipes.
+"""
+
+from __future__ import annotations
+
+import math
+from datetime import date
+from typing import Annotated, Literal
+
+from pydantic import BaseModel, ConfigDict, Field, FiniteFloat, model_validator
+
+Provider = Literal["esri-wayback", "sentinel2"]
+Method = Literal["colour", "structure", "brightness", "index", "water_objects", "smoke",
+ "vessels", "hotspots"]
+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, so asking for a
+# reference image would be asking for something the method cannot use.
+SINGLE_METHODS = frozenset({"water_objects", "vessels", "hotspots"})
+
+# Methods that measure reflectance, which a rendered picture has already
+# stretched away. Each needs the band product named here, fetched beside the
+# picture the analyst reviews. `index` picks its product from the recipe's
+# parameters instead, so it is not in this table.
+PRODUCT_METHODS: dict[str, str] = {"vessels": "vessel", "hotspots": "fire"}
+
+# Reflectance is Copernicus only: Wayback serves pictures, not bands.
+SENTINEL_ONLY = frozenset({"index", *PRODUCT_METHODS})
+
+# How each method can exclude cloud and the shadow it casts.
+#
+# ``classes`` reads Sentinel-2's own per-pixel scene classification, which is
+# the real answer. ``picture`` has only the rendered image, so it goes on what
+# cloud looks like — bright and colourless, its shadow near-black — which is a
+# guess, and the UI says so rather than dressing it up.
+#
+# Three methods are absent on purpose. The fire test rejects cloud by its band
+# ratios and spends its fourth channel on the data mask instead. Smoke and
+# bright shapes on water *are* bright and colourless: there, the picture test
+# would mask the very thing the method looks for.
+CLOUD_FILTERS: dict[str, str] = {
+ "index": "classes", "vessels": "classes",
+ "colour": "picture", "structure": "picture", "brightness": "picture",
+}
+
+
+def both_providers() -> list[Provider]:
+ return ["esri-wayback", "sentinel2"]
+
+
+class Model(BaseModel):
+ model_config = ConfigDict(extra="forbid", allow_inf_nan=False)
+
+
+class Parameters(Model):
+ sensitivity: int = Field(default=55, ge=0, le=100)
+ min_area: FiniteFloat = Field(default=20, ge=0, le=100_000_000)
+ min_score: FiniteFloat = Field(default=0, ge=0, le=1)
+ cleanup: int = Field(default=1, ge=0, le=3)
+ smoothing: int = Field(default=0, ge=0, le=3)
+ normalize: bool = False
+ index: Literal["ndvi", "ndwi", "nbr", "ndbi"] = "ndvi"
+ direction: Literal["both", "gain", "loss"] = "both"
+ # Sentinel-2's own scene classification: the sensor says which pixels are
+ # cloud, so this is on by default.
+ ignore_clouds: bool = True
+ ignore_shadows: bool = True
+ # The same exclusion where there is no classification to ask, read off the
+ # rendered picture instead. Off by default, and it stays off by default:
+ # bright and colourless is what a white roof, a gravel pad and fresh snow
+ # look like too, and those are things analysts come here to find. A guess
+ # this broad is the analyst's to make, never one made for them.
+ guess_clouds: bool = False
+ # A cloud fades out at its edges and its shadow has no edge at all, so both
+ # masks stop short of what a reader would call the cloud. Growing them by a
+ # couple of pixels takes the fringe that otherwise survives as a ring of
+ # candidates around every mask.
+ cloud_margin: int = Field(default=2, ge=0, le=10)
+ merge_metres: FiniteFloat = Field(default=0, ge=0, le=500)
+
+
+class Zone(Model):
+ id: ShortId
+ name: str = Field(default="Area", min_length=1, max_length=120)
+ kind: Literal["rect", "polygon", "ellipse"] = "rect"
+ points: list[tuple[FiniteFloat, FiniteFloat]] = Field(min_length=2, max_length=100)
+
+ @model_validator(mode="after")
+ def geometry(self) -> Zone:
+ if self.kind == "polygon":
+ if len(self.points) < 3:
+ raise ValueError("a polygon needs at least three corners")
+ elif len(self.points) != 2:
+ raise ValueError("a rectangle or ellipse needs two opposite corners")
+ if any(abs(x) > 180 or abs(y) > 85 for x, y in self.points):
+ raise ValueError("areas must be within longitude ±180 and latitude ±85")
+ xs, ys = zip(*self.points)
+ if max(xs) - min(xs) > 180:
+ raise ValueError("split areas crossing the antimeridian into separate zones")
+ if max(xs) == min(xs) or max(ys) == min(ys):
+ raise ValueError("an area must have width and height")
+ if self.kind == "polygon":
+ edges = list(zip(self.points, self.points[1:] + self.points[:1]))
+ area = sum(a[0] * b[1] - b[0] * a[1] for a, b in edges)
+ if abs(area) < 1e-14:
+ raise ValueError("a polygon must enclose an area")
+ return self
+
+ def ring(self) -> list[tuple[float, float]]:
+ if self.kind == "polygon":
+ return list(self.points)
+ (x1, y1), (x2, y2) = self.points
+ if self.kind == "rect":
+ return [(x1, y1), (x2, y1), (x2, y2), (x1, y2)]
+ return [((x1 + x2) / 2 + abs(x2 - x1) / 2 * math.cos(i * math.tau / 64),
+ (y1 + y2) / 2 + abs(y2 - y1) / 2 * math.sin(i * math.tau / 64))
+ for i in range(64)]
+
+
+class Recipe(Model):
+ id: ShortId = "custom"
+ name: str = Field(min_length=1, max_length=120)
+ description: str = Field(default="", max_length=500)
+ phenomenon: str = Field(default="Surface change", min_length=1, max_length=120)
+ method: Method = "colour"
+ providers: list[Provider] = Field(
+ default_factory=both_providers, min_length=1, max_length=2
+ )
+ 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="after")
+ def compatible(self) -> Recipe:
+ if self.method in SENTINEL_ONLY and self.providers != ["sentinel2"]:
+ raise ValueError("this method reads Copernicus Sentinel-2 bands, so it is "
+ "compatible with that source only")
+ return self
+
+
+class Source(Model):
+ provider: Provider = "esri-wayback"
+ date: str = Field(default="", max_length=10)
+ release: int | None = Field(default=None, ge=1, le=999999999)
+ layer: str = Field(default="TRUE_COLOR", pattern=r"^[A-Z0-9_]{1,40}$")
+ maxcc: int = Field(default=30, ge=0, le=100)
+
+ @model_validator(mode="after")
+ def dated(self) -> Source:
+ if self.provider == "sentinel2" and self.date:
+ try:
+ date.fromisoformat(self.date)
+ except ValueError as exc:
+ raise ValueError("choose a dated Sentinel-2 acquisition") from exc
+ return self
+
+
+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):
+ recipe: Recipe
+ a: Source
+ b: Source
+ offline: bool = False
+ followup_id: ShortId | None = None
+ date_rule: Literal["manual", "latest_reference", "latest_previous"] = "manual"
+
+ @model_validator(mode="after")
+ def pair(self) -> RunInput:
+ if self.a.provider != self.b.provider or self.b.provider not in self.recipe.providers:
+ raise ValueError("use one compatible provider for both images")
+ if self.recipe.method != "index" and self.a.layer != self.b.layer:
+ raise ValueError("use the same rendering layer for both images")
+ if len({zone.id for zone in self.zones}) != len(self.zones):
+ raise ValueError("area ids must be unique")
+ single = self.recipe.method in SINGLE_METHODS
+ required = []
+ if self.date_rule == "manual":
+ required.append(self.b)
+ if not single and (self.date_rule != "latest_previous" or not self.followup_id):
+ required.append(self.a)
+ for source in required:
+ if source.provider == "sentinel2" and not source.date:
+ raise ValueError("choose a dated Sentinel-2 acquisition")
+ if source.provider == "esri-wayback" and source.release is None:
+ raise ValueError("choose a named Wayback release")
+ return self
+
+
+# The names say what is measured, never what it means. "Vessels on water" is a
+# claim about infrared contrast over sea, and the description is where the
+# limits of that claim live — a preset called "Boats" would promise recognition
+# no method here performs.
+BUILTINS = [
+ Recipe(id="large-change", name="Large surface change",
+ description="Broad changes in colour between two dated images. New construction, "
+ "clearing, earthworks and flooding all read as change; so does a different season.",
+ parameters=Parameters(min_area=500)),
+ Recipe(id="boats", name="Vessels on water (Sentinel-2)", method="vessels",
+ phenomenon="Vessel candidate",
+ providers=["sentinel2"],
+ description="Targets brighter than the sea around them in the near-infrared, which "
+ "water absorbs almost completely. Ships, rigs, buoys and breaking waves all qualify; "
+ "at 10 m a pixel, anything under about 20 m is unlikely to appear at all.",
+ parameters=Parameters(min_area=200, min_score=0.2, cleanup=0), colour="#38bdf8"),
+ Recipe(id="structures", name="New structures or ground disturbance", method="structure",
+ phenomenon="Possible structure or disturbed ground",
+ description="New or lost edges; buildings, roads and bare ground need visual review.",
+ parameters=Parameters(min_area=80), colour="#a78bfa"),
+ Recipe(id="anomaly", name="Active fire or hotspot (Sentinel-2)", method="hotspots",
+ phenomenon="Hotspot candidate",
+ providers=["sentinel2"],
+ description="Short-wave infrared high in absolute terms and high against the bands "
+ "either side of it, which is the published active-fire test. It sees flame through "
+ "smoke, and says nothing about what is burning or why.",
+ parameters=Parameters(min_area=100, cleanup=0), colour="#fb7185"),
+]
+
+# What the panel reads so it never has to know a method by name: `single` stops
+# it asking for a reference image, `sentinel_only` stops it offering Wayback,
+# and `classes` decides whether the cloud and shadow switches mean anything.
+METHODS = [
+ {"id": method, "label": label, "single": method in SINGLE_METHODS,
+ "sentinel_only": method in SENTINEL_ONLY, "cloud_filter": CLOUD_FILTERS.get(method, "")}
+ for method, label in [
+ ("colour", "Colour change"),
+ ("structure", "Edge change"),
+ ("brightness", "Brightness change"),
+ ("index", "Spectral index change (Sentinel-2)"),
+ ("vessels", "Infrared contrast over water (Sentinel-2)"),
+ ("hotspots", "Short-wave infrared hotspot (Sentinel-2)"),
+ ("water_objects", "Bright shapes on water (picture only)"),
+ ("smoke", "Smoke-like visual change (picture only)"),
+ ]
+]
diff --git a/src/azimut/engine/analyzers.py b/src/azimut/engine/analyzers.py
new file mode 100644
index 0000000..3c01e4f
--- /dev/null
+++ b/src/azimut/engine/analyzers.py
@@ -0,0 +1,717 @@
+"""Bounded, explicit, local analysis runs over fixed geographic tile grids.
+
+Source frames are owned evidence, not an expiring map cache. Completed runs
+never change when their recipe, area, camera or provider catalogue changes.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import io
+import json
+import math
+import secrets
+import threading
+from datetime import date, datetime, timedelta, timezone
+from typing import Any
+
+import httpx
+from PIL import Image
+
+from .. import config, layout
+from ..workspace import Case
+from . import media, sentinel, tilecache, tiles, wayback, workqueue
+from .analysis_models import (
+ CLOUD_FILTERS,
+ PRODUCT_METHODS,
+ SINGLE_METHODS,
+ Parameters,
+ RunInput,
+ Source,
+ Zone,
+)
+
+# What one run may sweep. The ceiling is not memory — tiles are read one at a
+# time — it is the permanent copy of every tile read, which `prune_frames`
+# now drops for tiles that found nothing. What is left to bound is the
+# provider's own metering and the analyst's patience, and both of those the
+# panel states before the run starts and the cancel button ends after.
+#
+# At Sentinel's 4.89 km tile that is 313 km on a side; at Wayback's 76 m one,
+# 4.9 km.
+MAX_TILES = 4096
+MAX_RESULTS = 2000
+MAX_FRAME_BYTES = 8_000_000
+# Sentinel-2's own scene classification, as the classes worth excluding.
+CLOUD_CLASSES = (0, 1, 8, 9, 10, 11)
+SHADOW_CLASSES = (2, 3)
+# What cloud looks like with no classification to ask: bright and colourless,
+# its shadow near-black. Deliberately tight — a guess this filter makes on a
+# rendered picture also eats a white roof, a sand flat and fresh snow, so it
+# waits for cloud-like rather than merely pale.
+PICTURE_CLOUD_LEVEL = 205
+PICTURE_CLOUD_SPREAD = 28
+PICTURE_SHADOW_LEVEL = 28
+# A pixel on the Sentinel analysis grid is 9.55 m across, so the ring the
+# vessel detector measures its background over spans 583 m of sea, and the hole
+# punched in its middle is 105 m — wider than all but the largest hulls, which
+# is what stops a ship from quietly raising its own background.
+VESSEL_RING = 61
+VESSEL_GUARD = 11
+# The ring has to be mostly sea for its statistics to mean anything; below this
+# fraction the pixel is a shoreline or an island, not a place a ship can be.
+VESSEL_WATER_SHARE = 0.5
+# Below this short-wave reflectance there is no fire to discuss, whatever the
+# band ratios say. It is the floor the published Sentinel-2 test uses.
+HOTSPOT_FLOOR = 0.15
+# How far back an automatic date rule looks for its latest usable pass.
+LOOKBACK_DAYS = 90
+# Coverage at or above this counts as covering the whole area. It is not 1.0
+# because coverage is measured by sampling, and a ring's own edge lands a point
+# or two outside the granule that in truth reaches it.
+FULL_COVER = 0.98
+WORLD = 40_075_016.68557849
+LOCK = threading.RLock()
+KINDS = {"zones": "analysis-zones", "followups": "analysis-follow-up", "runs": "analysis-run"}
+ACTIVE = {"queued", "running"}
+JOB = "compare-analyzer"
+
+
+def now() -> str:
+ return datetime.now(timezone.utc).isoformat(timespec="seconds")
+
+
+def relpath(kind: str, ident: str) -> str:
+ if kind not in KINDS or not ident or any(c not in "0123456789abcdef" for c in ident):
+ raise ValueError("unknown analysis item")
+ if len(ident) != 12:
+ raise ValueError("unknown analysis item")
+ return f"{layout.ANALYSIS_DIR}/{kind}-{ident}.json"
+
+
+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"))
+
+
+def listing(case: Case, kind: str) -> list[dict[str, Any]]:
+ 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})
+ 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]:
+ with LOCK, case._lock:
+ if ident:
+ old = read(case, kind, ident)
+ else:
+ ident = secrets.token_hex(6)
+ old = {}
+ rel = relpath(kind, ident)
+ saved = {**data, "id": ident, "created_at": old.get("created_at", now()),
+ "updated_at": now(), "version": 1}
+ path = case.resolve_inside(rel)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ media.write_json_atomic(path, saved)
+ entity = case.find_entity(attr="spec", value=rel)
+ if entity:
+ case.update_entity(entity["id"], {"label": saved["title"]})
+ else:
+ case.add_entity(KINDS[kind], saved["title"], attrs={"spec": rel}, by="compare")
+ return saved
+
+
+def persist_run(case: Case, saved: dict[str, Any]) -> None:
+ # The worker holds the same case lock as deletion: a removed entity cannot
+ # be resurrected by a late progress write or a late network response.
+ with LOCK, case._lock:
+ rel = relpath("runs", saved["id"])
+ if not case.find_entity(attr="spec", value=rel):
+ raise workqueue.JobCancelled()
+ current = read(case, "runs", saved["id"])
+ if current["status"] == "cancelled":
+ raise workqueue.JobCancelled()
+ saved["updated_at"] = now()
+ media.write_json_atomic(case.resolve_inside(rel), saved)
+
+
+def mercator(lon: float, lat: float) -> tuple[float, float]:
+ return ((lon + 180) / 360, (1 - math.asinh(math.tan(math.radians(lat))) / math.pi) / 2)
+
+
+def geographic(x: float, y: float) -> tuple[float, float]:
+ return (x * 360 - 180, math.degrees(math.atan(math.sinh(math.pi * (1 - 2 * y)))))
+
+
+# Same native grids as the tile proxy. Sentinel's 512px WMTS tiles use grid
+# level 13 (view level 14), which lands on 9.55 m/px — the sensor's own
+# resolution; Wayback uses 256px at level 19. The panel reads these to say what
+# a run will cost before it starts, so they are published rather than copied.
+GRIDS: dict[str, tuple[int, int]] = {"sentinel2": (13, 512), "esri-wayback": (19, 256)}
+
+
+def grid(body: RunInput) -> tuple[int, int]:
+ return GRIDS.get(body.b.provider, GRIDS["esri-wayback"])
+
+
+def plan(body: RunInput) -> list[tuple[int, int]]:
+ import cv2
+ import numpy as np
+
+ z, size = grid(body)
+ count = 1 << z
+ found: set[tuple[int, int]] = set()
+ # One scratch mask for the whole plan: a large area visits tens of
+ # thousands of boxes, and allocating a fresh one per box is the difference
+ # between planning in a second and planning in a minute.
+ mask = np.zeros((size, size), np.uint8)
+ for zone in body.zones:
+ ring = [mercator(*point) for point in zone.ring()]
+ xs, ys = zip(*ring)
+ left, right = math.floor(min(xs) * count), math.ceil(max(xs) * count) - 1
+ top, bottom = math.floor(min(ys) * count), math.ceil(max(ys) * count) - 1
+ # Bound even a thin polygon's enumeration before visiting its boxes.
+ if (right - left + 1) * (bottom - top + 1) > MAX_TILES * 8:
+ raise ValueError("area too large at native resolution; split it into smaller runs")
+ for y in range(max(0, top), min(count - 1, bottom) + 1):
+ for x in range(max(0, left), min(count - 1, right) + 1):
+ pixels = np.array([[(px * count - x) * size, (py * count - y) * size]
+ for px, py in ring], dtype=np.int32)
+ mask[:] = 0
+ cv2.fillPoly(mask, [pixels], 1)
+ if mask.any():
+ found.add((x, y))
+ if len(found) > MAX_TILES:
+ raise ValueError(f"area needs more than {MAX_TILES} tiles; use smaller zones")
+ if not found:
+ raise ValueError("the areas contain no pixels at this resolution")
+ return sorted(found, key=lambda pair: (pair[1], pair[0]))
+
+
+def check_active(case: Case, ident: str) -> None:
+ try:
+ if read(case, "runs", ident)["status"] not in ACTIVE:
+ raise workqueue.JobCancelled()
+ except FileNotFoundError as exc:
+ raise workqueue.JobCancelled() from exc
+
+
+def _key(source: Source, z: int, x: int, y: int, index: str | None) -> str:
+ encoded = json.dumps([source.model_dump(), z, x, y, index], sort_keys=True).encode()
+ return hashlib.sha256(encoded).hexdigest()[:32]
+
+
+def _decode(raw: bytes, size: int) -> Any:
+ import numpy as np
+
+ if len(raw) > MAX_FRAME_BYTES:
+ raise ValueError("imagery frame exceeds the byte limit")
+ with Image.open(io.BytesIO(raw)) as image:
+ if image.size != (size, size):
+ raise ValueError("provider returned an unexpected image size")
+ return np.array(image.convert("RGBA"))
+
+
+def frame(case: Case, run: dict[str, Any], source: Source, x: int, y: int,
+ index: str | None = None) -> Any:
+ body = RunInput.model_validate(run["input"])
+ z, size = grid(body)
+ key = _key(source, z, x, y, index)
+ name = f"{key}.png"
+ assets_rel = layout.analysis_assets_rel(f"runs-{run['id']}")
+ destination = case.resolve_inside(f"{assets_rel}/{name}")
+ raw = None
+ # Reuse permanent evidence from this case, including after a bundle import.
+ for folder in case.subdir(layout.ANALYSIS_DIR).glob("runs-*.assets"):
+ cached = folder / name
+ if cached.is_file() and cached.stat().st_size <= MAX_FRAME_BYTES:
+ raw = cached.read_bytes()
+ break
+ provider_id = (f"esri-wayback~{source.release}" if source.provider == "esri-wayback" else
+ sentinel.variant_id("sentinel2", source.layer, source.date, source.date,
+ source.maxcc))
+ if raw is None and index is None:
+ cached_tile = tilecache.get(provider_id, z, x, y)
+ if cached_tile:
+ raw = cached_tile[0]
+ if raw is None:
+ if body.offline:
+ raise ValueError("some required images are unavailable offline; no request was sent")
+ check_active(case, run["id"])
+ if source.provider == "sentinel2" and config.usage_blocked("sentinelhub"):
+ raise ValueError("Sentinel Hub usage limit reached; review Settings")
+ if index:
+ instance = (config.load_settings().get("api_keys") or {}).get("sentinelhub")
+ if not instance:
+ raise ValueError("configure Copernicus Sentinel Hub in Settings")
+ box = (x / (1 << z) * WORLD - WORLD / 2,
+ WORLD / 2 - (y + 1) / (1 << z) * WORLD,
+ (x + 1) / (1 << z) * WORLD - WORLD / 2,
+ WORLD / 2 - y / (1 << z) * WORLD)
+ try:
+ raw = sentinel.band_frame(instance, box, size, size, source.date, index,
+ source.maxcc, layer=source.layer)
+ finally:
+ config.record_usage("sentinelhub", 1)
+ else:
+ # A named Wayback release never needs a catalogue lookup to fetch
+ # its tiles. In particular, cached runs can work without network.
+ if source.provider == "esri-wayback":
+ assert source.release is not None
+ url = wayback.tile_url(source.release)
+ offset = 0
+ else:
+ instance = (config.load_settings().get("api_keys") or {}).get("sentinelhub")
+ if not instance:
+ raise ValueError("configure Copernicus Sentinel Hub in Settings")
+ url = sentinel.wmts_url(source.layer, source.date, source.date, source.maxcc)
+ url = url.replace("{key}", instance)
+ offset = 1
+ with httpx.stream("GET", tiles.tile_url(url, z, x, y, offset), timeout=30) as response:
+ if response.status_code == 404:
+ raise ValueError("imagery is missing at the requested resolution or date")
+ response.raise_for_status()
+ if source.provider == "sentinel2":
+ config.record_usage("sentinelhub", 1)
+ chunks = bytearray()
+ for chunk in response.iter_bytes():
+ check_active(case, run["id"])
+ chunks.extend(chunk)
+ if len(chunks) > MAX_FRAME_BYTES:
+ raise ValueError("imagery frame exceeds the byte limit")
+ raw = bytes(chunks)
+ if tiles.is_placeholder_tile(raw):
+ raise ValueError("provider has no imagery here at native resolution")
+ pixels = _decode(raw, size)
+ # Canonical PNGs preserve the exact decoded input, independently of cache TTL.
+ with LOCK, case._lock:
+ check_active(case, run["id"])
+ destination.parent.mkdir(parents=True, exist_ok=True)
+ if not destination.exists():
+ Image.fromarray(pixels).save(destination, "PNG")
+ run["frames"][key] = {"path": f"{assets_rel}/{name}", "source": source.model_dump(),
+ "tile": [z, x, y], "index": index,
+ "sha256": hashlib.sha256(destination.read_bytes()).hexdigest()}
+ return pixels
+
+
+def mask_for(zones: list[Zone], z: int, size: int, x: int, y: int) -> Any:
+ import cv2
+ import numpy as np
+
+ mask = np.zeros((size, size), np.uint8)
+ for zone in zones:
+ points = np.array([[(px * (1 << z) - x) * size, (py * (1 << z) - y) * size]
+ for px, py in map(lambda point: mercator(*point), zone.ring())],
+ dtype=np.int32)
+ cv2.fillPoly(mask, [points], 1)
+ return mask
+
+
+def local_contrast(values: Any, water: Any, outer: int, guard: int) -> tuple[Any, Any]:
+ """How far each pixel stands above the water around it, in deviations.
+
+ A vessel is not bright, it is brighter than its own patch of sea — which is
+ what lets one threshold work over a calm lagoon and a sunlit swell alike,
+ where an absolute cut-off would have to be retuned for every scene. The
+ statistics come from a ring, a square window with its middle punched out,
+ so a large hull cannot raise the background it is then measured against.
+
+ Only water contributes. The second value returned is the ring's water
+ share, which is how a pixel says whether it is at sea at all: the target
+ itself reflects infrared and so is never classed as water.
+ """
+ import cv2
+ import numpy as np
+
+ weight = water.astype(np.float64)
+ signal = values * weight
+
+ def ring(source: Any) -> Any:
+ return (cv2.boxFilter(source, cv2.CV_64F, (outer, outer), normalize=False,
+ borderType=cv2.BORDER_REFLECT)
+ - cv2.boxFilter(source, cv2.CV_64F, (guard, guard), normalize=False,
+ borderType=cv2.BORDER_REFLECT))
+
+ count = ring(weight)
+ total = ring(signal)
+ squares = ring(signal * values)
+ safe = np.maximum(count, 1)
+ mean = total / safe
+ deviation = np.sqrt(np.maximum(squares / safe - mean * mean, 0))
+ # A flat patch of water has no deviation to divide by, and one quantisation
+ # step would then read as a hundred-sigma detection. One digital number is
+ # the floor because one digital number is the smallest difference there is.
+ contrast = (values - mean) / np.maximum(deviation, 1.0)
+ share = count / float(outer * outer - guard * guard)
+ # Too little water in the ring and the background is somebody else's.
+ return np.where(share > 0, contrast, 0.0), share
+
+
+def weather_mask(frames: tuple[Any, ...], kind: str, options: Parameters) -> Any:
+ """Pixels to drop as cloud or the shadow it casts, or None when nothing is.
+
+ ``classes`` reads Sentinel-2's scene classification out of the band frame's
+ second channel, and ``ignore_clouds``/``ignore_shadows`` pick which of them
+ to drop. ``picture`` has no classification to ask and goes on what cloud
+ looks like in a rendered image, so it is one switch — ``guess_clouds`` — and
+ it is off until someone asks for it.
+
+ Either mask is then grown by the margin, because both stop short of where a
+ reader would put the cloud's edge and the fringe left behind is what turns
+ up as a ring of candidates around every mask.
+
+ Cloud on *either* date invalidates the pixel: a difference is only a
+ measurement when both sides of it are ground.
+ """
+ import cv2
+ import numpy as np
+
+ if kind == "classes":
+ wanted = options.ignore_clouds or options.ignore_shadows
+ else:
+ wanted = kind == "picture" and options.guess_clouds
+ if not wanted:
+ return None
+ blocked = None
+ for image in frames:
+ if image is None:
+ continue
+ if kind == "classes":
+ classes = image[:, :, 1]
+ hit = np.zeros(classes.shape, dtype=bool)
+ if options.ignore_clouds:
+ hit |= np.isin(classes, CLOUD_CLASSES)
+ if options.ignore_shadows:
+ hit |= np.isin(classes, SHADOW_CLASSES)
+ else:
+ pixels = image[:, :, :3].astype(np.int16)
+ level = pixels.mean(axis=2)
+ spread = pixels.max(axis=2) - pixels.min(axis=2)
+ hit = ((level >= PICTURE_CLOUD_LEVEL) & (spread <= PICTURE_CLOUD_SPREAD)) | (
+ level <= PICTURE_SHADOW_LEVEL
+ )
+ blocked = hit if blocked is None else (blocked | hit)
+ if blocked is None or not options.cloud_margin or not blocked.any():
+ return blocked
+ kernel = np.ones((options.cloud_margin * 2 + 1,) * 2, np.uint8)
+ grown = cv2.dilate(blocked.astype(np.uint8), kernel, borderType=cv2.BORDER_REPLICATE)
+ return grown.astype(bool)
+
+
+def detect(a: Any, b: Any, mask: Any, body: RunInput, index_a: Any = None,
+ index_b: Any = None) -> tuple[Any, Any]:
+ """One deterministic tile. Score is signal strength, never model confidence."""
+ import cv2
+ import numpy as np
+
+ options = body.recipe.parameters
+ left, right = a[:, :, :3].astype(np.float32), b[:, :, :3].astype(np.float32)
+ valid = mask.astype(bool) & (a[:, :, 3] > 0) & (b[:, :, 3] > 0)
+ kind = CLOUD_FILTERS.get(body.recipe.method, "")
+ weather = weather_mask(
+ (index_a, index_b) if body.recipe.method == "index"
+ else (index_b,) if kind == "classes" else (a, b),
+ kind, options,
+ )
+ if weather is not None:
+ valid &= ~weather
+ if options.normalize and body.recipe.method != "index":
+ # Optional local brightness correction; off by default because it can
+ # erase the large changes an analyst came here to find.
+ right = np.clip(right + np.median(left - right, axis=(0, 1)), 0, 255)
+ method = body.recipe.method
+ delta = right.mean(axis=2) - left.mean(axis=2)
+ if method == "index":
+ delta = (index_b[:, :, 0].astype(np.float32) - index_a[:, :, 0]) / 127.5
+ valid &= (index_a[:, :, 3] > 0) & (index_b[:, :, 3] > 0)
+ strength = np.abs(delta)
+ elif method == "vessels":
+ # Near-infrared over water, against the water around it. NDWI rides in
+ # the same frame, so deciding what is sea costs no extra request.
+ nir = index_b[:, :, 0].astype(np.float64)
+ ndwi = (index_b[:, :, 2].astype(np.float32) - 127.5) / 127.5
+ valid &= index_b[:, :, 3] > 0
+ # Cloud is bright in the near-infrared too, so it has to leave the sea
+ # the background is measured over *and* stop being a candidate itself.
+ water = ndwi > 0
+ if weather is not None:
+ water &= ~weather
+ contrast, share = local_contrast(nir, water, VESSEL_RING, VESSEL_GUARD)
+ valid &= share > VESSEL_WATER_SHARE
+ # Two deviations is noise anywhere; twelve is a hull. Sensitivity then
+ # moves the cut inside that range rather than across an absolute scale.
+ strength = np.clip((contrast - 2) / 10, 0, 1)
+ elif method == "hotspots":
+ swir = index_b[:, :, 0].astype(np.float32) / (255 * sentinel.SWIR_GAIN)
+ over11 = index_b[:, :, 1].astype(np.float32) / sentinel.RATIO_GAIN
+ over08 = index_b[:, :, 2].astype(np.float32) / sentinel.RATIO_GAIN
+ valid &= (index_b[:, :, 3] > 0) & (swir >= HOTSPOT_FLOOR)
+ # Cloud is bright in the short-wave too, but bright in its neighbours
+ # as well, so its ratios sit near one. Fire pulls both of them up.
+ strength = np.clip((np.minimum(over11, over08) - 1) / 2, 0, 1)
+ elif method == "structure":
+ def edges(image: Any) -> Any:
+ grey = image.mean(axis=2)
+ return cv2.magnitude(cv2.Sobel(grey, cv2.CV_32F, 1, 0),
+ cv2.Sobel(grey, cv2.CV_32F, 0, 1))
+ delta = edges(right) - edges(left)
+ strength = np.abs(delta) / 255
+ elif method == "water_objects":
+ grey = right.mean(axis=2).astype(np.uint8)
+ background = cv2.medianBlur(grey, 15).astype(np.float32)
+ strength = np.maximum(0, grey.astype(np.float32) - background) / 100
+ # User draws the water area. Dark local surroundings reject broad land
+ # surfaces, but this deliberately remains a visual candidate detector.
+ valid &= background < 120
+ elif method == "smoke":
+ strength = np.maximum(0, delta) / 100
+ valid &= (right.max(axis=2) - right.min(axis=2) < 45) & (right.mean(axis=2) > 110)
+ elif method == "brightness":
+ strength = np.abs(delta) / 255
+ else:
+ strength = np.linalg.norm(right - left, axis=2) / (255 * math.sqrt(3))
+ if options.direction != "both" and method not in SINGLE_METHODS:
+ valid &= delta > 0 if options.direction == "gain" else delta < 0
+ strength = np.clip(strength, 0, 1).astype(np.float32)
+ if options.smoothing:
+ strength = cv2.GaussianBlur(strength, (options.smoothing * 2 + 1,) * 2, 0)
+ threshold = 0.02 + (1 - options.sensitivity / 100) * 0.48
+ binary = ((strength >= threshold) & valid).astype(np.uint8)
+ if options.cleanup:
+ kernel = np.ones((2 * options.cleanup + 1,) * 2, np.uint8)
+ binary = cv2.morphologyEx(binary, cv2.MORPH_OPEN, kernel,
+ borderType=cv2.BORDER_REPLICATE)
+ binary = cv2.morphologyEx(binary, cv2.MORPH_CLOSE, np.ones((3, 3), np.uint8),
+ borderType=cv2.BORDER_REPLICATE)
+ binary &= valid.astype(np.uint8)
+ return binary, strength
+
+
+def _candidates(binary: Any, strength: Any, body: RunInput, x: int, y: int,
+ part: int, frame_keys: list[str]) -> list[dict[str, Any]]:
+ import cv2
+ import numpy as np
+
+ z, size = grid(body)
+ n, labels, stats, centres = cv2.connectedComponentsWithStats(binary, connectivity=8)
+ if n > MAX_RESULTS * 4:
+ raise ValueError("too many fragments; increase cleanup or reduce sensitivity")
+ rows = []
+ for label in range(1, n):
+ px, py, width, height, pixels = map(int, stats[label])
+ cx, cy = centres[label]
+ lon, lat = geographic((x + (cx + .5) / size) / (1 << z),
+ (y + (cy + .5) / size) / (1 << z))
+ mpp = WORLD * math.cos(math.radians(lat)) / ((1 << z) * size)
+ west, north = geographic((x + px / size) / (1 << z), (y + py / size) / (1 << z))
+ east, south = geographic((x + (px + width) / size) / (1 << z),
+ (y + (py + height) / size) / (1 << z))
+ score = float(np.mean(strength[labels == label]))
+ rows.append({"id": f"{part}-{label}", "bbox": [west, south, east, north],
+ "coordinates": [lon, lat], "area": pixels * mpp * mpp,
+ "width": width * mpp, "height": height * mpp,
+ "signal_score": round(score, 4), "confidence": None,
+ "phenomenon": body.recipe.phenomenon, "review": "new",
+ "parts": [{"frames": frame_keys, "box": [px, py, width, height]}]})
+ return rows
+
+
+def merge(rows: list[dict[str, Any]], distance: float) -> list[dict[str, Any]]:
+ """Join touching seam components or explicitly requested nearby candidates."""
+ kept: list[dict[str, Any]] = []
+ for row in rows:
+ i = 0
+ while i < len(kept):
+ other = kept[i]
+ a, b = row["bbox"], other["bbox"]
+ lat = (a[1] + a[3]) / 2
+ dy = distance / 111_320
+ dx = dy / max(.08, math.cos(math.radians(lat)))
+ if a[0] <= b[2] + dx + 1e-10 and b[0] <= a[2] + dx + 1e-10 and \
+ a[1] <= b[3] + dy + 1e-10 and b[1] <= a[3] + dy + 1e-10:
+ kept.pop(i)
+ area = row["area"] + other["area"]
+ row["signal_score"] = (row["signal_score"] * row["area"] +
+ other["signal_score"] * other["area"]) / area
+ row["area"] = 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"])
+ 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))
+ row["height"] = (a[3] - a[1]) * 111_320
+ i = 0
+ else:
+ i += 1
+ kept.append(row)
+ if len(kept) > MAX_RESULTS * 2:
+ raise ValueError("too many candidates; reduce the area or increase cleanup")
+ return kept
+
+
+def prune_frames(case: Case, run: dict[str, Any]) -> None:
+ """Keep the tiles that back a result, and drop the rest of the sweep.
+
+ Every tile read is written out as a canonical PNG, because a candidate has
+ to be able to show the exact pixels it came from — that is the difference
+ between evidence and a claim. Over a large area most tiles show nothing,
+ and keeping those would tie a case's size to how much sea was swept rather
+ than to what was found in it, which is what kept the allowed area small.
+
+ A tile that produced a candidate keeps *all* of its frames, the measured
+ bands included, so the run can still say what it read. The tile cache still
+ holds the others for a re-run; what goes here is the permanent copy.
+ """
+ shown = {key for row in run["results"] for part in row["parts"] for key in part["frames"]}
+ 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:
+ 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
+ if body.offline:
+ raise ValueError("latest-date lookup needs network; select explicit dates for offline runs")
+ source = body.b.model_copy(deep=True)
+ if source.provider == "esri-wayback":
+ source.release = wayback.releases()[0].number
+ else:
+ 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(),
+ )
+ 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]
+ 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"; 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.provider == source.provider and candidate.layer == source.layer:
+ reference = candidate
+ break
+ if body.recipe.method not in SINGLE_METHODS and (
+ reference.provider == "sentinel2" and not reference.date or
+ reference.provider == "esri-wayback" and reference.release is None
+ ):
+ raise ValueError("choose a reference image for the first execution of this follow-up")
+ return body.model_copy(update={"a": reference, "b": source})
+
+
+def execute(case: Case, job: dict[str, Any]) -> None:
+ ident = job["payload"]["run_id"]
+ 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)
+ z, size = grid(body)
+ run.update(status="running", total=len(planned), resolution={"grid_zoom": z,
+ "tile_size": size}, engine_version=1)
+ persist_run(case, run)
+
+ results: list[dict[str, Any]] = []
+ identical = True
+ # 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):
+ check_active(case, ident)
+ b = frame(case, run, body.b, x, y)
+ a = b if single else frame(case, run, body.a, x, y)
+ identical &= bool((a == b).all())
+ index_a = index_b = None
+ product = PRODUCT_METHODS.get(body.recipe.method)
+ if body.recipe.method == "index":
+ index_a = frame(case, run, body.a, x, y, body.recipe.parameters.index)
+ index_b = frame(case, run, body.b, x, y, body.recipe.parameters.index)
+ identical &= bool((index_a == index_b).all())
+ elif product:
+ # Two frames for one tile: the picture the analyst reviews, and
+ # the bands the detector measures. Both are metered.
+ index_b = frame(case, run, body.b, x, y, product)
+ mask = mask_for(body.zones, z, size, x, y)
+ inside = mask.astype(bool)
+ asked += int(inside.sum())
+ imaged += int((inside & (a[:, :, 3] > 0) & (b[:, :, 3] > 0)).sum())
+ binary, strength = detect(a, b, mask, body, index_a, index_b)
+ # 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(binary, strength, body, x, y, part, keys))
+ if len(results) > MAX_RESULTS * 4:
+ raise ValueError("too many fragments; increase cleanup or use smaller areas")
+ run["progress"] = part + 1
+ persist_run(case, run)
+ joined = merge(results, body.recipe.parameters.merge_metres)
+ kept = [r for r in joined if r["area"] >= body.recipe.parameters.min_area and
+ r["signal_score"] >= body.recipe.parameters.min_score]
+ if len(kept) > MAX_RESULTS:
+ raise ValueError("too many results; increase minimum area or signal threshold")
+ kept.sort(key=lambda row: row["area"] * row["signal_score"], 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]]]}
+ swept = round(imaged / asked, 3) if asked else 0.0
+ run.update(results=kept, count=len(kept), status="ready", swept=swept,
+ message="The imagery pixels are identical" if identical and not single else "",
+ completed_at=now())
+ prune_frames(case, run)
+ persist_run(case, run)
+ except workqueue.JobCancelled:
+ raise
+ except Exception as exc:
+ # Never persist provider URLs or credentials from network exception text.
+ message = str(exc) if isinstance(exc, ValueError) else "Analysis failed; imagery could not be read"
+ run.update(status="failed", message=message)
+ persist_run(case, run)
+
+
+workqueue.register(JOB, execute)
diff --git a/src/azimut/engine/artifacts.py b/src/azimut/engine/artifacts.py
index a1c816a..11e718d 100644
--- a/src/azimut/engine/artifacts.py
+++ b/src/azimut/engine/artifacts.py
@@ -111,6 +111,12 @@ KINDS: dict[str, Kind] = {
),
"post": Kind(path_attr="draft"),
"inspect-session": Kind(path_attr="spec"),
+ # The rendered image is a media working file of its own, not a companion:
+ # 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-follow-up": Kind(path_attr="spec"),
+ "analysis-run": Kind(path_attr="spec", companions=(Named(layout.analysis_assets_rel),)),
"note": Kind(path_attr="path"),
"sheet": Kind(path_attr="path", companions=(Named(layout.sheet_meta_rel),)),
}
diff --git a/src/azimut/engine/entities.py b/src/azimut/engine/entities.py
index 59d0e17..4c536b7 100644
--- a/src/azimut/engine/entities.py
+++ b/src/azimut/engine/entities.py
@@ -531,8 +531,17 @@ ENTITY_TYPES: tuple[EntityType, ...] = (
EntityType("capture", "Capture", COLLECTED, "satellite", ATTESTATION,
hint="a map screenshot, with the provider and view it was taken from"),
# -- documents ------------------------------------------------------------
+ # `when` is the one fact a proof states that its own pixels cannot: the file
+ # it rests on may carry no date at all, and the date a video was uploaded is
+ # not the date it was shot. The composer writes it, and it is what puts the
+ # proof on the Timeline (`engine/timeline.project_entity`) rather than only
+ # the day it was filed.
EntityType("proof", "Proof", DOCUMENT, "proof", ATTESTATION,
- hint="a composed panel image, exported and still editable"),
+ hint="a composed panel image, exported and still editable",
+ attrs=(
+ Attr("when", "Taken", kind="temporal",
+ hint="when the material this proof rests on was taken"),
+ )),
EntityType("post", "Post", DOCUMENT, "post", DELIVERABLE,
hint="a prepared thread or report, saved rather than published"),
EntityType("note", "Note", DOCUMENT, "note", ANNEX,
@@ -546,6 +555,16 @@ ENTITY_TYPES: tuple[EntityType, ...] = (
hint="a CSV table in the case, edited as a grid"),
EntityType("inspect-session", "Inspect session", DOCUMENT, "inspect", ANNEX,
hint="saved adjustments over one file, which die with it"),
+ EntityType("compare-session", "Compare session", DOCUMENT, "compare", ANNEX,
+ 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"),
+ # 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,
+ hint="an analyzer, its areas and a date rule, rerun on demand"),
+ EntityType("analysis-run", "Analysis run", DOCUMENT, "changes", ANNEX,
+ hint="candidate detections with frozen inputs and review decisions"),
# The page a claim rests on. `url` and `fetched_at` are written by whatever
# filed it — the extension is on the page, so the server stamps the moment it
# was seen — and are not declared here: a declared attr is a field an analyst
diff --git a/src/azimut/engine/links.py b/src/azimut/engine/links.py
index ddac989..156ca1f 100644
--- a/src/azimut/engine/links.py
+++ b/src/azimut/engine/links.py
@@ -81,9 +81,10 @@ MADE_HERE: tuple[str, ...] = ("inspect",)
#: there a capture is noise: a geolocation ends with sixty of them beside the handful of
#: files the case collected, and the Satellite tool's own Saved panel is where they are
#: read. The extension's screenshot is the same act through another window — a map view
-#: grabbed on purpose, filed as a capture — so it is held back with them. What stays out
+#: grabbed on purpose, filed as a capture — so it is held back with them, and so is the
+#: image a saved Compare session renders of two such views. What stays out
#: is material that came from outside: an upload, a paste, a download.
-PRODUCED_HERE: tuple[str, ...] = (*MADE_HERE, "satellite", "screenshot")
+PRODUCED_HERE: tuple[str, ...] = (*MADE_HERE, "satellite", "screenshot", "compare")
#: Exact artifact contract. These are not ordinary relations: producing tools
#: record them, and the pair decides delete behaviour. A file path resolving to an
diff --git a/src/azimut/engine/media.py b/src/azimut/engine/media.py
index bc088c4..a3aad46 100644
--- a/src/azimut/engine/media.py
+++ b/src/azimut/engine/media.py
@@ -391,8 +391,8 @@ def _register(
rel_path = f"media/{media_path.name}"
kind = media_kind(media_path.name)
# Cheap image thumbnails render inline for instant feedback; a failed image
- # render and every (CPU-heavy) video are queued to the single worker, which
- # fills the sidecar in later via `set_thumbnail`.
+ # render and every (CPU-heavy) video are queued to the single worker once the
+ # sidecar exists, and the worker fills it in later via `set_thumbnail`.
thumb_rel = thumbnail_engine.on_register(case, rel_path, digest, kind)
display_name = media_path.stem
@@ -423,6 +423,7 @@ def _register(
)
indexed = {**sidecar, "path": rel_path}
case.upsert_media_item(indexed, entity_id=entity["id"])
+ thumbnail_engine.queue_if_missing(case, rel_path, kind, thumb_rel)
# Enrichment runs after the sidecar and index row exist: the handler reads
# the item back, and the worker can claim the job the moment it is queued.
enrich_engine.on_register(case, rel_path, kind, entity["id"])
@@ -584,6 +585,7 @@ def relink_existing(
old_sidecar = _sidecar_path(case.resolve_inside(old_rel))
if old_sidecar != _sidecar_path(media_path):
old_sidecar.unlink(missing_ok=True)
+ thumbnail_engine.queue_if_missing(case, rel_path, kind, thumbnail)
enrich_engine.on_register(case, rel_path, kind, entity_id)
return {"entity": updated, "item": indexed}
@@ -646,6 +648,83 @@ def import_produced_file(
return _register(case, dest, source, by=by)
+def import_rendered_bytes(
+ case: Case,
+ data: bytes,
+ title: str,
+ suffix: str,
+ source: dict[str, Any],
+ *,
+ by: str,
+ extra_attrs: dict[str, Any] | None = None,
+) -> dict[str, Any]:
+ """File an image a tool encoded itself (a PNG, an animated GIF) as media.
+
+ ``import_image`` re-encodes a PIL frame as PNG, which would flatten a GIF to
+ its first frame. The bytes here are already final, so they are written as
+ they are, and never collapsed into an identical earlier file: the entity is
+ the tool's output, and the tool may replace it later
+ (`replace_rendered_bytes`).
+ """
+ media_dir = case.subdir("media")
+ dest = unique_path(media_dir, layout.visible_filename(title, suffix))
+ dest.write_bytes(data)
+ return _register(
+ case, dest, source, by=by, extra_attrs=extra_attrs, title=title, dedupe=False
+ )
+
+
+def replace_rendered_bytes(
+ case: Case,
+ rel_path: str,
+ data: bytes,
+ source: dict[str, Any],
+ *,
+ extra_attrs: dict[str, Any] | None = None,
+) -> dict[str, Any]:
+ """Swap the pixels of a tool's own output, keeping its name, entity and links.
+
+ The caller decides this is allowed: an output something else was derived
+ from must not change under it (`api/compare.py` checks before calling). The
+ new bytes land beside the file and replace it by rename, so a reader sees the
+ old image or the new one, never half of each. The thumbnail is
+ content-addressed, so it is rendered again for the new digest.
+ """
+ with case.lock:
+ media_path = case.resolve_inside(rel_path)
+ sidecar = _sidecar_path(media_path)
+ if not media_path.is_file() or not sidecar.is_file():
+ raise ValueError(f"no media found for {rel_path!r}")
+ temporary = media_path.with_name(f".{media_path.name}.{uuid.uuid4().hex}.tmp")
+ try:
+ temporary.write_bytes(data)
+ temporary.replace(media_path)
+ finally:
+ temporary.unlink(missing_ok=True)
+ digest = sha256_file(media_path)
+ item = json.loads(sidecar.read_text(encoding="utf-8"))
+ kind = media_kind(media_path.name)
+ item.update({
+ "sha256": digest,
+ "size": media_path.stat().st_size,
+ "kind": kind,
+ "source": source,
+ "updated_at": _now(),
+ "thumbnail": thumbnail_engine.on_register(case, rel_path, digest, kind),
+ })
+ _write_sidecar(media_path, item)
+ entity = case.find_entity(attr="path", value=rel_path)
+ if entity:
+ case.update_entity(
+ entity["id"],
+ {"attrs": {"sha256": digest, "kind": kind, **(extra_attrs or {})}},
+ )
+ indexed = {**item, "path": rel_path}
+ case.upsert_media_item(indexed, entity_id=entity["id"] if entity else None)
+ thumbnail_engine.queue_if_missing(case, rel_path, kind, item["thumbnail"])
+ return {"entity": entity, "item": indexed}
+
+
def _entry_kind(entry: dict[str, Any] | None) -> str:
"""What an extracted entry would land as, read off its extension.
diff --git a/src/azimut/engine/satellite.py b/src/azimut/engine/satellite.py
index 6074014..b8ce1a7 100644
--- a/src/azimut/engine/satellite.py
+++ b/src/azimut/engine/satellite.py
@@ -969,8 +969,15 @@ def _place_geo(case: Case) -> dict[tuple[float, float], dict[str, Any]]:
Locate pass ran and the place a proof filed on the same metre are one spot,
and only the one that knows its country answers anything.
"""
+ return _geo_by_point(_page_all(case, ["place"]))
+
+
+def _geo_by_point(
+ entities: list[dict[str, Any]],
+) -> dict[tuple[float, float], dict[str, Any]]:
+ """The attrs of each point these entities stand on, a located one winning."""
found: dict[tuple[float, float], dict[str, Any]] = {}
- for place in _page_all(case, ["place"]):
+ for place in entities:
attrs = place.get("attrs") or {}
key = _at(attrs.get("lat"), attrs.get("lon"))
if key is not None and not _located(found.get(key) or {}):
@@ -1089,6 +1096,187 @@ def proof_index(
return rows
+#: What the Media position draws: photographs and footage. Audio has a place it was
+#: recorded but nothing to look at beside the imagery, and a document has neither.
+MAP_MEDIA_KINDS = ("image", "video")
+
+
+def media_index(case: Case) -> list[dict[str, Any]]:
+ """Located images and videos as map rows, newest first — one row per point.
+
+ A file holds no coordinates (ONTOLOGY §2), so where it stands is read off the
+ graph, by every road that says it:
+
+ - a ``located-at`` or ``depicts`` edge to a place: stated in Details, posed on a
+ proof's material by the point the proof concludes on, or proposed by
+ enrichment from the file's own GPS;
+ - the derivation chain (:func:`placements`), which puts a video where the proof
+ that composed a frame of it stands.
+
+ One file can stand in several places — recorded from a rooftop, showing the
+ crossroads below — and each is a row, as each of a proof's points is. Roads
+ that agree on a point are one row that keeps every one of them, so the map
+ never draws one file twice on the same metre.
+
+ **Only material the case collected.** What the app produced out of that
+ material — a frame cut in Inspect, a capture, a screenshot, a rendered
+ comparison — is working material, and it stands where the thing it was made
+ from already stands: a layer drawing both marks one spot twice and buries the
+ footage under the frames taken out of it. The set is the Media Library's own
+ (``links.PRODUCED_HERE``), so both surfaces answer "what did I bring in" the
+ same way, and the captures are read in Saved work where they belong.
+
+ Only files touching a place or a chain edge are walked. The rest cannot be
+ placed, and one grouped count finds them rather than a walk per file.
+
+ Lazy like the proofs index: read when the Media position is opened.
+ """
+ unrelated = [
+ *(verb.type for verb in links.RELATION_TYPES if verb.type not in PLACE_VERBS),
+ links.MENTIONS,
+ links.SAME_IMAGE_AS,
+ *links.CLAIM_CONNECTION_TYPES,
+ ]
+ linked = case.count_incident_links(exclude_types=unrelated)
+ saved = saved_entities(case)
+ places = {entity["id"]: entity for entity in saved if entity["type"] == "place"}
+ geo = _geo_by_point(saved)
+ proofs = {entity["id"]: entity for entity in _page_all(case, ["proof"])}
+
+ rows: list[dict[str, Any]] = []
+ for item in case.list_media_items():
+ entity_id = item.get("entity_id")
+ if (
+ not entity_id
+ or not linked.get(entity_id)
+ or (item.get("source") or {}).get("type") in links.PRODUCED_HERE
+ or item.get("kind") not in MAP_MEDIA_KINDS
+ ):
+ continue
+ incident = case.links_of(entity_id)
+ spots: dict[tuple[float, float], dict[str, Any]] = {}
+ for link in incident:
+ if link["from"] != entity_id or link["type"] not in PLACE_VERBS:
+ continue
+ place = places.get(link["to"])
+ attrs = (place or {}).get("attrs") or {}
+ point = _point(attrs.get("lat"), attrs.get("lon"))
+ if place is None or point is None:
+ continue
+ proposed = "suggested" in (
+ (link.get("provenance") or {}).get("status"),
+ (place.get("provenance") or {}).get("status"),
+ )
+ _stand(spots, point, {
+ "type": link["type"],
+ "status": "suggested" if proposed else "confirmed",
+ })
+ # A file with no chain edge derives from nothing and nothing derives from
+ # it, so the walk could only come back empty: the edges are already read
+ # here, and asking anyway is two queries per file on a whole library.
+ walked = (
+ placements(case, entity_id)
+ if any(link["type"] in links.CHAIN_TYPES for link in incident)
+ else None
+ )
+ for point in (walked or {}).get("points", []):
+ via = point.get("via") or {}
+ road: dict[str, Any] = {
+ "type": via.get("type"),
+ "id": via.get("id"),
+ "title": via.get("label") or "",
+ "status": "confirmed",
+ }
+ if via.get("id") in proofs:
+ road["name"] = _proof_name(proofs[via["id"]])
+ _stand(spots, point, road)
+ if not spots:
+ continue
+ # the proofs built straight on this file, offered wherever it stands: the
+ # one that placed a row is listed first on that row
+ composed = [
+ proofs[link["from"]]
+ for link in incident
+ if link["type"] == links.DERIVED_FROM
+ and link["to"] == entity_id
+ and link["from"] in proofs
+ ]
+ rows.extend(_media_row(case, item, spot, geo, composed) for spot in spots.values())
+ rows.sort(key=lambda r: r["fetched_at"], reverse=True)
+ return rows
+
+
+def _proof_name(entity: dict[str, Any]) -> str:
+ """The name the composer reopens a proof by: its spec file's stem."""
+ spec = str((entity.get("attrs") or {}).get("spec") or "")
+ return spec.rsplit("/", 1)[-1].removesuffix(".json")
+
+
+def _stand(
+ spots: dict[tuple[float, float], dict[str, Any]],
+ point: dict[str, Any],
+ road: dict[str, Any],
+) -> None:
+ """File one road to a point, merging it with any road already at that metre."""
+ key = _at(point["lat"], point["lon"])
+ if key is None:
+ return
+ spot = spots.setdefault(key, {"lat": point["lat"], "lon": point["lon"], "roads": []})
+ if road not in spot["roads"]:
+ spot["roads"].append(road)
+
+
+def _media_row(
+ case: Case,
+ item: dict[str, Any],
+ spot: dict[str, Any],
+ geo_at: dict[tuple[float, float], dict[str, Any]],
+ composed: list[dict[str, Any]],
+) -> dict[str, Any]:
+ lat, lon = spot["lat"], spot["lon"]
+ key = _at(lat, lon)
+ here = (geo_at.get(key) if key else None) or {}
+ geo = here.get("geo") if isinstance(here.get("geo"), dict) else None
+ thumbnail = item.get("thumbnail")
+ if thumbnail and not case.resolve_inside(str(thumbnail)).exists():
+ thumbnail = None # evicted by the budget: the row falls back to its glyph
+ linked_proofs: list[dict[str, Any]] = []
+ for road in spot["roads"]:
+ if road.get("name"):
+ linked_proofs.append({"id": road["id"], "name": road["name"], "title": road["title"]})
+ for proof in composed:
+ if all(known["id"] != proof["id"] for known in linked_proofs):
+ linked_proofs.append({
+ "id": proof["id"],
+ "name": _proof_name(proof),
+ "title": proof.get("label") or "",
+ })
+ return {
+ "id": item["entity_id"],
+ "key": f"{item['entity_id']}@{lat},{lon}",
+ "kind": "media",
+ "media_kind": item.get("kind"),
+ "title": item.get("title") or item.get("filename") or "",
+ "folder": item.get("folder") or "",
+ "notes": item.get("notes") or "",
+ "path": item.get("path"),
+ "thumbnail": thumbnail,
+ "lat": lat,
+ "lon": lon,
+ "geo": geo,
+ "continent": continents.continent_for((geo or {}).get("country_code"), lat, lon),
+ "country_en": countries.name_for((geo or {}).get("country_code")),
+ "fetched_at": _utc_stamp(item.get("added_at")),
+ # a file placed only by what a tool proposed reads as a proposal; one road
+ # the analyst stands behind is enough to make the point theirs
+ "status": "suggested"
+ if all(road["status"] == "suggested" for road in spot["roads"])
+ else "confirmed",
+ "roads": spot["roads"],
+ "linked_proofs": linked_proofs,
+ }
+
+
# -- placement: where the chain puts an entity (ONTOLOGY §3) ----------------------
#
# The chain is read backwards as geography: a proof with no point of its own stands
diff --git a/src/azimut/engine/sentinel.py b/src/azimut/engine/sentinel.py
index f9dfe23..60c9a37 100644
--- a/src/azimut/engine/sentinel.py
+++ b/src/azimut/engine/sentinel.py
@@ -223,6 +223,16 @@ _BBOX_PAD = 0.005
# dates that collapsed to.
_MAX_FEATURES = 100
+# How many points stand in for a drawn area when measuring how much of it a
+# day's granules really cover. Sampling keeps this to the geometry already
+# here — a ring and a point-in-ring test — instead of a polygon clipper, and a
+# few hundred points land the answer within a percent, which is all a "62% of
+# the area" badge can honestly claim anyway.
+_AREA_SAMPLES = 600
+# Even the smallest area in a set gets this many, so a 2 km² zone beside a
+# 2000 km² one can never be reported on by a single point.
+_AREA_SAMPLES_MIN = 9
+
# A metadata hit says a scene intersects the search area. It does not prove the
# configured layer has source pixels at the crosshair. This tiny WMS override
# asks the layer's own data source for dataMask only, over an 80 m square. The
@@ -250,6 +260,192 @@ class CoverageError(RuntimeError):
"""Sentinel Hub did not return a usable dataMask image."""
+# Spectral indices Compare's change reading can ask for. Each is a normalised
+# difference of two L2A bands, so it lands in -1…1 whatever the light that day,
+# which is what makes two dates comparable where two true-colour renders are not.
+# Only these expressions ever reach an evalscript: the request names a key.
+INDEX_BANDS: dict[str, tuple[str, str]] = {
+ "ndvi": ("B08", "B04"), # vegetation vigour
+ "ndwi": ("B03", "B08"), # open water
+ "nbr": ("B08", "B12"), # burn scars
+ "ndbi": ("B11", "B08"), # built-up and bare surfaces
+}
+PRODUCT_MAX_EDGE = 2048
+_PRODUCT_MAX_BYTES = 24_000_000
+_WEB_MERCATOR_LIMIT = 20_037_508.342789244
+
+
+def _index_evalscript(index: str) -> str:
+ high, low = INDEX_BANDS[index]
+ # R carries the index scaled to a byte, G the scene classification (cloud,
+ # shadow, snow…), A the data mask. The browser decodes all three.
+ script = f"""//VERSION=3
+function setup() {{
+ return {{
+ input: [{{ bands: ["{high}", "{low}", "SCL", "dataMask"] }}],
+ output: {{ bands: 4, sampleType: "UINT8" }}
+ }};
+}}
+function evaluatePixel(p) {{
+ const sum = p.{high} + p.{low};
+ const value = sum === 0 ? 0 : (p.{high} - p.{low}) / sum;
+ const clamped = Math.max(-1, Math.min(1, value));
+ return [Math.round((clamped + 1) * 127.5), p.SCL, 0, p.dataMask * 255];
+}}
+"""
+ return base64.b64encode(script.encode("ascii")).decode("ascii")
+
+
+# How much a reflectance is stretched before it is rounded into a byte. A
+# detector that thresholds against its own local background needs resolution
+# where the signal lives, not a scale that reaches 100% reflectance: open water
+# in the near-infrared sits under 3%, so at this gain it spans the bottom fifth
+# of the byte instead of two or three values. Anything above 1/gain saturates,
+# which costs nothing — these are detections, not measurements.
+NIR_GAIN = 8.0
+SWIR_GAIN = 4.0
+# Band ratios are stretched the same way, and 64 puts the useful 1…4 range
+# across the byte.
+RATIO_GAIN = 64.0
+
+
+def _vessel_evalscript() -> str:
+ """Bands for finding something floating: infrared, water, and the classes.
+
+ Water absorbs near-infrared almost completely, so a hull, a wake or a rig
+ is an outlier against a near-black background — which is why this reads
+ B08 rather than the rendered picture, where the stretch has already thrown
+ the difference away. NDWI rides along in B so the detector can tell which
+ pixels are sea without a second request.
+ """
+ script = """//VERSION=3
+function setup() {
+ return {
+ input: [{ bands: ["B03", "B08", "SCL", "dataMask"] }],
+ output: { bands: 4, sampleType: "UINT8" }
+ };
+}
+function evaluatePixel(p) {
+ const sum = p.B03 + p.B08;
+ const ndwi = sum === 0 ? 0 : (p.B03 - p.B08) / sum;
+ return [
+ Math.min(255, Math.round(p.B08 * 255 * %(nir)s)),
+ p.SCL,
+ Math.round((Math.max(-1, Math.min(1, ndwi)) + 1) * 127.5),
+ p.dataMask * 255
+ ];
+}
+""" % {"nir": NIR_GAIN}
+ return base64.b64encode(script.encode("ascii")).decode("ascii")
+
+
+def _fire_evalscript() -> str:
+ """Bands for the published Sentinel-2 active-fire test.
+
+ Flame radiates in the short-wave infrared, so B12 rises first and hardest
+ and does it through smoke. Absolute brightness alone would call every
+ cloud a fire; the two ratios are what separate them, because cloud is
+ bright in all three bands at once and sits near a ratio of one.
+
+ No scene classification here: the ratios already reject cloud, and the
+ fourth channel is worth more as the data mask.
+ """
+ script = """//VERSION=3
+function setup() {
+ return {
+ input: [{ bands: ["B08", "B11", "B12", "dataMask"] }],
+ output: { bands: 4, sampleType: "UINT8" }
+ };
+}
+function evaluatePixel(p) {
+ const over11 = p.B11 <= 0 ? 0 : p.B12 / p.B11;
+ const over08 = p.B08 <= 0 ? 0 : p.B12 / p.B08;
+ return [
+ Math.min(255, Math.round(p.B12 * 255 * %(swir)s)),
+ Math.min(255, Math.round(over11 * %(ratio)s)),
+ Math.min(255, Math.round(over08 * %(ratio)s)),
+ p.dataMask * 255
+ ];
+}
+""" % {"swir": SWIR_GAIN, "ratio": RATIO_GAIN}
+ return base64.b64encode(script.encode("ascii")).decode("ascii")
+
+
+# Everything a caller may ask `band_frame` for. Indices are normalised
+# differences the change reading compares between two dates; the other two are
+# detector inputs, read from one date.
+PRODUCTS: frozenset[str] = frozenset({*INDEX_BANDS, "vessel", "fire"})
+
+
+def _evalscript(product: str) -> str:
+ if product in INDEX_BANDS:
+ return _index_evalscript(product)
+ return _vessel_evalscript() if product == "vessel" else _fire_evalscript()
+
+
+def band_frame(
+ instance: str,
+ bbox: tuple[float, float, float, float],
+ width: int,
+ height: int,
+ day: str,
+ product: str,
+ maxcc: int = DEFAULT_MAXCC,
+ *,
+ layer: str = DEFAULT_LAYER,
+ 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.
+ """
+ if product not in PRODUCTS:
+ raise ValueError(f"unknown band product '{product}'")
+ west, south, east, north = bbox
+ if not all(abs(value) <= _WEB_MERCATOR_LIMIT for value in bbox):
+ raise ValueError("the frame is outside Web Mercator bounds")
+ if west >= east or south >= north:
+ raise ValueError("the frame is empty")
+ if not (1 <= width <= PRODUCT_MAX_EDGE and 1 <= height <= PRODUCT_MAX_EDGE):
+ raise ValueError(f"the frame must be 1 to {PRODUCT_MAX_EDGE} px on each side")
+ checked_layer, checked_day, _, checked_maxcc = parse_variant(
+ f"{layer}{VARIANT_SEP}{day}{VARIANT_SEP}{day}{VARIANT_SEP}CC{int(maxcc)}"
+ )
+ params = {
+ "SERVICE": "WMS",
+ "REQUEST": "GetMap",
+ "VERSION": "1.3.0",
+ "LAYERS": checked_layer,
+ "CRS": "EPSG:3857",
+ "BBOX": f"{west},{south},{east},{north}",
+ "WIDTH": str(width),
+ "HEIGHT": str(height),
+ "FORMAT": "image/png",
+ "TIME": f"{checked_day}/{checked_day}",
+ "MAXCC": str(checked_maxcc),
+ "EVALSCRIPT": _evalscript(product),
+ }
+ fetch = get or httpx.get
+ response = fetch(
+ f"{BASE}/wms/{instance}", params=params,
+ headers={"User-Agent": USER_AGENT}, timeout=45,
+ )
+ response.raise_for_status()
+ body = response.content
+ if len(body) > _PRODUCT_MAX_BYTES:
+ raise CoverageError("the index frame is too large")
+ try:
+ with Image.open(io.BytesIO(body)) as frame:
+ if frame.format != "PNG" or frame.size != (width, height):
+ raise CoverageError("Sentinel Hub returned an unexpected index frame")
+ except (OSError, UnidentifiedImageError) as exc:
+ raise CoverageError("Sentinel Hub returned no readable index frame") from exc
+ return body
+
+
def _cloud(props: dict[str, Any]) -> float | None:
for name in ("cloudCoverPercentage", "tileCloudCoverPercentage"):
value = props.get(name)
@@ -287,52 +483,102 @@ def _in_ring(x: float, y: float, ring: list[list[float]]) -> bool:
return inside
-def _covers(lat: float, lon: float, geometry: dict[str, Any] | None) -> bool:
- """Does this granule's footprint actually contain the point?
+Box = tuple[float, float, float, float]
+Ring = list[Any]
+
+
+def _ring_box(ring: Ring) -> Box:
+ """A ring's bounds as ``(left, bottom, right, top)`` in its own axis order."""
+ xs = [point[0] for point in ring]
+ ys = [point[1] for point in ring]
+ return min(xs), min(ys), max(xs), max(ys)
+
+
+def _boxes_meet(one: Box, other: Box) -> bool:
+ return not (one[2] < other[0] or one[0] > other[2] or one[3] < other[1] or one[1] > other[3])
+
+
+def _oriented(ring: Ring, box: Box) -> Ring:
+ """A granule ring as (lon, lat), whichever axis order the service answered in.
+
+ GeoJSON says longitude first, but an OGC service asked for EPSG:4326 may
+ honour the CRS's latitude-first order instead, and read backwards every
+ footprint on Earth misses. So the reading that lands near the area asked
+ about wins; when neither does, the standard one stays and the ring simply
+ covers nothing — which is the right answer for a granule a province away.
+ """
+ if _boxes_meet(_ring_box(ring), box):
+ return ring
+ swapped = [(point[1], point[0]) for point in ring]
+ return swapped if _boxes_meet(_ring_box(swapped), box) else ring
+
+
+def _covered(feature: dict[str, Any], samples: list[tuple[float, float]], box: Box) -> set[int]:
+ """Which of ``samples`` this granule's footprint actually contains.
Why it matters: a granule's *bounding box* is a square, but its data is the
slice of orbit swath inside it — the rest is nodata. WFS answers on the box,
- so a day can be listed while the pixels over your point are black. Pinned to
+ so a day can be listed while the pixels over the area are black. Pinned to
that day the map has nothing to show and goes dark, which is the "why is
this date black?" a date list exists to prevent.
- GeoJSON says longitude first, but an OGC service asked for EPSG:4326 may
- honour the CRS's latitude-first axis order instead, and getting it backwards
- would reject every granule on Earth. So a granule counts as covering the
- point if it does under *either* reading: a footprint genuinely 100 km away
- contains it under neither, which is the case worth acting on. Unparseable
- geometry keeps the granule — never drop a real pass over a guess.
+ Unparseable geometry counts as covering everything — never drop a real pass
+ over a guess.
"""
- rings = _rings(geometry)
+ rings = _rings(feature.get("geometry"))
if not rings:
- return True
- return any(_in_ring(lon, lat, ring) or _in_ring(lat, lon, ring) for ring in rings)
+ return set(range(len(samples)))
+ hit: set[int] = set()
+ for ring in rings:
+ oriented = _oriented(ring, box)
+ left, bottom, right, top = _ring_box(oriented)
+ for position, (x, y) in enumerate(samples):
+ if position in hit or not (left <= x <= right and bottom <= y <= top):
+ continue
+ if _in_ring(x, y, oriented):
+ hit.add(position)
+ return hit
+
+
+def _window(start: str, end: str) -> str:
+ """The ``TIME`` window, checked before it becomes a request parameter.
+
+ Shape *and* calendar: ``2026-13-01`` is the right shape and not a day, and
+ unchecked it would leave as a request and come back as a gateway error
+ rather than the plain "that is not a date" it is.
+ """
+ for value in (start, end):
+ if not _DATE_RE.match(value or ""):
+ raise ValueError(f"malformed date '{value}' (expected YYYY-MM-DD)")
+ try:
+ date.fromisoformat(value)
+ except ValueError as exc:
+ raise ValueError(f"impossible date '{value}'") from exc
+ if start > end:
+ raise ValueError(f"window ends before it starts ({start} → {end})")
+ return f"{start}/{end}"
-def dates(
+def _passes(
instance: str,
- lat: float,
- lon: float,
+ box: Box,
+ samples: list[tuple[float, float]],
start: str,
end: str,
*,
get: Callable[..., Any] | None = None,
-) -> list[dict[str, Any]]:
- """Sentinel-2 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.
+) -> tuple[dict[str, dict[str, Any]], int]:
+ """One WFS query, collapsed to per-day entries and the samples each covers.
- 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. A WFS query is billed as
- one request (~0.01 PU, versus a tile's 1 PU), so the caller counts it on the
- meter — cheap, but not free, and the meter never lies by omission.
+ A WFS query is billed as one request (~0.01 PU, versus a tile's 1 PU), so
+ the caller counts it on the meter — cheap, but not free, and the meter never
+ lies by omission.
Raises httpx.HTTPError / ValueError upward: a date list that failed must not
read as "no imagery here".
"""
fetch = get or httpx.get
+ left, bottom, right, top = box
params = {
"SERVICE": "WFS",
"REQUEST": "GetFeature",
@@ -342,8 +588,8 @@ def dates(
# 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.
"SRSNAME": "EPSG:4326",
- "BBOX": f"{lat - _BBOX_PAD},{lon - _BBOX_PAD},{lat + _BBOX_PAD},{lon + _BBOX_PAD}",
- "TIME": f"{start}/{end}",
+ "BBOX": f"{bottom},{left},{top},{right}",
+ "TIME": _window(start, end),
"MAXFEATURES": str(_MAX_FEATURES),
# every pass, cloudy ones included: the calendar shows cover per day and
# the user's own ceiling decides what to grey out. A list already cut by
@@ -363,16 +609,131 @@ def dates(
day = str(props.get("date") or "")[:10]
if not _DATE_RE.match(day):
continue
- # the granule's box may reach the point while its imagery doesn't
- if not _covers(lat, lon, feature.get("geometry")):
+ # the granule's box may reach the area while its imagery doesn't
+ hit = _covered(feature, samples, box)
+ if not hit:
continue
cloud = _cloud(props)
- entry = by_date.setdefault(day, {"date": day, "cloud": cloud, "granules": 0})
+ entry = by_date.setdefault(
+ day, {"date": day, "cloud": cloud, "granules": 0, "covered": set()}
+ )
entry["granules"] += 1
- # the granule that actually covers the point may be the clearer of two
+ entry["covered"] |= hit
+ # 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 sorted(by_date.values(), key=lambda entry: entry["date"], reverse=True)
+ return by_date, len(features)
+
+
+def dates(
+ instance: str,
+ lat: float,
+ lon: float,
+ start: str,
+ end: str,
+ *,
+ get: Callable[..., Any] | None = None,
+) -> list[dict[str, Any]]:
+ """Sentinel-2 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.
+
+ 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
+ than a crosshair, ``acquisitions`` answers the same question with a coverage
+ 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)
+ return sorted(
+ ({"date": e["date"], "cloud": e["cloud"], "granules": e["granules"]}
+ for e in found.values()),
+ key=lambda entry: entry["date"], reverse=True,
+ )
+
+
+def _shoelace(ring: Ring) -> float:
+ """A ring's area in square degrees, narrowed for the latitude it sits at.
+
+ Only ever compared against other rings in the same set, so a flat local
+ approximation is enough — this decides how to share sample points out, not
+ what to report.
+ """
+ middle = sum(point[1] for point in ring) / len(ring)
+ scale = math.cos(math.radians(max(-89.0, min(89.0, middle))))
+ total = 0.0
+ for index, (x1, y1) in enumerate(ring):
+ x2, y2 = ring[(index + 1) % len(ring)]
+ total += (x1 * scale) * y2 - (x2 * scale) * y1
+ return abs(total) / 2
+
+
+def _ring_samples(ring: Ring, want: int) -> list[tuple[float, float]]:
+ """``want``-ish points spread evenly over a ring's interior."""
+ left, bottom, right, top = _ring_box(ring)
+ # a ring fills roughly π/4 of its own box, so a grid that size lands near
+ # the count asked for once the outside points are dropped
+ side = max(3, math.ceil(math.sqrt(want * 4 / math.pi)))
+ found = []
+ for row in range(side):
+ y = bottom + (row + 0.5) * (top - bottom) / side
+ for column in range(side):
+ x = left + (column + 0.5) * (right - left) / side
+ if _in_ring(x, y, ring):
+ found.append((x, y))
+ # a ring too thin for the grid to land in still stands for somewhere
+ return found or [((left + right) / 2, (bottom + top) / 2)]
+
+
+def _area_samples(rings: list[Ring]) -> list[tuple[float, float]]:
+ """Points standing in for the drawn areas, at one density across all of them."""
+ weights = [_shoelace(ring) for ring in rings]
+ total = sum(weights) or 1.0
+ samples: list[tuple[float, float]] = []
+ for ring, weight in zip(rings, weights):
+ samples.extend(_ring_samples(ring, max(_AREA_SAMPLES_MIN, round(_AREA_SAMPLES * weight / total))))
+ return samples
+
+
+def acquisitions(
+ instance: str,
+ rings: list[Ring],
+ start: str,
+ end: str,
+ *,
+ get: Callable[..., Any] | None = None,
+) -> dict[str, Any]:
+ """Sentinel-2 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
+ lookup cannot give and an area sweep cannot do without — Sentinel-2 flies
+ 290 km-wide swaths, so an area wider than one of them has *no* single day
+ that covers it, and pinned to one date half the sweep reads nodata.
+
+ ``truncated`` says the WFS hit its feature ceiling, so older passes in the
+ window are missing and the window wants narrowing.
+ """
+ if not rings:
+ raise ValueError("no area to look up")
+ samples = _area_samples(rings)
+ boxes = [_ring_box(ring) for ring in rings]
+ box = (
+ max(-180.0, min(b[0] for b in boxes) - _BBOX_PAD),
+ max(-90.0, min(b[1] for b in boxes) - _BBOX_PAD),
+ 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)
+ listed = sorted(
+ ({"date": entry["date"], "cloud": entry["cloud"], "granules": entry["granules"],
+ "coverage": round(len(entry["covered"]) / len(samples), 3)}
+ for entry in found.values()),
+ key=lambda entry: entry["date"], reverse=True,
+ )
+ return {"dates": listed, "truncated": features >= _MAX_FEATURES}
def coverage(
diff --git a/src/azimut/engine/thumbnails.py b/src/azimut/engine/thumbnails.py
index 0c96bf9..05a21d2 100644
--- a/src/azimut/engine/thumbnails.py
+++ b/src/azimut/engine/thumbnails.py
@@ -155,22 +155,30 @@ def enqueue(case: "CaseType", rel_media: str) -> dict[str, Any]:
def on_register(case: "CaseType", rel_media: str, sha256: str, kind: str) -> str | None:
- """Decide a freshly-registered media file's thumbnail. Cheap image thumbnails
- render inline (instant feedback); a failed image render and every video are
- handed to the durable queue. Returns the thumbnail path if produced inline,
- else None (the worker fills it in and updates the sidecar)."""
+ """Render a freshly-registered media file's thumbnail inline when that is
+ cheap (an image). Returns the thumbnail path, or None when the file needs the
+ queue instead: every video, and an image whose inline render failed.
+
+ It never queues. The caller writes the sidecar first and then calls
+ `queue_if_missing`, because the worker can claim a job the moment it exists
+ and reads that sidecar back to record its result."""
if kind == "image":
try:
return generate(case, rel_media, sha256, kind)
except ThumbnailError:
- enqueue(case, rel_media)
return None
- if kind == "video":
- enqueue(case, rel_media)
- return None
return None
+def queue_if_missing(case: "CaseType", rel_media: str, kind: str, thumbnail: str | None) -> None:
+ """Hand a registered file with no thumbnail yet to the durable queue. Called
+ once its sidecar and index row exist: queued earlier, a quick worker found no
+ sidecar and dropped the job, or set the thumbnail only to have the sidecar
+ write that followed put it back to None."""
+ if kind in ("image", "video") and not thumbnail:
+ enqueue(case, rel_media)
+
+
# -- the enqueued (CPU-heavy) path -----------------------------------------
#
# Video frames go through the shared durable queue (engine/workqueue.py) so
diff --git a/src/azimut/engine/timeline.py b/src/azimut/engine/timeline.py
index dfb7faa..1bd45cc 100644
--- a/src/azimut/engine/timeline.py
+++ b/src/azimut/engine/timeline.py
@@ -134,7 +134,7 @@ def project_entity(entity: dict[str, Any]) -> list[ProjectionRow]:
# the graph filing timestamp beside the more specific "Added to case" value.
if type_ in {"media", "capture"}:
return []
- return [
+ rows = [
_project_value(
id=f"temporal:activity:{entity_id}:filed",
owner_id=entity_id,
@@ -144,6 +144,23 @@ def project_entity(entity: dict[str, Any]) -> list[ProjectionRow]:
raw=provenance.get("at"),
)
]
+ # A proof states when the material it rests on was taken — read off the file
+ # when it carried a date, typed when it did not. It is a statement and not a
+ # media fact: the sidecar's own `captured` says what the file claims, this
+ # says what the analyst concluded, and a proof keeps its filing row either way.
+ if type_ == "proof" and attrs.get("when") not in (None, ""):
+ rows.append(
+ _project_value(
+ id=f"temporal:proof:{entity_id}:taken",
+ owner_id=entity_id,
+ authority="entity",
+ category=STATEMENT,
+ kind="taken",
+ raw=attrs.get("when"),
+ time_role="occurred",
+ )
+ )
+ return rows
_COMPACT_DATE = re.compile(r"(?P<year>\d{4})(?P<month>\d{2})(?P<day>\d{2})\Z")
diff --git a/src/azimut/layout.py b/src/azimut/layout.py
index 1f1e65a..960a880 100644
--- a/src/azimut/layout.py
+++ b/src/azimut/layout.py
@@ -52,6 +52,10 @@ TOOL_DIR = "azimut"
DRAFTS_DIR = ".drafts"
#: Saved Inspect session specs.
INSPECT_DIR = ".inspect"
+#: Saved Compare session specs. Their rendered image is a media working file.
+COMPARE_DIR = ".compare"
+# Saved analyzer zones, follow-ups and runs with their owned input frames.
+ANALYSIS_DIR = ".analysis"
#: Saved Grid Search state.
SEARCH_DIR = ".search"
#: Machinery that belongs to a visible sibling: `media/.meta/` holds sidecars,
@@ -75,6 +79,8 @@ CASE_SUBDIRS = (
"exports",
DRAFTS_DIR,
INSPECT_DIR,
+ COMPARE_DIR,
+ ANALYSIS_DIR,
SEARCH_DIR,
)
@@ -455,6 +461,14 @@ def session_rel(name: str) -> str:
return f"{INSPECT_DIR}/{name}.json"
+def compare_session_rel(name: str) -> str:
+ return f"{COMPARE_DIR}/{name}.json"
+
+
+def analysis_assets_rel(name: str) -> str:
+ return f"{ANALYSIS_DIR}/{name}.assets"
+
+
def grid_rel(name: str) -> str:
return f"{SEARCH_DIR}/{name}.json"
diff --git a/src/azimut/server.py b/src/azimut/server.py
index 787993b..93be4a7 100644
--- a/src/azimut/server.py
+++ b/src/azimut/server.py
@@ -36,12 +36,10 @@ LOCAL_HOSTNAMES = frozenset({"127.0.0.1", "localhost", "::1", "[::1]"})
class BulkBodyLimit:
- """Bound the JSON routes that carry a payload the browser assembled, before parsing.
+ """Bound routes that carry browser-assembled files or documents before parsing.
- Four of them: a note's PDF export posts its Mermaid diagrams, an analysis plate posts
- the page itself, a sheet posts a whole table, and saving a proof posts the composer's
- rendered export plus the images pasted into it. Each is bounded by its own route's
- number, so the limit stays beside the code that knows what it is for.
+ Each route owns its number, so the limit stays beside the code that knows what the
+ payload contains. This covers JSON documents, images and multipart comparison frames.
"""
#: `(method, tail, module, attribute)`, where the tail is the path segments after
@@ -64,6 +62,8 @@ class BulkBodyLimit:
("PUT", ("notes",), "notes", "MAX_NOTE_BODY_BYTES"),
("PUT", ("notes", "*"), "notes", "MAX_NOTE_BODY_BYTES"),
("POST", ("plates",), "plates", "MAX_PLATE_BODY_BYTES"),
+ ("POST", ("compare", "gif"), "compare", "MAX_GIF_BODY_BYTES"),
+ ("POST", ("compare", "sessions", "*", "preview"), "compare", "MAX_GIF_BODY_BYTES"),
("POST", ("proofs",), "proofs", "MAX_PROOF_BODY_BYTES"),
("POST", ("sheets",), "sheets", "MAX_SHEET_BODY_BYTES"),
("POST", ("sheets", "import"), "sheets", "MAX_SHEET_BODY_BYTES"),
@@ -287,7 +287,7 @@ def create_app() -> FastAPI:
)
from .api import (
- analysis_views, cases, drafts, events, files, folders, ingest, inspect, media,
+ analysis_views, analyzers, cases, compare, drafts, events, files, folders, ingest, inspect, media,
notes, plates, proofimports, proofs, satellite, settings, sheetproofs, sheets,
templates,
)
@@ -303,6 +303,8 @@ def create_app() -> FastAPI:
app.include_router(sheetproofs.router)
app.include_router(media.router)
app.include_router(inspect.router)
+ app.include_router(compare.router)
+ app.include_router(analyzers.router)
app.include_router(satellite.router)
app.include_router(proofs.router)
app.include_router(proofimports.router)
diff --git a/src/azimut/sqlite_backend.py b/src/azimut/sqlite_backend.py
index ef7d41c..bf6b6a0 100644
--- a/src/azimut/sqlite_backend.py
+++ b/src/azimut/sqlite_backend.py
@@ -119,7 +119,10 @@ if TYPE_CHECKING:
# Schema 16 lets the existing Analysis View store own Timeline recipes and snapshots.
# Schema 17 rebuilds the derived temporal projection with fixed-width UTC bounds, so
# SQLite text ordering remains chronological at sub-second precision.
-SQLITE_SCHEMA = 17
+# Schema 18 rebuilds it again, now that a proof's stated date is projected as a
+# statement: proofs dated before the projection could read them still reach the
+# Timeline, without re-saving each one.
+SQLITE_SCHEMA = 18
_SCHEMA = """
CREATE TABLE meta (
diff --git a/src/azimut/store/migrations.py b/src/azimut/store/migrations.py
index dd1b373..9e98635 100644
--- a/src/azimut/store/migrations.py
+++ b/src/azimut/store/migrations.py
@@ -293,6 +293,17 @@ def _migrate_16_to_17(conn: sqlite3.Connection) -> None:
_rebuild_temporal_projection_conn(conn)
+def _migrate_17_to_18(conn: sqlite3.Connection) -> None:
+ """Project the date a proof states for the material it rests on.
+
+ Nothing about the stored proofs changes: the projection is derived, and it
+ simply did not read that attribute before. A case whose proofs were dated by
+ an older build — the attribute survives a schema it predates — reaches the
+ Timeline on the first open rather than on the next save of each proof.
+ """
+ _rebuild_temporal_projection_conn(conn)
+
+
# from_version -> function(conn) applying the in-place upgrade to from_version + 1.
# The whole chain runs inside one immediate transaction in `SqliteCase._upgrade`,
# which stamps each new schema_version and records each migration as it goes; a
@@ -315,4 +326,5 @@ _SQLITE_MIGRATIONS: dict[int, Callable[[sqlite3.Connection], None]] = {
14: _migrate_14_to_15,
15: _migrate_15_to_16,
16: _migrate_16_to_17,
+ 17: _migrate_17_to_18,
}
diff --git a/src/azimut/store/rows.py b/src/azimut/store/rows.py
index ee6e537..fa6683b 100644
--- a/src/azimut/store/rows.py
+++ b/src/azimut/store/rows.py
@@ -54,19 +54,22 @@ _MEDIA_CATEGORIES = (
"video",
"collage",
"satellite",
+ "comparison",
"upload",
"download",
"other",
)
+_NOT_COMPARISON_SQL = "COALESCE(source_type, '') != 'compare'"
_SATELLITE_SQL = (
"(COALESCE(source_type, '') = 'satellite' OR "
"(COALESCE(source_type, '') = 'screenshot' AND imagery_mode = 'satellite'))"
)
_MEDIA_CATEGORY_SQL = {
- "image": f"(kind = 'image' AND NOT {_SATELLITE_SQL})",
+ "image": f"(kind = 'image' AND NOT {_SATELLITE_SQL} AND {_NOT_COMPARISON_SQL})",
"video": "kind = 'video'",
"collage": "source_op = 'collage'",
"satellite": _SATELLITE_SQL,
+ "comparison": "source_type = 'compare'",
# A paste and a drop are one facet: both are material the analyst brought in
# by hand, which is the question this filter asks. They stay two source types
# because the gesture is part of the record — a screenshot is not a file that
diff --git a/src/azimut/workspace.py b/src/azimut/workspace.py
index d0f26dd..3a818f3 100644
--- a/src/azimut/workspace.py
+++ b/src/azimut/workspace.py
@@ -555,7 +555,7 @@ class Case(CaseStore):
has_graph = bool(case.list_entities() or case.list_links())
except (OSError, json.JSONDecodeError, sqlite3.Error):
continue
- if has_graph:
+ if has_graph or data.get("todos", {}).get("lists"):
continue
stamp = data.get("updated_at") or data.get("created_at") or ""
try:
@@ -696,6 +696,21 @@ class Case(CaseStore):
tmp.write_text(json.dumps(data, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
_replace_with_retry(tmp, self.json_path)
+ def read_todos(self) -> dict[str, Any]:
+ return self.read().get("todos", {
+ "revision": 0,
+ "lists": [{"id": "default", "name": "Tasks", "tasks": []}],
+ })
+
+ def write_todos(self, todos: dict[str, Any]) -> dict[str, Any]:
+ """Write case metadata atomically; it owns no separate artifact files."""
+ with self._lock:
+ data = self.read()
+ saved = {**todos, "revision": todos["revision"] + 1}
+ data["todos"] = saved
+ self._write_json(data)
+ return saved
+
# -- graph reads (CaseRepository boundary) ------------------------------
#
# The one way engine and API code reads the graph: no caller reaches into
@@ -950,6 +965,7 @@ class Case(CaseStore):
rules: dict[str, tuple[str, Callable[[str], str], str]] = {
"proof": ("spec", layout.proof_spec_rel, "Proof"),
"inspect-session": ("spec", layout.session_rel, "Inspect"),
+ "compare-session": ("spec", layout.compare_session_rel, "Comparison"),
"post": ("draft", layout.draft_rel, "Post"),
"sheet": ("path", layout.sheet_rel, "Sheet"),
}
diff --git a/tests/analyzerfixture.py b/tests/analyzerfixture.py
new file mode 100644
index 0000000..bb97d1f
--- /dev/null
+++ b/tests/analyzerfixture.py
@@ -0,0 +1,124 @@
+"""Synthetic imagery inputs for analyzer and full-case integration gates."""
+
+import io
+
+import numpy as np
+from PIL import Image
+
+from azimut import layout
+from azimut.engine import analyzers, sentinel, tilecache
+from azimut.engine.analysis_models import BUILTINS, PRODUCT_METHODS, RunInput
+
+
+def sample_input():
+ # One complete interior patch, in exactly one native Wayback tile.
+ z, x, y = 19, 265056, 182248
+ west, north = analyzers.geographic((x + .1) / 2**z, (y + .1) / 2**z)
+ east, south = analyzers.geographic((x + .9) / 2**z, (y + .9) / 2**z)
+ recipe = BUILTINS[0].model_dump()
+ recipe["parameters"].update(min_area=0, cleanup=0, smoothing=0)
+ return {"title": "Harbour check", "recipe": recipe,
+ "zones": [{"id": "harbour", "name": "Harbour", "kind": "rect",
+ "points": [[west, south], [east, north]]}],
+ "a": {"provider": "esri-wayback", "release": 1},
+ "b": {"provider": "esri-wayback", "release": 2}, "offline": True}
+
+
+def seed_images(body):
+ for x, y in analyzers.plan(RunInput.model_validate(body)):
+ for release in (1, 2):
+ pixels = np.full((256, 256, 3), 40, np.uint8)
+ if release == 2:
+ pixels[90:120, 100:150] = 230
+ out = io.BytesIO()
+ Image.fromarray(pixels).save(out, "PNG")
+ tilecache.put(f"esri-wayback~{release}", 19, x, y, out.getvalue(), "image/png")
+
+
+# One native Sentinel tile: level 13 of the 512px grid, which is 9.55 m a pixel.
+SENTINEL_TILE = (13, 4230, 2930)
+SENTINEL_DAY = "2026-05-11"
+
+
+def sentinel_input(recipe_id, **parameters):
+ """A one-tile Copernicus run for a detector that reads bands, not pictures.
+
+ Keeps the preset's own thresholds unless a test says otherwise: they are
+ part of what is being tested, and a detector tuned down to catch everything
+ would prove nothing about the one it ships with.
+ """
+ z, x, y = SENTINEL_TILE
+ west, north = analyzers.geographic((x + .1) / 2**z, (y + .1) / 2**z)
+ east, south = analyzers.geographic((x + .9) / 2**z, (y + .9) / 2**z)
+ recipe = next(r for r in BUILTINS if r.id == recipe_id).model_dump()
+ recipe["parameters"].update(parameters)
+ source = {"provider": "sentinel2", "date": SENTINEL_DAY,
+ "layer": "TRUE_COLOR", "maxcc": 30}
+ return {"title": f"{recipe_id} sweep", "recipe": recipe,
+ "zones": [{"id": "patch", "name": "Patch", "kind": "rect",
+ "points": [[west, south], [east, north]]}],
+ "a": dict(source), "b": dict(source), "offline": True}
+
+
+def seed_sentinel(case, body, bands):
+ """Put one picture and one band product where an offline run will find them.
+
+ The product lands under a preserved run's assets, which is the path a
+ reopened case takes, and its filename comes from the engine's own key
+ function — a copy of that naming here would be a second source of truth
+ that silently stops matching.
+ """
+ z, x, y = SENTINEL_TILE
+ parsed = RunInput.model_validate(body)
+ picture = io.BytesIO()
+ Image.fromarray(np.full((512, 512, 3), 30, np.uint8)).save(picture, "PNG")
+ tilecache.put(
+ sentinel.variant_id("sentinel2", parsed.b.layer, parsed.b.date,
+ parsed.b.date, parsed.b.maxcc),
+ z, x, y, picture.getvalue(), "image/png",
+ )
+ product = PRODUCT_METHODS[parsed.recipe.method]
+ folder = case.subdir(layout.ANALYSIS_DIR) / "runs-seed.assets"
+ folder.mkdir(parents=True, exist_ok=True)
+ frame = io.BytesIO()
+ Image.fromarray(bands, "RGBA").save(frame, "PNG")
+ (folder / f"{analyzers._key(parsed.b, z, x, y, product)}.png").write_bytes(frame.getvalue())
+
+
+def vessel_bands(targets):
+ """Near-infrared over a sea that brightens across the tile, plus targets.
+
+ The ramp is the point: a sunlit swell can be brighter than a hull half a
+ kilometre away, so an absolute threshold has to be retuned per scene and a
+ local one does not. Channels are what the vessel evalscript returns —
+ infrared, scene class, NDWI, data mask.
+ """
+ ramp = np.linspace(10, 130, 512, dtype=np.float32)
+ bands = np.zeros((512, 512, 4), np.uint8)
+ bands[:, :, 0] = np.broadcast_to(ramp, (512, 512)).astype(np.uint8)
+ bands[:, :, 1] = 6 # Sentinel-2 scene class 6 is water
+ bands[:, :, 2] = 178 # NDWI ≈ +0.4
+ bands[:, :, 3] = 255
+ for px, py, width, height in targets:
+ bands[py:py + height, px:px + width, 0] = np.clip(
+ bands[py:py + height, px:px + width, 0].astype(np.int16) + 100, 0, 255).astype(np.uint8)
+ bands[py:py + height, px:px + width, 2] = 64 # a hull is not water
+ return bands
+
+
+def fire_bands(fire, cloud):
+ """Short-wave infrared and the two band ratios the fire test reads.
+
+ The cloud patch is the trap: bright in B12 like a fire, but bright in its
+ neighbours too, so its ratios sit at one and the test must pass it over.
+ """
+ bands = np.zeros((512, 512, 4), np.uint8)
+ bands[:, :, 0] = 102 # B12 ≈ 0.10 reflectance, under the fire floor
+ bands[:, :, 1] = 70 # B12/B11 ≈ 1.1
+ bands[:, :, 2] = 51 # B12/B08 ≈ 0.8
+ bands[:, :, 3] = 255
+ px, py, width, height = cloud
+ bands[py:py + height, px:px + width] = [255, 64, 64, 255] # bright, ratios at one
+ px, py, width, height = fire
+ bands[py:py + height, px:px + width] = [255, 160, 192, 255] # bright, ratios well over
+ return bands
diff --git a/tests/fullcase.py b/tests/fullcase.py
index 874b313..efb9626 100644
--- a/tests/fullcase.py
+++ b/tests/fullcase.py
@@ -41,6 +41,11 @@ class FullCase:
collage: str = ""
capture: str = ""
session: str = ""
+ compare_session: str = ""
+ compare_image: str = "" # the session's render, a media working file
+ analyzer_zones: str = ""
+ analyzer_followup: str = ""
+ analyzer_run: str = ""
proof: str = ""
proof_asset: str = ""
draft: str = ""
@@ -81,6 +86,15 @@ def build_full_case(client, name: str = "Full case") -> FullCase:
case_id = client.post("/api/cases", json={"name": name}).json()["id"]
full = FullCase(case_id=case_id)
+ # Checklists are manifest metadata, with no graph entity or owned files.
+ response = client.put(f"/api/cases/{case_id}/todos", json={
+ "revision": 0,
+ "lists": [{"id": "checks", "name": "Checks", "tasks": [
+ {"id": "source", "text": "Verify source", "done": True},
+ ]}],
+ })
+ assert response.status_code == 200, response.text
+
# -- media: two uploads, and a collage composed from both ----------------
def upload(filename: str, data: bytes) -> str:
res = client.post(
@@ -134,6 +148,31 @@ def build_full_case(client, name: str = "Full case") -> FullCase:
assert session.status_code == 200, session.text
full.session = f".inspect/{session.json()['name']}.json"
+ comparison = client.post(
+ f"/api/cases/{case_id}/compare/sessions",
+ json={
+ "title": "Harbour change",
+ "spec": {
+ "version": 2,
+ "camera": {"lat": 48.8584, "lon": 2.2945, "zoom": 17, "bearing": 0},
+ "mode": "swipe",
+ "divider": 55,
+ "opacity": 50,
+ "a": {"present": True, "provider": "esri-world-imagery", "overlays": []},
+ "b": {"present": True, "provider": "osm", "overlays": ["boundaries"]},
+ },
+ },
+ )
+ assert comparison.status_code == 200, comparison.text
+ full.compare_session = f".compare/{comparison.json()['name']}.json"
+ rendered = client.post(
+ f"/api/cases/{case_id}/compare/sessions/{comparison.json()['name']}/preview",
+ files={"image_a": ("comparison.png", _png(color=(90, 60, 30)), "image/png")},
+ data={"format": "png"},
+ )
+ assert rendered.status_code == 200, rendered.text
+ full.compare_image = rendered.json()["path"]
+
# -- a place, and a relation to the photo ---------------------------------
place = client.post(
f"/api/cases/{case_id}/satellite/place",
@@ -433,9 +472,26 @@ def build_full_case(client, name: str = "Full case") -> FullCase:
assert timeline_view.status_code == 200, timeline_view.text
full.timeline_view_id = timeline_view.json()["id"]
+ # Analyzer input tiles are deterministic cached provider responses; all
+ # permanent case artifacts are still produced through the public API.
+ from analyzerfixture import sample_input, seed_images
+ analysis = sample_input()
+ seed_images(analysis)
+ for kind, body, attr in (
+ ("zones", {"title": "Port areas", "zones": analysis["zones"]}, "analyzer_zones"),
+ ("followups", analysis, "analyzer_followup"),
+ ("runs", analysis, "analyzer_run"),
+ ):
+ saved = client.post(f"/api/cases/{case_id}/analysis/{kind}", json=body)
+ assert saved.status_code == 200, saved.text
+ setattr(full, attr, f"{layout.ANALYSIS_DIR}/{kind}-{saved.json()['id']}.json")
+
# Enrichment and thumbnails were queued along the way; let them land, or the
# caller's first delete races a background write into the same case.
workqueue.wait_until_idle(timeout=20)
+ run_id = Path(full.analyzer_run).stem.split("-", 1)[1]
+ result = client.get(f"/api/cases/{case_id}/analysis/runs/{run_id}").json()
+ assert result["status"] == "ready", result
entities = client.get(
f"/api/cases/{case_id}/catalog/entities", params={"limit": 500}
diff --git a/tests/jobwait.py b/tests/jobwait.py
index 82b1c2b..08bba42 100644
--- a/tests/jobwait.py
+++ b/tests/jobwait.py
@@ -16,10 +16,11 @@ import time
from typing import Any
#: Long enough for the slowest box we run on. Windows spends around twenty seconds on a
-#: three-row proofs press, against under one here, and a job that is genuinely stuck
-#: fails the shard either way — so the cost of being generous is paid only when something
+#: three-row proofs press, against under one here, and a loaded runner has taken past a
+#: minute on that same press while still filing its rows. A job that is genuinely stuck
+#: fails the shard either way, so the cost of being generous is paid only when something
#: is already broken.
-WAIT = 60.0
+WAIT = 180.0
def wait_for_job(client, job_id: str, *, timeout: float = WAIT) -> dict[str, Any]:
diff --git a/tests/legacy_case.py b/tests/legacy_case.py
index 5b61b3c..33350df 100644
--- a/tests/legacy_case.py
+++ b/tests/legacy_case.py
@@ -168,7 +168,7 @@ def _rewind_hidden_layout(case: Case) -> None:
#: Content directories the layout gained after the `azimut/` wrapper shipped. They
#: postdate every unwrapped checkpoint, so a rewind removes them rather than putting
#: them at the case root where they never were.
-POST_WRAPPER_DIRS = frozenset({"sheets"})
+POST_WRAPPER_DIRS = frozenset({"sheets", ".compare", ".analysis"})
def rewind_case(case: Case, schema: int) -> None:
diff --git a/tests/test_analyzers.py b/tests/test_analyzers.py
new file mode 100644
index 0000000..6febb2f
--- /dev/null
+++ b/tests/test_analyzers.py
@@ -0,0 +1,563 @@
+"""Local analyzer behavior, bounds, provenance and persistence boundaries."""
+
+import io
+from copy import deepcopy
+
+import numpy as np
+import pytest
+from PIL import Image
+
+from azimut import config, layout
+from azimut.engine import analysis_models as analyzers_models
+from azimut.engine import analyzers, tilecache, workqueue
+from azimut.engine.analysis_models import METHODS, Recipe, RunInput, Zone
+from azimut.workspace import Case
+from analyzerfixture import (
+ SENTINEL_TILE,
+ fire_bands,
+ sample_input,
+ seed_images,
+ seed_sentinel,
+ sentinel_input,
+ vessel_bands,
+)
+
+
+def scenario(client, monkeypatch):
+ monkeypatch.setattr(workqueue, "start_workers", False)
+ ident = client.post("/api/cases", json={"name": "Analyzer tests"}).json()["id"]
+ case = Case.open(ident)
+ body = sample_input()
+ seed_images(body)
+ def forbidden(*args, **kwargs):
+ raise AssertionError("unexpected network")
+ monkeypatch.setattr(analyzers.httpx, "stream", forbidden)
+ monkeypatch.setattr(analyzers.wayback, "releases", forbidden)
+ return case, body
+
+
+def run(client, case, body):
+ result = client.post(f"/api/cases/{case.id}/analysis/runs", json=body)
+ assert result.status_code == 200, result.text
+ workqueue.drain(case)
+ return client.get(f"/api/cases/{case.id}/analysis/runs/{result.json()['id']}").json()
+
+
+def test_local_run_keeps_frames_and_review_without_network(client, scenario):
+ case, body = scenario
+ saved = run(client, case, body)
+ assert saved["status"] == "ready", saved
+ assert saved["count"] == 1
+ assert len(saved["frames"]) == 2
+ row = saved["results"][0]
+ assert row["confidence"] is None
+ assert row["area"] > 0
+ assert row["geometry"]["type"] == "Polygon"
+ for frame in saved["frames"].values():
+ assert case.resolve_inside(frame["path"]).is_file()
+ assert row["review"] == "new"
+ endpoint = f"/api/cases/{case.id}/analysis/runs/{saved['id']}/results/{row['id']}"
+ assert client.get(endpoint + "/preview").content.startswith(b"\x89PNG")
+ promoted = client.post(endpoint + "/promote", json={"title": "Reviewed change"}).json()
+ assert promoted["entity"]["type"] == "place"
+ assert client.post(endpoint + "/promote", json={"title": "Again"}).json()["entity"]["id"] == promoted["entity"]["id"]
+ # Promoted evidence survives deletion of the working analysis.
+ assert client.delete(f"/api/cases/{case.id}/analysis/runs/{saved['id']}").status_code == 200
+ assert case.resolve_inside(promoted["image"]).is_file()
+ assert not case.resolve_inside(layout.analysis_assets_rel(f"runs-{saved['id']}" )).exists()
+
+
+def test_keeping_a_candidate_is_the_only_thing_that_reaches_the_case(client, scenario):
+ """A sweep proposes; the analyst disposes, one candidate at a time."""
+ case, body = scenario
+ saved = run(client, case, body)
+ row = saved["results"][0]
+ places = [e for e in case.list_entities() if e["type"] == "place"]
+ 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"
+ 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.
+ kept = client.post(endpoint + "/promote", json={"title": "Kept candidate"}).json()
+ assert client.get(endpoint.rsplit("/results/", 1)[0]).json()["results"][0]["review"] == "kept"
+ assert len([e for e in case.list_entities() if e["type"] == "place"]) == 1
+
+ # A kept candidate cannot be quietly re-triaged behind the pin's back.
+ assert client.patch(endpoint, json={"review": "dismissed"}).status_code == 409
+
+ # Undoing takes the pin away and gives the candidate back.
+ 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
+
+
+def test_a_candidate_preview_is_enlarged_so_its_pixels_can_be_read(client, scenario):
+ """Legibility comes from whole-number nearest-neighbour zoom, not smoothing.
+
+ A candidate can be a dozen pixels across. Served at that size the browser
+ stretches it into a blur, so the server does the enlarging itself, by an
+ integer factor and with no interpolation: bigger, and still the pixels the
+ sensor recorded.
+ """
+ case, body = scenario
+ saved = run(client, case, body)
+ row = saved["results"][0]
+ endpoint = f"/api/cases/{case.id}/analysis/runs/{saved['id']}/results/{row['id']}"
+ with Image.open(io.BytesIO(client.get(endpoint + "/preview").content)) as preview:
+ box = row["parts"][0]["box"]
+ crop = max(box[2], box[3]) + 2 * 20
+ 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
+
+
+def test_reading_saved_items_never_starts_jobs(client, scenario):
+ case, body = scenario
+ before = case.list_jobs()
+ assert client.get("/api/compare/analyzers").status_code == 200
+ for kind in ("zones", "followups", "runs"):
+ assert client.get(f"/api/cases/{case.id}/analysis/{kind}").json() == []
+ assert case.list_jobs() == before
+ zone = client.post(f"/api/cases/{case.id}/analysis/zones", json={"title": "Port", "zones": body["zones"]}).json()
+ follow = client.post(f"/api/cases/{case.id}/analysis/followups", json=body).json()
+ for kind, saved in (("zones", zone), ("followups", follow)):
+ assert client.get(f"/api/cases/{case.id}/analysis/{kind}/{saved['id']}").status_code == 200
+ assert case.list_jobs() == before
+
+
+def test_recipe_backup_and_duplicate_preserve_builtin(client):
+ original = client.get("/api/compare/analyzers").json()["builtins"][0]
+ custom = deepcopy(original)
+ custom["name"] = "Weekly port check"
+ saved = client.post("/api/compare/analyzers", json=custom).json()
+ assert saved["id"] != original["id"]
+ backup = client.get("/api/settings/export").json()
+ client.delete(f"/api/compare/analyzers/{saved['id']}")
+ restored = client.post("/api/settings/import", json=backup)
+ assert restored.status_code == 200, restored.text
+ catalogue = client.get("/api/compare/analyzers").json()
+ assert catalogue["custom"] == [saved]
+ assert catalogue["builtins"][0] == original
+
+
+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"
+ workqueue.drain(case)
+ assert client.get(url).json()["frames"] == {}
+ assert client.delete(url).status_code == 200
+ assert client.get(url).status_code == 404
+
+
+def test_reexecution_uses_preserved_frames_after_tile_cache_loss(client, scenario, monkeypatch):
+ case, body = scenario
+ first = run(client, case, body)
+ monkeypatch.setattr(tilecache, "get", lambda *args: None)
+ second = run(client, case, body)
+ assert second["status"] == "ready"
+ assert first["id"] != second["id"]
+ assert first["results"] == second["results"]
+ assert first["input"] == second["input"]
+
+
+def test_missing_offline_frames_fail_without_partial_results(client, scenario):
+ case, body = scenario
+ body["b"]["release"] = 3
+ saved = run(client, case, body)
+ assert saved["status"] == "failed"
+ assert "offline" in saved["message"]
+ assert saved["results"] == []
+
+
+def test_tile_ceiling_and_provider_validation_before_job_creation(client, scenario):
+ case, body = scenario
+ # The panel prices an area against this number, so it has to be published.
+ assert client.get("/api/compare/analyzers").json()["max_tiles"] == analyzers.MAX_TILES
+ body["zones"][0]["points"] = [[0, 0], [1, 1]]
+ response = client.post(f"/api/cases/{case.id}/analysis/runs", json=body)
+ assert response.status_code == 422
+ assert "smaller" in response.text
+ assert case.list_jobs() == []
+ body["b"]["provider"] = "google"
+ assert client.post(f"/api/cases/{case.id}/analysis/runs", json=body).status_code == 422
+
+
+def test_zone_union_does_not_duplicate_detections(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"]
+
+
+def test_masks_filters_and_methods():
+ body = RunInput.model_validate(sample_input())
+ a = np.full((64, 64, 4), 30, np.uint8)
+ a[:, :, 3] = 255
+ b = a.copy()
+ b[10:20, 10:20, :3] = 240
+ b[40, 40, :3] = 240
+ mask = np.ones((64, 64), np.uint8)
+ for method in ("colour", "structure", "brightness", "water_objects", "smoke"):
+ body.recipe.method = method
+ binary, _ = analyzers.detect(a, b, mask, body)
+ assert binary[8:22, 8:22].any(), method
+ body.recipe.method = "colour"
+ body.recipe.parameters.cleanup = 1
+ binary, _ = analyzers.detect(a, b, mask, body)
+ assert binary[15, 15] and not binary[40, 40]
+ mask[:30] = 0
+ binary, _ = analyzers.detect(a, b, mask, body)
+ assert not binary[:30].any()
+
+
+def _spectral_pair():
+ a = np.zeros((16, 16, 4), np.uint8)
+ a[:, :, 3] = 255
+ a[:, :, 1] = 4
+ b = a.copy()
+ b[:, :, 0] = 200
+ b[:8, :, 1] = 9 # the top half is cloud, by Sentinel-2's own classification
+ return a, b
+
+
+def test_spectral_cloud_mask_and_native_grid():
+ body = sample_input()
+ body["a"] = {"provider": "sentinel2", "date": "2026-08-01"}
+ body["b"] = {"provider": "sentinel2", "date": "2026-09-01"}
+ body["recipe"].update(method="index", providers=["sentinel2"])
+ body["recipe"]["parameters"]["cloud_margin"] = 0
+ model = RunInput.model_validate(body)
+ assert analyzers.grid(model) == (13, 512)
+ a, b = _spectral_pair()
+ mask = np.ones((16, 16), np.uint8)
+ binary, _ = analyzers.detect(a, b, mask, model, a, b)
+ assert not binary[:8].any()
+ assert binary[8:].all()
+
+
+def test_the_cloud_margin_grows_the_mask_past_the_classified_edge():
+ """A classification calls the cloud's soft edge ground, and that edge is
+ where the ring of false candidates around every mask comes from. The margin
+ is what takes it, so it has to cost exactly the pixels it claims."""
+ body = sample_input()
+ body["a"] = {"provider": "sentinel2", "date": "2026-08-01"}
+ body["b"] = {"provider": "sentinel2", "date": "2026-09-01"}
+ body["recipe"].update(method="index", providers=["sentinel2"])
+ body["recipe"]["parameters"]["cloud_margin"] = 2
+ model = RunInput.model_validate(body)
+ a, b = _spectral_pair()
+ binary, _ = analyzers.detect(a, b, np.ones((16, 16), np.uint8), model, a, b)
+ assert not binary[:10].any()
+ assert binary[10:].all()
+
+
+def test_named_followup_freezes_input_and_previous_date(client, scenario, monkeypatch):
+ case, body = scenario
+ follow = client.post(f"/api/cases/{case.id}/analysis/followups", json=body).json()
+ body["followup_id"] = follow["id"]
+ previous = run(client, case, body)
+ newer = {**body, "offline": False, "date_rule": "latest_previous"}
+ monkeypatch.setattr(analyzers.wayback, "releases", lambda: [type("Release", (), {"number": 3})()])
+ resolved = analyzers.resolve_dates(case, RunInput.model_validate(newer))
+ assert resolved.a.release == 2 and resolved.b.release == 3
+ changed = deepcopy(body)
+ changed["zones"][0]["name"] = "New name"
+ assert client.put(f"/api/cases/{case.id}/analysis/followups/{follow['id']}", json=changed).status_code == 200
+ assert analyzers.read(case, "runs", previous["id"])["input"]["zones"][0]["name"] == "Harbour"
+
+
+def _picture_pair():
+ """A flat grey tile, and the same with a bright colourless patch added.
+
+ Which is the whole difficulty: on a rendered picture that patch is equally
+ a cloud, a white roof and a gravel pad, and nothing in the image says which.
+ """
+ a = np.zeros((32, 32, 4), np.uint8)
+ a[:, :, :3] = 60
+ a[:, :, 3] = 255
+ b = a.copy()
+ b[10:20, 10:20, :3] = 235
+ return a, b
+
+
+def test_the_picture_cloud_guess_is_off_until_it_is_asked_for():
+ """It cannot tell cloud from a white roof, so it is never turned on for
+ anyone: a saved recipe must keep finding what it found yesterday."""
+ body = sample_input()
+ assert Recipe.model_validate(body["recipe"]).parameters.guess_clouds is False
+ model = RunInput.model_validate(body)
+ a, b = _picture_pair()
+ binary, _ = analyzers.detect(a, b, np.ones((32, 32), np.uint8), model)
+ assert binary[10:20, 10:20].any()
+
+
+def test_the_picture_cloud_guess_masks_bright_colourless_pixels_when_asked():
+ body = sample_input()
+ body["recipe"]["parameters"].update(guess_clouds=True, cloud_margin=0)
+ model = RunInput.model_validate(body)
+ a, b = _picture_pair()
+ binary, _ = analyzers.detect(a, b, np.ones((32, 32), np.uint8), model)
+ assert not binary.any()
+
+
+def test_no_cloud_filter_is_offered_where_it_would_eat_the_signal():
+ """Smoke, bright shapes on water and a short-wave hotspot are bright and
+ colourless themselves. There the picture test would mask the method's own
+ subject, so the catalogue offers nothing rather than a switch that ruins it."""
+ offered = {entry["id"]: entry["cloud_filter"] for entry in METHODS}
+ assert offered["smoke"] == "" and offered["water_objects"] == ""
+ assert offered["hotspots"] == "" # its band ratios reject cloud already
+ assert offered["index"] == "classes" and offered["vessels"] == "classes"
+ assert offered["colour"] == "picture"
+
+ body = sample_input()
+ body["recipe"].update(method="smoke")
+ body["recipe"]["parameters"].update(guess_clouds=True, cloud_margin=0, sensitivity=90)
+ model = RunInput.model_validate(body)
+ a, b = _picture_pair()
+ binary, _ = analyzers.detect(a, b, np.ones((32, 32), np.uint8), model)
+ # the switch is set and the method ignores it, because it has to
+ assert binary[10:20, 10:20].any()
+
+
+def _sentinel_rule(body, rule="latest_reference"):
+ sentinel_body = deepcopy(body)
+ sentinel_body["recipe"]["providers"] = ["sentinel2"]
+ sentinel_body["a"] = {"provider": "sentinel2", "date": "2026-04-01", "maxcc": 30}
+ sentinel_body["b"] = {"provider": "sentinel2", "date": "2026-04-01", "maxcc": 30}
+ return {**sentinel_body, "offline": False, "date_rule": rule}
+
+
+def test_an_automatic_date_rule_takes_the_newest_pass_that_covers_the_whole_area(
+ client, scenario, monkeypatch
+):
+ """The old rule asked about each area's *centre*, which a swath can reach
+ while missing most of the shape around it. Picking that date sweeps nodata."""
+ case, body = scenario
+ client.put("/api/settings/keys", json={"sentinelhub": "inst-uuid"})
+ asked = {}
+
+ def acquisitions(instance, rings, start, end):
+ asked.update(instance=instance, rings=rings, start=start, end=end)
+ return {"dates": [
+ {"date": "2026-05-20", "cloud": 5.0, "granules": 1, "coverage": 0.61},
+ {"date": "2026-05-11", "cloud": 5.0, "granules": 2, "coverage": 1.0},
+ {"date": "2026-05-04", "cloud": 5.0, "granules": 1, "coverage": 1.0},
+ ], "truncated": False}
+
+ monkeypatch.setattr(analyzers.sentinel, "acquisitions", acquisitions)
+ resolved = analyzers.resolve_dates(case, RunInput.model_validate(_sentinel_rule(body)))
+ # the newest is 2026-05-20 and it reaches 61% of the area, so it is not it
+ assert resolved.b.date == "2026-05-11"
+ # one lookup for the whole set, not one per area
+ assert len(asked["rings"]) == 1
+
+
+def test_an_automatic_date_rule_says_how_far_the_best_pass_reached(
+ client, scenario, monkeypatch
+):
+ case, body = scenario
+ client.put("/api/settings/keys", json={"sentinelhub": "inst-uuid"})
+ monkeypatch.setattr(analyzers.sentinel, "acquisitions", lambda *a, **k: {"dates": [
+ {"date": "2026-05-20", "cloud": 5.0, "granules": 1, "coverage": 0.61},
+ ], "truncated": False})
+ with pytest.raises(ValueError) as raised:
+ analyzers.resolve_dates(case, RunInput.model_validate(_sentinel_rule(body)))
+ # naming the number turns "it failed" into "pick the dates by hand"
+ assert "61%" in str(raised.value)
+
+
+def test_an_automatic_date_rule_still_honours_the_cloud_ceiling(client, scenario, monkeypatch):
+ case, body = scenario
+ client.put("/api/settings/keys", json={"sentinelhub": "inst-uuid"})
+ monkeypatch.setattr(analyzers.sentinel, "acquisitions", lambda *a, **k: {"dates": [
+ {"date": "2026-05-20", "cloud": 80.0, "granules": 1, "coverage": 1.0},
+ {"date": "2026-05-11", "cloud": 5.0, "granules": 1, "coverage": 1.0},
+ ], "truncated": False})
+ resolved = analyzers.resolve_dates(case, RunInput.model_validate(_sentinel_rule(body)))
+ assert resolved.b.date == "2026-05-11"
+
+
+def test_a_run_reports_the_share_of_its_areas_that_had_imagery(client, scenario):
+ """"Nothing found" and "never looked" are not the same answer, and a date
+ whose granules only half reach the area produces the second while reading
+ like the first."""
+ case, body = scenario
+ saved = run(client, case, body)
+ assert saved["status"] == "ready"
+ # the fixture's frames are fully opaque, so the sweep saw all of it
+ assert saved["swept"] == 1.0
+
+
[email protected]("points", [[[0, 0], [0, 1]], [[179, 0], [-179, 1]], [[0, 86], [1, 87]]])
+def test_invalid_areas_are_rejected(points):
+ with pytest.raises(ValueError):
+ Zone(id="zone", points=points)
+
+
+def test_models_cannot_smuggle_executable_recipes():
+ with pytest.raises(ValueError):
+ Recipe(name="Bad", method="python", code="anything")
+ assert config.DEFAULT_SETTINGS["analyzers"] == []
+
+
+def test_local_contrast_reads_a_target_against_its_own_patch_of_sea():
+ """The same hull, on calm water and on water twice as bright, reads the same.
+
+ That is the whole reason the detector is local: an absolute cut-off would
+ need a different number for every scene, and would call a sunlit swell a
+ fleet.
+ """
+ rng = np.random.default_rng(7)
+ calm = np.full((200, 200), 20.0) + rng.normal(0, 1.5, (200, 200))
+ water = np.ones((200, 200), bool)
+ readings = []
+ for sea in (calm, calm + 120):
+ empty, share = analyzers.local_contrast(sea, water, 61, 11)
+ assert share.min() > 0.99
+ assert abs(empty[100, 100]) < 4
+ target = sea.copy()
+ target[99:102, 99:102] += 100
+ contrast, _ = analyzers.local_contrast(target, water, 61, 11)
+ readings.append(contrast[100, 100])
+ assert min(readings) > 20
+ assert abs(readings[0] - readings[1]) < 5
+
+
+def test_local_contrast_treats_land_in_the_ring_as_missing_background():
+ values = np.full((160, 160), 20.0)
+ water = np.zeros((160, 160), bool)
+ water[:, :40] = True
+ _, share = analyzers.local_contrast(values, water, 61, 11)
+ assert share[80, 5] > 0.9 # open sea
+ assert share[80, 120] == 0 # inland, no water in the ring at all
+ assert share[80, 60] < 0.5 # a shoreline is not somewhere a ship can be
+
+
+def sea(client, monkeypatch):
+ monkeypatch.setattr(workqueue, "start_workers", False)
+ ident = client.post("/api/cases", json={"name": "Copernicus detectors"}).json()["id"]
+ case = Case.open(ident)
+ def forbidden(*args, **kwargs):
+ raise AssertionError("unexpected network")
+ monkeypatch.setattr(analyzers.httpx, "stream", forbidden)
+ monkeypatch.setattr(analyzers.sentinel, "band_frame", forbidden)
+ return case
+
+
+def test_vessel_sweep_finds_the_targets_and_not_the_bright_water(client, sea):
+ body = sentinel_input("boats")
+ seed_sentinel(sea, body, vessel_bands([(120, 140, 3, 3), (300, 220, 4, 2)]))
+ saved = run(client, sea, body)
+ assert saved["status"] == "ready", saved
+ assert saved["count"] == 2, [r["coordinates"] for r in saved["results"]]
+ assert {r["phenomenon"] for r in saved["results"]} == {"Vessel candidate"}
+ for row in saved["results"]:
+ # Nine pixels of 9.55 m is a little over 800 m²; two of them, 180 m².
+ assert 150 < row["area"] < 1000
+ assert row["signal_score"] > 0.2
+ # A signal score is not a probability, and nothing here pretends it is.
+ assert row["confidence"] is None
+ assert len(saved["frames"]) == 2 # the picture reviewed, and the bands measured
+
+
+def test_vessel_sweep_asks_for_one_date_and_never_for_a_reference(client, sea):
+ body = sentinel_input("boats")
+ seed_sentinel(sea, body, vessel_bands([(200, 200, 3, 3)]))
+ body["a"] = {"provider": "sentinel2", "date": "", "layer": "TRUE_COLOR", "maxcc": 30}
+ saved = run(client, sea, body)
+ assert saved["status"] == "ready", saved
+ assert saved["input"]["a"] == saved["input"]["b"]
+ assert saved["count"] == 1
+
+
+def test_hotspot_sweep_separates_fire_from_a_cloud_that_is_just_as_bright(client, sea):
+ body = sentinel_input("anomaly")
+ seed_sentinel(sea, body, fire_bands(fire=(150, 160, 3, 3), cloud=(300, 300, 40, 40)))
+ saved = run(client, sea, body)
+ assert saved["status"] == "ready", saved
+ assert saved["count"] == 1, [r["area"] for r in saved["results"]]
+ row = saved["results"][0]
+ assert row["phenomenon"] == "Hotspot candidate"
+ # The fire patch, not the cloud forty times its size.
+ assert row["area"] < 2000
+ z, x, y = SENTINEL_TILE
+ west, north = analyzers.geographic((x + 150 / 512) / 2**z, (y + 160 / 512) / 2**z)
+ assert abs(row["coordinates"][0] - west) < 0.001
+ assert abs(row["coordinates"][1] - north) < 0.001
+
+
+def test_hotspot_sweep_ignores_short_wave_below_the_published_floor(client, sea):
+ body = sentinel_input("anomaly")
+ bands = fire_bands(fire=(150, 160, 3, 3), cloud=(300, 300, 40, 40))
+ # Right ratios, not enough energy: warm ground is not a fire.
+ bands[160:163, 150:153, 0] = int(255 * (analyzers.HOTSPOT_FLOOR - 0.02) * 4)
+ seed_sentinel(sea, body, bands)
+ saved = run(client, sea, body)
+ assert saved["status"] == "ready", saved
+ assert saved["count"] == 0
+
+
[email protected]("recipe_id", ["boats", "anomaly"])
+def test_band_detectors_refuse_a_provider_that_serves_pictures(recipe_id):
+ recipe = next(r for r in analyzers_models.BUILTINS if r.id == recipe_id)
+ assert recipe.providers == ["sentinel2"]
+ with pytest.raises(ValueError):
+ recipe.model_copy(update={"providers": ["esri-wayback", "sentinel2"]}).compatible()
+
+
+def seed_tile(x, y, changed):
+ """One Wayback tile pair, with the change only where a test asks for it."""
+ for release in (1, 2):
+ pixels = np.full((256, 256, 3), 40, np.uint8)
+ if release == 2 and changed:
+ pixels[90:120, 100:150] = 230
+ out = io.BytesIO()
+ Image.fromarray(pixels).save(out, "PNG")
+ tilecache.put(f"esri-wayback~{release}", 19, x, y, out.getvalue(), "image/png")
+
+
+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.
+
+ This is what lets the allowed area be large: two tiles are read, one shows
+ nothing, and only the tile behind the candidate keeps a permanent copy.
+ """
+ case, body = scenario
+ z, x, y = 19, 265056, 182248
+ west, north = analyzers.geographic((x + .1) / 2**z, (y + .1) / 2**z)
+ east, south = analyzers.geographic((x + 1.9) / 2**z, (y + .9) / 2**z)
+ body["zones"][0]["points"] = [[west, south], [east, north]]
+ seed_tile(x, y, changed=True)
+ seed_tile(x + 1, y, changed=False)
+
+ saved = run(client, case, body)
+ assert saved["status"] == "ready", saved
+ assert saved["total"] == 2
+ assert saved["count"] == 1
+ assert len(saved["frames"]) == 2
+ assert {tuple(record["tile"]) for record in saved["frames"].values()} == {(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()
+ }
+ # Whatever a candidate points at still resolves, which is the invariant
+ # the preview and the bundle both rely on.
+ for row in saved["results"]:
+ for part in row["parts"]:
+ for key in part["frames"]:
+ assert case.resolve_inside(saved["frames"][key]["path"]).is_file()
+ endpoint = f"/api/cases/{case.id}/analysis/runs/{saved['id']}/results/{saved['results'][0]['id']}"
+ assert client.get(endpoint + "/preview").content.startswith(b"\x89PNG")
diff --git a/tests/test_cases_api.py b/tests/test_cases_api.py
index 386b623..16cdee2 100644
--- a/tests/test_cases_api.py
+++ b/tests/test_cases_api.py
@@ -1035,6 +1035,13 @@ def test_details_title_edit_moves_every_named_tool_file(client):
"New inspect",
layout.session_rel("New inspect"),
),
+ (
+ "compare-session",
+ "spec",
+ layout.compare_session_rel("Old comparison"),
+ "New comparison",
+ layout.compare_session_rel("New comparison"),
+ ),
(
"post",
"draft",
diff --git a/tests/test_compare_api.py b/tests/test_compare_api.py
new file mode 100644
index 0000000..e00caca
--- /dev/null
+++ b/tests/test_compare_api.py
@@ -0,0 +1,512 @@
+"""Compare sessions, their media working file, animated exports and index frames."""
+
+import io
+from pathlib import Path
+
+import graph_read
+import pytest
+from PIL import Image
+
+from azimut import config
+from azimut.api import compare as compare_api
+from azimut.api.compare import MAX_GIF_EDGE, _gif_frames, change_refusal
+from azimut.engine import links as link_engine
+from azimut.workspace import Case
+
+
+def _png(color: tuple[int, int, int], size: tuple[int, int] = (96, 64)) -> bytes:
+ out = io.BytesIO()
+ Image.new("RGB", size, color).save(out, "PNG")
+ return out.getvalue()
+
+
+def _side(provider: str = "esri-world-imagery", **extra) -> dict:
+ return {
+ "present": True,
+ "provider": provider,
+ "overlays": [],
+ "sentinel": {"layer": "TRUE_COLOR", "date": "", "maxcc": 100},
+ "wayback_release": None,
+ **extra,
+ }
+
+
+def _spec() -> dict:
+ return {
+ "version": 2,
+ "camera": {"lat": 48.8584, "lon": 2.2945, "zoom": 17.25, "bearing": 31},
+ "mode": "swipe",
+ "divider": 63,
+ "opacity": 45,
+ "a": _side(
+ overlays=["roads", "boundaries", "firms", "nightlights", "saved"],
+ firms={
+ "sensor": "viirs_snpp",
+ "window": "dates",
+ "first": "2026-09-01",
+ "last": "2026-09-03",
+ },
+ nightlights={"source": "snpp", "day": "2026-09-02"},
+ ),
+ "b": _side(
+ "esri-wayback",
+ overlays=["railway"],
+ sentinel={"layer": "FALSE_COLOR", "date": "2026-09-01", "maxcc": 40},
+ wayback_release=146,
+ ),
+ }
+
+
+def _case(client, name: str) -> str:
+ return client.post("/api/cases", json={"name": name}).json()["id"]
+
+
+def _save(client, cid: str, title: str, spec: dict | None = None, **extra):
+ return client.post(
+ f"/api/cases/{cid}/compare/sessions",
+ json={"title": title, "spec": spec or _spec(), **extra},
+ )
+
+
+def _preview(client, cid: str, name: str, colour=(30, 60, 90), fmt: str = "png"):
+ files = {"image_a": ("a.png", _png(colour), "image/png")}
+ if fmt == "blink":
+ files["image_b"] = ("b.png", _png((20, 40, 220)), "image/png")
+ return client.post(
+ f"/api/cases/{cid}/compare/sessions/{name}/preview",
+ files=files,
+ data={"format": fmt},
+ )
+
+
+def _entities(cid: str, type_: str) -> list[dict]:
+ return [entity for entity in graph_read.entities(cid) if entity["type"] == type_]
+
+
+# -- the editable session -------------------------------------------------------
+
+
+def test_compare_session_roundtrip_rename_and_sidebar_delete(client):
+ cid = _case(client, "Compare")
+ spec = _spec()
+ spec["change_assist"] = {
+ "method": "structure",
+ "index": "nbr",
+ "threshold": "manual",
+ "sensitivity": 62,
+ "normalize": "mean",
+ "smoothing": 2,
+ "alignment": 5,
+ "cleanup": 2,
+ "min_area": 250,
+ "ignore_clouds": False,
+ "ignore_shadows": True,
+ "classes": ["loss", "gain", "loss"],
+ "display": "outline",
+ "palette": "colourblind",
+ "zones": False,
+ "opacity": 71,
+ "base": "side",
+ "visible": True,
+ }
+ spec["blink"] = {"interval": 1200}
+ spec["annotations"] = [
+ {"id": "before", "kind": "text", "side": "a", "colour": "#f6a81a",
+ "points": [[2.2945, 48.8584]], "text": "Before"},
+ {"id": "yard", "kind": "polygon", "colour": "#22c55e",
+ "points": [[2.29, 48.85], [2.30, 48.85], [2.30, 48.86]], "fill_opacity": 0.2},
+ ]
+ saved = _save(client, cid, "Harbour change", spec)
+ assert saved.status_code == 200, saved.text
+ assert saved.json()["spec_path"] == ".compare/Harbour change.json"
+
+ listing = client.get(f"/api/cases/{cid}/compare/sessions").json()
+ assert listing == [{
+ "name": "Harbour change",
+ "title": "Harbour change",
+ "updated_at": listing[0]["updated_at"],
+ "provider_a": "esri-world-imagery",
+ "provider_b": "esri-wayback",
+ "mode": "swipe",
+ "preview": None,
+ }]
+ loaded = client.get(f"/api/cases/{cid}/compare/sessions/Harbour change").json()
+ assert loaded["azimut_compare"] == 1
+ assert loaded["spec"]["camera"]["zoom"] == 17.25
+ assert loaded["spec"]["b"]["overlays"] == ["railway"]
+ assert loaded["spec"]["a"]["nightlights"] == {"source": "snpp", "day": "2026-09-02"}
+ assist = loaded["spec"]["change_assist"]
+ assert assist["classes"] == ["loss", "gain"]
+ assert {key: assist[key] for key in ("method", "min_area", "display")} == {
+ "method": "structure", "min_area": 250, "display": "outline",
+ }
+ assert loaded["spec"]["blink"] == {"interval": 1200}
+ assert loaded["spec"]["annotations"][0]["side"] == "a"
+ assert loaded["spec"]["annotations"][1]["points"][2] == [2.30, 48.86]
+
+ entity = _entities(cid, "compare-session")[0]
+ renamed = _save(client, cid, "Harbour after", rename_from="Harbour change")
+ assert renamed.status_code == 200, renamed.text
+ after = _entities(cid, "compare-session")
+ assert len(after) == 1 and after[0]["id"] == entity["id"]
+ assert after[0]["attrs"]["spec"] == ".compare/Harbour after.json"
+ assert not Case.open(cid).resolve_inside(".compare/Harbour change.json").exists()
+
+ client.delete(f"/api/cases/{cid}/entities/{entity['id']}")
+ assert client.get(f"/api/cases/{cid}/compare/sessions").json() == []
+
+
+ "mutate",
+ [
+ lambda spec: spec["a"].update(provider="missing"),
+ lambda spec: spec["a"].update(overlays=["buildings"]),
+ lambda spec: spec["camera"].update(zoom=30),
+ lambda spec: spec.update(version=1),
+ lambda spec: spec.update(annotations=[{
+ "id": "x", "kind": "arrow", "colour": "#ffffff", "points": [[2, 48]],
+ }]),
+ lambda spec: spec.update(annotations=[{
+ "id": "x", "kind": "line", "colour": "#ffffff", "points": [[200, 48], [2, 48]],
+ }]),
+ lambda spec: spec.update(annotations=[{
+ "id": "x", "kind": "text", "colour": "#ffffff", "points": [[2, 48]], "text": " ",
+ }]),
+ lambda spec: spec.update(change_assist={"method": "ratio"}),
+ ],
+)
+def test_compare_session_refuses_what_it_cannot_reopen(client, mutate):
+ cid = _case(client, "Compare validation")
+ spec = _spec()
+ mutate(spec)
+ assert _save(client, cid, "Bad", spec).status_code == 422
+
+
+def test_compare_session_keeps_google_maps_js_as_a_reopenable_source(client):
+ cid = _case(client, "Compare Google JS")
+ client.put("/api/settings/keys", json={"google_js": "AIza.js"})
+ spec = _spec()
+ spec["b"]["provider"] = "google-js"
+
+ assert _save(client, cid, "Google reading", spec).status_code == 200
+ loaded = client.get(f"/api/cases/{cid}/compare/sessions/Google reading").json()
+ assert loaded["spec"]["b"]["provider"] == "google-js"
+
+
+# -- which pairs a pixel reading is fair on --------------------------------------
+
+
+def _pair(a: dict, b: dict, mode: str = "change", method: str = "colour") -> dict:
+ spec = _spec()
+ spec.update(mode=mode, a=a, b=b, change_assist={"method": method})
+ return spec
+
+
+ ("a", "b", "method"),
+ [
+ (_side("esri-wayback", wayback_release=145), _side("esri-wayback", wayback_release=146), "colour"),
+ # the same Esri chain: World Imagery is the newest Wayback release
+ (_side("esri-world-imagery"), _side("esri-wayback", wayback_release=146), "structure"),
+ (
+ _side("sentinel2", sentinel={"layer": "TRUE_COLOR", "date": "2026-05-01", "maxcc": 20}),
+ _side("sentinel2", sentinel={"layer": "TRUE_COLOR", "date": "2026-06-01", "maxcc": 60}),
+ "colour",
+ ),
+ (
+ _side("sentinel2", sentinel={"layer": "SWIR", "date": "2026-05-01", "maxcc": 100}),
+ _side("sentinel2", sentinel={"layer": "NDVI", "date": "2026-06-01", "maxcc": 100}),
+ "index",
+ ),
+ (
+ _side("osm", overlays=["nightlights"], nightlights={"source": "noaa20", "day": "2026-01-01"}),
+ _side("osm", overlays=["nightlights"], nightlights={"source": "noaa20", "day": "2026-02-01"}),
+ "brightness",
+ ),
+ ],
+)
+def test_change_assist_accepts_comparable_pairs(client, a, b, method):
+ client.put("/api/settings/keys", json={"sentinelhub": "inst-uuid"})
+ cid = _case(client, "Compare change")
+ response = _save(client, cid, "Fair pair", _pair(a, b, method=method))
+ assert response.status_code == 200, response.text
+
+
+ ("a", "b", "method", "reason"),
+ [
+ (_side("esri-world-imagery"), _side("osm"), "colour", "reads Sentinel-2"),
+ (_side("esri-wayback", wayback_release=146), _side("esri-wayback", wayback_release=146), "colour", "different Esri"),
+ (
+ _side("esri-wayback", wayback_release=145, overlays=["roads"]),
+ _side("esri-wayback", wayback_release=146),
+ "colour",
+ "reference layers",
+ ),
+ (
+ _side("sentinel2", sentinel={"layer": "TRUE_COLOR", "date": "2026-05-01", "maxcc": 100}),
+ _side("sentinel2", sentinel={"layer": "SWIR", "date": "2026-06-01", "maxcc": 100}),
+ "colour",
+ "same layer",
+ ),
+ (_side("esri-wayback", wayback_release=145), _side("esri-wayback", wayback_release=146), "index", "Sentinel-2 on both"),
+ (
+ _side("sentinel2", sentinel={"layer": "TRUE_COLOR", "date": "", "maxcc": 100}),
+ _side("sentinel2", sentinel={"layer": "TRUE_COLOR", "date": "2026-06-01", "maxcc": 100}),
+ "index",
+ "dated pass",
+ ),
+ ],
+)
+def test_change_assist_refuses_misleading_pairs(client, a, b, method, reason):
+ client.put("/api/settings/keys", json={"sentinelhub": "inst-uuid"})
+ cid = _case(client, "Compare change refused")
+ 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
+
+
+def test_change_refusal_needs_both_sides():
+ assert change_refusal(_side(present=False), _side()) == "Change assist needs imagery A and B"
+
+
+# -- the rendered image is a media working file ----------------------------------
+
+
+def test_the_rendered_comparison_is_a_media_working_file(client):
+ cid = _case(client, "Compare working file")
+ assert _save(client, cid, "Harbour reading").status_code == 200
+ response = _preview(client, cid, "Harbour reading")
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body == {"path": "media/Harbour reading.png", "format": "png", "replaced": False}
+
+ media = _entities(cid, "media")
+ assert len(media) == 1
+ assert media[0]["attrs"]["path"] == body["path"]
+ assert media[0]["attrs"]["compare_session"] == ".compare/Harbour reading.json"
+ session = _entities(cid, "compare-session")[0]
+ assert session["attrs"]["preview"] == body["path"]
+ # never `path`: that attribute is how a delete finds its artifact, and the
+ # media's own delete must not resolve to the session
+ assert "path" not in session["attrs"]
+
+ item = next(row for row in client.get(f"/api/cases/{cid}/media").json() if row["path"] == body["path"])
+ assert item["source"]["type"] == "compare"
+ assert item["source"]["providers"] == {"a": "esri-world-imagery", "b": "esri-wayback"}
+ assert item["source"]["mode"] == "swipe"
+
+ collected = client.get(f"/api/cases/{cid}/media/page", params={"collected_only": "true"}).json()
+ assert collected["items"] == []
+ assert collected["facets"]["made_here_count"] == 1
+ everything = client.get(f"/api/cases/{cid}/media/page").json()
+ assert everything["facets"]["category_counts"]["comparison"] == 1
+ assert everything["facets"]["category_counts"]["image"] == 0
+
+ listing = client.get(f"/api/cases/{cid}/compare/sessions").json()
+ assert listing[0]["preview"] == body["path"]
+
+
+def test_saving_again_replaces_the_one_file(client):
+ cid = _case(client, "Compare replace")
+ _save(client, cid, "Harbour reading")
+ first = _preview(client, cid, "Harbour reading", (10, 10, 10)).json()
+ before = _entities(cid, "media")[0]
+
+ second = _preview(client, cid, "Harbour reading", (240, 240, 240)).json()
+
+ assert second == {**first, "replaced": True}
+ after = _entities(cid, "media")
+ assert len(after) == 1 and after[0]["id"] == before["id"]
+ assert after[0]["attrs"]["sha256"] != before["attrs"]["sha256"]
+ with Image.open(Case.open(cid).resolve_inside(second["path"])) as image:
+ assert image.getpixel((0, 0)) == (240, 240, 240)
+
+
+def test_a_new_format_becomes_a_new_file_and_the_old_render_goes_to_the_trash(client):
+ cid = _case(client, "Compare format")
+ _save(client, cid, "Harbour reading")
+ still = _preview(client, cid, "Harbour reading").json()
+
+ animated = _preview(client, cid, "Harbour reading", fmt="blink").json()
+
+ assert animated["path"] == "media/Harbour reading.gif"
+ assert [entity["attrs"]["path"] for entity in _entities(cid, "media")] == [animated["path"]]
+ assert not Case.open(cid).resolve_inside(still["path"]).exists()
+ with Image.open(Case.open(cid).resolve_inside(animated["path"])) as gif:
+ assert gif.n_frames == 2
+
+
+def test_a_render_something_was_built_on_is_never_overwritten(client):
+ cid = _case(client, "Compare in use")
+ _save(client, cid, "Harbour reading")
+ first = _preview(client, cid, "Harbour reading", (10, 10, 10)).json()
+ derived = client.post(
+ f"/api/cases/{cid}/media/upload",
+ files={"file": ("crop.png", _png((1, 2, 3)), "image/png")},
+ ).json()
+ case = Case.open(cid)
+ link_engine.link_all(
+ case, derived["entity"]["id"], link_engine.DERIVED_FROM, [first["path"]], by="test"
+ )
+
+ second = _preview(client, cid, "Harbour reading", (240, 240, 240)).json()
+
+ assert second["replaced"] is False
+ assert second["path"] != first["path"]
+ with Image.open(case.resolve_inside(first["path"])) as image:
+ assert image.getpixel((0, 0)) == (10, 10, 10)
+ assert _entities(cid, "compare-session")[0]["attrs"]["preview"] == second["path"]
+
+
+def test_the_image_outlives_its_session_and_a_lost_image_is_filed_again(client):
+ cid = _case(client, "Compare lifetimes")
+ _save(client, cid, "Harbour reading")
+ first = _preview(client, cid, "Harbour reading").json()
+
+ media = _entities(cid, "media")[0]
+ assert client.delete(f"/api/cases/{cid}/entities/{media['id']}").status_code == 200
+ assert client.get(f"/api/cases/{cid}/compare/sessions").json()[0]["preview"] is None
+ again = _preview(client, cid, "Harbour reading").json()
+ assert again["replaced"] is False
+ assert Case.open(cid).resolve_inside(again["path"]).is_file()
+ assert first["path"]
+
+ assert client.delete(f"/api/cases/{cid}/compare/sessions/Harbour reading").status_code == 200
+ assert _entities(cid, "compare-session") == []
+ assert [entity["attrs"]["path"] for entity in _entities(cid, "media")] == [again["path"]]
+
+
+def test_renaming_the_session_renames_its_image_on_the_next_save(client):
+ cid = _case(client, "Compare rename")
+ _save(client, cid, "Harbour reading")
+ _preview(client, cid, "Harbour reading")
+ _save(client, cid, "Harbour at dusk", rename_from="Harbour reading")
+
+ renamed = _preview(client, cid, "Harbour at dusk").json()
+
+ assert renamed == {"path": "media/Harbour at dusk.png", "format": "png", "replaced": True}
+ assert [entity["attrs"]["path"] for entity in _entities(cid, "media")] == [renamed["path"]]
+
+
+def test_a_preview_needs_its_session_and_a_blink_needs_b(client):
+ cid = _case(client, "Compare preview refused")
+ assert _preview(client, cid, "Nothing here").status_code == 404
+ _save(client, cid, "Harbour reading")
+ refused = client.post(
+ f"/api/cases/{cid}/compare/sessions/Harbour reading/preview",
+ files={"image_a": ("a.png", _png((0, 0, 0)), "image/png")},
+ data={"format": "blink"},
+ )
+ assert refused.status_code == 422
+
+
+# -- finished animated copies -----------------------------------------------------
+
+
+def test_compare_gif_exports_blink_and_slide(client):
+ cid = _case(client, "Compare GIF")
+ for animation, expected_frames in (("blink", 2), ("slide", 16)):
+ response = client.post(
+ f"/api/cases/{cid}/compare/gif",
+ files={
+ "image_a": ("a.png", _png((220, 30, 30)), "image/png"),
+ "image_b": ("b.png", _png((20, 40, 220)), "image/png"),
+ },
+ data={"animation": animation, "filename": "Harbour reading", "interval": "1500"},
+ )
+ assert response.status_code == 200, response.text
+ assert response.json()["file"] == f"Harbour reading-{animation}.gif"
+ with Image.open(Path(response.json()["path"]) / response.json()["file"]) as gif:
+ assert gif.n_frames == expected_frames
+ if animation == "blink":
+ assert gif.info["duration"] == 1500
+
+
+def test_compare_gif_rejects_non_png_and_unknown_animation(client):
+ cid = _case(client, "Compare GIF bad")
+ assert client.post(
+ f"/api/cases/{cid}/compare/gif",
+ files={
+ "image_a": ("a.png", b"not an image", "image/png"),
+ "image_b": ("b.png", _png((0, 0, 0)), "image/png"),
+ },
+ data={"animation": "blink", "filename": "Bad"},
+ ).status_code == 422
+ assert client.post(
+ f"/api/cases/{cid}/compare/gif",
+ files={
+ "image_a": ("a.png", _png((0, 0, 0)), "image/png"),
+ "image_b": ("b.png", _png((255, 255, 255)), "image/png"),
+ },
+ data={"animation": "fade", "filename": "Bad"},
+ ).status_code == 422
+
+
+def test_compare_gif_scales_large_frames_before_building_the_animation():
+ frames = _gif_frames(
+ Image.new("RGB", (MAX_GIF_EDGE * 2, 300), "black"),
+ Image.new("RGB", (MAX_GIF_EDGE * 2, 300), "white"),
+ "slide",
+ )
+ assert len(frames) == 16
+ assert frames[0].size == (MAX_GIF_EDGE, 150)
+
+
+# -- Sentinel-2 index frames ------------------------------------------------------
+
+
+INDEX_BODY = {
+ "west": 250_000, "south": 6_250_000, "east": 251_000, "north": 6_250_600,
+ "width": 320, "height": 192, "day": "2026-05-11", "index": "ndvi", "maxcc": 40,
+}
+
+
+def test_band_frame_needs_a_key_and_refuses_when_the_tier_is_spent(client, monkeypatch):
+ sent = []
+ monkeypatch.setattr(compare_api.sentinel, "band_frame", lambda *a, **k: sent.append(a) or b"")
+ assert client.post("/api/compare/sentinel-index", json=INDEX_BODY).status_code == 404
+
+ client.put("/api/settings/keys", json={"sentinelhub": "inst-uuid"})
+ monkeypatch.setattr(compare_api.config, "usage_blocked", lambda meter: True)
+ assert client.post("/api/compare/sentinel-index", json=INDEX_BODY).status_code == 429
+ assert sent == []
+
+
+def test_band_frame_is_metered_and_answered_as_a_png(client, monkeypatch):
+ client.put("/api/settings/keys", json={"sentinelhub": "inst-uuid"})
+ asked = {}
+
+ def frame(instance, bbox, width, height, day, index, maxcc, *, layer):
+ asked.update(instance=instance, bbox=bbox, size=(width, height), day=day,
+ index=index, maxcc=maxcc, layer=layer)
+ return _png((1, 2, 3), (width, height))
+
+ monkeypatch.setattr(compare_api.sentinel, "band_frame", frame)
+ before = config.month_usage("sentinelhub")
+
+ response = client.post("/api/compare/sentinel-index", json=INDEX_BODY)
+
+ assert response.status_code == 200, response.text
+ assert response.headers["content-type"] == "image/png"
+ assert asked == {
+ "instance": "inst-uuid", "bbox": (250_000, 6_250_000, 251_000, 6_250_600),
+ "size": (320, 192), "day": "2026-05-11", "index": "ndvi", "maxcc": 40,
+ "layer": "TRUE_COLOR",
+ }
+ assert config.month_usage("sentinelhub") == before + 1
+
+
+def test_band_frame_validates_before_asking(client, monkeypatch):
+ client.put("/api/settings/keys", json={"sentinelhub": "inst-uuid"})
+ monkeypatch.setattr(
+ compare_api.sentinel, "band_frame",
+ lambda *a, **k: (_ for _ in ()).throw(ValueError("the frame is empty")),
+ )
+ before = config.month_usage("sentinelhub")
+ assert client.post("/api/compare/sentinel-index", json={**INDEX_BODY, "index": "evi"}).status_code == 422
+ assert client.post("/api/compare/sentinel-index", json={**INDEX_BODY, "width": 5000}).status_code == 422
+ assert client.post("/api/compare/sentinel-index", json=INDEX_BODY).status_code == 422
+ assert config.month_usage("sentinelhub") == before
diff --git a/tests/test_graph.py b/tests/test_graph.py
index f92d5c1..2dfbae7 100644
--- a/tests/test_graph.py
+++ b/tests/test_graph.py
@@ -168,7 +168,8 @@ def test_a_reading_of_the_case_leaves_out_what_the_analyst_wrote():
are derived from the relation registry: a type added there lands in the right
readings with no edit here."""
filing = entity_engine.types_with_role(entity_engine.ANNEX, entity_engine.DELIVERABLE)
- assert filing == {"note", "sheet", "inspect-session", "post"}
+ assert filing == {"note", "sheet", "inspect-session", "compare-session", "post",
+ "analysis-zones", "analysis-follow-up", "analysis-run"}
for lens_id in ("all", "subjects", "ground", "claims"):
assert set(graph_engine.lens(lens_id).hides) == filing, lens_id
diff --git a/tests/test_ingest_api.py b/tests/test_ingest_api.py
index 9c60419..ae3c773 100644
--- a/tests/test_ingest_api.py
+++ b/tests/test_ingest_api.py
@@ -430,9 +430,38 @@ def test_the_extension_reads_back_the_attachments_a_thread_carries(client):
assert client.get("/api/ingest/file", params={"case_id": cid, "path": item["path"]}).status_code == 401
+def test_a_reference_window_pulls_a_long_file_across_in_pieces(client):
+ """A reference is often a video, and a video is not one message. The extension
+ asks for a slice at a time (``background.js``, ``mapFile``) and glues them, so
+ what this route has to serve is a ``Range`` — and say how much there is, since
+ a slice that came up short is not on its own the end of the file."""
+ token = _token(client)
+ cid = client.post("/api/cases", json={"name": "Long clip"}).json()["id"]
+ whole = _png_bytes()
+ item = _upload(client, cid, "clip.png", whole)
+ headers = {"X-Azimut-Token": token}
+
+ got = b""
+ offset, total, rounds = 0, None, 0
+ while total is None or offset < total:
+ r = client.get(
+ "/api/ingest/file",
+ params={"case_id": cid, "path": item["path"]},
+ headers={**headers, "Range": f"bytes={offset}-{offset + 63}"},
+ )
+ assert r.status_code == 206
+ total = int(r.headers["content-range"].split("/")[-1])
+ got += r.content
+ offset += len(r.content)
+ rounds += 1
+ assert rounds > 1 # it really was handed over in pieces
+ assert got == whole
+ assert total == len(whole)
+
+
def test_a_file_past_the_ceiling_is_refused_with_the_number_in_it(client, monkeypatch):
- """The bytes cross the extension as base64 in a message, so there is a size
- past which handing over is not worth the memory. The extension prints this
+ """There is a size past which carrying a case file into someone else's page
+ is not worth it, whatever the transfer does. The extension prints this
sentence rather than keeping a second copy of the number, so it states it."""
from azimut.api import ingest
diff --git a/tests/test_layout.py b/tests/test_layout.py
index fab3d95..f0d69df 100644
--- a/tests/test_layout.py
+++ b/tests/test_layout.py
@@ -97,6 +97,7 @@ def _tool_relative(slug: int, media: int) -> dict[str, int]:
"proof export": len(layout.proof_export_rel(longest_name)),
"draft": len(layout.draft_rel(longest_name)),
"session": len(layout.session_rel(longest_name)),
+ "compare session": len(layout.compare_session_rel(longest_name)),
"grid": len(layout.grid_rel(longest_name)),
"trash slot": len(f"{layout.TRASH_DIR}/") + TRASH_GROUP_ID + 1 + TRASH_SLOT,
}
diff --git a/tests/test_media_map_index.py b/tests/test_media_map_index.py
new file mode 100644
index 0000000..439c695
--- /dev/null
+++ b/tests/test_media_map_index.py
@@ -0,0 +1,244 @@
+"""The Saved panel's Media position: images and videos placed on the map.
+
+A file carries no coordinates (ONTOLOGY §2), so where it stands is read off the
+graph. What must hold: every road that places a file counts (a relation to a place,
+a GPS reading enrichment proposed, a proof reached through the derivation chain);
+one file can stand in several places and is a row at each; roads that agree on a
+point are one row; a file nothing places is not listed; only material the case
+collected is listed, never what it made out of that material; and a row names the
+proofs it can open.
+"""
+
+import base64
+import io
+
+from PIL import Image
+import pytest
+
+from azimut.engine import geo
+from azimut.engine import media as media_engine
+from azimut.workspace import Case
+
+import graph_read
+
+
+def _png_bytes(color=(200, 30, 30), size=(64, 48)) -> bytes:
+ buf = io.BytesIO()
+ Image.new("RGB", size, color).save(buf, "PNG")
+ return buf.getvalue()
+
+
+def sat_tiles(monkeypatch):
+ """Captures without the network: every tile is a solid green square."""
+ from azimut.engine import tiles
+
+ monkeypatch.setattr(
+ tiles, "_default_fetch", lambda client, url: Image.new("RGB", (256, 256), (10, 120, 10))
+ )
+
+
+def _ukraine(lat, lon, timeout=8, language=None):
+ return {
+ "display_name": "x",
+ "address": {"country_code": "ua", "country": "Ukraine", "state": "Donetsk Oblast"},
+ "attribution": "x",
+ }
+
+
+def _new_case(client, name="Media map"):
+ return client.post("/api/cases", json={"name": name}).json()["id"]
+
+
+def _upload(client, cid, name, color=(200, 30, 30)):
+ return client.post(
+ f"/api/cases/{cid}/media/upload",
+ files={"file": (name, io.BytesIO(_png_bytes(color)), "image/png")},
+ ).json()["item"]["path"]
+
+
+def _id(cid, **attrs):
+ found = graph_read.entity(cid, **attrs)
+ assert found is not None, f"no entity with {attrs}"
+ return found["id"]
+
+
+def _place(client, cid, lat, lon):
+ return client.post(
+ f"/api/cases/{cid}/satellite/place", json={"lat": lat, "lon": lon}
+ ).json()["id"]
+
+
+def _link(client, cid, from_id, to_id, type_):
+ res = client.post(
+ f"/api/cases/{cid}/links",
+ json={"from_id": from_id, "to_id": to_id, "type": type_},
+ )
+ assert res.status_code == 200, res.text
+
+
+def _sat(client, cid, lat, lon):
+ return client.post(
+ f"/api/cases/{cid}/satellite/capture",
+ json={"lat": lat, "lon": lon, "zoom": 16, "width": 256, "height": 256},
+ ).json()["path"]
+
+
+def _save_proof(client, cid, title, srcs, **spec_extra):
+ spec = {"panels": [{"id": f"p{i}", "src": s} for i, s in enumerate(srcs)], **spec_extra}
+ png = base64.b64encode(_png_bytes((10, 10, 10))).decode()
+ res = client.post(
+ f"/api/cases/{cid}/proofs",
+ json={"title": title, "spec": spec, "png_base64": png},
+ )
+ assert res.status_code == 200, res.text
+
+
+def _frame_of(cid, source_path, name="frame.png"):
+ """A frame filed the way Inspect files one, derived from its video."""
+ return media_engine.import_image(
+ Case.open(cid),
+ Image.new("RGB", (32, 24), (90, 90, 90)),
+ name,
+ {"type": "inspect", "from": source_path},
+ by="inspect",
+ dedupe=False,
+ )["item"]["path"]
+
+
+def _index(client, cid):
+ res = client.get(f"/api/cases/{cid}/satellite/media")
+ assert res.status_code == 200, res.text
+ return res.json()
+
+
+def _points(rows, path):
+ return sorted((row["lat"], row["lon"]) for row in rows if row["path"] == path)
+
+
+def test_a_file_placed_by_nothing_is_not_listed(client, sat_tiles):
+ cid = _new_case(client)
+ _upload(client, cid, "loose.png")
+ _sat(client, cid, 50.45, 30.52) # a capture is saved work, never a media row
+ assert _index(client, cid) == []
+
+
+def test_a_file_recorded_at_a_place_stands_there_with_its_geography(client, monkeypatch):
+ monkeypatch.setattr(geo, "reverse_geocode", _ukraine)
+ cid = _new_case(client)
+ photo = _upload(client, cid, "quay.png")
+ _link(client, cid, _id(cid, path=photo), _place(client, cid, 48.0159, 37.8029), "located-at")
+
+ [row] = _index(client, cid)
+ assert row["kind"] == "media"
+ assert row["media_kind"] == "image"
+ assert row["title"] == "quay"
+ assert row["path"] == photo
+ assert (row["lat"], row["lon"]) == (48.0159, 37.8029)
+ assert row["key"] == f"{row['id']}@48.0159,37.8029"
+ # borrowed from the place it stands on, so the tree files it under its country
+ assert row["geo"]["country"] == "Ukraine"
+ assert row["continent"] == "Europe"
+ assert row["roads"] == [{"type": "located-at", "status": "confirmed"}]
+ assert row["status"] == "confirmed"
+ assert row["linked_proofs"] == []
+
+
+def test_one_file_recorded_in_one_place_and_showing_another_is_two_rows(client):
+ cid = _new_case(client)
+ clip = _upload(client, cid, "rooftop.png")
+ clip_id = _id(cid, path=clip)
+ _link(client, cid, clip_id, _place(client, cid, 48.0, 37.0), "located-at")
+ _link(client, cid, clip_id, _place(client, cid, 48.01, 37.02), "depicts")
+
+ rows = _index(client, cid)
+ assert _points(rows, clip) == [(48.0, 37.0), (48.01, 37.02)]
+ roads = {(row["lat"], row["lon"]): row["roads"] for row in rows}
+ assert roads[(48.0, 37.0)][0]["type"] == "located-at"
+ assert roads[(48.01, 37.02)][0]["type"] == "depicts"
+ # two rows of one file must not collide as render keys or marker identities
+ assert len({row["key"] for row in rows}) == 2
+
+
+def test_a_gps_reading_nobody_confirmed_reads_as_a_proposal(client):
+ cid = _new_case(client)
+ photo = _upload(client, cid, "exif.png")
+ case = Case.open(cid)
+ place = case.add_entity(
+ "place", "48.8583, 2.2945", {"lat": 48.8583, "lon": 2.2945}, by="enrich",
+ status="suggested",
+ )
+ edge = case.add_link(
+ _id(cid, path=photo), place["id"], "located-at", by="enrich", status="suggested"
+ )
+
+ [row] = _index(client, cid)
+ assert row["status"] == "suggested"
+ assert row["roads"] == [{"type": "located-at", "status": "suggested"}]
+
+ client.patch(f"/api/cases/{cid}/entities/{place['id']}", json={"status": "confirmed"})
+ client.patch(f"/api/cases/{cid}/links/{edge['id']}", json={"status": "confirmed"})
+ [row] = _index(client, cid)
+ assert row["status"] == "confirmed"
+
+
+def test_a_video_stands_where_the_proof_using_its_frame_concludes(client, sat_tiles):
+ """video ◀ frame ◀ proof ▶ capture: the video is placed three hops away, and the
+ row names the proof that placed it so the viewer can open it."""
+ cid = _new_case(client)
+ video = _upload(client, cid, "clip.png")
+ frame = _frame_of(cid, video)
+ cap = _sat(client, cid, 50.4501, 30.5234)
+ _save_proof(client, cid, "Roofline", [frame, cap], coords={"lat": 50.4501, "lon": 30.5234})
+
+ rows = _index(client, cid)
+ assert _points(rows, video) == [(50.4501, 30.5234)]
+ # the frame was cut here and stands where the video already stands: listing it
+ # would mark one spot twice and bury the footage under what came out of it
+ assert _points(rows, frame) == []
+ [video_row] = [row for row in rows if row["path"] == video]
+ assert {"type": "proof", "name": "Roofline"}.items() <= video_row["roads"][-1].items()
+ assert video_row["linked_proofs"][0]["name"] == "Roofline"
+ assert video_row["linked_proofs"][0]["title"] == "Roofline"
+
+
+def test_roads_that_agree_on_a_point_are_one_row(client, sat_tiles):
+ """The composer poses the proof's point on its material as `depicts`, and the
+ same file reaches that proof along the chain. One file on one metre is one mark,
+ keeping both reasons."""
+ cid = _new_case(client)
+ frame = _upload(client, cid, "frame.png")
+ cap = _sat(client, cid, 50.4501, 30.5234)
+ _save_proof(client, cid, "Roofline", [frame, cap], coordsText="50.4501, 30.5234")
+
+ [row] = [row for row in _index(client, cid) if row["path"] == frame]
+ assert [road["type"] for road in row["roads"]] == ["depicts", "proof"]
+ assert [proof["name"] for proof in row["linked_proofs"]] == ["Roofline"]
+
+
+def test_what_the_case_made_is_not_listed_beside_what_it_collected(client, sat_tiles):
+ """Frames, captures and rendered comparisons are working material: they stand
+ where their source stands, and the Media position is about what was brought in.
+ Same question the Media Library asks with its own switch (`links.PRODUCED_HERE`)."""
+ cid = _new_case(client)
+ video = _upload(client, cid, "clip.png")
+ frame = _frame_of(cid, video)
+ cap = _sat(client, cid, 50.4501, 30.5234)
+ _save_proof(client, cid, "Roofline", [frame, cap], coords={"lat": 50.4501, "lon": 30.5234})
+
+ assert [row["path"] for row in _index(client, cid)] == [video]
+
+
+def test_a_proof_composing_the_file_is_offered_even_when_a_capture_placed_it(
+ client, sat_tiles
+):
+ """A proof saved without a point of its own places nothing, so the walk credits
+ the capture. The proof is still one click from the file it was built on."""
+ cid = _new_case(client)
+ photo = _upload(client, cid, "photo.png")
+ cap = _sat(client, cid, 50.4501, 30.5234)
+ _save_proof(client, cid, "Unstated", [photo, cap])
+
+ [row] = _index(client, cid)
+ assert row["roads"][0]["type"] == "capture"
+ assert [proof["name"] for proof in row["linked_proofs"]] == ["Unstated"]
diff --git a/tests/test_migrations.py b/tests/test_migrations.py
index 4800fcf..346f5fb 100644
--- a/tests/test_migrations.py
+++ b/tests/test_migrations.py
@@ -808,3 +808,28 @@ def test_schema_17_rewrites_temporal_bounds_to_fixed_width(tmp_workspace):
item = reopened.timeline_page(categories=["statement"])["items"][0]
assert item["earliest"] == "2026-08-11T10:32:14.500000Z"
assert item["latest"] == "2026-08-11T10:32:14.600000Z"
+
+
+def test_schema_18_projects_a_proof_dated_before_the_projection_read_it(tmp_workspace):
+ case = Case.create("Proof dated by an older build")
+ proof = case.add_entity(
+ "proof",
+ "Kharkiv strike proof",
+ {"spec": "proofs/.meta/Kharkiv strike proof.json", "when": "2024-03-11"},
+ by="proof-composer",
+ )
+ # The state schema 17 left behind: the attribute is on the entity, and the
+ # projection has no row for it because nothing read that attribute yet.
+ with closing(sqlite3.connect(case.db_path)) as conn, conn:
+ conn.execute(
+ "DELETE FROM temporal_items WHERE owner_id = ? AND category = 'statement'",
+ (proof["id"],),
+ )
+ conn.execute("UPDATE meta SET value = '17' WHERE key = 'schema_version'")
+ conn.execute("DELETE FROM schema_migrations WHERE version >= 18")
+
+ reopened = Case.open(case.id)
+
+ items = reopened.timeline_page(categories=["statement"])["items"]
+ assert [item["raw"] for item in items] == ["2024-03-11"]
+ assert items[0]["kind"] == "taken"
diff --git a/tests/test_proofs_api.py b/tests/test_proofs_api.py
index c428a48..0125319 100644
--- a/tests/test_proofs_api.py
+++ b/tests/test_proofs_api.py
@@ -1455,3 +1455,330 @@ def test_a_proof_the_panels_place_opens_with_an_empty_field(client, sat_tiles):
spec = client.get(f"/api/cases/{cid}/proofs/Auto").json()
assert spec.get("points") in (None, [])
+
+
+def test_the_date_and_the_description_travel_to_the_entity(client):
+ cid = client.post("/api/cases", json={"name": "Dated proof"}).json()["id"]
+
+ saved = client.post(
+ f"/api/cases/{cid}/proofs",
+ json={
+ "title": "Dated proof",
+ "spec": {
+ **SPEC,
+ "when": "2024-03-11~",
+ "description": "A formation of 13 helicopters heading east",
+ },
+ },
+ ).json()
+
+ spec = client.get(f"/api/cases/{cid}/proofs/{saved['name']}").json()
+ assert spec["when"] == "2024-03-11~"
+ assert spec["description"] == "A formation of 13 helicopters heading east"
+
+ # On the entity too: the graph reads the date and the notes off the row it
+ # already holds, and the Timeline projects the proof from that attribute.
+ proof = next(e for e in graph_read.entities(cid) if e["type"] == "proof")
+ assert proof["attrs"]["when"] == "2024-03-11~"
+ assert proof["attrs"]["notes"] == "A formation of 13 helicopters heading east"
+
+
+def test_a_dated_proof_states_its_date_on_the_timeline(client):
+ cid = client.post("/api/cases", json={"name": "Proof on the timeline"}).json()["id"]
+ client.post(
+ f"/api/cases/{cid}/proofs",
+ json={"title": "Dated proof", "spec": {**SPEC, "when": "2024-03-11"}},
+ )
+
+ items = client.get(
+ f"/api/cases/{cid}/timeline", params={"categories": "statement"}
+ ).json()["items"]
+
+ assert [(item["kind"], item["raw"]) for item in items] == [("taken", "2024-03-11")]
+
+
+def test_a_date_outside_the_profile_is_refused_before_anything_moves(client):
+ cid = client.post("/api/cases", json={"name": "Bad date"}).json()["id"]
+ client.post(
+ f"/api/cases/{cid}/proofs",
+ json={"title": "Dated proof", "spec": {**SPEC, "when": "2024-03-11"}},
+ )
+
+ refused = client.post(
+ f"/api/cases/{cid}/proofs",
+ json={
+ "rename_from": "Dated proof",
+ "title": "Renamed proof",
+ "spec": {**SPEC, "when": "late summer"},
+ },
+ )
+
+ assert refused.status_code == 422
+ # The rename never happened: the proof is still the one that was there.
+ assert [p["name"] for p in client.get(f"/api/cases/{cid}/proofs").json()] == [
+ "Dated proof"
+ ]
+ spec = client.get(f"/api/cases/{cid}/proofs/Dated proof").json()
+ assert spec["when"] == "2024-03-11"
+
+
+def test_clearing_the_date_takes_it_off_the_entity(client):
+ cid = client.post("/api/cases", json={"name": "Undated again"}).json()["id"]
+ client.post(
+ f"/api/cases/{cid}/proofs",
+ json={"title": "Dated proof", "spec": {**SPEC, "when": "2024-03-11"}},
+ )
+
+ client.post(
+ f"/api/cases/{cid}/proofs",
+ json={"rename_from": "Dated proof", "title": "Dated proof", "spec": SPEC},
+ )
+
+ proof = next(e for e in graph_read.entities(cid) if e["type"] == "proof")
+ assert proof["attrs"]["when"] == ""
+ assert client.get(f"/api/cases/{cid}/proofs/Dated proof").json()["when"] is None
+ assert (
+ client.get(f"/api/cases/{cid}/timeline", params={"categories": "statement"})
+ .json()["items"]
+ == []
+ )
+
+
+def test_a_description_edited_in_the_graph_is_what_reopens(client):
+ cid = client.post("/api/cases", json={"name": "Edited notes"}).json()["id"]
+ client.post(
+ f"/api/cases/{cid}/proofs",
+ json={"title": "Dated proof", "spec": {**SPEC, "description": "First reading"}},
+ )
+ proof = next(e for e in graph_read.entities(cid) if e["type"] == "proof")
+
+ client.patch(
+ f"/api/cases/{cid}/entities/{proof['id']}",
+ json={"attrs": {"notes": "Corrected reading", "when": "2024-03-12"}},
+ )
+
+ spec = client.get(f"/api/cases/{cid}/proofs/Dated proof").json()
+ assert spec["description"] == "Corrected reading"
+ assert spec["when"] == "2024-03-12"
+
+
+def _collected_clip(cid, name="clip.png"):
+ """A collected file, as a download would leave it."""
+ from azimut.engine import media as media_engine
+
+ return media_engine.import_image(
+ Case.open(cid),
+ Image.new("RGB", (48, 32), (30, 30, 30)),
+ name,
+ {"type": "download", "webpage_url": "https://x.com/a/status/1"},
+ by="ingest",
+ )["item"]["path"]
+
+
+def _cut_frame(cid, parent, name="clip_frame.png"):
+ """A frame cut out of it: the panel a proof actually composes."""
+ from azimut.engine import media as media_engine
+
+ return media_engine.import_image(
+ Case.open(cid),
+ Image.new("RGB", (48, 32), (60, 60, 60)),
+ name,
+ {"type": "derived", "op": "frame", "from": parent, "time": 69.0},
+ by="inspect",
+ )["item"]["path"]
+
+
+def _claims(cid):
+ return [e for e in graph_read.entities(cid) if e["type"] == "claim"]
+
+
+def test_the_date_states_itself_for_the_footage_behind_the_panel(client):
+ cid = client.post("/api/cases", json={"name": "Dated footage"}).json()["id"]
+ video = _collected_clip(cid)
+ frame = _cut_frame(cid, video)
+
+ saved = client.post(
+ f"/api/cases/{cid}/proofs",
+ json={
+ "title": "Dated proof",
+ "spec": {**_panels(frame), "when": "2024-03-11~"},
+ },
+ ).json()
+
+ # The save says what it wrote, rather than filing into the graph in silence.
+ assert saved["dated"] == ["clip"]
+ claim = _claims(cid)[0]
+ assert claim["attrs"]["when"] == "2024-03-11~"
+ assert claim["attrs"]["time_role"] == "observed"
+ assert claim["label"] == "Material of Dated proof was taken"
+
+ # About the video, not about the frame cut out of it: the thing that was
+ # filmed is the one the date is a fact about.
+ entities = {e["id"]: e for e in graph_read.entities(cid)}
+ subjects = [
+ entities[link["to"]]["label"]
+ for link in graph_read.links(cid)
+ if link["from"] == claim["id"] and link["type"] == "about"
+ ]
+ assert subjects == ["clip"]
+ cites = [
+ entities[link["to"]]["type"]
+ for link in graph_read.links(cid)
+ if link["from"] == claim["id"] and link["type"] == "cites"
+ ]
+ assert cites == ["proof"]
+
+
+def test_the_stated_date_shows_on_the_file_it_is_about(client):
+ cid = client.post("/api/cases", json={"name": "Seen from the video"}).json()["id"]
+ video = _collected_clip(cid)
+ client.post(
+ f"/api/cases/{cid}/proofs",
+ json={"title": "Dated proof", "spec": {**_panels(video), "when": "2024-03-11"}},
+ )
+ media = next(e for e in graph_read.entities(cid) if e["type"] == "media")
+
+ page = client.get(
+ f"/api/cases/{cid}/timeline",
+ params={"entity": media["id"], "categories": ["statement", "media"]},
+ ).json()
+
+ stated = [item for item in page["items"] if item["category"] == "statement"]
+ assert [item["raw"] for item in stated] == ["2024-03-11"]
+ # The file's own clock is untouched: the sidecar still says what it said.
+ item = client.get(f"/api/cases/{cid}/media/item", params={"path": video}).json()
+ assert "taken_at" not in item
+
+
+def test_a_satellite_capture_is_never_dated_by_the_proof(client, sat_tiles):
+ cid = client.post("/api/cases", json={"name": "Reference imagery"}).json()["id"]
+ cap = _sat(client, cid, 50.4501, 30.5234)
+
+ saved = client.post(
+ f"/api/cases/{cid}/proofs",
+ json={"title": "Dated proof", "spec": {**_panels(cap["path"]), "when": "2024-03-11"}},
+ ).json()
+
+ # Its date is the provider's flyover, and the proof has nothing to say about it.
+ assert saved["dated"] == []
+ assert _claims(cid) == []
+
+
+def test_re_saving_restates_the_date_rather_than_filing_a_second_one(client):
+ cid = client.post("/api/cases", json={"name": "Restated"}).json()["id"]
+ video = _collected_clip(cid)
+ body = {"title": "Dated proof", "spec": {**_panels(video), "when": "2024-03-11"}}
+ client.post(f"/api/cases/{cid}/proofs", json=body)
+
+ client.post(
+ f"/api/cases/{cid}/proofs",
+ json={
+ "rename_from": "Dated proof",
+ "title": "Renamed proof",
+ "spec": {**_panels(video), "when": "2024-03-12"},
+ },
+ )
+
+ claims = _claims(cid)
+ assert len(claims) == 1
+ assert claims[0]["attrs"]["when"] == "2024-03-12"
+ # The statement follows the rename, like every other file the proof owns.
+ assert claims[0]["label"] == "Material of Renamed proof was taken"
+
+
+def test_clearing_the_date_takes_the_statement_back(client):
+ cid = client.post("/api/cases", json={"name": "Withdrawn"}).json()["id"]
+ video = _collected_clip(cid)
+ client.post(
+ f"/api/cases/{cid}/proofs",
+ json={"title": "Dated proof", "spec": {**_panels(video), "when": "2024-03-11"}},
+ )
+
+ client.post(
+ f"/api/cases/{cid}/proofs",
+ json={"rename_from": "Dated proof", "title": "Dated proof", "spec": _panels(video)},
+ )
+
+ assert _claims(cid) == []
+
+
+def test_a_statement_the_analyst_worked_on_is_not_deleted_from_the_composer(client):
+ cid = client.post("/api/cases", json={"name": "Enriched"}).json()["id"]
+ video = _collected_clip(cid)
+ client.post(
+ f"/api/cases/{cid}/proofs",
+ json={"title": "Dated proof", "spec": {**_panels(video), "when": "2024-03-11"}},
+ )
+ claim = _claims(cid)[0]
+ client.patch(
+ f"/api/cases/{cid}/entities/{claim['id']}",
+ json={"attrs": {"method": "Matched against the shadow length"}},
+ )
+
+ client.post(
+ f"/api/cases/{cid}/proofs",
+ json={"rename_from": "Dated proof", "title": "Dated proof", "spec": _panels(video)},
+ )
+
+ # Clearing a field in the composer must not delete reasoning written elsewhere.
+ kept = _claims(cid)
+ assert len(kept) == 1
+ assert kept[0]["attrs"]["method"] == "Matched against the shadow length"
+
+
+def test_a_source_taken_off_the_proof_is_no_longer_dated_by_it(client):
+ cid = client.post("/api/cases", json={"name": "Two clips"}).json()["id"]
+ first = _collected_clip(cid, "first.png")
+ second = _collected_clip(cid, "second.png")
+ client.post(
+ f"/api/cases/{cid}/proofs",
+ json={
+ "title": "Dated proof",
+ "spec": {**_panels(first, second), "when": "2024-03-11"},
+ },
+ )
+
+ client.post(
+ f"/api/cases/{cid}/proofs",
+ json={
+ "rename_from": "Dated proof",
+ "title": "Dated proof",
+ "spec": {**_panels(first), "when": "2024-03-11"},
+ },
+ )
+
+ claim = _claims(cid)[0]
+ entities = {e["id"]: e for e in graph_read.entities(cid)}
+ subjects = sorted(
+ entities[link["to"]]["label"]
+ for link in graph_read.links(cid)
+ if link["from"] == claim["id"] and link["type"] == "about"
+ )
+ assert subjects == ["first"]
+
+
+def test_a_statement_reworded_by_hand_keeps_its_own_wording(client):
+ cid = client.post("/api/cases", json={"name": "Reworded"}).json()["id"]
+ video = _collected_clip(cid)
+ client.post(
+ f"/api/cases/{cid}/proofs",
+ json={"title": "Dated proof", "spec": {**_panels(video), "when": "2024-03-11"}},
+ )
+ claim = _claims(cid)[0]
+ client.patch(
+ f"/api/cases/{cid}/entities/{claim['id']}",
+ json={"label": "The convoy was filmed that morning"},
+ )
+
+ client.post(
+ f"/api/cases/{cid}/proofs",
+ json={
+ "rename_from": "Dated proof",
+ "title": "Dated proof",
+ "spec": {**_panels(video), "when": "2024-03-12"},
+ },
+ )
+
+ restated = _claims(cid)[0]
+ assert restated["label"] == "The convoy was filmed that morning"
+ assert restated["attrs"]["when"] == "2024-03-12" # the date is still restated
diff --git a/tests/test_proofs_assets_api.py b/tests/test_proofs_assets_api.py
index 4e79a43..33a2207 100644
--- a/tests/test_proofs_assets_api.py
+++ b/tests/test_proofs_assets_api.py
@@ -248,3 +248,24 @@ def test_a_proof_without_pastes_keeps_no_assets_folder(client):
f"/api/cases/{cid}/proofs", json={"title": "Plain", "spec": _spec(panels=["media/a.jpg"])}
)
assert not get_case(cid).resolve_inside(layout.proof_assets_rel("Plain")).exists()
+
+
+def test_the_composer_reads_a_paste_back_where_the_save_wrote_it():
+ """The one server-owned path the frontend spells for itself.
+
+ Everything else a proof holds comes back through the API — the spec names its
+ panels, the list names the export. A pasted image is addressed by the composer
+ building the URL itself, so the two spellings can drift apart in silence, and
+ when they did the composer reported an overlay the case had never lost. Pinned
+ here rather than in the frontend suite, because only this side knows where the
+ save actually put the file.
+ """
+ from pathlib import Path
+
+ source = (
+ Path(__file__).resolve().parents[1]
+ / "frontend" / "src" / "tools" / "ProofComposer.svelte"
+ ).read_text(encoding="utf-8")
+
+ folder = layout.proof_assets_rel("${entry.name}")
+ assert f"`{folder}/${{p.asset}}`" in source
diff --git a/tests/test_sentinel.py b/tests/test_sentinel.py
index 8d4beac..991ee77 100644
--- a/tests/test_sentinel.py
+++ b/tests/test_sentinel.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+import base64
import json
import io
@@ -280,6 +281,131 @@ def test_dates_raises_rather_than_report_an_empty_sky():
sentinel.dates("inst-uuid", 48.0, 2.0, "2026-05-01", "2026-05-31", get=get)
+# -- acquisitions over a drawn area -------------------------------------------
+
+
+def _rect(west, south, east, north):
+ """A drawn area's ring, the way `analysis_models.Zone.ring()` gives it."""
+ return [(west, south), (east, south), (east, north), (west, north)]
+
+
+def _granule(day, west, south, east, north, cloud=5.0):
+ return {
+ "properties": {"date": day, "cloudCoverPercentage": cloud},
+ "geometry": {"type": "Polygon", "coordinates": [[
+ [west, south], [east, south], [east, north], [west, north], [west, south],
+ ]]},
+ }
+
+
+def test_acquisitions_measures_how_much_of_the_area_a_pass_reaches():
+ """The number a crosshair lookup cannot give. Sentinel-2 flies 290 km swaths,
+ so a wide area can have no single day covering it — and pinned to one date
+ anyway, the rest of the sweep reads nodata."""
+ area = _rect(2.0, 48.0, 4.0, 49.0)
+
+ def get(url, params=None, **kwargs):
+ return _response(url, {"features": [
+ # covers the lot
+ _granule("2026-05-11", 1.5, 47.5, 4.5, 49.5, cloud=3.0),
+ # only the western half
+ _granule("2026-05-08", 1.5, 47.5, 3.0, 49.5, cloud=9.0),
+ ]})
+
+ found = sentinel.acquisitions("inst-uuid", [area], "2026-05-01", "2026-05-31", get=get)
+ whole, half = found["dates"]
+ assert whole["date"] == "2026-05-11" # newest first
+ assert whole["coverage"] == 1.0
+ assert half["date"] == "2026-05-08"
+ assert 0.45 < half["coverage"] < 0.55
+ assert not found["truncated"]
+
+
+def test_acquisitions_adds_up_two_granules_of_the_same_day():
+ """One day, two granules of the same orbit: together they cover the area,
+ and reporting either alone would call a usable date partial."""
+ area = _rect(2.0, 48.0, 4.0, 49.0)
+
+ def get(url, params=None, **kwargs):
+ return _response(url, {"features": [
+ _granule("2026-05-11", 1.5, 47.5, 3.0, 49.5, cloud=40.0),
+ _granule("2026-05-11", 3.0, 47.5, 4.5, 49.5, cloud=4.0),
+ ]})
+
+ entry = sentinel.acquisitions("inst-uuid", [area], "2026-05-01", "2026-05-31", get=get)["dates"][0]
+ assert entry["coverage"] == 1.0
+ assert entry["granules"] == 2
+ # the clearer of the two is the one worth reporting
+ assert entry["cloud"] == 4.0
+
+
+def test_acquisitions_drops_a_day_that_reaches_none_of_the_area():
+ area = _rect(2.0, 48.0, 2.5, 48.5)
+
+ def get(url, params=None, **kwargs):
+ return _response(url, {"features": [_granule("2026-05-04", 8.0, 44.0, 9.0, 45.0)]})
+
+ # a box may intersect the search area while its swath is a province away
+ assert sentinel.acquisitions("inst-uuid", [area], "2026-05-01", "2026-05-31", get=get)["dates"] == []
+
+
+def test_acquisitions_weighs_a_small_area_beside_a_large_one():
+ """Every drawn area gets sampled, so a pass that misses the small one cannot
+ report as full cover just because the big one dwarfs it."""
+ big = _rect(2.0, 48.0, 4.0, 49.0)
+ small = _rect(10.0, 40.0, 10.02, 40.02)
+
+ def get(url, params=None, **kwargs):
+ return _response(url, {"features": [_granule("2026-05-11", 1.5, 47.5, 4.5, 49.5)]})
+
+ entry = sentinel.acquisitions("inst-uuid", [big, small], "2026-05-01", "2026-05-31", get=get)["dates"][0]
+ assert entry["coverage"] < 1.0
+
+
+def test_acquisitions_asks_about_the_whole_set_latitude_first():
+ captured = {}
+
+ def get(url, params=None, **kwargs):
+ captured.update(params)
+ return _response(url, {"features": []})
+
+ sentinel.acquisitions(
+ "inst-uuid", [_rect(2.0, 48.0, 2.5, 48.5), _rect(6.0, 44.0, 6.5, 44.5)],
+ "2026-05-01", "2026-05-31", get=get,
+ )
+ lat_min, lon_min, lat_max, lon_max = (float(v) for v in captured["BBOX"].split(","))
+ # one box around both areas, and EPSG:4326's declared latitude-first order
+ assert lat_min < 44.0 and lat_max > 48.5
+ assert lon_min < 2.0 and lon_max > 6.5
+
+
+def test_acquisitions_says_when_the_catalogue_stopped_short():
+ """Silently truncated, the list reads as "these are all the passes" while
+ the older half is missing."""
+ area = _rect(2.0, 48.0, 2.5, 48.5)
+ crowd = [_granule(f"2026-05-{day:02d}", 1.5, 47.5, 3.0, 49.5) for day in range(1, 31)]
+
+ def get(url, params=None, **kwargs):
+ return _response(url, {"features": crowd * 4}) # 120, past the 100 ceiling
+
+ assert sentinel.acquisitions("inst-uuid", [area], "2026-05-01", "2026-05-31", get=get)["truncated"]
+
+
[email protected]("start,end", [
+ ("2026-13-01", "2026-05-31"), ("2026-05-01", "not-a-date"), ("2026-05-31", "2026-05-01"),
+])
+def test_acquisitions_refuses_a_malformed_window(start, end):
+ with pytest.raises(ValueError):
+ sentinel.acquisitions("inst-uuid", [_rect(2.0, 48.0, 2.5, 48.5)], start, end,
+ get=lambda *a, **k: _response("x", {"features": []}))
+
+
+def test_acquisitions_refuses_an_empty_area_set():
+ with pytest.raises(ValueError):
+ sentinel.acquisitions("inst-uuid", [], "2026-05-01", "2026-05-31",
+ get=lambda *a, **k: _response("x", {"features": []}))
+
+
# -- rendered coverage --------------------------------------------------------
@@ -402,3 +528,116 @@ def test_capabilities_layers_drops_names_that_could_not_be_asked_for():
# "bad id" can't survive a variant id (URL path segment + cache directory),
# so offering it would only produce a broken selection
assert all(" " not in entry["id"] for entry in sentinel.capabilities_layers("i", get=get))
+
+
+# -- spectral index frames ------------------------------------------------------
+
+
+def _rgba_response(url, size):
+ payload = io.BytesIO()
+ Image.new("RGBA", size, (200, 4, 0, 255)).save(payload, format="PNG")
+ return httpx.Response(200, content=payload.getvalue(), request=httpx.Request("GET", url))
+
+
+BOX = (250_000.0, 6_250_000.0, 251_000.0, 6_250_600.0)
+
+
+ ("index", "high", "low"),
+ [("ndvi", "B08", "B04"), ("ndwi", "B03", "B08"), ("nbr", "B08", "B12"), ("ndbi", "B11", "B08")],
+)
+def test_band_frame_asks_for_the_named_normalised_difference(index, high, low):
+ captured = {}
+
+ def get(url, params=None, **kwargs):
+ captured.update(params)
+ return _rgba_response(url, (320, 192))
+
+ body = sentinel.band_frame("inst-uuid", BOX, 320, 192, "2026-05-11", index, 30, get=get)
+
+ script = base64.b64decode(captured["EVALSCRIPT"]).decode("ascii")
+ assert f'bands: ["{high}", "{low}", "SCL", "dataMask"]' in script
+ assert f"p.{high} - p.{low}" in script
+ assert captured["CRS"] == "EPSG:3857"
+ assert captured["BBOX"] == "250000.0,6250000.0,251000.0,6250600.0"
+ assert (captured["WIDTH"], captured["HEIGHT"]) == ("320", "192")
+ assert captured["TIME"] == "2026-05-11/2026-05-11"
+ assert captured["MAXCC"] == "30"
+ assert body.startswith(b"\x89PNG")
+
+
+ "kwargs",
+ [
+ {"index": "evi"},
+ {"bbox": (10.0, 10.0, 5.0, 20.0)},
+ {"bbox": (0.0, 0.0, 30_000_000.0, 10.0)},
+ {"width": 4096},
+ {"day": "2026-13-40"},
+ ],
+)
+def test_band_frame_refuses_a_malformed_request_before_sending_it(kwargs):
+ asked = dict(bbox=BOX, width=64, height=64, day="2026-05-11", index="ndvi")
+ asked.update(kwargs)
+
+ def get(*args, **kw): # pragma: no cover - must never run
+ raise AssertionError("nothing may be sent")
+
+ with pytest.raises(ValueError):
+ sentinel.band_frame(
+ "inst-uuid", asked["bbox"], asked["width"], asked["height"],
+ asked["day"], asked["index"], get=get,
+ )
+
+
+def test_band_frame_refuses_an_image_of_the_wrong_size():
+ with pytest.raises(sentinel.CoverageError):
+ sentinel.band_frame(
+ "inst-uuid", BOX, 64, 64, "2026-05-11", "ndvi",
+ get=lambda url, **kw: _rgba_response(url, (32, 32)),
+ )
+
+
+def test_band_frame_asks_for_infrared_and_water_when_looking_for_vessels():
+ captured = {}
+
+ def get(url, params=None, **kwargs):
+ captured.update(params)
+ return _rgba_response(url, (64, 64))
+
+ sentinel.band_frame("inst-uuid", BOX, 64, 64, "2026-05-11", "vessel", get=get)
+
+ script = base64.b64decode(captured["EVALSCRIPT"]).decode("ascii")
+ assert 'bands: ["B03", "B08", "SCL", "dataMask"]' in script
+ # Near-infrared first, stretched so open water spans a usable part of the
+ # byte, then the scene class, then NDWI, then the data mask.
+ assert f"p.B08 * 255 * {sentinel.NIR_GAIN}" in script
+ assert "p.B03 - p.B08" in script
+ assert "p.SCL" in script
+
+
+def test_band_frame_asks_for_the_short_wave_ratios_when_looking_for_fire():
+ captured = {}
+
+ def get(url, params=None, **kwargs):
+ captured.update(params)
+ return _rgba_response(url, (64, 64))
+
+ sentinel.band_frame("inst-uuid", BOX, 64, 64, "2026-05-11", "fire", get=get)
+
+ script = base64.b64decode(captured["EVALSCRIPT"]).decode("ascii")
+ assert 'bands: ["B08", "B11", "B12", "dataMask"]' in script
+ assert "p.B12 / p.B11" in script
+ assert "p.B12 / p.B08" in script
+ # No scene class: the ratios are what reject cloud, and the fourth channel
+ # is worth more as the data mask.
+ assert "SCL" not in script
+
+
+def test_band_frame_refuses_a_product_it_has_no_evalscript_for():
+ def get(*args, **kwargs): # pragma: no cover - must never run
+ raise AssertionError("nothing may be sent")
+
+ with pytest.raises(ValueError):
+ sentinel.band_frame("inst-uuid", BOX, 64, 64, "2026-05-11", "thermal", get=get)
+ assert sentinel.PRODUCTS == {"ndvi", "ndwi", "nbr", "ndbi", "vessel", "fire"}
diff --git a/tests/test_settings_api.py b/tests/test_settings_api.py
index aeaf9e8..c6f7de4 100644
--- a/tests/test_settings_api.py
+++ b/tests/test_settings_api.py
@@ -1,6 +1,7 @@
"""Settings API: API keys management, key tests, usage counters (all offline)."""
import httpx
+import pytest
from azimut import config
from azimut.engine import google_tiles, scrapers, sentinel
@@ -531,6 +532,55 @@ def test_sentinel_dates_lists_passes_and_counts_the_request(client, monkeypatch)
assert settings["usage"]["sentinelhub"][settings["month"]] == 1
+def _area(west=2.0, south=48.0, east=2.5, north=48.5):
+ return {"id": "harbour", "name": "Harbour", "kind": "rect",
+ "points": [[west, south], [east, north]]}
+
+
+def test_sentinel_acquisitions_reports_cover_over_the_areas_and_counts_the_request(
+ client, monkeypatch
+):
+ client.put("/api/settings/keys", json={"sentinelhub": "inst-uuid"})
+ payload = (
+ '{"features": [{"properties": {"date": "2026-05-11", "cloudCoverPercentage": 4},'
+ ' "geometry": {"type": "Polygon", "coordinates": [[[1.5, 47.5], [2.2, 47.5],'
+ ' [2.2, 49.5], [1.5, 49.5], [1.5, 47.5]]]}}]}'
+ )
+
+ def get(url, **kwargs):
+ assert "/ogc/wfs/inst-uuid" in url
+ return httpx.Response(200, content=payload.encode(), request=httpx.Request("GET", url))
+
+ monkeypatch.setattr(httpx, "get", get)
+ body = client.post("/api/satellite/sentinel/acquisitions", json={
+ "zones": [_area()], "start": "2026-05-01", "end": "2026-05-31",
+ }).json()
+ entry = body["dates"][0]
+ assert entry["date"] == "2026-05-11"
+ # the granule stops at longitude 2.2, so it reaches part of a 2.0…2.5 area
+ assert 0 < entry["coverage"] < 1
+ assert body["truncated"] is False
+ settings = client.get("/api/settings").json()
+ assert settings["usage"]["sentinelhub"][settings["month"]] == 1
+
+
+ {"zones": []},
+ {"start": "not-a-date"},
+ {"end": "2026-13-01"},
+ {"zones": [{**_area(), "shade": "#fff"}]}, # extra="forbid" on the zone model
+])
+def test_sentinel_acquisitions_refuses_a_malformed_request(client, patch):
+ client.put("/api/settings/keys", json={"sentinelhub": "inst-uuid"})
+ body = {"zones": [_area()], "start": "2026-05-01", "end": "2026-05-31", **patch}
+ assert client.post("/api/satellite/sentinel/acquisitions", json=body).status_code == 422
+
+
+def test_sentinel_acquisitions_without_a_key_is_a_404(client):
+ body = {"zones": [_area()], "start": "2026-05-01", "end": "2026-05-31"}
+ assert client.post("/api/satellite/sentinel/acquisitions", json=body).status_code == 404
+
+
def test_sentinel_dates_without_a_key_is_a_404(client):
assert (
client.get(
diff --git a/tests/test_sheet_pass.py b/tests/test_sheet_pass.py
index c944f63..b9b2801 100644
--- a/tests/test_sheet_pass.py
+++ b/tests/test_sheet_pass.py
@@ -332,7 +332,9 @@ def test_no_mode_of_this_screen_creates_anything_that_owns_a_file(client):
from azimut.engine import sheetpromote
offered = set(sheetpromote.promotable_types())
- assert offered.isdisjoint({"media", "capture", "proof", "post", "inspect-session"})
+ assert offered.isdisjoint({
+ "media", "capture", "proof", "post", "inspect-session", "compare-session"
+ })
case_id = make_case(client)
sheet = roster(client, case_id)
diff --git a/tests/test_sqlite_backend.py b/tests/test_sqlite_backend.py
index c4ca18f..e99dd44 100644
--- a/tests/test_sqlite_backend.py
+++ b/tests/test_sqlite_backend.py
@@ -481,6 +481,7 @@ def test_media_browse_index_pages_searches_and_counts_categories(tmp_path):
assert first["facets"]["category_counts"] == {
"image": 1,
"video": 1,
+ "comparison": 0,
"collage": 0,
"satellite": 1,
"upload": 1,
diff --git a/tests/test_thumbnails.py b/tests/test_thumbnails.py
index e5dfb78..761f3ae 100644
--- a/tests/test_thumbnails.py
+++ b/tests/test_thumbnails.py
@@ -216,6 +216,27 @@ def test_worker_wakes_and_drains_in_the_background(tmp_workspace, monkeypatch):
assert workqueue.wait_until_idle(WAIT)
+def test_a_worker_that_claims_at_once_still_records_the_thumbnail(case, monkeypatch):
+ """The job is queued only once the sidecar exists.
+
+ Queued before it, a worker quick enough to claim the job found no sidecar and
+ dropped it as media gone, so the video never got a thumbnail. A macOS runner
+ was that quick. Draining inside `wake` is the quickest a worker can be.
+ """
+ def fake_render(media_path, out_path, kind):
+ out_path.write_bytes(b"\xff\xd8\xff\xe0jpeg")
+ return True
+
+ monkeypatch.setattr(thumbnails, "_render", fake_render)
+ monkeypatch.setattr(workqueue, "wake", workqueue.drain)
+
+ item = _register_video(case)["item"]
+
+ refreshed = media_engine.read_item(case, item["path"])
+ assert refreshed["thumbnail"] and case.resolve_inside(refreshed["thumbnail"]).exists()
+ assert case.list_media_items()[0]["thumbnail"] == refreshed["thumbnail"]
+
+
# -- videos shorter than the seek -----------------------------------------
diff --git a/tests/test_timeline.py b/tests/test_timeline.py
index bb4632c..b22062d 100644
--- a/tests/test_timeline.py
+++ b/tests/test_timeline.py
@@ -62,6 +62,42 @@ def test_a_local_media_time_is_known_but_not_invented_on_the_utc_axis():
assert row.sortable is False
+def test_a_dated_proof_states_when_its_material_was_taken():
+ rows = timeline.project_entity(
+ {
+ "id": "e_proof",
+ "type": "proof",
+ "label": "Kharkiv strike proof",
+ "attrs": {"spec": "proofs/.meta/p.json", "when": "2024-03-11~"},
+ "provenance": {"by": "proof-composer", "at": "2026-08-11T10:00:00Z"},
+ }
+ )
+ by_kind = {row.kind: row for row in rows}
+
+ # The filing row stays: when the proof was made and when the footage was shot
+ # are two answers, and the second one replacing the first would lose a date.
+ assert set(by_kind) == {"filed", "taken"}
+ taken = by_kind["taken"]
+ assert taken.category == "statement"
+ assert taken.authority == "entity"
+ assert taken.raw == "2024-03-11~"
+ assert taken.approximate is True
+ assert taken.time_role == "occurred"
+
+
+def test_an_undated_proof_reaches_the_timeline_only_as_a_filing():
+ rows = timeline.project_entity(
+ {
+ "id": "e_proof",
+ "type": "proof",
+ "attrs": {"spec": "proofs/.meta/p.json", "when": ""},
+ "provenance": {"at": "2026-08-11T10:00:00Z"},
+ }
+ )
+
+ assert [row.kind for row in rows] == ["filed"]
+
+
def test_media_dates_keep_world_time_separate_from_case_activity():
rows = timeline.project_media(
{
diff --git a/tests/test_todos.py b/tests/test_todos.py
new file mode 100644
index 0000000..e737ca4
--- /dev/null
+++ b/tests/test_todos.py
@@ -0,0 +1,87 @@
+"""Case checklist persistence, validation, concurrency and portable bundles."""
+
+from copy import deepcopy
+
+import pytest
+
+from azimut.engine import bundles
+from azimut.workspace import Case
+
+
+def checklist():
+ return {"revision": 0, "lists": [
+ {"id": "first", "name": "Checks", "tasks": [
+ {"id": "task", "text": "Verify source", "done": False},
+ ]},
+ {"id": "second", "name": "Follow up", "tasks": []},
+ ]}
+
+
+def test_checklist_lifecycle_and_case_isolation(client):
+ cid = client.post("/api/cases", json={"name": "Checklist"}).json()["id"]
+ other = client.post("/api/cases", json={"name": "Other case"}).json()["id"]
+ url = f"/api/cases/{cid}/todos"
+ initial = client.get(url).json()
+ assert initial == {"revision": 0, "lists": [{"id": "default", "name": "Tasks", "tasks": []}]}
+ assert "todos" not in Case.open(cid).read() # viewing an old case needs no migration
+ saved = client.put(url, json=checklist()).json()
+ assert saved["revision"] == 1
+ saved["lists"][0]["tasks"][0].update(text="Verify original source", done=True)
+ saved["lists"][1]["name"] = "Contacts"
+ saved = client.put(url, json=saved).json()
+ assert Case.open(cid).read_todos() == saved
+ assert client.get(f"/api/cases/{other}/todos").json() == initial
+ assert client.put(url, json=checklist()).status_code == 409
+ assert client.get(url).json() == saved
+ saved["lists"][0]["tasks"] = []
+ saved = client.put(url, json=saved).json()
+ saved["lists"] = []
+ assert client.put(url, json=saved).json()["lists"] == []
+ assert Case.open(cid).list_entities() == []
+
+
[email protected]("change", [
+ lambda data: data["lists"][0].update(name=" "),
+ lambda data: data["lists"][0]["tasks"][0].update(text=" "),
+ lambda data: data["lists"][0]["tasks"][0].update(text="x" * 2001),
+ lambda data: data["lists"].append(deepcopy(data["lists"][0])),
+ lambda data: data["lists"][0]["tasks"].append(deepcopy(data["lists"][0]["tasks"][0])),
+ lambda data: data.update(revision=-1),
+ lambda data: data["lists"][0].update(id="../escape"),
+ lambda data: data["lists"][0].update(tasks=[{"id": str(i), "text": "Check"} for i in range(201)]),
+ lambda data: data.update(lists=[{"id": str(i), "name": "List"} for i in range(51)]),
+])
+def test_invalid_checklist_does_not_change_case(client, change):
+ cid = client.post("/api/cases", json={"name": "Validation"}).json()["id"]
+ data = checklist()
+ change(data)
+ assert client.put(f"/api/cases/{cid}/todos", json=data).status_code == 422
+ assert Case.open(cid).read_todos()["revision"] == 0
+
+
+def test_checklists_survive_bundle_round_trip(client):
+ cid = client.post("/api/cases", json={"name": "Portable tasks"}).json()["id"]
+ data = checklist()
+ data["lists"][0]["tasks"][0]["done"] = True
+ saved = client.put(f"/api/cases/{cid}/todos", json=data).json()
+ exported = bundles.export_case(Case.open(cid))
+ destination = Case.create("Imported tasks")
+ bundles.import_into(destination, exported)
+ assert Case.open(destination.id).read_todos() == saved
+
+
+def test_missing_case_does_not_create_checklist(client):
+ assert client.get("/api/cases/missing/todos").status_code == 404
+ assert client.put("/api/cases/missing/todos", json=checklist()).status_code == 404
+
+
+def test_scratch_cleanup_keeps_checklists(tmp_workspace):
+ case = Case.create("Scratch tasks", scratch=True)
+ case.write_todos(checklist())
+ data = case.read()
+ data["updated_at"] = "2000-01-01T00:00:00Z"
+ import json
+
+ case.json_path.write_text(json.dumps(data), encoding="utf-8")
+ assert Case.cleanup_scratch() == 0
+ assert Case.open(case.id).read_todos()["lists"] == checklist()["lists"]
diff --git a/tests/test_updates.py b/tests/test_updates.py
index 8011571..0469c17 100644
--- a/tests/test_updates.py
+++ b/tests/test_updates.py
@@ -139,7 +139,7 @@ def test_update_endpoint_with_check_queries_github(client, monkeypatch):
# 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_PAYLOAD = "6723a66d5221f4465fb87f3031ca9f53772393efcf9d63b4ca28aa8958917a01"
+EXTENSION_PAYLOAD = "a91b35eaeb29427e0519963c6a0a74e67670fbf38f6090b8c553125e7111e96a"
# The digest itself lives in engine/extinstall.py, because the update button
# compares the same number: what the app ships against what the installed folder
diff --git a/tests/test_workspace_lock.py b/tests/test_workspace_lock.py
index 007391f..eeb73cb 100644
--- a/tests/test_workspace_lock.py
+++ b/tests/test_workspace_lock.py
@@ -78,6 +78,26 @@ def _holder_process(root: Path) -> subprocess.Popen:
return child
+def _acquire_once_free(port: int, timeout: float = 10.0) -> None:
+ """Take the lock a dead holder left behind.
+
+ Windows reports a killed process as gone before it has finished tearing it
+ down, so the handle it held can outlive `wait()` by a moment and the first
+ attempt meets a corpse's lock. What the tests claim is that nobody has to
+ delete a file for the workspace to open again; how long the kernel takes to
+ say so is the operating system's business, not the property under test.
+ """
+ deadline = time.monotonic() + timeout
+ while True:
+ try:
+ workspacelock.acquire(port)
+ return
+ except WorkspaceBusy:
+ if time.monotonic() >= deadline:
+ raise
+ time.sleep(0.05)
+
+
# -- another process -----------------------------------------------------------
@@ -108,7 +128,7 @@ def test_the_lock_dies_with_the_process(workspace):
child.kill()
child.wait(timeout=10)
- workspacelock.acquire(8478) # no exception: the OS let go on its own
+ _acquire_once_free(8478) # no exception: the OS let go on its own
assert workspacelock.holder() is None
@@ -120,7 +140,7 @@ def test_a_clean_exit_leaves_no_payload_to_age(workspace):
# The child's atexit-free path still releases via the OS; what matters is
# that the next run can take it without judging a corpse.
- workspacelock.acquire(8478)
+ _acquire_once_free(8478)
assert _payload(workspace)["pid"] == os.getpid()