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

Rework Examine into Inspect and Collage, build your own Detect analyzers, and share one camera across the map tabs (#85)

OsintMeThatd1c6493654b8
diff --git a/README.md b/README.md
index 1b501c1..03bd920 100644
--- a/README.md
+++ b/README.md
@@ -59,10 +59,11 @@ to fix a point on the map.*
| **Media** | Import local files or download by URL (X, Telegram, TikTok, YouTube, Instagram and more via yt-dlp, with a gallery-dl fallback for image-only posts). Public media is fetched cookie-less; a login-walled post prompts once for a browser session or an exported `cookies.txt`. Each item gets a clean local file, metadata and a SHA-256. Multi-photo posts open a picker. |
| **Files** | Every saved artifact in one Finder-style view of your folders, not just media: select several, drag them into a folder, search across the lot. |
| **Reverse Search** | Prepare an image or a video frame for keyless reverse-image services. With the capture extension, pressing an engine opens it with the picture already in it. Nothing leaves the machine until you press one. |
-| **Inspect** | A scratch workspace over any photo or video: frame adjustments, editable crop, sharpest-frame capture, hand-made collage with per-piece warp/scale/rotate, auto-stitch to solve a panorama's layout, and ELA hints. Nothing enters the case until you save. |
+| **Inspect** | Reads any photo or video closely: sharpest-frame capture onto a strip, frame adjustments, editable crop and ELA hints. Frames and edits are kept with the file as you make them; a frame or an adjusted video enters the Media Library only when you save it to the case. |
+| **Collage** | Lays out frames and images from any number of files on one canvas, with per-piece warp, scale, rotate and crop, and auto-stitch to solve a panorama's layout. Saved as you go; the picture it exports is case media. |
| **Satellite** | Coordinates or a place name become an imagery crop. The search bar proposes matches as you type: saved work, coordinates and a bundled city list answer offline, and the geocoder fills in the rest once you pause. Select-area capture with an optional scale bar and north arrow, map rotation, measurement tools, a right-click menu on any point, stacked overlays (borders, roads, railways, power lines, fires, night lights), your own KML, KMZ, GeoJSON, GPX or My Maps layers, GeoConfirmed conflicts narrowed to a period, and editable AOI grids for area review. Esri/OSM by default, plus the Esri Wayback archive, Sentinel-2 with a date calendar and a cloud-ceiling slider, and Sentinel-1 radar passes; add a Mapbox or Google key for more basemaps. Open it in several tabs and they stay in sync. |
| **Compare** | Links two dated map views for side-by-side, swipe, fade or blink, with Difference highlights laid over any of them. All dates lists every picture of a point and narrows down when a change appeared. Ground-anchored notes, shapes, numbered markers and measurements follow both maps. Editable sessions and rendered previews stay in the case; attributed PNG/GIF copies go to exports. |
-| **Detect** | Sweeps drawn areas of Sentinel-2 for vessels, fires, construction, burn scars and other changes, and of Sentinel-1 radar for vessels, razed buildings, new structures and floods through cloud, once or as a saved routine. Only a candidate you keep becomes a case pin. |
+| **Detect** | Sweeps drawn areas of Sentinel-2 for vessels, fires, construction, burn scars and other changes, and of Sentinel-1 radar for vessels, razed buildings, new structures and floods through cloud, once or as a saved routine. Only a candidate you keep becomes a case pin, dated by the passes that found it. |
| **Coords & Sky** | Convert common coordinate formats, copy the result, open map or geocoding links, and read the sun and moon at that point on a date: rise, set, azimuth, altitude, twilights, moon phase and bright-limb angle, in local time and UTC, computed offline. |
| **Geo Proof** | Start a named proof from a reusable house style, or from a published post whose pictures become its panels. Compose case panels in a grid or free layout, turn or crop them, annotate with colored shapes, fills, symbols, numbered markers, blur boxes, freehand and text, state every place and every source the proof argues, and export `proof.png` plus a re-editable spec. |
| **Geo Report** | Turn a proof into a prepared thread for X or Bluesky: coordinates, plus code, attribution, target-specific character counts, media, and a structured Markdown case note with linked evidence. |
diff --git a/docs/IMAGERY_PROVIDERS.md b/docs/IMAGERY_PROVIDERS.md
index bc70884..e290bcd 100644
--- a/docs/IMAGERY_PROVIDERS.md
+++ b/docs/IMAGERY_PROVIDERS.md
@@ -266,11 +266,11 @@ stay at the repo's `tile_z` either way, so only the level's *name* differs:
`Provider.zoom_offset=1` re-adds what `z_shift` took off. A wrong offset returns
`400 Invalid TILECOL`.
-**Eco mode needs its own threshold here** (`Provider.eco_max_zoom=11`). The global
+**Eco mode needs its own threshold here** (`Provider.eco_max_zoom=7`). The global
default (z15) is tuned for basemaps that run to z22; Sentinel-2's imagery stops at
-z14, so sharing it would replace the layer at most supported zooms. At z11 and
-out, one Sentinel-2 pixel covers about 40 m and free Esri imagery has comparable
-detail. The swap is limited to those low-detail views.
+z14, so sharing it would replace the layer at most supported zooms. At z7 and out
+the view spans a whole region and free Esri imagery serves it just as well. The
+swap is limited to those overview zooms.
| Limit | Value | Consequence |
|-------|-------|-------------|
@@ -309,6 +309,24 @@ Products are cached beside their picture under `<variant>~<product>~v<N>`
and `PRODUCT_VERSION` keeps a frame from an older layout from being decoded as a
newer one.
+An analyzer of your own reads raw bands instead: `bands-B04-B08`, up to three
+Level-2A bands a product, named in the collection's order and checked against
+`sentinel.L2A_BANDS` before a script is built, so no free expression reaches an
+evalscript. Its channels are 16 bits, reflectance in ten-thousandths (Sentinel-2's
+own scale), because an index computed on the server from two dark bands loses its
+meaning at a byte's 0.2% step; the fourth channel is the same sky. Pillow cannot
+hold 16 bits across four channels, so the engine decodes these with OpenCV and
+keeps a run's copy as the PNG that arrived. A recipe reads every three distinct
+bands as one more request per date and tile, which the wizard counts. The
+builder's preview reads the same products over the view from the tile cache and
+fetches the missing ones only when **Read** is pressed, one metered request each,
+over at most three tiles a side. A check does the same on the tiles under its
+marks alone (`detect_rules.check_tiles`), cache first and **Run all** for the
+rest. The shipped examples were calibrated on Planetary Computer's key-less
+Level-2A, laid out as this evalscript returns it (the 1000 offset taken off from
+processing baseline 04.00, the way Sentinel Hub harmonises), so their marks cost
+no Copernicus request until a user runs them.
+
Difference asks for the same bands over the view on screen (`sentinel.CHANGE_PRODUCTS`:
`change-<index>`, and `change-sky` for the sky alone). Those frames are decoded in
the browser, which draws them into a canvas, so alpha has to stay the data mask —
diff --git a/docs/ONTOLOGY.md b/docs/ONTOLOGY.md
index 520adbe..ed93ed6 100644
--- a/docs/ONTOLOGY.md
+++ b/docs/ONTOLOGY.md
@@ -132,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`, `compare-session`, `bookmark` |
+| `document` | it is read rather than gathered: made or consulted | `proof`, `post`, `note`, `sheet`, `inspect-session`, `collage`, `compare-session`, `bookmark` |
| `place` | a point, never a thing | `place` |
| `claim` | a statement about the graph, carrying its own reasoning | `claim` |
@@ -161,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`, `compare-session` | out of the case readings, drawn by **My work** |
+| `annex` | consulted rather than seen, hanging off one node | `note`, `sheet`, `inspect-session`, `collage`, `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
@@ -182,8 +182,9 @@ answer by omission (`tests/test_entities.py`).
| `place` | place | subject | ✅ | satellite, ingest, enrich | `coords`, `lat`, `lon`, `plus_code`, `zoom`, `bearing`, `notes?`, `geo?`, `source_url?`, `site?`, `enrich_coord_key?`, plus the precision fields below | no (a point) |
| `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 |
+| `inspect-session` | document | annex | ✅ | inspect | `spec` (json), one per file | yes |
+| `collage` | document | annex | ✅ | inspect | `spec` (json) | yes |
+| `compare-session` | document | annex | ✅ | compare | `spec` (json), `preview?`, `lat`, `lon`, `zoom`, `bearing`, `footprint?`, `geo?` | yes |
| `map-layer` | document | annex | ✅ | map layers | `spec` (json), `format`, `source_url?` | yes (spec + snapshot + icons) |
| `note` | document | annex | ✅ | notebook | `path`, `folder?` | yes (Markdown) |
| `sheet` | document | annex | ✅ | sheet | `path` (csv) | yes (CSV + sidecar) |
@@ -225,7 +226,7 @@ Three modelling calls the table alone does not show:
place cites — which is the reason it is an entity at all.
Retired: `event` (replaced by the claim node), `alias` (see above), and `panorama`
-(Inspect's auto-stitch export is a derived `media`). Still coming from the roadmap,
+(a collage's auto-stitch export is a derived `media`). Still coming from the roadmap,
to declare here when built:
| Type | Family | Shape | Note |
@@ -379,6 +380,14 @@ 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 picture of two moments carries two dates, never a range.** A saved comparison and
+a paired Detect picture record `imagery_a` and `imagery_b`, projected as `imagery-a`
+and `imagery-b`: a day, or a radar pass's UTC instant. The image shows two moments
+and argues nothing about what lies between them, so a change is a Claim the analyst
+files, citing the picture. An imagery date a provider only estimated (Esri, Wayback)
+is stored as the provider gave it with `exact: false` beside it, since a capture
+shows that date on its face, and the projection places it with a final `~`.
+
**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
@@ -506,9 +515,14 @@ 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`, `inspect-session` and
+The file-backed pointers of `proof`, `post`, `inspect-session`, `collage` 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
+one in its tool rewrites its `spec`, `draft` or `path` on the same entity. A
+comparison's images follow it: its preview and every image kept from it name it in
+`compare_session`, which a rename rewrites. Each save also restates where the
+comparison stands (`engine/comparisons.py`): its frame's centre, or its view's, with
+the frame as `footprint`, which is what lists it in Saved work beside the captures. An
+`inspect-session` still named after its file is also renamed with that file. Look
these up by id, or re-read the pointer — never cache one across a save.
## 3. Link
@@ -779,8 +793,11 @@ A tool selects one of two deletion behaviours through its link type:
| `depends-on` | inspect-session | media, capture |
A `derived-from` holder owns pixels or text and survives a deleted source with a
-tombstone. An `inspect-session` is only adjustments over its subject, so a deleted
-subject removes it transitively.
+tombstone. An `inspect-session` is the frames and edits made over one file, never
+more than one per file, so a deleted subject removes it transitively. A `collage`
+carries no chain edge: its pieces are recipes over any number of files, a lost one
+leaves a gap rather than voiding the layout, and the picture it exports is a
+`media` derived from them.
- `derived-from` never cascades into an output. A post keeps its text when its
proof is deleted; a frame keeps its pixels when its video is deleted.
@@ -867,6 +884,21 @@ Saving a proof files the points it carries as `place`s and states
the analyst typed into the composer, or what its panels froze and they left
standing (`spec_points`, §3 placement).
+Pinning a Detect candidate files its evidence picture and the place together, and
+states `media --depicts--> place`: orbital imagery shows the ground and was
+recorded nowhere on it.
+
+**A kept candidate says when it was seen, and the place never does.** A place is
+permanent ground and no verb carries a date (§3), so keeping one also files a Claim
+`at` the place that `cites` the picture (`engine/analysis_dating.py`). A change was
+read between two passes, so it `occurred` in that interval, and a thing on one pass
+was `observed` then, to the second for a radar pass. It carries no confidence:
+keeping is the review, and a grade nobody gave would read as one somebody did.
+One pin owns one statement, found by its `detection` key. Undoing the pin takes it
+to the same Trash group unless the analyst has written to it since, the proof
+composer's rule. Pins kept before this are dated once when a case opens at schema
+11, from the run and candidate their provenance kept.
+
**A proof states as many points as it argues.** Three impacts, a building, the
camera that filmed it: each is a point somebody concluded on, and they are peers,
in the order they were typed. **The first is the conclusion** — the map mark, the
diff --git a/docs/SPEC.md b/docs/SPEC.md
index 0d62282..8935278 100644
--- a/docs/SPEC.md
+++ b/docs/SPEC.md
@@ -57,7 +57,8 @@ azimut/ # everything Azimut owns; the rest of the folder is yours
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
+ .inspect/ # each file's Inspect work: its frames and their edits
+ .collages/ # collage layouts; the picture one exports is media
.compare/ # saved Compare session specs
.analysis/ # Detect areas, saved detections, runs and the frames behind their results
.search/ # saved Grid Search state
@@ -87,7 +88,7 @@ The entity/link schema has existed since v1. Full vocabulary lives in
| class | equipment-type |
| identifier | account, email, phone, domain, ip, network |
| collected | media, capture |
- | document | proof, post, note, inspect-session, bookmark |
+ | document | proof, post, note, inspect-session, collage, bookmark |
| place | place |
| claim | claim |
@@ -114,7 +115,7 @@ proof for publication.
| Tool | What it does |
|------|--------------|
-| ✅ **Media Library & Inspect** | Imports or downloads case media with metadata, provenance and hashes, then reviews images and video through saved editing sessions. |
+| ✅ **Media Library & Inspect** | Imports or downloads case media with metadata, provenance and hashes, then reviews images and video closely. |
| ✅ **Satellite** | Saves places and attributed map captures from free or optional keyed imagery, including dated Sentinel-2 passes and usage controls. |
| ✅ **Geo Proof** | Composes annotated panels, files their coordinates as places and exports an editable PNG proof. |
| ✅ **Geo Report** | Prepares sourced proof threads and saved drafts without posting automatically. |
@@ -167,7 +168,7 @@ proof for publication.
|------|--------------|
| ✅ **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, 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. |
+| ✅ **Point menu** | Right-clicking the ground copies that point in every format, looks it up, saves, measures, reads the sky or opens its imagery history from it, opens it in the other map tabs, and links it out. |
| ✅ **Map windows** | Opens the map in several tabs with the view in the URL, links map tabs and extension panels on other sites to one camera, and syncs saved points, grids and sweeps live to every tab and extension panel. |
| ✅ **Map layers** | Stacks key-less overlays (borders, roads, railways, power lines, sea marks, GPS traces), NASA FIRMS fires and VIIRS night lights for a chosen day, and filters drawn pins by kind and folder. |
| ✅ **Added map layers** | Opens a KML, KMZ, GeoJSON or GPX file, or follows a public My Maps or map URL refreshed only while enabled, and draws it with its own colours, optionally its own icons composed once at import, a legend that filters and a search that goes to one feature — read, cited and never adopted into the case. |
@@ -199,6 +200,13 @@ proof for publication.
| ✅ **All dates** | Lists every dated picture of the point in Compare and narrows down, a question at a time, between which two a change appeared. |
| ✅ **Copernicus where it is needed** | Detect and Compare say in the middle of the tool what Copernicus still lacks, with the free account, the Sentinel-2 configuration and the Sentinel-1 layer form field by field. |
| ✅ **A candidate in Compare** | Opens a Detect candidate in Compare on the passes that found it, or against high-resolution imagery for a thing present on one pass. |
+| ✅ **Sizes in Detect** | Right-clicks Detect's map for its own point menu, measures a hull with a ruler, sizes each candidate along its footprint, walks the largest first, and hides the drawing or blinks A against B from the review. |
+| ✅ **Analyzers of your own** | Builds a Detect analyzer from up to six rules on any band, index, ground class or radar polarisation, read on A, B or the change, tried live on the map over any Copernicus layer with a point reading; optional checks (marked places reread as the rules change) and five calibrated examples that ship with theirs; also opened from a built-in or a Difference reading, with a shape filter for every analyzer. |
+| ✅ **Examine: Inspect and Collage** | Keeps one work per file, saved as it is made, with its frames on a strip; lays collages out of frames and images from any file; merges a case's 0.3.0 sessions on open. |
+| ✅ **One camera for the map tabs** | Satellite, Compare and Detect show the same ground, and the link carries it to other windows; a Detect review and a saved comparison keep theirs, and Settings turns it off. |
+| ✅ **Comparisons in Saved work** | A saved comparison stands on the map with the captures, at its frame's centre with the frame outlined, dated A → B, and reopens in Compare; an export can also be kept in the case under it. |
+| ✅ **Dated pins and pictures** | A kept Detect candidate files a claim at its pin (a change between two passes, or a thing seen on one); comparisons and pinned evidence carry each picture's date, estimates marked; Detect layers filter a change by its span; exports are named by their pictures' dates. |
+| ✅ **One turn on every map** | A middle-drag turns any map or Inspect frame like a wheel about the grabbed point, settling on north, in 15° steps with Ctrl; a middle click or Shift+↑ puts north back, Shift+← / → steps. |
---
@@ -230,7 +238,7 @@ Each version delivers one complete daily workflow. Firm ideas move here from
| **OCR** | Reads signs and plates on import (tesseract, a native binary rather than a wheel), and detects script and language. |
| **Audio Transcript** | Transcribe and translate speech offline; flag acoustic context such as bells, adhan, aircraft or language. |
| **Ground Imagery** | Ground-level photos: Panoramax/Mapillary/KartaView key-less first; Street View easy link, optional keyed in-app view. |
-| **Panorama** | Stitch a video window / frame set. Auto-stitch already in Inspect; still to do: sample a video window directly, seam blending. |
+| **Panorama** | Stitch a video window / frame set. Auto-stitch already in Collage; still to do: sample a video window directly, seam blending. |
| **Proof annotation** | Grow the Geo Proof toolbox: dashed strokes; a document-level free layer so shapes cross panels and reach the margins; callout / zoom insets. |
| **Detached tool windows** | The rule the map already follows, applied to the rest: a read-and-work surface (Board, Graph, Timeline) opens as many tabs as wanted and the tab it left stays live; a document editor opens one window per document and is greyed out where it was. Cross-tool handoffs route to wherever the tool now lives. |
| **Command palette** | Ctrl+K reaches a tool, a case or an artifact. |
@@ -315,12 +323,13 @@ stops making sense.
- **Media in the analyst's half:** a button that looks for media beside `azimut/` and offers to bring them into the case, rather than waiting for them to be moved into `media/` by hand.
- **Count a statement's independence by origin, not by wrapper:** three collages made from one video are three sources today, and are arguably one. The graph already answers this for a place; changing it for a statement changes a published number.
-- **Free-form montage editor:** consider only if it stays distinct from Geo Proof and Inspect collage.
+- **Free-form montage editor:** consider only if it stays distinct from Geo Proof and the Collage tool.
- **In-app OSINT assistant:** local chat and vision suggestions for analyst confirmation, with no cloud or API key by default.
- **Geographic playback:** step through dated case items on the map instead of showing one fixed Timeline window.
- **More on the home page:** the case's own notes beside the tiles, and panels the analyst arranges rather than a fixed grid. Each has to earn its place there rather than beside Board, Graph and Timeline, which already read the case.
- **Radar damage from a stack of passes:** the pixel-wise t-test (PWTT) over a year of passes before and weeks after, which two passes cannot match.
- **Oil slicks by radar:** dark patches on the sea near anchorages and lanes, which Sentinel-1 shows through cloud.
+- **Map files out of the case:** export pins, claims and Detect findings as KML or GeoJSON, with TimeStamp and TimeSpan so another viewer's time slider reads them.
- **A deleted case waits before it is gone:** artifacts, entities and bulk deletes are all recoverable, while removing a case is the one act with no way back and only a typed DELETE in front of it. Move the folder aside instead, and empty it later.
## 8. Explicit non-goals
diff --git a/docs/STORAGE_AND_PERFORMANCE.md b/docs/STORAGE_AND_PERFORMANCE.md
index a70f296..dfb0b00 100644
--- a/docs/STORAGE_AND_PERFORMANCE.md
+++ b/docs/STORAGE_AND_PERFORMANCE.md
@@ -284,13 +284,17 @@ 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.
-The case manifest is at `CASE_SCHEMA` 9. Schema 3 is the last released folder
+The case manifest is at `CASE_SCHEMA` 11. Schema 3 is the last released folder
shape before the `azimut/` boundary; schemas 4–8 were development checkpoints
and never became public formats. `FolderMigration` therefore declares a target
schema instead of assuming `+1`: every schema-3 case and any development case at
4–8 runs the same idempotent normalizer and is stamped 9 only after the whole
layout and visible-name contract are valid. A stopped migration keeps its older
-stamp and resumes the same normalizer on the next open. Media moves additionally
+stamp and resumes the same normalizer on the next open. Schema 9 is what 0.3.0
+wrote; one step takes it to 11, giving each file one Inspect work, then dating
+every kept Detect pin (`analysis_dating.backfill`) and standing every saved
+comparison on the map (`comparisons.backfill`). Schema 10 was a development
+checkpoint and runs only those last two. Media moves additionally
use `.data/rename.json`, so a restart can finish references after the bytes moved.
### Tables
diff --git a/docs/UI.md b/docs/UI.md
index 6ba6b80..78f95d4 100644
--- a/docs/UI.md
+++ b/docs/UI.md
@@ -22,7 +22,7 @@ in `frontend/src/lib/workspaces.js` and appear as tabs, never as new rail entrie
| **Home** (the mark) | Overview, Guide | |
| **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 |
+| **Examine** | Inspect, Collage | Edit Provenance, Shot contact sheet, OCR, Image Compare, Hints, Sky Clock, audio |
| **Map** | Satellite, Compare, Detect, Coords & Sky | Imagery Wayback, Event layers, Ground Imagery, Measures, Viewshed, OSM Query, Map Board |
| **Compose** | Geo Proof, Geo Report, Notebook | Report Builder, GIF maker |
@@ -330,7 +330,7 @@ single root to expand from. Expansion is the drill-down.
so a relation or a type added to the engine joins its lens with no edit.
Narrowing the verbs never hides a subject: an entity with no edge *in this lens* is
an answer. What a lens takes out of the drawing is a whole **role** — a post, a note
- and an Inspect session are the filing rather than the case, and My work is the one
+ and a file's Inspect work are the filing rather than the case, and My work is the one
click back to them. A node's degree follows the reading, so it never prices a click
that could bring nothing in, and a name typed into the search can be brought into
every reading except one that does not draw its type: that one says so instead.
@@ -1204,9 +1204,15 @@ file, Delete. The menu is placed against the window rather than inside the row,
because a card clips what overflows it and the last row of a scrolled list would
cut the menu off.
+**Reverse Search starts from Inspect's file list.** Every image and video in the
+case, filterable and searchable, with no worked-on row since the tab keeps nothing.
+The engines' own pages sit beside it, for a file that is not in the case. Once a
+picture is picked, **Change file** and the cross in the header work as in Inspect,
+and a case change drops the picture with its handoff.
+
**Reverse Search opens on the picture it was sent.** From a Media Library row it
-is the case file; from Inspect's Frame tab it is the frame as it reads there —
-turned, adjusted and cropped — rendered by the tray's own route and filed nowhere,
+is the case file; from a frame in Inspect it is the frame as it reads there —
+turned, adjusted and cropped — rendered by the strip's own route and filed nowhere,
and the tool says so under the preview. The crop is the point: an engine matches a
subject better than the picture it sits in. The handoff is spent once, on the tab
it was meant for, and a case change drops it with every other handoff.
@@ -1217,10 +1223,59 @@ the file; the backend returns the portable stem after replacing forbidden
characters or resolving a case-insensitive collision. Downloads keep dates and
remote ids in provenance instead of appending them to the visible name.
+## Examine
+
+Two tabs: **Inspect** reads one file closely, **Collage** lays out pieces from any
+number of files. Neither has a session to start, name or save.
+
+**The work stays with the file.** Opening a video or an image opens what was done to
+it: the frames cut from it, their turns, adjustments and crops, the clip's own
+adjustments. It is saved as it is made, a second or so after the last change, and
+the header says *Saving…*, *Saved* or *Not saved* with a retry. Opening a file only
+to look at it files nothing; the first real change does. A file has one work, named
+after the file, which the sidebar lists and reopens on that file. The name in the
+header renames the file itself, and the work follows unless it was given a name of
+its own. **Clear work** sends it to the Trash, so the reset can be undone.
+
+**The empty state is the file list.** Every image and video, the files already worked
+on first with their frame count, filterable by kind and searchable, with the folder
+browser behind `…`. **Change file** in the header opens the same list over the
+file; the cross closes it and goes back. Neither asks anything, since nothing is
+unsaved.
+
+**A strip instead of tabs.** Under the viewer, a video leads the strip and the frames
+cut from it follow, labelled by timecode. Clicking a tile is what the viewer and the
+panel show: the player with stepping, capture, orientation, clip adjustments and the
+sharpest-frame scan, or one frame with orientation, adjustments, crop, **Analyze**
+and reverse search. An image is its own single frame and needs no strip until
+**Duplicate** makes a second copy to crop differently. Removing a frame offers Undo.
+
+**Save to case is the one step that files media.** Each output carries its own block
+under the controls that shape it: a name that holds real text from the start, a
+folder, an optional note. A frame, the adjusted video or an exported collage then
+reads *In the case*, linked to the Media Library, until an edit makes it a
+different picture. **Save N frames** in the strip files every frame not in the case
+yet, under its default name.
+
+**A collage is a document.** New starts an empty canvas, filed once the first piece
+lands; the name in the header renames it and refuses a name another collage holds.
+Pieces come from **Frames**, the works of any file grouped by file, or **Images**,
+any case image. A piece is a recipe frozen when it is placed, so editing the frame
+later does not change the collage. A piece still rendering holds its place with a
+spinner. A renamed file is followed; a piece whose file was deleted keeps its place
+as a hatched gap, and the export waits until it is removed. The export is a
+transparent PNG of the pieces trimmed to their bounds.
+
+**0.3.0 sessions come over on open.** The sessions of one file merge into its work:
+frames are joined, the latest session carries on, typed names and notes are kept in
+its notes, relations move to it, and each collage becomes a collage document named
+after the session that built it. The sessions are copied as they were to
+`.inspect/.v1/` first. A session brought back from the Trash merges the same way.
+
## Map
-**Compare assembles two imagery views on one camera.** It opens on the home view
-with a key-less pair: an Esri Wayback release published a year or more back on A,
+**Compare assembles two imagery views on one camera.** It opens where the other map
+tabs left the window, or on the home view, with a key-less pair: an Esri Wayback release published a year or more back on A,
today's World Imagery on B. That costs the release list and tiles, never a
Copernicus request or a point's history, and A stays empty when no release list
comes back rather than showing B twice. Panning that untouched pair leaves
@@ -1294,7 +1349,10 @@ the last reading stays up, marked in the strip as an earlier read, until **Read*
export. A reading recomputes by itself after every move, on the
frames it holds; what it never does on a pan is spend a request.
These viewport captures depend on display resolution and zoom. Use the Detect
-tab for a fixed analysis grid across camera changes.
+tab for a fixed analysis grid across camera changes. An index reading carries
+**Save as a Detect analyzer** in the Detection tab: the same index, line, way it
+moved, cleanup and cloud switches become an analyzer of your own rules, and the
+toast opens it in Detect's builder, ready to sweep areas or run as a routine.
The strip's **A / B / Both** says which images carry the highlights, in any view;
Both is the default, because it shows what a change went *from* and *to* at the
same time. **Blink** flashes the highlights on and off, because a thin highlight
@@ -1353,17 +1411,24 @@ Maker's: the way out of a drawing tool is the button you are already on.
**Right-click the ground** here too, on either map, for the acts Compare can
honour: copy the point in every coordinate format, ask what is there, save a
-place there, or start a distance measure from it — the annotation of the same
-name, anchored on the point and closed by the next click. The rows Satellite
-offers for its own rails are left out rather than shown dead.
+place there, start a distance measure from it — the annotation of the same
+name, anchored on the point and closed by the next click — or open it in
+Satellite or Detect. The rows Satellite offers for its own rails are left out
+rather than shown dead.
**Save comparison** writes the editable version-2 session under `.compare/` and
-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.
+updates its rendered media preview in My work (PNG, or GIF for blink). The preview
+records the date of each picture, one Esri or Wayback only estimated marked `~` on
+its Time tab, where **Date a change** offers a claim that something changed between
+them. A preview used by a derived proof is preserved when a later save creates new pixels.
**Open** restores the sources, layers, camera, view, the Difference switch, blink speed,
detection settings, annotations and the optional export frame; a session saved while
Difference was a view of its own reopens side by side with Difference on. Export writes an attributed PNG, blink GIF or divider-sweep GIF to the
-shared Views destination; an optional ground-anchored frame cuts any of the three to the
+shared Views destination, named by the comparison and its two pictures' dates, and
+never over an earlier file. **Also keep it in this case** files the same image in My
+work under the comparison, stamped with the reading on screen and never replaced by a
+later save; asked on a comparison never saved, it asks for a name first. An optional
+ground-anchored frame cuts any of the three to the
chosen area, while Full view remains the default. The frame keeps the bearing it was
drawn at: turning the camera turns it with the ground rather than reshaping it, and
the export comes out upright as it was drawn, once all four corners are in view. Copy current PNG uses the clipboard.
@@ -1392,11 +1457,21 @@ over the imagery is reachable from nowhere else. Each section states its own
count, so the strip carries none — folded shut, the panel shows the active half's
name and its number.
-Saved work — places, captures and screenshots filed by the extension — lives in
-the **Saved** half, grouped by geography rather than by date. The
-tree's depth follows the case: one country opens straight on its regions, a
+Saved work — places, captures, screenshots filed by the extension and saved
+comparisons — lives in the **Saved** half, 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 a `Media / Places / Captures`
-switch stay pinned above it; a screenshot counts as a capture. The panel opens on
+switch stay pinned above it; a screenshot counts as a capture, and so does a saved
+comparison, which is imagery of a point at two dates.
+
+**A comparison is one row, whatever was made from it.** It stands at its export
+frame's centre, or its view's when no frame was drawn, and the frame is outlined in
+dashes on the map, since it is the ground the images show rather than a guess about
+a place. The row reads its two pictures' dates, `2024-05-03~ → 2026-09-02`, and
+how many images were kept from it; its card lists them, and **Open in Compare**
+reopens it, from Satellite or from Compare's own maps. Deleting it moves the
+session to the Trash and leaves its images in Media. Its country is looked up on
+save, again only once it has moved about a kilometre. The panel opens on
**Media**, which is what a map is read for: where the case's footage stands. That
position is a **mode** — it reads its own index (`GET /satellite/media`, the first
time it is opened, never on case open) — while Places and Captures filter the one
@@ -1594,8 +1669,10 @@ The row states five things:
itself rather than a grouping guessed out of whichever property looked like one.
- **Its dates, when it has any.** A layer that is on and whose features are
dated (GeoConfirmed's events, a KML's TimeStamp or TimeSpan, a GPX waypoint's
- time) draws its events over time as a strip of bars under the counts: a bar a
- day for up to three months, a week for up to two years, a month past that.
+ time, a Detect snapshot's passes) draws its events over time as a strip of bars
+ under the counts: a bar a day for up to three months, a week for up to two years,
+ a month past that. A feature spanning days, a TimeSpan or a Detect change, counts
+ in every bar it meets and is in any period that meets it.
The period is set on the strip itself. Drag across the bars to draw one, drag
either handle to move a bound, slide the band between them, or click a bar to
keep its day, week or month. Clicking one of the two dates under the strip
@@ -1691,6 +1768,8 @@ and time, and hands over no computed value.
**Coords & Sky opens on the point the map is on.** The map publishes the point it
records — its moved pin, else its centre — once it has been moved off the view it
opened at, and the tab converts that point rather than opening on an empty field.
+Compare and Detect publish their centre each time they come to rest, so the tab
+reads whichever map was looked at last.
A view nobody has moved yet is a setting rather than a finding, so it offers
nothing. The conversion is local and that is all that happens: naming the place is
a geocoder call, so the row offers **Name this place** instead of making it.
@@ -1783,7 +1862,8 @@ and captures credited under it.
centre: copy it in every coordinate format, the analyst's own first; ask what
is there, answered inside the menu; save a place there; start a distance from
it; anchor the sun and moon on it; open its Wayback history; centre the map
-on it; compare it across time; or open it in another map site. A right-click on a shape that answers
+on it; compare it across time; or open it in Compare, in Detect or in another
+map site. A right-click on a shape that answers
its own (a search-grid cell) stays that shape's. The menu flips away from the
map's edges, walks with the arrow keys, and closes on Escape, a press outside,
or a zoom that moves the ground from under it.
@@ -1799,6 +1879,33 @@ few seconds: the walk through Esri's releases is slow, and a message that went o
halfway through left the map looking like nothing was happening. Compare receives it the way it receives a saved comparison — older on
A, newer on B — unsaved and unnamed, because nothing has been filed.
+**Open in…** lists the app's other map tabs first, then the maps outside it. A
+tab opens on the point at the zoom it was looked at: Satellite flies there, and
+Compare and Detect move their camera and keep their own pictures and work. In
+Detect a point asked for this way wins over the case's landing frame. A
+fullscreen map is left first.
+
+**The map tabs share one camera.** Satellite, Compare and Detect look at the same
+ground: a map leaves the window's camera where it comes to rest, even when its glide
+ends after you switched tab, and a map tab that shows takes it in one move, turn
+included. A hidden map never moves, so it loads no tiles and asks Copernicus nothing
+for ground nobody is looking at.
+A map whose imagery stops short of the shared zoom lands at its own ceiling and
+leaves the deeper zoom standing for the tab that has it. Two things keep their
+ground: a Detect run under review, and a saved comparison, whose camera is part of
+what was saved.
+Switching case leaves the camera where it is, since a view is not case state.
+Settings → General → Map tabs turns it off, and each tab keeps its own camera again.
+
+**Every map turns the same way.** A middle-drag, or Shift and the left button,
+turns it like a wheel about the point grabbed: a dashed circle marks that point,
+and the map follows the angle the pointer sweeps around it outside the circle.
+Inside, the map holds, so the pointer can cross the middle without a flip. Near
+north it settles on north, and Ctrl held lays the turn on 15° steps. A middle click puts north back up, as does Shift+↑;
+Shift+← and Shift+→ turn a step. The Move the point dialog in Geo Proof turns
+the same way, and Inspect's frame viewer takes the same drag, with a middle
+click standing the frame upright.
+
**Compare here…** and **Open in…** are the two rows that open a list, and they
open it *beside* the menu. A list unfolding inside would make the menu taller, and a menu already
placed against the frame's edge answers that by moving — which slides the next
@@ -1852,7 +1959,10 @@ Google, Bing, Earth and the other sites they draw on: an open panel counts as a
second map, follows this tab's camera and leads it (`extension/README.md`). A
panel in a background tab keeps the view until that tab is looked at, because
following one costs those sites a reload; the app's own tabs have none to pay
-and follow wherever they are.
+and follow wherever they are. While the map tabs share one camera, the link carries
+that camera rather than Satellite's own: a pan in Compare or Detect reaches the
+other windows and the extension, and a view arriving moves whichever map tab is on
+screen.
**The map keeps up with the other windows on the case.** A point saved, a grid
drawn or a cell swept from the extension's panel over another map lands here
@@ -1879,13 +1989,32 @@ hand for the radar analyzers, field by field — and one press opens the Coperni
card in Settings. The panel still opens on what the case already holds.
Detect opens on Esri World Imagery, with Borders and saved results visible, framed
-on the areas this case watches — once, after which the camera is yours. A case
-with no area opens on the home view. The search, the compass and SAT's
+on the areas this case watches — once, after which the camera is yours. That
+framing waits for the tab to show. Arriving from another map tab while they share
+one view, Detect opens where that map was instead, since that is the ground in hand.
+A case with no area opens where the other map tabs left the window, or on the home
+view. A run under review keeps the map on it when you come back from another map
+tab. The search, the compass, the ruler and SAT's
imagery/layer controls float over the map. There is no Detect header or
full-width bottom strip. Attribution stays in the map's corner and the scale stays
at bottom left; provider usage is a small chip beside the imagery selector. A pass
date appears only while reading that pass, and run status stays in the panel.
-Leaving a pass restores the chosen basemap.
+Leaving a pass restores the chosen basemap. Sentinel-2 and Sentinel-1 sit in the
+imagery selector too, with their layer and day, so any Copernicus layer can be read
+over the ground; neither is remembered as the basemap, and Detect opens on free
+imagery.
+
+Right-clicking the map, or a candidate, area or measure drawn on it, opens
+Satellite's point menu, cut to what Detect can do:
+copy the point, **What is here?**, **Measure from here**, **Centre the map here**,
+**Compare here…** and **Open in…**, which lists Satellite and Compare first. While a finished run is under review, a point
+inside one of its areas also offers **Add candidate here**, for a hull the
+detector missed. The ruler under the compass, or `M`, measures a length: drag
+from one end to the other, then drag either end to adjust it. The label reads in
+the units set in Settings. `Delete` drops the selected measure and the bin beside
+the ruler clears them all. Measures are a scratch aid and are not saved. Taking
+the ruler up lets go of an area or a candidate being drawn, and drawing one puts
+the ruler down.
The right dock has Routines, Saved and Areas tabs, with New detection always at
the top. The tabs name their own list, so nothing is titled twice, and a second
@@ -1922,7 +2051,8 @@ else, because the answer changes every question after it:
its trash hides or shows it, the one on a group's heading does the whole group,
and showing frames the ground it covers. The layers button beside them snapshots
what was kept or pinned into a SAT layer, a routine's heading into its one layer;
- a run with nothing kept says so and stays greyed. A group folds shut from its heading.
+ a run with nothing kept says so and stays greyed. A change spans its two passes
+ in that layer, so its date filter finds it in any period between them. A group folds shut from its heading.
- a **routine** is a place you come back to. It keeps its areas, its analyzer and
what each pass compares against; it is run again whenever there is a new pass,
and it remembers what it found.
@@ -2029,9 +2159,13 @@ has to stand out of the sea around it in both polarisations, which a strong
target's ghosts and sea spikes do not, and a weak return beside a much stronger one
is taken for its sidelobe. What counts as sea is Sentinel-2's own water class on
the clearest pass of the year before, because dry desert is as radar-dark as calm
-water; the radar decides only where that pass saw cloud. A radar change is the
-power of both polarisations averaged over the size's window and compared between
-two passes of one track; *bright* ground is ground that answered like walls on the
+water; the radar decides only where that pass saw cloud. In a large port a
+terminal that Sentinel-2 took for water still gives candidates among the ships at
+berth, which no mask tried could remove without dropping the ships too. A radar
+change is the power of both polarisations averaged over ground, 45 m a step of the
+size's averaging (90 m at Medium), and compared between two passes of one track: a
+window counted in pixels held too few radar samples, and ground that did not change
+came back as thousands of pieces or one region kilometres wide. *Bright* ground is ground that answered like walls on the
side that had them, and *water* is ground that went as dark as calm water. Two
passes only flag where to look: the razed-buildings analyzer says so, and the
flood one starts at Large, since a flood is fields wide. Without the radar layer
@@ -2050,13 +2184,100 @@ shadows the classification missed. The fire detector offers no switch: its band
ratios reject cloud already. Thresholds open from a link rather than sitting in
the way, and tuning them there changes this detection only.
-**Analyzers** lists the built-ins and your own, shared by every case. An analyzer
-is one calibrated method and how picky it is, so one of your own starts as a copy
-of the closest built-in: **New analyzer** asks what to start from, and the copy
-keeps that method while its name, sizes, thresholds, candidate label and colour
-become yours. A built-in opens read-only with **Copy to tune**; your own can be
-edited or removed from the list. A detection being built keeps its place while the
-library is open, and an analyzer saved from there comes back picked.
+**Analyzers** lists the built-ins and your own, shared by every case; one of your
+own with checks says under its name how they last came out (**3 checks · all
+pass**, **1 fails**, **not run**). **New analyzer** offers three roads, in this
+order. **Start from an example** lists five ready analyzers of your own, each with
+its checks: a fresh burn (Lahaina, August 2023), a forest cleared (Grünheide,
+2019 → 2020), water drained (the Kakhovka reservoir, June 2023), a solar farm built
+(Dubai, 2019 → 2023) and ships at anchor (Fujairah, one pass). A press copies it
+into the library at once, checks and all, under a free name, and opens it on its
+checks with the first one on the map. **Build your own rules** starts blank: an
+analyzer made of up to six rules, each a line a pixel has to cross. The last road
+starts from a built-in: the copy keeps its calibrated method while its name, sizes,
+thresholds, candidate label and colour become yours. Burn scars, vegetation loss
+and new water also carry **rules**, which opens them in the builder as the rules
+they apply. A built-in opens read-only with **Copy to tune** (and **Open as rules**
+where it has them); your own can be edited or removed from the list. A detection
+being built keeps its place while the library is open, and an analyzer saved from
+there comes back picked.
+
+The builder keeps the name and the sentence it reads as at the top, the map bench
+under them, and three tabs: **Rules**, **Checks** and **Settings** (sizes, shape,
+cleanup, smoothing, grouping, description, candidate label and colour). A rule
+names a quantity, then when it is read, then the line. The quantity is one of the
+six indices, **My index** (a normalised difference of any two Level-2A bands, with
+NDMI, NDSI, NDRE, NBR2 and GNDVI one pick away), one band's reflectance,
+brightness, a colour change, Sentinel-2's own ground class, or radar backscatter in
+VV, VH or VV − VH. It is read on **A**, on **B** or as the change **A → B** (B minus
+A, so a loss is negative), against **at least**, **at most**, **between** or, for a
+change, **either way**. Reflectance shows in percent and radar in decibels; a change
+in reflectance or radar takes the passes' overall shift in light out, as the
+built-ins do. **Against its surroundings** reads the quantity against the ground
+within a set distance, up to 300 m, the ring with a hole in the middle the vessel
+detectors use, so one line holds over a dark sea and a bright desert. **Keep what
+passes all** keeps a pixel that passes every rule and **any** one that passes a
+single one. The first measured rule, marked ★, ranks candidates: two of its units
+past its line is Strong (0.2 of an index, 4% reflectance, 4 dB). Rules that only
+read B need no reference, like a vessel. Radar and optical rules do not mix, and
+one analyzer reads at most six bands, each three a request per date and tile. The
+sentence at the top says the whole analyzer, and becomes its description unless
+one is written.
+
+The map is the builder's bench. **On the map** takes two passes typed or picked
+from **Find passes**. The **Imagery** switch lays A, B or the basemap under the
+preview, in any layer the Copernicus configuration offers, and the builder
+suggests the one that reads rule ★ best: NDVI for vegetation, short-wave infrared
+for burns and heat, false colour for water and hulls. The preview follows the map.
+Nothing reaches Copernicus unasked: it reads frames the app already holds, judges
+every tile it has, and when the view lacks some it says how many and waits for
+**Show the detections here** (**Read the rest of the view** once part of it is
+shown), one metered request each. Past three tiles a side it previews the middle
+of the view. From then on every change redraws within a moment, on those frames
+and without a request: each rule paints the pixels it keeps in its own colour (its
+dot hides or shows them, and pointing at a row shows that rule alone), the
+candidates a run would return are outlined with their pins, and each row says what
+share of the measured ground it keeps, alone and with the rules above it. The
+preview runs the engine's own evaluation, cleanup, sizes, shape and grouping, so
+what it outlines is what a sweep of the same ground returns. A click on the map
+reads every rule at that point: the value, before and after for a change, and a
+tick or a cross, so a thing that was not kept says which rule let it go. Under
+cloud or off the passes the card says so instead.
+
+**Checks** are the analyzer's own proof, and optional: nothing asks for one and
+saving never waits on them. A check keeps a place, a pair of passes and the layer B
+shows in, and pins marked **Should be found** or **Should stay empty**. **Add a
+check** opens one where the map is: until it has a pin it moves with the map (the
+map's search box reaches the other side of the world), the passes picked from then
+on are its passes (**Find passes** from the check opens the list), and while one of
+its two pins is armed every click on the map drops it, the crosshair and a chip on
+the map saying which, until the pin is pressed again or the chip closed. **Done**
+closes it; the analyzer is not saved while a check lacks its passes. The point card
+of a click opens anywhere, read or not, and carries both pins too: a point on the
+ground of the open check goes into it, one anywhere else makes the view a new check.
+A view moved off the ground its passes were picked for drops them. A check with no
+pins counts the candidates of its whole view, which its row says costs more frames
+than pins, each read on its own tile. The open check's view is framed on the map
+with its name, and its pins drawn: a filled ring where a candidate should come out,
+a struck ring where none should, green or red once read. While the builder has
+passes, a bar on the map switches the imagery under the preview between **A**,
+**B** and **Blink**, and back to the basemap. Checks reread themselves
+from the tile cache a moment after every change to the rules, with no request, so
+the tab's badge (**2/3**) and each row follow the lines as they move: **2 of 2
+found**, **stayed empty**, **1 of 1 flagged**. A check whose frames are not held
+says how many it lacks; **Run all** reads them, up to the count on its face, one
+request each, and a check reads only the tiles under its marks. A result read with
+other rules than the current ones says **Not rerun since the rules changed**. Each
+example's empty marks are traps for one of its rules: the reef off Lahaina and a
+cloud the mask missed, the mown meadows at Grünheide, the river and the cooling pond
+at Kakhovka (flagged as soon as the change reads **either way**), the panels already
+there in Dubai and the dunes the wind moved, the town of Fujairah. Removing the
+rule that guards one turns it red, which is the lesson. Checks are saved with the
+analyzer, so Settings backup carries them.
+
+**Shape** is offered to every analyzer: **compact** keeps roofs, craters and
+vehicles, **long and thin** roads, tracks and trenches, measured along each
+candidate's own length.
**Start** names it, says what it is for, and runs it: **Run this pass** for a one
pass, **Save and run the first pass** for a routine, which can also be saved
@@ -2084,10 +2305,15 @@ What a sweep produces is a list of candidates, strongest first, and nothing else
reaches the case on its own. Each says how strong it is in a word (weak, clear or
strong: how far past its threshold it got) and what was measured in units a reader
can check, such as "6.2× brighter than the water around it" or "NBR 0.61 → −0.28".
+It also says how big it is: its area, then its length and width measured along its
+footprint, so a ship lying on the diagonal reads as long as it is. At 10 m a pixel
+that is a size class, not a survey, and a wake or a radar smear lengthens it.
+**Largest first** walks the queue by length instead, from its top; pressing it
+again returns to the run's order.
A candidate that crosses a tile edge is one candidate with one picture, stitched
from the tiles it touches. New candidates use the detector mask's simplified
outline; merged components retain their parts as a MultiPolygon. The bounding
-box still drives crops, sizing and merge tests. Existing results keep their
+box still drives crops and merge tests. Existing results keep their
stored rectangle geometry.
Opening a run puts the map on the candidate the panel is about, close enough to
@@ -2104,16 +2330,28 @@ candidate in its run without creating a place or image. **Dismiss** removes it
from the run. **Pin** opens the standard dialog for a name, optional description,
after-only image and Point/Area geometry. Single-image methods default to after-only
and Point; change methods default to paired images and Area. Pinning creates a
-place and a PNG in Files. The picture says on its face when and where: each image
+place and a PNG in Files, and links them: the picture shows the place. The picture says on its face when and where: each image
carries its letter and its date (a radar pass its UTC time), and the foot holds the
point's coordinates and the imagery's attribution, so the file still reads after
-the run is gone. Undo sends those copies to Trash. Evidence is enlarged
+the run is gone. The same dates reach the case's time. The PNG carries them on its
+Time tab, and a claim at the place, citing the picture, says what the sweep read: a
+change `occurred` between the two passes, a thing on one pass was `observed` on it.
+The place itself carries no date, and the claim no confidence. Undo sends those
+copies to Trash, the claim with them unless something was added to it. Evidence is enlarged
by a whole-number factor with no interpolation, so a candidate a dozen pixels
across can be read without pretending to detail the sensor never recorded. The
-candidate under review wears a ring on the map. **Add candidate** records a point or polygon on a successfully read area,
+candidate under review wears a ring on the map. **Add candidate**, or the map's right-click, records a point or polygon on a successfully read area,
with `origin: manual`, the same pass pair, preview and verdicts. Manual candidates
have dashed map outlines and a Manual label.
+Beside **Export as layer**, the eye (`H`) takes the candidates and areas off the
+map, so the pass shows bare; leaving the review puts them back. When the run
+read two passes, the blink (`B`) flips A against B on the map at Compare's
+normal speed, and a chip over the map says which is showing, in Compare's
+letters. Both passes are laid in the one map and kept loaded, so the blink
+reloads nothing; it is offered only for two dates of one archive, never for a
+detector that read one pass. Leaving the pass stops it.
+
**Export as layer** is an explicit snapshot of kept and pinned candidates only.
A routine updates one SAT layer, with a category per effective pass date; a one-off
run has its own layer. Re-exporting a date replaces its category. Older dates are
diff --git a/extension/maptheme.js b/extension/maptheme.js
index ea20e3b..9bf08c6 100644
--- a/extension/maptheme.js
+++ b/extension/maptheme.js
@@ -85,6 +85,7 @@
minus: "M5 12h14",
crosshair: "M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18Zm0-1v4m0 12v4M2 12h4m12 0h4",
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",
screen: "M4 5h16a1 1 0 0 1 1 1v9a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V6a1 1 0 0 1 1-1Zm5 15h6m-3-4v4",
alert: "M12 3 2.5 19.5h19L12 3Zm0 7v4m0 3.5h.01",
@@ -104,9 +105,12 @@
);
}
- /** Which glyph a saved row is drawn with — `SavedOverlay.svelte`'s own map.
- * A stack holding more than one kind falls back to the place glyph. */
- const SAVED_GLYPH = { place: "pin", capture: "satellite", screenshot: "screen" };
+ /** Which glyph a saved row is drawn with — `SavedOverlay.svelte`'s own map. */
+ const SAVED_GLYPH = { place: "pin", capture: "satellite", screenshot: "screen", comparison: "compare" };
+
+ /** The kinds a stack may mix and still draw as a capture — `geoTree.js`'s
+ * `CAPTURE_KINDS`. Any other mix draws as a place (`markKind` in the app). */
+ const SAVED_CAPTURE_KINDS = ["capture", "screenshot", "comparison"];
window.AzimutMapTheme = {
TOKENS,
@@ -118,6 +122,7 @@
MEASURE_DOT,
ICONS,
SAVED_GLYPH,
+ SAVED_CAPTURE_KINDS,
icon,
};
})();
diff --git a/extension/maptools.js b/extension/maptools.js
index f481bbf..1d18aeb 100644
--- a/extension/maptools.js
+++ b/extension/maptools.js
@@ -387,7 +387,14 @@
},
shapes() {
const out = marks.map((mark) => {
- const only = mark.kinds.length === 1 ? mark.kinds[0] : "place";
+ // one kind draws as itself, a stack of imagery as a capture, and any
+ // mix holding a place as the place (`markKind` in the app)
+ const only =
+ mark.kinds.length === 1
+ ? mark.kinds[0]
+ : mark.kinds.every((kind) => THEME.SAVED_CAPTURE_KINDS.includes(kind))
+ ? "capture"
+ : "place";
const shown = mark.key === hovered || mark.key === held;
// a stack of files draws as footage only when all of it is footage,
// the way the app's own layer glyphs one (`SavedOverlay.svelte`)
diff --git a/frontend/e2e/app.fixture.js b/frontend/e2e/app.fixture.js
index f30e179..a16e4fb 100644
--- a/frontend/e2e/app.fixture.js
+++ b/frontend/e2e/app.fixture.js
@@ -1781,6 +1781,11 @@ export async function installAppFixture(page, options = {}) {
});
}
if (path === `/api/cases/${CASE_ID}/media`) return json(route, fixtureMedia);
+ // Inspect and Collage open on their pickers: no file worked on and no
+ // collage saved unless a spec brings some.
+ if (path === '/api/inspect/ops') return json(route, { filters: [], analyses: [] });
+ if (path === `/api/cases/${CASE_ID}/inspect/works`) return json(route, options.inspectWorks ?? []);
+ if (path === `/api/cases/${CASE_ID}/collages`) return json(route, options.collages ?? []);
// One media file with everything its sidecar holds. The browse index leaves
// enrichment's metadata dumps out, so the Details panel reads a file at a time.
if (path === `/api/cases/${CASE_ID}/media/item`) {
diff --git a/frontend/e2e/detect.spec.js b/frontend/e2e/detect.spec.js
index c967634..e08788a 100644
--- a/frontend/e2e/detect.spec.js
+++ b/frontend/e2e/detect.spec.js
@@ -17,10 +17,10 @@ async function openDetect(page, withRun = false) {
const candidate = { id: 'candidate-1', origin: 'detector', area_id: area.id, area_name: area.name,
phenomenon: 'Surface change', coordinates: [2.2945, 48.8584], geometry: area.geometry,
bbox: [2.29, 48.855, 2.3, 48.862], review: 'new', strength: 'clear', measure: {},
- sources: { a, b }, area: 300, width: 20, height: 15 };
+ sources: { a, b }, area: 300 };
const run = { id: 'bbbbbbbbbbbb', title: 'North site pass', status: 'ready', progress: 1, total: 1,
count: 3, created_at: '2026-09-10T12:00:00Z', results: [candidate,
- { ...candidate, id: 'candidate-2', phenomenon: 'A longer candidate name wrapping across several lines in the review panel', width: 12345 },
+ { ...candidate, id: 'candidate-2', phenomenon: 'A longer candidate name wrapping across several lines in the review panel' },
{ ...candidate, id: 'candidate-3', phenomenon: 'Third candidate' }],
input: { title: 'North site pass', recipe, zones: [zone], a, b },
area_runs: [{ area_id: area.id, name: area.name, a, b, status: 'ready' }] };
@@ -142,3 +142,143 @@ test('review adds a manual point and uses the standard pin dialog', async ({ pag
await expect(page.getByRole('button', { name: 'Imagery provider', exact: true })).toContainText('Esri World Imagery');
expect(errors).toEqual([]);
});
+
+test('an analyzer of your own is built over the map: its rules painted, a point read and marked in a check, then kept', async ({ page }) => {
+ const { errors } = await openDetect(page);
+ const R = 6378137;
+ const mercator = (lon, lat) => [R * (lon * Math.PI) / 180, R * Math.log(Math.tan(Math.PI / 4 + (lat * Math.PI) / 360))];
+ // What the engine sends: one byte a pixel. 64 is measured ground, 195 a
+ // kept pixel both rules passed (bits 0, 1, 6 and 7).
+ const mask = await page.evaluate(() => {
+ const canvas = document.createElement('canvas');
+ canvas.width = 512; canvas.height = 512;
+ const context = canvas.getContext('2d');
+ context.fillStyle = 'rgb(64,64,64)'; context.fillRect(0, 0, 512, 512);
+ context.fillStyle = 'rgb(195,195,195)'; context.fillRect(200, 200, 112, 112);
+ return canvas.toDataURL('image/png').split(',')[1];
+ });
+ const saved = [], previews = [], checked = [];
+ await page.route('**/api/compare/analyzers', async (route) => {
+ if (route.request().method() === 'POST') {
+ const body = route.request().postDataJSON();
+ saved.push(body);
+ return route.fulfill({ json: { ...body, id: 'custom-aaaaaaaaaaaa' } });
+ }
+ return route.fulfill({ json: {
+ builtins: [recipe], custom: [], grid: [13, 512], max_tiles: 4096, max_results: 2000,
+ methods: [{ id: 'surface', single: false, sizes: {} }, { id: 'rules', single: false, clouds: true, sensor: 'sentinel2', frames: 4,
+ sizes: { medium: { min_area: 0, max_area: 0, cleanup: 0, smoothing: 0, merge_metres: 0 } }, rules: true, measure: '' }],
+ rules: { bands: ['B02', 'B03', 'B04', 'B08', 'B11', 'B12'], classes: ['vegetation', 'bare', 'water'],
+ max_rules: 6, max_bands: 6, max_around: 300, max_checks: 12, max_marks: 20, preview_span: 3 }, examples: [] } });
+ });
+ await page.route('**/api/satellite/sentinel/acquisitions', (route) => route.fulfill({ json: {
+ dates: [{ date: '2026-09-10', cloud: 4, coverage: 1 }, { date: '2026-09-01', cloud: 2, coverage: 1 }], truncated: false } }));
+ await page.route('**/api/compare/analyzers/preview', (route) => {
+ const body = route.request().postDataJSON();
+ previews.push(body);
+ const { west, south, east, north } = body.bounds;
+ const [x0, y0] = mercator(west, south);
+ const [x1, y1] = mercator(east, north);
+ const cx = (x0 + x1) / 2, cy = (y0 + y1) / 2, half = Math.min(x1 - x0, y1 - y0) / 2;
+ const base = { tiles: [[1, 1]], clipped: false, size: [512, 512],
+ box: { west: cx - half, east: cx + half, south: cy - half, north: cy + half } };
+ if (!body.read && previews.filter((entry) => entry.read).length === 0) return route.fulfill({ json: { ...base, ready: false, missing: 2 } });
+ const middle = [(west + east) / 2, (south + north) / 2];
+ return route.fulfill({ json: { ...base, ready: true, missing: 0, mask, measured: 1,
+ rules: body.recipe.rules.map(() => ({ share: 0.048, kept: 0.048 })), kept: 0.048, count: 1, note: '',
+ candidates: [{ id: '0-1', coordinates: middle, bbox: [middle[0] - 0.001, middle[1] - 0.001, middle[0] + 0.001, middle[1] + 0.001],
+ area: 12000, margin: 3.4, strength: 'strong', measure: { before: 0.8, after: 0.2, signed: -0.6 } }] } });
+ });
+ await page.route('**/api/satellite/sentinel/layers', (route) => route.fulfill({ json: { source: 'catalogue', layers: [
+ { id: 'TRUE_COLOR', label: 'True colour' }, { id: 'FALSE_COLOR', label: 'False colour (infrared)' },
+ { id: 'SWIR', label: 'SWIR (short-wave infrared)' }, { id: 'NDVI', label: 'NDVI (vegetation index)' }] } }));
+ await page.route('**/api/compare/analyzers/probe', (route) => route.fulfill({ json: {
+ ready: true, imaged: true, measured: true, kept: true,
+ rules: [{ passes: true, value: -0.6, before: 0.8, after: 0.2 }, { passes: true, value: 0.8, before: null, after: null }] } }));
+ await page.route('**/api/compare/analyzers/check', (route) => {
+ const body = route.request().postDataJSON();
+ checked.push(body);
+ return route.fulfill({ json: { ready: true, missing: 0, count: 1, covered: body.check.marks.map(() => true) } });
+ });
+
+ await page.getByRole('button', { name: 'Analyzers', exact: true }).click();
+ await page.getByRole('button', { name: 'New analyzer', exact: true }).click();
+ await page.getByRole('button', { name: /^Build your own rules/ }).click();
+ await expect(page.getByRole('heading', { name: 'Build an analyzer' })).toBeVisible();
+ await page.getByRole('button', { name: 'Add a rule', exact: true }).click();
+ await page.getByRole('button', { name: 'Find passes', exact: true }).click();
+ await page.getByLabel('Use 2026-09-01').getByRole('button', { name: 'A', exact: true }).click();
+ await page.getByLabel('Use 2026-09-10').getByRole('button', { name: 'B', exact: true }).click();
+ const read = page.getByRole('button', { name: 'Show the detections here', exact: true });
+ await expect(read).toBeVisible();
+ await read.click();
+ await expect(page.getByText('1 candidate on the map')).toBeVisible();
+ // B is on the map in the layer that reads rule ★, and any other is one pick away
+ await expect(page.getByLabel('Copernicus layer')).toHaveValue('TRUE_COLOR');
+ await page.getByRole('button', { name: /^Show it in NDVI/ }).click();
+ await expect(page.getByLabel('Copernicus layer')).toHaveValue('NDVI');
+ await expect(page.getByRole('button', { name: 'Imagery provider', exact: true })).toContainText('Copernicus Sentinel-2');
+
+ // the rules are on the ground, each in its colour: the later one on top
+ const layers = page.locator('canvas.rule-layers');
+ await expect(layers).toBeVisible();
+ // A canvas keeps its colours premultiplied, so a channel can read one off.
+ const tint = (expected) => async () => {
+ const read = await layers.evaluate((canvas) => [...canvas.getContext('2d').getImageData(256, 256, 1, 1).data]);
+ return read.every((value, i) => Math.abs(value - expected[i]) <= 2);
+ };
+ await expect.poll(tint([56, 189, 248, 110])).toBe(true);
+ await page.getByRole('button', { name: 'Hide rule 2 on the map', exact: true }).click();
+ await expect.poll(tint([250, 204, 21, 110])).toBe(true);
+ expect(await layers.evaluate((canvas) => canvas.getContext('2d').getImageData(10, 10, 1, 1).data[3])).toBe(0);
+
+ const map = page.locator('.detect-tool .map');
+ const box = await map.boundingBox();
+ await map.click({ position: { x: box.width / 2 - 40, y: box.height / 2 + 40 } });
+ const reading = page.getByRole('dialog', { name: 'Rules at this point' });
+ await expect(reading).toContainText('Kept');
+ await expect(reading).toContainText('0.80 → 0.20 (−0.60)');
+ await page.screenshot({ path: test.info().outputPath('detect-builder.png') });
+
+ // the point becomes a check of this view, marked on the ground, read from the cache
+ await expect(reading).toContainText('Mark it in a new check of this view');
+ await reading.getByRole('button', { name: 'Should be found', exact: true }).click();
+ await expect(reading).toHaveCount(0);
+ await expect(page.locator('.mark.pin-found')).toHaveCount(1);
+ await expect(page.getByRole('tab', { name: /^Checks/ })).toHaveAttribute('aria-selected', 'true');
+ await expect(page.getByText('1 of 1 found')).toBeVisible();
+ await expect(page.locator('.mark.pin-found.pass')).toHaveCount(1);
+ expect(checked.every((body) => body.read === false)).toBe(true);
+ await expect(page.locator('svg.ground polygon')).toHaveCount(1); // the check's view, framed
+
+ // an armed pin drops where the map is clicked, and the map says which one is armed
+ await page.getByRole('button', { name: 'Should stay empty', exact: true }).click();
+ await expect(page.getByText('Click where none should be')).toBeVisible();
+ await map.click({ position: { x: box.width / 2 + 120, y: box.height / 2 - 80 } });
+ await expect(page.locator('.mark.pin-empty')).toHaveCount(1);
+ await page.getByRole('button', { name: 'Stop dropping pins', exact: true }).click();
+ await expect(page.getByText('Click where none should be')).toHaveCount(0);
+ await page.screenshot({ path: test.info().outputPath('detect-builder-checks.png') });
+
+ // A, B or the two blinking, from the map itself
+ const bar = page.getByRole('group', { name: 'Passes under the preview' });
+ await bar.getByRole('button', { name: 'Blink', exact: true }).click();
+ await expect(bar.getByRole('button', { name: 'Blink', exact: true })).toHaveAttribute('aria-pressed', 'true');
+ await bar.getByRole('button', { name: 'B', exact: true }).click();
+ await expect(bar.getByRole('button', { name: 'Blink', exact: true })).toHaveAttribute('aria-pressed', 'false');
+ // the new pin is read with the rest: the stand-in engine puts a candidate on both
+ await expect(page.getByText('1 of 1 found · 1 of 1 flagged')).toBeVisible();
+
+ await page.getByLabel('Analyzer name').fill('Cleared ground');
+ await page.getByRole('button', { name: 'Add to my analyzers', exact: true }).click();
+ await expect.poll(() => saved.length).toBe(1);
+ expect(saved[0]).toMatchObject({ method: 'rules', name: 'Cleared ground', match: 'all' });
+ expect(saved[0].rules).toHaveLength(2);
+ expect(saved[0].checks).toEqual([expect.objectContaining({ name: 'Check 1',
+ marks: [expect.objectContaining({ expect: 'found' }), expect.objectContaining({ expect: 'empty' })],
+ result: expect.objectContaining({ covered: [true, true] }) })]);
+ await expect(layers).toHaveCount(0);
+ await expect(page.locator('.mark')).toHaveCount(0);
+ expect(previews.every((entry) => entry.recipe.method === 'rules')).toBe(true);
+ expect(errors).toEqual([]);
+});
diff --git a/frontend/e2e/examine-pickers.spec.js b/frontend/e2e/examine-pickers.spec.js
new file mode 100644
index 0000000..cdb1c40
--- /dev/null
+++ b/frontend/e2e/examine-pickers.spec.js
@@ -0,0 +1,59 @@
+import { test, expect } from '@playwright/test';
+import { installAppFixture } from './app.fixture.js';
+
+// Wide enough that the centred column leaves margins on both sides.
+test.use({ viewport: { width: 1900, height: 700 } });
+
+const manyImages = Array.from({ length: 60 }, (_, i) => ({
+ path: `media/shot-${i}.png`,
+ filename: `shot-${i}.png`,
+ kind: 'image',
+ width: 640,
+ height: 360,
+ size: 256,
+ source: { type: 'upload' },
+ thumbnail: null,
+ folder: '',
+}));
+
+const manyCollages = Array.from({ length: 40 }, (_, i) => ({
+ name: `collage-${i}`,
+ title: `Collage ${i}`,
+ pieces: 2,
+ updated_at: '2026-09-20T10:00:00Z',
+}));
+
+/** Wheel over the empty margin left of the column: the heading has to move up. */
+async function wheelInMargin(page, heading) {
+ await expect(heading).toBeVisible();
+ const tool = await page.locator('.tool').filter({ has: heading }).boundingBox();
+ const before = await heading.boundingBox();
+ expect(before.x - tool.x).toBeGreaterThan(80);
+ await page.mouse.move(tool.x + (before.x - tool.x) / 2, tool.y + tool.height / 2);
+ await page.mouse.wheel(0, 600);
+ await expect.poll(async () => (await heading.boundingBox()).y).toBeLessThan(before.y);
+}
+
+test('scrolls the Inspect picker from the margins beside it', async ({ page }) => {
+ const fixture = await installAppFixture(page, { media: manyImages });
+
+ await page.goto('/#inspect');
+ await wheelInMargin(page, page.getByRole('heading', { name: 'Open a file' }));
+ fixture.expectNoUnexpectedRequests();
+});
+
+test('scrolls the Reverse Search picker, the same list, from the margins beside it', async ({ page }) => {
+ const fixture = await installAppFixture(page, { media: manyImages });
+
+ await page.goto('/#reverse');
+ await wheelInMargin(page, page.getByRole('heading', { name: 'Pick a picture' }));
+ fixture.expectNoUnexpectedRequests();
+});
+
+test('scrolls the collage list from the margins beside it', async ({ page }) => {
+ const fixture = await installAppFixture(page, { collages: manyCollages });
+
+ await page.goto('/#collage');
+ await wheelInMargin(page, page.getByRole('heading', { name: 'Collages' }));
+ fixture.expectNoUnexpectedRequests();
+});
diff --git a/frontend/e2e/map-tabs.spec.js b/frontend/e2e/map-tabs.spec.js
new file mode 100644
index 0000000..185b839
--- /dev/null
+++ b/frontend/e2e/map-tabs.spec.js
@@ -0,0 +1,91 @@
+import { test, expect } from '@playwright/test';
+import { awaitMapReady, installAppFixture } from './app.fixture.js';
+
+/**
+ * One camera for the map tabs, on the real engine (`lib/map/sharedView.js`).
+ *
+ * The unit tests drive fakes; what only a browser can say is whether a real
+ * map, hidden while another tab shows, comes back on the ground the window
+ * moved to, and whether a jump the engine makes on showing settles once.
+ *
+ * The fixture's home view is 48.8584, 2.2945 at z16, and Satellite opens
+ * somewhere else from its address, so a map that opened on its own home view
+ * would show z16.
+ */
+
+const readout = (page) => page.locator('.hud-coords');
+
+/** The app on Satellite, away from home, with what Compare's opening pair reads. */
+async function openSatellite(page) {
+ await installAppFixture(page);
+ await page.route('**/api/satellite/providers', (route) => route.fulfill({ json: [
+ { id: 'esri-world-imagery', label: 'Esri World Imagery', url: 'https://tiles.invalid/{z}/{x}/{y}.png', imagery: true, max_zoom: 19, tile_size: 256, oversample: 1, attribution: 'Browser fixture' },
+ { id: 'esri-wayback', label: 'Esri Wayback', url: 'https://tiles.invalid/{z}/{x}/{y}.png', imagery: true, max_zoom: 19, tile_size: 256, oversample: 1, attribution: 'Browser fixture' },
+ ] }));
+ await page.route('**/api/satellite/wayback/releases', (route) => route.fulfill({ json: { releases: [{ release: 2, date: '2099-01-01' }, { release: 1, date: '2020-01-01' }] } }));
+ await page.goto('/#satellite?ll=50.4501,30.5234&z=13');
+ await awaitMapReady(page);
+}
+
+async function openTab(page, name) {
+ await page.locator('.tabstrip').getByRole('button', { name, exact: true }).click();
+}
+
+/** Every map built so far is up. Hidden ones stay built, so they count too. */
+async function mapsReady(page, count) {
+ await expect(page.locator('.map[data-map-ready="true"]')).toHaveCount(count);
+}
+
+test('Compare opens where Satellite was, and Satellite follows a pan made in Compare', async ({ page }) => {
+ await openSatellite(page);
+
+ await openTab(page, 'Compare');
+ await mapsReady(page, 3);
+ await expect(page.locator('.camera-readout')).toHaveText('z13.0');
+
+ // a drag across A, as Compare's own specs pan: some 3 km east to west at z13
+ const box = await page.locator('.compare-stage').boundingBox();
+ await page.mouse.move(box.x + 420, box.y + 140);
+ await page.mouse.down();
+ await page.mouse.move(box.x + 100, box.y + 120, { steps: 10 });
+ await page.mouse.up();
+
+ await openTab(page, 'Satellite');
+ await expect(readout(page)).not.toContainText('30.523');
+ await expect(readout(page)).toContainText('z13');
+});
+
+test('Detect opens where Satellite was on its first visit, rather than on the watched ground', async ({ page }) => {
+ await openSatellite(page);
+ // the case watches ground in Paris; Satellite is in Kyiv
+ const northSite = { id: 'aaaaaaaaaaaa', name: 'North site', colour: '#38bdf8',
+ geometry: { type: 'Polygon', coordinates: [[[2.29, 48.855], [2.3, 48.855], [2.3, 48.862], [2.29, 48.862], [2.29, 48.855]]] } };
+ await page.route('**/api/cases/*/analysis/**', (route) => route.fulfill({
+ json: new URL(route.request().url()).pathname.endsWith('/analysis/areas') ? [northSite] : [],
+ }));
+
+ await openTab(page, 'Detect');
+ await mapsReady(page, 2);
+ // the areas are in, so the case's landing has had its chance
+ await expect(page.locator('.detect-areas polygon').first()).toBeAttached();
+
+ // a Detect that had framed Paris would have taken Satellite there too
+ await openTab(page, 'Satellite');
+ await expect(readout(page)).toContainText('50.450100, 30.523400');
+});
+
+test('with the switch off in Settings, each map tab keeps its own camera', async ({ page }) => {
+ await openSatellite(page);
+
+ // the title carries a badge's words when something is out of date
+ await page.getByTitle(/^Settings/).click();
+ const share = page.getByRole('checkbox', { name: 'Share one view across the map tabs' });
+ await expect(share).toBeChecked();
+ await share.uncheck();
+ await expect(share).not.toBeChecked();
+
+ await page.getByTitle('Map', { exact: true }).click();
+ await openTab(page, 'Compare');
+ await mapsReady(page, 3);
+ await expect(page.locator('.camera-readout')).toHaveText('z16.0');
+});
diff --git a/frontend/e2e/satellite-canvas.spec.js b/frontend/e2e/satellite-canvas.spec.js
index b2d70ba..0cb278b 100644
--- a/frontend/e2e/satellite-canvas.spec.js
+++ b/frontend/e2e/satellite-canvas.spec.js
@@ -46,7 +46,12 @@ test('rotates the real map with a middle-button gesture', async ({ page }) => {
const y = box.y + box.height / 2;
await page.mouse.move(x, y);
await page.mouse.down({ button: 'middle' });
- await page.mouse.move(x + 100, y + 55, { steps: 8 });
+ // the turn is a wheel about the grabbed point: out of the guide circle, then
+ // a quarter of the way round
+ for (let deg = 0; deg <= 90; deg += 5) {
+ const a = (deg * Math.PI) / 180;
+ await page.mouse.move(x + 120 * Math.cos(a), y + 120 * Math.sin(a));
+ }
await page.mouse.up({ button: 'middle' });
await expect(page.locator('.deg')).not.toHaveText('0°');
diff --git a/frontend/e2e/satellite-map.spec.js b/frontend/e2e/satellite-map.spec.js
index 6bb96d1..a636b67 100644
--- a/frontend/e2e/satellite-map.spec.js
+++ b/frontend/e2e/satellite-map.spec.js
@@ -103,3 +103,39 @@ test('north is up again when the rose is pressed', async ({ page }) => {
await page.getByRole('button', { name: 'Reset to north' }).click();
await expect(page.getByRole('button', { name: /^0°$/ })).toBeVisible();
});
+
+test('a middle drag turns like a wheel about the grabbed point, and a middle click puts north back', async ({ page }) => {
+ await openMap(page);
+ const box = await page.locator('.map').boundingBox();
+ const x = box.x + box.width / 2;
+ const y = box.y + box.height / 2;
+ await page.mouse.move(x, y);
+ await page.mouse.down({ button: 'middle' });
+ await expect(page.locator('.turn-guide')).toBeVisible();
+ // out of the guide circle due east, then three quarters of the wheel
+ // clockwise, in small steps, the way a hand goes round
+ for (let deg = 0; deg <= 270; deg += 5) {
+ const a = (deg * Math.PI) / 180;
+ await page.mouse.move(x + 120 * Math.cos(a), y + 120 * Math.sin(a));
+ }
+ await page.mouse.up({ button: 'middle' });
+ await expect(page.locator('.turn-guide')).toHaveCount(0);
+ // past half a turn and still the same way: 270°, not back towards north
+ await expect(page.getByRole('button', { name: /^270°$/ })).toBeVisible();
+
+ await page.mouse.click(x, y, { button: 'middle' });
+ await expect(page.getByRole('button', { name: /^0°$/ })).toBeVisible();
+});
+
+test('Shift and an arrow turn a step at a time, and Shift and up is north', async ({ page }) => {
+ await openMap(page);
+ // with the map focused, the engine would add a turn of its own if it could
+ await page.locator('.map canvas').first().click();
+ await page.keyboard.press('Shift+ArrowRight');
+ await page.keyboard.press('Shift+ArrowRight');
+ await expect(page.getByRole('button', { name: /^30°$/ })).toBeVisible();
+ await page.keyboard.press('Shift+ArrowLeft');
+ await expect(page.getByRole('button', { name: /^15°$/ })).toBeVisible();
+ await page.keyboard.press('Shift+ArrowUp');
+ await expect(page.getByRole('button', { name: /^0°$/ })).toBeVisible();
+});
diff --git a/frontend/src/App.svelte b/frontend/src/App.svelte
index d5e02f6..a226c86 100644
--- a/frontend/src/App.svelte
+++ b/frontend/src/App.svelte
@@ -55,6 +55,7 @@
{ id: 'files', label: TOOL_LABELS.files, load: () => import('./tools/Files.svelte') },
{ id: 'reverse', label: TOOL_LABELS.reverse, load: () => import('./tools/ReverseSearch.svelte') },
{ id: 'inspect', label: TOOL_LABELS.inspect, load: () => import('./tools/Inspector.svelte') },
+ { id: 'collage', label: TOOL_LABELS.collage, load: () => import('./tools/Collage.svelte') },
{ id: 'satellite', label: TOOL_LABELS.satellite, load: () => import('./tools/Satellite.svelte') },
{ id: 'compare', label: TOOL_LABELS.compare, load: () => import('./tools/Compare.svelte') },
{ id: 'detect', label: TOOL_LABELS.detect, load: () => import('./tools/Detect.svelte') },
diff --git a/frontend/src/components/EntityTime.svelte b/frontend/src/components/EntityTime.svelte
index 004799a..82ab3ba 100644
--- a/frontend/src/components/EntityTime.svelte
+++ b/frontend/src/components/EntityTime.svelte
@@ -1,7 +1,7 @@
<script>
/** Entity-scoped temporal history. Mounted only while the Time tab is open. */
import { api } from '../lib/api.js';
- import { formatTemporalValue } from '../lib/timeline.js';
+ import { changeInterval, formatTemporalValue, temporalKindLabel } from '../lib/timeline.js';
import { reloadCase, toast, uiState } from '../lib/state.svelte.js';
import Icon from './Icon.svelte';
import TemporalClaimEditor from './TemporalClaimEditor.svelte';
@@ -11,7 +11,7 @@
let items = $state([]);
let cursor = $state(null);
let loading = $state(true);
- let editor = $state(null); // null, 'new', or a statement item
+ let editor = $state(null); // null, 'new', 'change', or a statement item
let seq = 0;
const dated = $derived(items.filter((item) => item.earliest));
@@ -41,6 +41,18 @@
? ownStatement?.raw ? 'Edit claim date' : 'Set claim date'
: entity.type === 'media' ? 'Claim a capture date' : 'Add dated claim'
);
+ /** A picture of two moments, a comparison or a Detect pair, dates a change
+ * seen between them. It says nothing of the kind by itself, so the claim is
+ * offered rather than filed. */
+ const changeSpan = $derived.by(() => {
+ if (entity.type !== 'media') return '';
+ const side = (kind) => media.find((item) => item.owner_id === entity.id && item.kind === kind)?.raw ?? '';
+ return changeInterval(side('imagery-a'), side('imagery-b'));
+ });
+ const editorTitle = $derived(
+ editor === 'change' ? 'Date a change'
+ : entity.type === 'claim' || editor === 'new' ? assessmentLabel : 'Edit claim'
+ );
async function load({ more = false } = {}) {
if (!caseId) return;
@@ -93,13 +105,6 @@
onclose?.();
}
- function kindLabel(item) {
- return {
- captured: 'Captured', published: 'Published', imagery: 'Imagery',
- collected: 'Collected', added: 'Added to case', filed: 'Filed in case', claim: 'Claim',
- }[item.kind] ?? item.kind;
- }
-
function timeLabel(item) {
return formatTemporalValue(item.raw ?? '').label;
}
@@ -111,7 +116,7 @@
<span class={`time-mark ${item.category}`}></span>
<span class="time-copy">
<strong>{item.label}</strong>
- <small>{kindLabel(item)}{#if item.time_role} · {item.time_role}{/if}{#if item.confidence} · {item.confidence}{/if}</small>
+ <small>{temporalKindLabel(item.kind)}{#if item.time_role} · {item.time_role}{/if}{#if item.confidence} · {item.confidence}{/if}</small>
</span>
<span class="time-value" class:undated={!item.raw} title={item.raw || undefined}>{timeLabel(item)}</span>
</button>
@@ -124,6 +129,9 @@
<div class="entity-time">
<div class="time-actions">
<button class="btn btn-primary btn-sm" onclick={newAssessment}><Icon name="plus" size={12} />{assessmentLabel}</button>
+ {#if changeSpan}
+ <button class="btn btn-ghost btn-sm" title="Claim that something changed between the two pictures" onclick={() => (editor = 'change')}><Icon name="plus" size={12} />Date a change</button>
+ {/if}
<button class="btn btn-ghost btn-sm" onclick={() => openTimeline()}><Icon name="clock" size={12} />Open in Timeline</button>
</div>
{#if entity.type === 'claim'}
@@ -131,12 +139,9 @@
{/if}
{#if editor}
- <section
- class="time-editor"
- aria-label={entity.type === 'claim' ? assessmentLabel : editor === 'new' ? assessmentLabel : 'Edit claim'}
- >
+ <section class="time-editor" aria-label={editorTitle}>
<header>
- <h3>{entity.type === 'claim' ? assessmentLabel : editor === 'new' ? assessmentLabel : 'Edit claim'}</h3>
+ <h3>{editorTitle}</h3>
<button class="btn btn-ghost btn-sm" aria-label="Close editor" title="Close editor" onclick={() => (editor = null)}>
<Icon name="x" size={13} />
</button>
@@ -147,10 +152,13 @@
{#key editor}
<TemporalClaimEditor
{caseId}
- item={editor === 'new' ? null : editor}
+ item={editor === 'new' || editor === 'change' ? null : editor}
subject={editor === 'new' ? entity : null}
- initialStatement={entity.type === 'media' ? 'This media was captured' : ''}
- initialRole={entity.type === 'media' ? 'observed' : ''}
+ initialWhen={editor === 'change' ? changeSpan : ''}
+ initialStatement={editor === 'change' ? 'Changed between the two pictures'
+ : entity.type === 'media' ? 'This media was captured' : ''}
+ initialRole={editor === 'change' ? 'occurred' : entity.type === 'media' ? 'observed' : ''}
+ initialCites={editor === 'change' ? [entity] : []}
onsaved={saved}
oncancel={() => (editor = null)}
/>
diff --git a/frontend/src/components/EntityTime.test.js b/frontend/src/components/EntityTime.test.js
index da9eacd..3c29841 100644
--- a/frontend/src/components/EntityTime.test.js
+++ b/frontend/src/components/EntityTime.test.js
@@ -20,8 +20,20 @@ describe('entity Time tab', () => {
it('prefills a media capture assessment without changing file metadata', () => {
expect(source).toContain("entity.type === 'media' ? 'Claim a capture date'");
- expect(source).toContain("initialStatement={entity.type === 'media' ? 'This media was captured' : ''}");
- expect(source).toContain("initialRole={entity.type === 'media' ? 'observed' : ''}");
+ expect(source).toContain(": entity.type === 'media' ? 'This media was captured' : ''}");
+ expect(source).toContain(": entity.type === 'media' ? 'observed' : ''}");
+ });
+
+ it('offers a change between two dated pictures as a claim citing them, never filed alone', () => {
+ // a comparison or a Detect pair: its two dates, as the Time panel carries them
+ expect(source).toContain("changeInterval(side('imagery-a'), side('imagery-b'))");
+ expect(source).toContain('{#if changeSpan}');
+ expect(source).toContain("onclick={() => (editor = 'change')}");
+ expect(source).toContain("initialWhen={editor === 'change' ? changeSpan : ''}");
+ expect(source).toContain("initialRole={editor === 'change' ? 'occurred'");
+ expect(source).toContain("initialCites={editor === 'change' ? [entity] : []}");
+ // cited, not the subject: the claim is about what changed, not about the picture
+ expect(source).toContain("subject={editor === 'new' ? entity : null}");
});
it('hands the visible entity scope to the global Timeline', () => {
diff --git a/frontend/src/components/SourcePicker.render.test.js b/frontend/src/components/SourcePicker.render.test.js
new file mode 100644
index 0000000..9ad49ff
--- /dev/null
+++ b/frontend/src/components/SourcePicker.render.test.js
@@ -0,0 +1,76 @@
+// @vitest-environment happy-dom
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { flushSync, mount, unmount } from 'svelte';
+
+const { default: SourcePicker } = await import('./SourcePicker.svelte');
+
+const MEDIA = [
+ { path: 'media/roof.png', kind: 'image', title: 'Roof', source: { type: 'upload' } },
+ { path: 'media/clip.mp4', kind: 'video', title: 'Convoy clip', source: { type: 'download' } },
+ { path: 'media/cap.png', kind: 'image', title: 'Harbour capture', source: { type: 'satellite' } },
+ { path: 'media/fr.png', kind: 'image', title: '00-00-12 Convoy clip', source: { op: 'frame' } },
+];
+const WORKS = [{ name: 'Convoy clip', title: 'Convoy clip', source: 'media/clip.mp4', frames: 3, kind: 'video' }];
+
+let live = null;
+let target = null;
+
+function show(props = {}) {
+ target = document.createElement('div');
+ document.body.append(target);
+ const all = { media: MEDIA, works: WORKS, caseId: 'case-a', onpick: vi.fn(), ...props };
+ live = mount(SourcePicker, { target, props: all });
+ flushSync();
+ return all;
+}
+
+const titles = () => [...target.querySelectorAll('.card .title')].map((el) => el.textContent);
+const button = (text) => [...target.querySelectorAll('button')].find((b) => b.textContent.trim() === text);
+
+afterEach(() => {
+ if (live) unmount(live);
+ live = null;
+ target?.remove();
+});
+
+describe('the file picker', () => {
+ it('leads with the files already worked on, and says how far', () => {
+ show();
+
+ expect(target.querySelector('h4').textContent).toBe('Worked on');
+ expect(titles()[0]).toBe('Convoy clip');
+ expect(target.querySelector('.count').textContent).toBe('3 frames');
+ // and each file shows once, not again under everything else
+ expect(titles().filter((t) => t === 'Convoy clip')).toHaveLength(1);
+ });
+
+ it('opens a file on a click', () => {
+ const props = show();
+ target.querySelector('.card').click();
+ expect(props.onpick).toHaveBeenCalledWith(MEDIA[1]);
+ });
+
+ it('sorts captures and frames out of plain media', () => {
+ show();
+
+ button('Captures').click();
+ flushSync();
+ expect(titles()).toEqual(['Harbour capture']);
+
+ button('Frames').click();
+ flushSync();
+ expect(titles()).toEqual(['00-00-12 Convoy clip']);
+ });
+
+ it('drops the worked-on row while a filter narrows the list', () => {
+ show();
+ button('Images').click();
+ flushSync();
+ expect(target.querySelector('h4')).toBeNull();
+ });
+
+ it('says when a case holds nothing to open', () => {
+ show({ media: [], works: [] });
+ expect(target.textContent).toContain('Add an image or a video to the case first.');
+ });
+});
diff --git a/frontend/src/components/SourcePicker.svelte b/frontend/src/components/SourcePicker.svelte
new file mode 100644
index 0000000..7f3ca55
--- /dev/null
+++ b/frontend/src/components/SourcePicker.svelte
@@ -0,0 +1,250 @@
+<script>
+ import { fileUrl } from '../lib/fileUrl.js';
+ import { matchesTerms } from '../lib/folderBrowse.js';
+ import { categoryOf } from '../lib/inspectWork.svelte.js';
+ import Icon from './Icon.svelte';
+ import SearchInput from './SearchInput.svelte';
+ import FolderBrowser from './FolderBrowser.svelte';
+
+ // Every image and video in the case, ready to open. The files already worked on
+ // lead, most recent first, because going back to one is the common move; the
+ // rest follow in library order. The same list is the empty state and the
+ // "change file" dialog of both Inspect and Reverse Search, so none of them drift.
+ let { media, works = [], caseId, current = null, onpick } = $props();
+
+ const FILTERS = [
+ { id: 'all', label: 'All' },
+ { id: 'image', label: 'Images' },
+ { id: 'video', label: 'Video' },
+ { id: 'capture', label: 'Captures' },
+ { id: 'frame', label: 'Frames' },
+ { id: 'collage', label: 'Collages' },
+ ];
+
+ let query = $state('');
+ let filter = $state('all');
+ let browsing = $state(false);
+ let browsePath = $state('');
+ let browseSelection = $state(null);
+
+ const framesBy = $derived(new Map(works.map((w) => [w.source, w.frames])));
+ const filtered = $derived(filter === 'all' ? media : media.filter((m) => categoryOf(m) === filter));
+ const matches = (m) => matchesTerms(m.title || m.filename || '', query);
+ const shown = $derived(query.trim() ? filtered.filter(matches) : filtered);
+ const byPath = $derived(new Map(media.map((m) => [m.path, m])));
+ const recent = $derived(
+ query.trim() || filter !== 'all'
+ ? []
+ : works.map((w) => byPath.get(w.source)).filter(Boolean).slice(0, 8)
+ );
+ const recentPaths = $derived(new Set(recent.map((m) => m.path)));
+ const rest = $derived(shown.filter((m) => !recentPaths.has(m.path)));
+ const browserEntries = $derived(filtered.map((m) => ({ ...m, id: m.path, attrs: { folder: m.folder ?? '' } })));
+
+ function frameCount(m) {
+ const n = framesBy.get(m.path);
+ if (n == null) return '';
+ return n === 1 ? '1 frame' : `${n} frames`;
+ }
+
+ function setFilter(id) {
+ filter = id;
+ browsePath = '';
+ browseSelection = null;
+ }
+
+ function confirmBrowse() {
+ const item = browserEntries.find((m) => m.path === browseSelection);
+ if (item) onpick(item);
+ }
+</script>
+
+<div class="picker">
+ {#if media.length === 0}
+ <p class="hint">Add an image or a video to the case first.</p>
+ {:else}
+ <div class="bar">
+ <SearchInput bind:value={query} placeholder="Search names…" width="100%" />
+ <button class="btn btn-ghost btn-sm browse" class:active={browsing} title="Browse folders" onclick={() => (browsing = !browsing)}>…</button>
+ </div>
+ <div class="filters" aria-label="Media type">
+ {#each FILTERS as f (f.id)}
+ <button class="btn btn-ghost btn-sm" class:active={filter === f.id} aria-pressed={filter === f.id} onclick={() => setFilter(f.id)}>
+ {f.label}
+ </button>
+ {/each}
+ </div>
+
+ {#if browsing}
+ <FolderBrowser
+ entries={browserEntries}
+ path={browsePath}
+ rootLabel="Case media"
+ selectedId={browseSelection}
+ {matches}
+ emptyText="This folder has no matching media."
+ icon={(m) => (m.kind === 'video' ? 'video' : 'image')}
+ label={(m) => m.title || m.filename}
+ onnavigate={(path) => { browsePath = path; browseSelection = null; }}
+ onselect={(m) => (browseSelection = m.path)}
+ onconfirm={(m) => onpick(m)}
+ />
+ <div class="actions">
+ <button class="btn btn-primary btn-sm" disabled={!browseSelection} onclick={confirmBrowse}>Open selected</button>
+ </div>
+ {:else}
+ {#snippet card(m)}
+ <button class="card" class:current={m.path === current} onclick={() => onpick(m)} title={m.title || m.filename}>
+ <span class="thumb">
+ {#if m.thumbnail}
+ <img src={fileUrl(caseId, m.thumbnail)} alt="" loading="lazy" />
+ {:else}
+ <Icon name={m.kind === 'video' ? 'video' : 'image'} size={22} />
+ {/if}
+ {#if m.kind === 'video'}<span class="kind"><Icon name="video" size={11} /></span>{/if}
+ {#if frameCount(m)}<span class="count">{frameCount(m)}</span>{/if}
+ </span>
+ <span class="title">{m.title || m.filename}</span>
+ <span class="meta">{categoryOf(m)}{m.folder ? ` · ${m.folder}` : ''}</span>
+ </button>
+ {/snippet}
+
+ {#if recent.length}
+ <h4>Worked on</h4>
+ <div class="grid">{#each recent as m (m.path)}{@render card(m)}{/each}</div>
+ {#if rest.length}<h4>Everything else</h4>{/if}
+ {/if}
+ {#if rest.length}
+ <div class="grid">{#each rest as m (m.path)}{@render card(m)}{/each}</div>
+ {:else if !recent.length}
+ <p class="hint">No media matches this filter.</p>
+ {/if}
+ {/if}
+ {/if}
+</div>
+
+<style>
+ .picker {
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+ }
+ /* The column scrolls as a whole. A row that shrank instead would collapse the
+ filters first: a scrolling row has no minimum height of its own. */
+ .picker > :global(*) {
+ flex-shrink: 0;
+ }
+ .bar {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ }
+ .bar :global(.search-box) {
+ flex: 1;
+ }
+ .browse {
+ min-width: 30px;
+ font-size: var(--fs-lg);
+ line-height: 1;
+ }
+ .filters {
+ display: flex;
+ gap: 4px;
+ overflow-x: auto;
+ padding-bottom: 2px;
+ }
+ .active {
+ color: var(--text-1);
+ background: var(--bg-3);
+ }
+ h4 {
+ margin: 4px 0 0;
+ font-size: var(--fs-xs);
+ font-weight: 600;
+ text-transform: uppercase;
+ letter-spacing: 0.04em;
+ color: var(--text-3);
+ }
+ .grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
+ gap: 10px;
+ }
+ .card {
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ padding: 6px;
+ text-align: left;
+ border: 1px solid var(--border);
+ border-radius: var(--r-md);
+ background: var(--bg-2);
+ min-width: 0;
+ }
+ .card:hover {
+ border-color: var(--accent);
+ background: var(--bg-3);
+ }
+ .card.current {
+ border-color: var(--accent);
+ }
+ .thumb {
+ position: relative;
+ display: grid;
+ place-items: center;
+ aspect-ratio: 4 / 3;
+ overflow: hidden;
+ border-radius: var(--r-sm);
+ background: var(--bg-0);
+ color: var(--text-3);
+ }
+ .thumb img {
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ }
+ .kind,
+ .count {
+ position: absolute;
+ display: flex;
+ align-items: center;
+ padding: 1px 5px;
+ border-radius: 4px;
+ background: rgba(10, 10, 10, 0.65);
+ color: #fff;
+ font-size: 10px;
+ }
+ .kind {
+ top: 4px;
+ left: 4px;
+ padding: 2px;
+ }
+ .count {
+ bottom: 4px;
+ right: 4px;
+ }
+ .title,
+ .meta {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ .title {
+ color: var(--text-1);
+ font-size: var(--fs-sm);
+ font-weight: 600;
+ }
+ .meta {
+ color: var(--text-3);
+ font-size: var(--fs-xs);
+ }
+ .hint {
+ color: var(--text-3);
+ font-size: var(--fs-sm);
+ margin: 0;
+ }
+ .actions {
+ display: flex;
+ justify-content: flex-end;
+ }
+</style>
diff --git a/frontend/src/components/TemporalClaimEditor.svelte b/frontend/src/components/TemporalClaimEditor.svelte
index 938421a..918cca4 100644
--- a/frontend/src/components/TemporalClaimEditor.svelte
+++ b/frontend/src/components/TemporalClaimEditor.svelte
@@ -12,6 +12,8 @@
initialWhen = '',
initialStatement = '',
initialRole = '',
+ /** Evidence a new claim cites from the start, such as the picture it was read on. */
+ initialCites = [],
onsaved,
oncancel,
} = $props();
@@ -39,6 +41,7 @@
when = item?.raw ?? initialWhen;
timeRole = item?.time_role ?? initialRole;
confidence = item?.confidence ?? '';
+ if (!item) cites = initialCites.map((entry) => ({ id: entry.id, label: entry.label, type: entry.type }));
});
$effect(() => {
diff --git a/frontend/src/components/TemporalClaimEditor.test.js b/frontend/src/components/TemporalClaimEditor.test.js
index 6d5cce3..e9b4b17 100644
--- a/frontend/src/components/TemporalClaimEditor.test.js
+++ b/frontend/src/components/TemporalClaimEditor.test.js
@@ -27,4 +27,9 @@ describe('temporal Claim editor', () => {
expect(picker).toContain("relationOptions('claim', entry.type, 'claim')");
expect(picker).toContain('buildCatalogQuery(caseId, { types, query: term, limit: 200 })');
});
+
+ it('starts a new claim citing the evidence it was opened from, and an edit from its own', () => {
+ expect(editor).toContain('initialCites = [],');
+ expect(editor).toContain('if (!item) cites = initialCites.map(');
+ });
});
diff --git a/frontend/src/components/TurnGuide.svelte b/frontend/src/components/TurnGuide.svelte
new file mode 100644
index 0000000..d8aee8c
--- /dev/null
+++ b/frontend/src/components/TurnGuide.svelte
@@ -0,0 +1,48 @@
+<script>
+ /**
+ * The wheel a turn is steered with: a dot on the grabbed point and the circle
+ * outside which the pointer's sweep is read (`lib/turn.js`). Every view that
+ * turns draws this same guide while the middle button is held.
+ */
+ import { TURN_RADIUS } from '../lib/turn.js';
+
+ /** The grabbed point, in px of the positioned parent. */
+ let { x, y } = $props();
+ const size = TURN_RADIUS * 2 + 4;
+ const mid = size / 2;
+</script>
+
+<svg
+ class="turn-guide"
+ width={size}
+ height={size}
+ viewBox="0 0 {size} {size}"
+ style:left={`${x}px`}
+ style:top={`${y}px`}
+ aria-hidden="true"
+>
+ <circle class="wheel" cx={mid} cy={mid} r={TURN_RADIUS} />
+ <circle class="dot" cx={mid} cy={mid} r="2" />
+</svg>
+
+<style>
+ .turn-guide {
+ position: absolute;
+ z-index: 650;
+ transform: translate(-50%, -50%);
+ pointer-events: none;
+ overflow: visible;
+ color: #fff;
+ filter: drop-shadow(0 0 1.5px rgba(0, 0, 0, 0.7));
+ }
+ .wheel {
+ fill: none;
+ stroke: currentColor;
+ stroke-width: 1.25;
+ stroke-dasharray: 4 4;
+ opacity: 0.75;
+ }
+ .dot {
+ fill: currentColor;
+ }
+</style>
diff --git a/frontend/src/lib/api.js b/frontend/src/lib/api.js
index b44d9f8..9e04ea2 100644
--- a/frontend/src/lib/api.js
+++ b/frontend/src/lib/api.js
@@ -54,8 +54,9 @@ export const api = {
// `opts` reaches fetch (e.g. `{ signal }`) so a caller can cancel a stale
// request — the bounded catalog aborts an in-flight page on case/filter change.
get: (path, opts) => request('GET', path, undefined, opts),
- post: (path, body) => request('POST', path, body),
- put: (path, body) => request('PUT', path, body),
+ // `keepalive` lets a save sent while the tab closes outlive the page.
+ post: (path, body, opts) => request('POST', path, body, opts),
+ put: (path, body, opts) => request('PUT', path, body, opts),
patch: (path, body) => request('PATCH', path, body),
del: (path) => request('DELETE', path),
};
diff --git a/frontend/src/lib/autosave.svelte.js b/frontend/src/lib/autosave.svelte.js
new file mode 100644
index 0000000..4508c8c
--- /dev/null
+++ b/frontend/src/lib/autosave.svelte.js
@@ -0,0 +1,75 @@
+/**
+ * Save-as-you-go for a document a tool holds in memory.
+ *
+ * Call `schedule()` after every change; the write runs once the changes have
+ * stopped for `delay` ms, so a slider drag is one save rather than sixty. Only one
+ * write is ever in flight: a change made during it is written right after, never
+ * alongside, because two racing writes can land in either order.
+ *
+ * `write` reads the document when it runs rather than when it was scheduled, so a
+ * burst of edits is saved as it ended. It may resolve without writing anything
+ * when nothing changed since the last save.
+ *
+ * `flush()` writes whatever is pending and waits for it. A tool calls it before it
+ * lets go of the document: switching file, closing the case, leaving the tool.
+ */
+export function createAutosave({ write, delay = 800 }) {
+ const state = $state({ status: 'idle', error: '' });
+ let timer = null;
+ let running = null;
+ let again = false;
+
+ async function run() {
+ clearTimeout(timer);
+ timer = null;
+ if (running) {
+ again = true;
+ return running;
+ }
+ running = (async () => {
+ state.status = 'saving';
+ try {
+ await write();
+ state.status = 'saved';
+ state.error = '';
+ } catch (e) {
+ state.status = 'error';
+ state.error = e?.message || 'save failed';
+ }
+ })();
+ try {
+ await running;
+ } finally {
+ running = null;
+ }
+ if (again) {
+ again = false;
+ await run();
+ }
+ }
+
+ return {
+ state,
+ schedule() {
+ state.status = 'pending';
+ clearTimeout(timer);
+ timer = setTimeout(run, delay);
+ },
+ async flush() {
+ if (timer || again) return run();
+ if (running) await running;
+ },
+ /** Forget a pending write, for a document that is being thrown away. */
+ cancel() {
+ clearTimeout(timer);
+ timer = null;
+ again = false;
+ state.status = 'idle';
+ state.error = '';
+ },
+ /** Whether a write is scheduled or running, so a page closing can send it. */
+ get pending() {
+ return timer !== null || running !== null;
+ },
+ };
+}
diff --git a/frontend/src/lib/autosave.svelte.test.js b/frontend/src/lib/autosave.svelte.test.js
new file mode 100644
index 0000000..b47a39c
--- /dev/null
+++ b/frontend/src/lib/autosave.svelte.test.js
@@ -0,0 +1,108 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { createAutosave } from './autosave.svelte.js';
+
+/** A write the test finishes by hand, to hold one in flight. */
+function deferred() {
+ let resolve;
+ let reject;
+ const promise = new Promise((res, rej) => {
+ resolve = res;
+ reject = rej;
+ });
+ return { promise, resolve, reject };
+}
+
+beforeEach(() => vi.useFakeTimers());
+afterEach(() => vi.useRealTimers());
+
+describe('createAutosave', () => {
+ it('writes once, after the changes stop', async () => {
+ const write = vi.fn(async () => {});
+ const saver = createAutosave({ write, delay: 500 });
+
+ saver.schedule();
+ await vi.advanceTimersByTimeAsync(300);
+ saver.schedule();
+ await vi.advanceTimersByTimeAsync(300);
+ expect(write).not.toHaveBeenCalled();
+ expect(saver.state.status).toBe('pending');
+
+ await vi.advanceTimersByTimeAsync(250);
+ expect(write).toHaveBeenCalledTimes(1);
+ expect(saver.state.status).toBe('saved');
+ });
+
+ it('never runs two writes at once, and writes a change made during one right after', async () => {
+ const first = deferred();
+ const write = vi.fn().mockReturnValueOnce(first.promise).mockResolvedValue();
+ const saver = createAutosave({ write, delay: 100 });
+
+ saver.schedule();
+ await vi.advanceTimersByTimeAsync(100);
+ expect(saver.state.status).toBe('saving');
+ saver.schedule();
+ await vi.advanceTimersByTimeAsync(100);
+ expect(write).toHaveBeenCalledTimes(1);
+
+ first.resolve();
+ await vi.advanceTimersByTimeAsync(0);
+ expect(write).toHaveBeenCalledTimes(2);
+ });
+
+ it('writes what is pending on flush, without waiting out the delay', async () => {
+ const write = vi.fn(async () => {});
+ const saver = createAutosave({ write, delay: 10_000 });
+
+ saver.schedule();
+ await saver.flush();
+
+ expect(write).toHaveBeenCalledTimes(1);
+ expect(saver.pending).toBe(false);
+ });
+
+ it('waits for a write in flight on flush', async () => {
+ const running = deferred();
+ const write = vi.fn(() => running.promise);
+ const saver = createAutosave({ write, delay: 10 });
+ saver.schedule();
+ await vi.advanceTimersByTimeAsync(10);
+
+ let flushed = false;
+ saver.flush().then(() => (flushed = true));
+ await vi.advanceTimersByTimeAsync(0);
+ expect(flushed).toBe(false);
+
+ running.resolve();
+ await vi.advanceTimersByTimeAsync(0);
+ expect(flushed).toBe(true);
+ expect(write).toHaveBeenCalledTimes(1);
+ });
+
+ it('says a failed write failed, and tries again when asked', async () => {
+ const write = vi.fn().mockRejectedValueOnce(new Error('disk full')).mockResolvedValue();
+ const saver = createAutosave({ write, delay: 10 });
+
+ saver.schedule();
+ await vi.advanceTimersByTimeAsync(10);
+ expect(saver.state.status).toBe('error');
+ expect(saver.state.error).toBe('disk full');
+
+ saver.schedule();
+ await saver.flush();
+ expect(saver.state.status).toBe('saved');
+ expect(saver.state.error).toBe('');
+ });
+
+ it('forgets a pending write for a document being thrown away', async () => {
+ const write = vi.fn(async () => {});
+ const saver = createAutosave({ write, delay: 50 });
+
+ saver.schedule();
+ saver.cancel();
+ await vi.advanceTimersByTimeAsync(100);
+ await saver.flush();
+
+ expect(write).not.toHaveBeenCalled();
+ expect(saver.state.status).toBe('idle');
+ });
+});
diff --git a/frontend/src/lib/extensionMapTheme.test.js b/frontend/src/lib/extensionMapTheme.test.js
index bb471cd..55ad49b 100644
--- a/frontend/src/lib/extensionMapTheme.test.js
+++ b/frontend/src/lib/extensionMapTheme.test.js
@@ -15,6 +15,7 @@ import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';
import { paths } from '../components/Icon.svelte';
+import { CAPTURE_KINDS } from './geoTree.js';
const here = dirname(fileURLToPath(import.meta.url));
const read = (rel) => readFileSync(join(here, rel), 'utf8');
@@ -120,6 +121,10 @@ describe('the paint the tools use', () => {
]);
});
+ it('draws the same stacks as captures as the Saved layer does', () => {
+ expect(theme.SAVED_CAPTURE_KINDS).toEqual([...CAPTURE_KINDS]);
+ });
+
it('names the same glyph for a saved row as the Saved layer', () => {
const overlay = read('../tools/satellite/SavedOverlay.svelte');
const block = /const GLYPH = \{([^}]*)\}/.exec(overlay)[1];
diff --git a/frontend/src/lib/frameRotate.js b/frontend/src/lib/frameRotate.js
index 781e104..c0e5a36 100644
--- a/frontend/src/lib/frameRotate.js
+++ b/frontend/src/lib/frameRotate.js
@@ -73,8 +73,3 @@ export function matrixAngleDeg(m) {
export function isIdentity(m, eps = 1e-6) {
return IDENTITY.every((v, i) => Math.abs(m[i] - v) < eps);
}
-
-/** Angle (deg) of the spoke from a pivot to a point, in screen space (Y down). */
-export function pointerAngleDeg(pivotX, pivotY, x, y) {
- return Math.atan2(y - pivotY, x - pivotX) / DEG;
-}
diff --git a/frontend/src/lib/frameRotate.test.js b/frontend/src/lib/frameRotate.test.js
index 9ee85bc..3a58e24 100644
--- a/frontend/src/lib/frameRotate.test.js
+++ b/frontend/src/lib/frameRotate.test.js
@@ -1,7 +1,7 @@
import { describe, it, expect } from 'vitest';
import {
IDENTITY, matMul, rotation, translation, apply,
- rotateAbout, matrixCss, matrixAngleDeg, isIdentity, pointerAngleDeg,
+ rotateAbout, matrixCss, matrixAngleDeg, isIdentity,
} from './frameRotate.js';
const near = (a, b, eps = 1e-9) => Math.abs(a - b) < eps;
@@ -85,14 +85,6 @@ describe('isIdentity', () => {
});
});
-describe('pointerAngleDeg', () => {
- it('measures the spoke angle in screen space (Y down)', () => {
- expect(near(pointerAngleDeg(0, 0, 1, 0), 0)).toBe(true);
- expect(near(pointerAngleDeg(0, 0, 0, 1), 90)).toBe(true);
- expect(near(Math.abs(pointerAngleDeg(0, 0, -1, 0)), 180)).toBe(true);
- });
-});
-
describe('matrixCss', () => {
it('serialises to a CSS matrix() string', () => {
expect(matrixCss(IDENTITY)).toBe('matrix(1, 0, 0, 1, 0, 0)');
diff --git a/frontend/src/lib/geoTree.js b/frontend/src/lib/geoTree.js
index 6e1c0fd..99ff97f 100644
--- a/frontend/src/lib/geoTree.js
+++ b/frontend/src/lib/geoTree.js
@@ -19,8 +19,8 @@ import { haversine } from './measure.js';
* **Media** is a mode, not a filter — a file carries no point of its own and
* stands where the graph puts it, so it has an index of its own and swaps the
* rows the panel reads. Places and captures filter the one saved index; a
- * screenshot is a capture with a different origin, not a thing to choose
- * between. */
+ * screenshot is a capture with a different origin, and a saved comparison is
+ * imagery of a point at two dates, so both read as captures. */
export const KINDS = [
{ id: 'media', label: 'Media' },
{ id: 'places', label: 'Places' },
@@ -47,9 +47,12 @@ export const UNLOCATED = 'Unlocated';
* country — the country is the useful part, the continent is the shelf. */
const OTHER_CONTINENT = 'Other';
+/** The row kinds the Captures position holds: imagery of a point, however made. */
+export const CAPTURE_KINDS = new Set(['capture', 'screenshot', 'comparison']);
+
function matchesKind(row, kind) {
if (kind === 'places') return row.kind === 'place';
- if (kind === 'captures') return row.kind === 'capture' || row.kind === 'screenshot';
+ if (kind === 'captures') return CAPTURE_KINDS.has(row.kind);
return true;
}
diff --git a/frontend/src/lib/geoTree.test.js b/frontend/src/lib/geoTree.test.js
index 9b07ef8..ded21ad 100644
--- a/frontend/src/lib/geoTree.test.js
+++ b/frontend/src/lib/geoTree.test.js
@@ -141,6 +141,10 @@ describe('buildGeoTree filtering', () => {
it('treats a screenshot as a capture in the kind filter', () => {
expect(filterSaved(rows, { kind: 'captures' }).map((r) => r.id)).toEqual(['bb', 'ccc']);
+ // a saved comparison is imagery of a point at two dates: a capture too
+ const compared = [...rows, UA('dddd', 'Kyiv Oblast', { kind: 'comparison', title: 'harbour' })];
+ expect(filterSaved(compared, { kind: 'captures' }).map((r) => r.id)).toEqual(['bb', 'ccc', 'dddd']);
+ expect(filterSaved(compared, { kind: 'places' }).map((r) => r.id)).toEqual(['a']);
expect(filterSaved(rows, { kind: 'places' }).map((r) => r.id)).toEqual(['a']);
expect(filterSaved(rows, { kind: 'all' })).toHaveLength(3);
});
diff --git a/frontend/src/lib/guide.js b/frontend/src/lib/guide.js
index 303cb0c..d454054 100644
--- a/frontend/src/lib/guide.js
+++ b/frontend/src/lib/guide.js
@@ -124,7 +124,7 @@ export const GUIDE = [
lead: 'From a URL to a dated claim the case can argue with.',
steps: [
{ tool: 'media', text: 'Paste the post URL. The first attempt is made without cookies, and only an "unavailable" answer offers your saved browser session.' },
- { tool: 'inspect', text: 'Step the video frame by frame and pull the stills the argument rests on. Each is filed as media made here.' },
+ { tool: 'inspect', text: 'Step the video frame by frame and capture the stills the argument rests on, then save them to the case as media made here.' },
{ tool: 'board', text: 'Confirm what the import proposed, then link the frames to the place, the account and the people.' },
{ tool: 'timeline', text: 'Date the claim, and read it in UTC, in your own clock, or in local time at the place itself.' },
],
@@ -164,27 +164,27 @@ export const GUIDE = [
},
{
label: 'Send a picture from where you are looking at it',
- text: 'Open in… on a Media Library row sends the file, and the Frame tab in Inspect sends the frame as you cropped it, saved or not.',
+ text: 'Open in… on a Media Library row sends the file, and a frame in Inspect goes as you cropped it, saved or not.',
},
],
},
{
id: 'examine',
title: 'Examine',
- lead: 'Inspect reads one image or one video closely, and saves the reading as a session you can reopen.',
- tools: ['inspect'],
+ lead: 'Inspect reads one image or one video closely. Collage lays out frames and images from any number of files.',
+ tools: ['inspect', 'collage'],
points: [
{
- label: 'Four tabs for a video, two for a picture',
- text: 'Selection pulls stills out of a clip, Frame adjusts and crops one picture with the error-level view folded inside, Collage stitches, and Save files what you made. A still image opens on Frame and Save.',
+ label: 'The work stays with the file',
+ text: 'Frames and edits are kept as you make them, one set per file. Opening the file again picks up where you left off.',
},
{
- label: 'What you make is case material',
- text: 'A frame or a collage is filed as ordinary media and marked as made here, so the graph can say what it came out of.',
+ label: 'A strip instead of tabs',
+ text: 'A video leads the strip and the frames cut from it follow. Click one to adjust, crop or analyse it.',
},
{
- label: 'The session is the artifact',
- text: 'Reopening one puts every adjustment back where it was. The file on disk is never overwritten.',
+ label: 'Save to case is the one step that files media',
+ text: 'A frame, an adjusted video or a collage becomes media marked as made here, so the graph can say what it came out of. The original is never overwritten.',
},
],
},
@@ -202,6 +202,10 @@ export const GUIDE = [
label: 'Right-click the ground',
text: 'The menu acts on the point under the cursor: copy it in any format, save it, measure or read the sun from it, see its imagery history, or open it in another map.',
},
+ {
+ label: 'The map tabs look at one place',
+ text: 'Satellite, Compare and Detect open where you last looked. A Detect review and a saved comparison stay put, and Settings → General turns it off.',
+ },
{
label: 'Layers cost nothing until they are on',
text: 'Roads, railways, power lines, sea marks, GPS traces, fires and night lights are listed in the Layers tab of the side panel, and none of them is fetched before its switch is pressed. Borders are the one layer the map opens with.',
@@ -238,6 +242,14 @@ export const GUIDE = [
label: 'Radar sees through cloud',
text: 'The radar analyzers read Sentinel-1 through a layer you add to your Copernicus configuration, found from Settings → Imagery. A and B have to share a track, which the pass list marks.',
},
+ {
+ label: 'An analyzer of your own is a list of rules',
+ text: 'Analyzers → New analyzer → start from an example, or build your own rules. Each rule is a line a pixel has to cross on A, on B or between them. Pick two passes and every change redraws what each rule keeps on the map; a click on the map says which rule let a point go.',
+ },
+ {
+ label: 'Checks prove an analyzer, if you want them',
+ text: 'Checks → Add a check, pick its passes, then arm Should be found or Should stay empty and click the map to drop pins. Checks reread themselves as the rules change, so a line that loses the burn or catches the reef turns its check red. The examples come with theirs.',
+ },
{
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.',
@@ -327,6 +339,16 @@ export const GUIDE = [
{ combo: 'Ctrl+Enter', does: 'files an Add claim form' },
],
},
+ {
+ where: 'Satellite, Compare, Detect',
+ keys: [
+ { combo: 'Middle-drag', does: 'turns the map like a wheel round the point grabbed, as does Shift-drag' },
+ { combo: 'Ctrl (turning)', does: 'turns in 15° steps' },
+ { combo: 'Middle-click', does: 'puts north back up' },
+ { combo: 'Shift+← / →', does: 'turns the map 15°' },
+ { combo: 'Shift+↑', does: 'puts north back up' },
+ ],
+ },
{
where: 'Graph',
keys: [
@@ -373,6 +395,18 @@ export const GUIDE = [
{ combo: 'Escape', does: 'drops the shape being drawn, then the selection, then the pen' },
],
},
+ {
+ where: 'Detect',
+ keys: [
+ { combo: ']', does: 'folds the column to a rail and back' },
+ { combo: '← / →', does: 'walks the review queue' },
+ { combo: 'K D P', does: 'keeps, dismisses or pins the candidate under review' },
+ { combo: 'H', does: 'hides the candidates and areas, or shows them again' },
+ { combo: 'B', does: 'blinks A and B on the map, when the run read two passes' },
+ { combo: 'M', does: 'picks up the ruler, or puts it down' },
+ { combo: 'Delete', does: 'removes the selected measure' },
+ ],
+ },
{
where: 'Inspect',
keys: [
@@ -380,6 +414,16 @@ export const GUIDE = [
{ combo: ', / .', does: 'the same step, on the keys mpv uses' },
{ combo: 'Space', does: 'plays and pauses' },
{ combo: 'Enter / Escape', does: 'applies the crop, or leaves it' },
+ { combo: 'Middle-drag', does: 'turns the frame, Ctrl for 15° steps' },
+ { combo: 'Middle-click', does: 'stands it upright again' },
+ ],
+ },
+ {
+ where: 'Collage',
+ keys: [
+ { combo: 'Delete', does: 'removes the selected pieces' },
+ { combo: 'Ctrl+Z', does: 'undoes the last change' },
+ { combo: 'Ctrl+Shift+Z', does: 'redoes it' },
],
},
{
diff --git a/frontend/src/lib/guide.test.js b/frontend/src/lib/guide.test.js
index 150ad42..bb2deb9 100644
--- a/frontend/src/lib/guide.test.js
+++ b/frontend/src/lib/guide.test.js
@@ -153,7 +153,9 @@ describe('the register the guide is written in', () => {
const labels = new Set(Object.values(TOOL_LABELS));
for (const section of GUIDE) {
for (const group of section.keymap ?? []) {
- expect(group.where === 'Anywhere' || labels.has(group.where), group.where).toBe(true);
+ // a group can name several tools that share the keys, comma-separated
+ const tools = group.where.split(', ');
+ expect(group.where === 'Anywhere' || tools.every((tool) => labels.has(tool)), group.where).toBe(true);
}
}
});
diff --git a/frontend/src/lib/inspect.js b/frontend/src/lib/inspect.js
index 09821b2..9ac110d 100644
--- a/frontend/src/lib/inspect.js
+++ b/frontend/src/lib/inspect.js
@@ -1,10 +1,10 @@
/**
- * Inspect-session helpers, shared by the Selection / Frame / Collage / Save tabs.
+ * Pure helpers shared by the Examine tools, Inspect and Collage.
*
- * The Inspect tool is a scratch workspace: captured frames, per-frame adjustments
- * and a collage layout live here as plain data ("recipes") and only become case
- * media on an explicit Save. These pure helpers turn slider values into the live
- * CSS preview + the backend op pipeline, and handle the collage perspective math.
+ * Frames, their adjustments and collage layouts are plain data ("recipes") that
+ * only become case media when an output is saved to the case. These turn slider
+ * values into the live CSS preview and the backend op pipeline, name what a save
+ * files, and handle the collage perspective math.
*/
// Order the adjust pipeline is applied in (matches the backend ORDER in bake()).
@@ -15,9 +15,9 @@ export const ADJUST_ORDER = [
let _seq = 0;
export const uid = (prefix = 'id') => `${prefix}_${Date.now().toString(36)}_${_seq++}`;
-// -- Save-tab naming ---------------------------------------------------------
-// What the user types at the Save gate becomes the media title *and* the stem of
-// the file on disk, so these defaults have to read as names, not placeholders.
+// -- naming what a save files ------------------------------------------------
+// What the analyst types at Save to case becomes the media title *and* the stem
+// of the file on disk, so these defaults have to read as names, not placeholders.
/**
* The name a savable inherits from what it was made out of.
@@ -57,12 +57,12 @@ export function frameSaveName(stem, time) {
}
/**
- * Default names for every frame in the tray, numbered only where they'd collide.
+ * Default names for every frame of a file, numbered only where they would collide.
*
* Naming by the second reads best, but two frames grabbed a few tenths apart
* round to one name. Those get a counter, and only those, so the common one
* frame per second stays clean. Inside a second the counter follows playback
- * order rather than the order the tray was filled in, which keeps a name sort
+ * order rather than the order the strip was filled in, which keeps a name sort
* walking the video forward even when frames were taken back to front.
*/
export function frameSaveNames(frames) {
@@ -82,22 +82,6 @@ export function frameSaveNames(frames) {
return frames.map((f, i) => `${frameSaveName(f.stem, f.time)}${counter[i]}`);
}
-/**
- * The name every savable starts out holding, before anyone edits it.
- *
- * A base name numbers the gallery (`Roof 01`, `Roof 02`); numbering runs over the
- * whole gallery, not the ticked subset, so a name never renumbers under you as
- * you tick boxes. A lone savable takes the base name bare — a `01` with nothing
- * to follow it just adds noise. With no base name, each item's default stands.
- */
-export function autoSaveNames(savables, baseName = '') {
- const base = String(baseName ?? '').trim();
- return savables.map((it, i) => {
- if (!base) return it.defaultName;
- return savables.length > 1 ? `${base} ${String(i + 1).padStart(2, '0')}` : base;
- });
-}
-
/** The name an item is filed under: what stands in its field, else its default. */
export function saveNameOf(item, value) {
return String(value ?? '').trim() || item.defaultName;
diff --git a/frontend/src/lib/inspect.test.js b/frontend/src/lib/inspect.test.js
index 3df8c3f..9aec35c 100644
--- a/frontend/src/lib/inspect.test.js
+++ b/frontend/src/lib/inspect.test.js
@@ -4,7 +4,7 @@ import {
QUAD_SIDES, quadEdgeMidpoints, moveQuadEdge, quadCentroid,
quadsBounds, translateQuad, moveQuads, rotateQuads, scaleQuads, pinholeOps,
buildFrameOps, hasVideoEdits, normalizeRightAngleRotation, rotationOps,
- sourceStem, timecode, frameSaveName, frameSaveNames, autoSaveNames, saveNameOf,
+ sourceStem, timecode, frameSaveName, frameSaveNames, saveNameOf,
newCollage, clampCollageDim, stitchCanvas, COLLAGE_MIN_DIM, COLLAGE_MAX_DIM,
COLLAGE_DEFAULT_SIZE,
} from './inspect.js';
@@ -435,34 +435,6 @@ describe('frameSaveNames', () => {
});
});
-describe('autoSaveNames', () => {
- const items = [
- { key: 'a', defaultName: '00-01-00 roof' },
- { key: 'b', defaultName: '00-02-00 roof' },
- ];
-
- it('starts every field on the item default', () => {
- expect(autoSaveNames(items)).toEqual(['00-01-00 roof', '00-02-00 roof']);
- });
-
- it('numbers the gallery under a base name', () => {
- expect(autoSaveNames(items, 'Roof')).toEqual(['Roof 01', 'Roof 02']);
- });
-
- it('numbers over the whole gallery, so ticking a box never renumbers a field', () => {
- const three = [...items, { key: 'c', defaultName: 'collage' }];
- expect(autoSaveNames(three, 'Roof')).toEqual(['Roof 01', 'Roof 02', 'Roof 03']);
- });
-
- it('leaves a lone item unnumbered', () => {
- expect(autoSaveNames([items[0]], 'Roof')).toEqual(['Roof']);
- });
-
- it('ignores a whitespace-only base name', () => {
- expect(autoSaveNames(items, ' ')).toEqual(['00-01-00 roof', '00-02-00 roof']);
- });
-});
-
describe('saveNameOf', () => {
const item = { key: 'a', defaultName: '00-01-00 roof' };
diff --git a/frontend/src/lib/inspectWork.svelte.js b/frontend/src/lib/inspectWork.svelte.js
new file mode 100644
index 0000000..95a06bb
--- /dev/null
+++ b/frontend/src/lib/inspectWork.svelte.js
@@ -0,0 +1,132 @@
+/**
+ * What Inspect writes for a file, and what a collage writes for itself.
+ *
+ * The shapes on disk are documented beside the code that stores them
+ * (`engine/inspectwork.py`). These helpers decide what goes into a save, when there
+ * is nothing worth saving yet, and whether an output already sits in the case as it
+ * reads now.
+ */
+import { buildFrameOps, hasVideoEdits, isNeutral, normalizeRightAngleRotation } from './inspect.js';
+
+/**
+ * Bumped after every work save, so a reader of the works list (the collage piece
+ * picker) refetches rather than showing frames from before the latest capture.
+ */
+export const workState = $state({ rev: 0 });
+
+/**
+ * What a case image or video is, in the words the pickers filter by: a map
+ * capture, something Inspect made (a frame, a collage), or plain imported media.
+ */
+export function categoryOf(item) {
+ const source = item?.source ?? {};
+ if (source.type === 'satellite' || source.type === 'screenshot') return 'capture';
+ if (source.op === 'collage') return 'collage';
+ if (source.op === 'frame' || source.op === 'adjust') return 'frame';
+ return item?.kind;
+}
+
+/** One frame as it is stored: its recipe, never the preview pixels. */
+export function frameRecord(frame) {
+ return {
+ id: frame.id,
+ path: frame.path,
+ time: frame.time ?? null,
+ adjust: { ...(frame.adjust ?? {}) },
+ crop: frame.crop ?? null,
+ sourceOps: frame.sourceOps ?? [],
+ rotation: normalizeRightAngleRotation(frame.rotation),
+ w: frame.w ?? null,
+ h: frame.h ?? null,
+ filed: frame.filed ?? null,
+ };
+}
+
+/** The body of a work save. */
+export function workSpec(work) {
+ return {
+ videoAdjust: { ...(work.videoAdjust ?? {}) },
+ videoRotation: normalizeRightAngleRotation(work.videoRotation),
+ videoFiled: work.videoFiled ?? null,
+ activeFrameId: work.activeFrameId ?? null,
+ frames: (work.frames ?? []).map(frameRecord),
+ };
+}
+
+/** A frame nobody has touched: the image exactly as the case holds it. */
+export function isUntouched(frame, filters) {
+ return (
+ !frame.crop &&
+ !normalizeRightAngleRotation(frame.rotation) &&
+ !(frame.sourceOps?.length) &&
+ isNeutral(filters, frame.adjust)
+ );
+}
+
+/**
+ * Whether the work holds anything at all.
+ *
+ * Opening a file to look at it must not file a work for it. A video has done
+ * nothing until a frame is cut or the clip is adjusted; an image starts as one
+ * frame, the image itself, and has done nothing until that frame changes or a
+ * second one appears.
+ */
+export function isPristine(work, filters, videoFilters) {
+ const frames = work.frames ?? [];
+ if (work.source?.kind === 'video') {
+ return frames.length === 0 && !hasVideoEdits(videoFilters, work.videoAdjust, work.videoRotation);
+ }
+ return frames.length <= 1 && frames.every((f) => isUntouched(f, filters) && !f.filed);
+}
+
+/** What a frame would be saved as: its whole op pipeline. */
+export const frameSignature = (filters, frame) => JSON.stringify(buildFrameOps(filters, frame));
+
+/** What the adjusted video would be saved as. */
+export const videoSignature = (videoFilters, adjust, rotation) =>
+ JSON.stringify([normalizeRightAngleRotation(rotation), videoFilters.map((f) => adjust?.[f.id] ?? null)]);
+
+/**
+ * Whether an output is in the case as it reads now.
+ *
+ * `filed` is what the last save recorded: the media it produced and the recipe it
+ * was made from. Editing after the save, or deleting that media, makes it unsaved
+ * again, which is what lets the check stay honest after a reopen.
+ */
+export function isFiled(filed, signature, mediaPaths) {
+ return !!filed && filed.signature === signature && mediaPaths.has(filed.path);
+}
+
+// -- collages -----------------------------------------------------------------
+
+/** One piece as it is stored: the recipe it was frozen from and where it sits. */
+export function pieceRecord(node) {
+ return {
+ id: node.id,
+ frameId: node.frameId ?? null,
+ save: node.save,
+ w: node.w,
+ h: node.h,
+ quad: node.quad.map(([x, y]) => [x, y]),
+ frameOps: node.frameOps ?? node.save?.ops ?? [],
+ crop: node.crop ?? null,
+ };
+}
+
+/** The body of a collage save. */
+export function collageSpec(collage) {
+ return {
+ width: collage.width,
+ height: collage.height,
+ background: collage.background,
+ transparent: collage.transparent,
+ nodes: collage.nodes.map(pieceRecord),
+ exported: collage.exported ?? null,
+ };
+}
+
+/** What a collage would export as: its pieces' recipes and corners. */
+export const collageSignature = (collage) => JSON.stringify(collage.nodes.map((n) => [n.save, n.quad]));
+
+/** Pieces whose file is gone. They keep their place but cannot be exported. */
+export const missingPieces = (collage) => collage.nodes.filter((n) => n.missing);
diff --git a/frontend/src/lib/inspectWork.test.js b/frontend/src/lib/inspectWork.test.js
new file mode 100644
index 0000000..d25480b
--- /dev/null
+++ b/frontend/src/lib/inspectWork.test.js
@@ -0,0 +1,121 @@
+import { describe, expect, it } from 'vitest';
+import {
+ categoryOf, collageSignature, collageSpec, frameRecord, frameSignature, isFiled, isPristine,
+ isUntouched, missingPieces, videoSignature, workSpec,
+} from './inspectWork.svelte.js';
+
+const FILTERS = [
+ { id: 'brightness', params: [{ name: 'value', default: 1 }], css: 'brightness({v})' },
+ { id: 'grayscale', params: [{ name: 'on', default: 0 }], css: 'grayscale({v})' },
+];
+const VIDEO_FILTERS = FILTERS;
+
+const frame = (extra = {}) => ({
+ id: 'fr_1', path: 'media/roof.png', time: null, adjust: { brightness: 1, grayscale: 0 },
+ crop: null, sourceOps: [], rotation: 0, w: 80, h: 60, filed: null, ...extra,
+});
+
+describe('what a work save writes', () => {
+ it('keeps the recipe and leaves the preview pixels behind', () => {
+ const record = frameRecord(frame({ url: 'blob:x', missing: true }));
+ expect(record).not.toHaveProperty('url');
+ expect(record).not.toHaveProperty('missing');
+ expect(record.path).toBe('media/roof.png');
+ });
+
+ it('holds a turn to the right angles the pipeline accepts', () => {
+ expect(workSpec({ videoRotation: 45, frames: [frame({ rotation: 33 })] })).toMatchObject({
+ videoRotation: 0,
+ frames: [{ rotation: 0 }],
+ });
+ });
+});
+
+describe('isPristine: looking at a file files nothing', () => {
+ it('holds for a video until a frame is cut or the clip is adjusted', () => {
+ const video = { source: { kind: 'video' }, frames: [], videoAdjust: { brightness: 1 }, videoRotation: 0 };
+ expect(isPristine(video, FILTERS, VIDEO_FILTERS)).toBe(true);
+ expect(isPristine({ ...video, frames: [frame()] }, FILTERS, VIDEO_FILTERS)).toBe(false);
+ expect(isPristine({ ...video, videoRotation: 90 }, FILTERS, VIDEO_FILTERS)).toBe(false);
+ expect(isPristine({ ...video, videoAdjust: { brightness: 1.4 } }, FILTERS, VIDEO_FILTERS)).toBe(false);
+ });
+
+ it('holds for an image until its one frame changes or a second appears', () => {
+ const image = { source: { kind: 'image' }, frames: [frame()] };
+ expect(isPristine(image, FILTERS, VIDEO_FILTERS)).toBe(true);
+ expect(isPristine({ ...image, frames: [frame({ crop: { x: 0, y: 0, w: 0.5, h: 0.5 } })] }, FILTERS, VIDEO_FILTERS)).toBe(false);
+ expect(isPristine({ ...image, frames: [frame(), frame({ id: 'fr_2' })] }, FILTERS, VIDEO_FILTERS)).toBe(false);
+ expect(isPristine({ ...image, frames: [frame({ filed: { path: 'media/x.png' } })] }, FILTERS, VIDEO_FILTERS)).toBe(false);
+ });
+
+ it('reads an untouched frame as the file itself', () => {
+ expect(isUntouched(frame(), FILTERS)).toBe(true);
+ expect(isUntouched(frame({ rotation: 90 }), FILTERS)).toBe(false);
+ expect(isUntouched(frame({ adjust: { brightness: 1.2 } }), FILTERS)).toBe(false);
+ });
+});
+
+describe('isFiled: an output in the case as it reads now', () => {
+ const paths = new Set(['media/roof edit.png']);
+
+ it('holds while the recipe is the one that was saved and the media is still there', () => {
+ const f = frame({ adjust: { brightness: 1.3 } });
+ const filed = { path: 'media/roof edit.png', signature: frameSignature(FILTERS, f) };
+ expect(isFiled(filed, frameSignature(FILTERS, f), paths)).toBe(true);
+ });
+
+ it('lapses when the frame is edited after the save', () => {
+ const f = frame({ adjust: { brightness: 1.3 } });
+ const filed = { path: 'media/roof edit.png', signature: frameSignature(FILTERS, f) };
+ const edited = { ...f, crop: { x: 0.1, y: 0.1, w: 0.2, h: 0.2 } };
+ expect(isFiled(filed, frameSignature(FILTERS, edited), paths)).toBe(false);
+ });
+
+ it('lapses when the saved media is deleted', () => {
+ const f = frame();
+ const filed = { path: 'media/gone.png', signature: frameSignature(FILTERS, f) };
+ expect(isFiled(filed, frameSignature(FILTERS, f), paths)).toBe(false);
+ expect(isFiled(null, frameSignature(FILTERS, f), paths)).toBe(false);
+ });
+
+ it('tells an adjusted video apart from its first save', () => {
+ const before = videoSignature(VIDEO_FILTERS, { brightness: 1.2 }, 0);
+ expect(videoSignature(VIDEO_FILTERS, { brightness: 1.2 }, 90)).not.toBe(before);
+ expect(videoSignature(VIDEO_FILTERS, { brightness: 1.2 }, 0)).toBe(before);
+ });
+});
+
+describe('collages', () => {
+ const piece = (extra = {}) => ({
+ id: 'nd_1', frameId: 'fr_1', save: { path: 'media/roof.png', time: null, ops: [] },
+ w: 80, h: 60, quad: [[0, 0], [80, 0], [80, 60], [0, 60]], url: 'blob:x', baseUrl: 'blob:y', ...extra,
+ });
+
+ it('stores recipes and corners, never the preview pixels', () => {
+ const spec = collageSpec({ width: 800, height: 400, background: '#000', transparent: true, nodes: [piece()] });
+ expect(spec.nodes[0]).not.toHaveProperty('url');
+ expect(spec.nodes[0]).not.toHaveProperty('baseUrl');
+ expect(spec.exported).toBeNull();
+ });
+
+ it('moves its signature when a piece moves', () => {
+ const before = collageSignature({ nodes: [piece()] });
+ const moved = collageSignature({ nodes: [piece({ quad: [[5, 0], [85, 0], [85, 60], [5, 60]] })] });
+ expect(moved).not.toBe(before);
+ });
+
+ it('finds the pieces whose file is gone', () => {
+ expect(missingPieces({ nodes: [piece(), piece({ id: 'nd_2', missing: true })] }).map((n) => n.id)).toEqual(['nd_2']);
+ });
+});
+
+describe('categoryOf', () => {
+ it('sorts captures, frames and collages out of plain media', () => {
+ expect(categoryOf({ kind: 'image', source: { type: 'satellite' } })).toBe('capture');
+ expect(categoryOf({ kind: 'image', source: { type: 'screenshot' } })).toBe('capture');
+ expect(categoryOf({ kind: 'image', source: { op: 'collage' } })).toBe('collage');
+ expect(categoryOf({ kind: 'image', source: { op: 'frame' } })).toBe('frame');
+ expect(categoryOf({ kind: 'image', source: { op: 'adjust' } })).toBe('frame');
+ expect(categoryOf({ kind: 'video', source: { type: 'upload' } })).toBe('video');
+ });
+});
diff --git a/frontend/src/lib/map/addedLayer.js b/frontend/src/lib/map/addedLayer.js
index 192f96a..1eefb41 100644
--- a/frontend/src/lib/map/addedLayer.js
+++ b/frontend/src/lib/map/addedLayer.js
@@ -271,13 +271,14 @@ export function visibilityFilter(hidden = []) {
* The row's time filter as a MapLibre filter, or null for every date.
*
* Days are `YYYY-MM-DD`, which sort as strings the way they sort as dates, so the
- * comparison needs no parsing on the engine's side. A feature with no date is
- * outside any period.
+ * comparison needs no parsing on the engine's side. A feature spanning several
+ * days (`date_end`) is kept when any of them is in the period. A feature with no
+ * date is outside any period.
*/
export function periodFilter(period = null) {
if (!period?.start && !period?.end) return null;
const rule = ['all', ['has', 'date']];
- if (period.start) rule.push(['>=', ['get', 'date'], period.start]);
+ if (period.start) rule.push(['>=', ['coalesce', ['get', 'date_end'], ['get', 'date']], period.start]);
if (period.end) rule.push(['<=', ['get', 'date'], period.end]);
return rule;
}
diff --git a/frontend/src/lib/map/addedLayer.test.js b/frontend/src/lib/map/addedLayer.test.js
index 0436dbf..9acc7f8 100644
--- a/frontend/src/lib/map/addedLayer.test.js
+++ b/frontend/src/lib/map/addedLayer.test.js
@@ -391,10 +391,11 @@ describe('an added layer on the map', () => {
it('keeps to a period by comparing days, and leaves the undated out of it', async () => {
expect(periodFilter(null)).toBeNull();
expect(periodFilter({ start: '', end: '' })).toBeNull();
+ // a span is kept while its last day is still in the period
expect(periodFilter({ start: '2026-09-01', end: '' })).toEqual([
'all',
['has', 'date'],
- ['>=', ['get', 'date'], '2026-09-01'],
+ ['>=', ['coalesce', ['get', 'date_end'], ['get', 'date']], '2026-09-01'],
]);
const engine = stubEngine();
diff --git a/frontend/src/lib/map/addedLayers.js b/frontend/src/lib/map/addedLayers.js
index 90d28a3..09fe07f 100644
--- a/frontend/src/lib/map/addedLayers.js
+++ b/frontend/src/lib/map/addedLayers.js
@@ -250,8 +250,8 @@ export function searchFeatures(collection, query, options = {}) {
colour: properties.colour || colours.get(category) || categoryColour(null, 0),
// A match in a group the legend switched off, or outside the period: it
// is a real feature, it is simply not on the map until that comes back.
- hidden: off.has(category) || !inPeriod(properties.date, period),
- outside: !inPeriod(properties.date, period),
+ hidden: off.has(category) || !inPeriod(properties, period),
+ outside: !inPeriod(properties, period),
});
});
return { total, results };
diff --git a/frontend/src/lib/map/analyzerRules.js b/frontend/src/lib/map/analyzerRules.js
new file mode 100644
index 0000000..0e7aa55
--- /dev/null
+++ b/frontend/src/lib/map/analyzerRules.js
@@ -0,0 +1,563 @@
+/**
+ * Analyzers of your own: a list of rules, read the way the engine reads them
+ * (engine/detect_rules.py). A rule is a quantity, the date it is read on (A,
+ * B, or the change from A to B) and the line it has to cross. Values travel in
+ * the engine's units: an index from -1 to 1, reflectance from 0 to 1, radar in
+ * decibels. Only the words and the sliders here show reflectance in percent.
+ */
+import { CHANGE_INDICES, indexThreshold } from './changeAssist.js';
+
+export const MEASURES = Object.freeze([
+ { id: 'index', label: 'Index', hint: 'A published spectral index.' },
+ { id: 'nd', label: 'My index', hint: 'Two bands of your choice: (first − second) / (first + second).' },
+ { id: 'band', label: 'Band', hint: 'One band’s reflectance.' },
+ { id: 'brightness', label: 'Brightness', hint: 'The visible bands, averaged.' },
+ { id: 'colour', label: 'Colour change', hint: 'How far the visible bands moved together.' },
+ { id: 'class', label: 'Ground class', hint: 'Sentinel-2’s own classification of the ground.' },
+ { id: 'radar', label: 'Radar', hint: 'Sentinel-1 backscatter, through cloud and at night.' },
+]);
+
+export const INDICES = CHANGE_INDICES;
+
+export const BAND_NAMES = Object.freeze({
+ B01: 'coastal', B02: 'blue', B03: 'green', B04: 'red', B05: 'red edge 1', B06: 'red edge 2',
+ B07: 'red edge 3', B08: 'near infrared', B8A: 'narrow near infrared', B09: 'water vapour',
+ B11: 'short-wave 1.6 µm', B12: 'short-wave 2.2 µm',
+});
+
+/** Normalised differences worth a name, offered as a start for My index. */
+export const PAIRS = Object.freeze([
+ { id: 'ndmi', label: 'NDMI', hint: 'Moisture', bands: ['B8A', 'B11'] },
+ { id: 'ndsi', label: 'NDSI', hint: 'Snow', bands: ['B03', 'B11'] },
+ { id: 'ndre', label: 'NDRE', hint: 'Red edge', bands: ['B8A', 'B05'] },
+ { id: 'nbr2', label: 'NBR2', hint: 'Burns and dry soil', bands: ['B11', 'B12'] },
+ { id: 'gndvi', label: 'GNDVI', hint: 'Chlorophyll', bands: ['B08', 'B03'] },
+]);
+
+export const CLASS_NAMES = Object.freeze({
+ vegetation: 'vegetation', bare: 'bare ground', water: 'water', snow: 'snow or ice',
+ cloud: 'cloud', shadow: 'cloud shadow', dark: 'dark ground',
+});
+
+export const POLARISATIONS = Object.freeze([
+ { id: 'vv', label: 'VV' }, { id: 'vh', label: 'VH' }, { id: 'ratio', label: 'VV − VH' },
+]);
+
+/** One colour a rule, on its row and on the map, in order. */
+export const RULE_COLOURS = Object.freeze(['#facc15', '#38bdf8', '#f472b6', '#a3e635', '#fb923c', '#c084fc']);
+
+/** The engine's own lists, for when a catalogue does not carry them. */
+export const L2A_BANDS = Object.freeze(['B01', 'B02', 'B03', 'B04', 'B05', 'B06', 'B07', 'B08', 'B8A', 'B09', 'B11', 'B12']);
+const SPECTRAL_BANDS = Object.freeze({
+ ndvi: ['B08', 'B04'], ndwi: ['B03', 'B08'], mndwi: ['B03', 'B11'], nbr: ['B08', 'B12'],
+ ndbi: ['B11', 'B08'], bsi: ['B11', 'B04', 'B08', 'B02'],
+});
+const VISIBLE = ['B02', 'B03', 'B04'];
+/** Bits of the preview mask past the rules' own. */
+export const MEASURED_BIT = 6;
+export const KEPT_BIT = 7;
+
+/** Which scale a rule's value lives on. */
+export function unitOf(rule) {
+ if (rule.measure === 'class') return 'class';
+ if (rule.measure === 'radar') return 'db';
+ if (['band', 'brightness', 'colour'].includes(rule.measure)) return 'reflectance';
+ return 'index';
+}
+
+/** Ops a rule can use, given what it measures and when. */
+export function opsFor(rule) {
+ if (rule.measure === 'class') return [['is', 'is'], ['not', 'is not']];
+ if (rule.measure === 'colour') return [['ge', 'at least'], ['le', 'at most'], ['between', 'between']];
+ const ops = [['ge', 'at least'], ['le', 'at most'], ['between', 'between']];
+ return rule.on === 'change' ? [...ops, ['moved', 'either way, at least']] : ops;
+}
+
+/**
+ * The slider a rule's value moves on, in the units shown: reflectance in
+ * percent, the rest as they are. `factor` turns an engine value into a shown one.
+ */
+export function scaleOf(rule) {
+ const unit = unitOf(rule);
+ const magnitude = rule.op === 'moved' || rule.measure === 'colour';
+ const change = rule.on === 'change' || rule.around > 0;
+ if (unit === 'reflectance') {
+ return { factor: 100, suffix: '%', step: 0.5,
+ min: magnitude ? 0 : change ? -50 : 0, max: magnitude ? 50 : change ? 50 : 100 };
+ }
+ if (unit === 'db') {
+ if (magnitude) return { factor: 1, suffix: ' dB', step: 0.5, min: 0, max: 20 };
+ if (change) return { factor: 1, suffix: ' dB', step: 0.5, min: -20, max: 20 };
+ return rule.polarisation === 'ratio'
+ ? { factor: 1, suffix: ' dB', step: 0.5, min: -5, max: 25 }
+ : { factor: 1, suffix: ' dB', step: 0.5, min: -35, max: 15 };
+ }
+ if (magnitude) return { factor: 1, suffix: '', step: 0.01, min: 0, max: 1 };
+ return { factor: 1, suffix: '', step: 0.01, min: -1, max: 1 };
+}
+
+/** A value as the builder shows it, signed where the rule reads a change. */
+export function formatValue(rule, value, { signed = false } = {}) {
+ if (value === null || value === undefined || !Number.isFinite(Number(value))) return '–';
+ const { factor, suffix } = scaleOf(rule);
+ const shown = Number(value) * factor;
+ const digits = unitOf(rule) === 'index' ? 2 : 1;
+ const text = Math.abs(shown).toFixed(digits);
+ const sign = shown < 0 ? '−' : signed && shown > 0 ? '+' : '';
+ return `${sign}${text}${suffix}`;
+}
+
+/** A shown value (percent for reflectance) back to the engine's units. */
+export function toEngine(rule, shown) {
+ const { factor } = scaleOf(rule);
+ return Number((Number(shown) / factor).toFixed(6));
+}
+
+// Where a new rule starts: the published marks where there are some, so the
+// first preview already means something. A change reads B minus A.
+const INDEX_LINES = {
+ ndvi: { change: ['le', -0.25], state: ['ge', 0.4] },
+ nbr: { change: ['le', -0.27], state: ['le', 0.1] },
+ ndwi: { change: ['ge', 0.25], state: ['ge', 0] },
+ mndwi: { change: ['ge', 0.25], state: ['ge', 0] },
+ ndbi: { change: ['ge', 0.1], state: ['ge', 0] },
+ bsi: { change: ['ge', 0.1], state: ['ge', 0] },
+};
+
+function line(rule) {
+ const change = rule.on === 'change';
+ switch (rule.measure) {
+ case 'index': return INDEX_LINES[rule.index][change ? 'change' : 'state'];
+ case 'nd': return change ? ['le', -0.2] : ['ge', 0];
+ case 'band': return change ? ['moved', 0.05] : ['ge', 0.25];
+ case 'brightness': return change ? ['moved', 0.05] : ['ge', 0.2];
+ case 'colour': return ['ge', 0.05];
+ case 'class': return ['is', 0];
+ case 'radar':
+ if (change) return ['moved', 3];
+ return rule.polarisation === 'ratio' ? ['ge', 8] : ['ge', rule.polarisation === 'vh' ? -12 : -4];
+ default: return ['ge', 0];
+ }
+}
+
+/**
+ * A new rule, whole, as the engine's model spells it. It starts on the usual
+ * line for what it measures unless `extra` names its own op, value or upper.
+ */
+export function newRule(measure = 'index', on = 'change', extra = {}) {
+ const { op, value, upper, ...rest } = extra;
+ const rule = {
+ measure, index: 'ndvi', bands: ['B08', 'B04'], band: 'B08', polarisation: 'vv', classes: [],
+ on: measure === 'colour' ? 'change' : measure === 'class' && on === 'change' ? 'b' : on,
+ op: 'ge', value: 0, upper: 0, around: 0, ...rest,
+ };
+ if (rule.measure === 'class' && !rule.classes.length) rule.classes = ['water'];
+ const lined = withLine(rule);
+ return {
+ ...lined,
+ ...(op === undefined ? {} : { op }),
+ ...(value === undefined ? {} : { value }),
+ ...(upper === undefined ? {} : { upper }),
+ };
+}
+
+function withLine(rule) {
+ const [op, value] = line(rule);
+ const scale = scaleOf({ ...rule, op });
+ return { ...rule, op, value, upper: op === 'between' ? value + (scale.max - scale.min) / scale.factor / 10 : 0 };
+}
+
+/**
+ * A rule after one of its fields changed. Changing what it measures, or when,
+ * puts it back on that quantity's usual line; the rest keeps what was set, as
+ * long as the combination still means something.
+ */
+export function retarget(rule, patch) {
+ const next = { ...rule, ...patch };
+ if (next.measure === 'colour') next.on = 'change';
+ if (next.measure === 'class') {
+ if (next.on === 'change') next.on = 'b';
+ if (!next.classes.length) next.classes = ['water'];
+ next.around = 0;
+ }
+ if ('measure' in patch || 'on' in patch || 'index' in patch || 'polarisation' in patch) return withLine(next);
+ if ('op' in patch) {
+ if (next.op === 'moved') next.value = Math.abs(next.value);
+ if (next.op === 'between' && next.upper <= next.value) {
+ const scale = scaleOf(next);
+ next.upper = Number((next.value + (scale.max - scale.min) / scale.factor / 10).toFixed(4));
+ }
+ }
+ return next;
+}
+
+/** Why a rule cannot run, or '' when it can, as the engine would refuse it. */
+export function ruleProblem(rule) {
+ if (rule.measure === 'class') {
+ if (!rule.classes?.length) return 'Choose at least one ground class.';
+ return '';
+ }
+ if (!Number.isFinite(Number(rule.value))) return 'Give the rule a value.';
+ if (rule.op === 'between' && !(Number(rule.upper) > Number(rule.value))) return 'The upper bound must be above the lower one.';
+ if (rule.measure === 'nd' && rule.bands[0] === rule.bands[1]) return 'Pick two different bands.';
+ return '';
+}
+
+/** The bands a rule reads. */
+export function ruleBands(rule) {
+ if (rule.measure === 'index') return SPECTRAL_BANDS[rule.index] ?? [];
+ if (rule.measure === 'nd') return [...rule.bands];
+ if (rule.measure === 'band') return [rule.band];
+ if (rule.measure === 'brightness' || rule.measure === 'colour') return VISIBLE;
+ return [];
+}
+
+export function recipeBands(recipe) {
+ const wanted = new Set((recipe?.rules ?? []).flatMap(ruleBands));
+ return L2A_BANDS.filter((band) => wanted.has(band));
+}
+
+export const isRules = (recipe) => recipe?.method === 'rules';
+export const readsRadar = (recipe) => isRules(recipe) && recipe.rules.some((rule) => rule.measure === 'radar');
+export const readsOneDate = (recipe) => isRules(recipe) && recipe.rules.every((rule) => rule.on === 'b');
+
+/** Band products one date costs: every three bands are one request. */
+export function productCount(recipe) {
+ if (readsRadar(recipe)) return 1;
+ return Math.max(1, Math.ceil(recipeBands(recipe).length / 3));
+}
+
+/** Why the recipe cannot run, or '' when it can. */
+export function recipeProblem(recipe, limits = {}) {
+ const rules = recipe?.rules ?? [];
+ if (!rules.length) return 'Add a rule.';
+ const most = limits.max_rules ?? 6;
+ if (rules.length > most) return `An analyzer holds at most ${most} rules.`;
+ for (const rule of rules) {
+ const problem = ruleProblem(rule);
+ if (problem) return problem;
+ }
+ const radar = new Set(rules.filter((rule) => rule.measure !== 'class').map((rule) => rule.measure === 'radar'));
+ if (radar.size > 1) return 'Radar and optical rules read two satellites; keep them in two analyzers.';
+ if (radar.has(true) && rules.some((rule) => rule.measure === 'class')) return 'Ground classes come from Sentinel-2, which a radar analyzer does not read.';
+ const bands = limits.max_bands ?? 6;
+ if (recipeBands(recipe).length > bands) return `An analyzer reads at most ${bands} bands.`;
+ return '';
+}
+
+/**
+ * What the panel asks of a recipe's method, worked out from its rules for an
+ * analyzer of your own: which dates, which satellite, what a tile costs, and
+ * the sizes and smoothing that fit.
+ */
+export function recipeCapability(recipe, methods = []) {
+ const base = methods.find((entry) => entry.id === recipe?.method) ?? {};
+ if (!isRules(recipe)) return base;
+ const radar = readsRadar(recipe);
+ const single = readsOneDate(recipe);
+ const radarChange = methods.find((entry) => entry.id === 'sar-change') ?? {};
+ return {
+ ...base,
+ single,
+ sensor: radar ? 'sentinel1' : 'sentinel2',
+ clouds: !radar,
+ frames: (single ? 1 : 2) * (1 + productCount(recipe)),
+ sizes: radar ? radarChange.sizes ?? base.sizes : base.sizes,
+ smoothing_m: radar ? radarChange.smoothing_m ?? null : null,
+ };
+}
+
+/** The rule that ranks candidates: the first that measures something. */
+export const signalOf = (recipe) => (recipe?.rules ?? []).findIndex((rule) => rule.measure !== 'class');
+
+function pairName(bands) {
+ return PAIRS.find((pair) => pair.bands[0] === bands[0] && pair.bands[1] === bands[1])?.label;
+}
+
+/** What a rule measures, in a few words. */
+export function quantityLabel(rule) {
+ switch (rule.measure) {
+ case 'index': return INDICES.find((entry) => entry.id === rule.index)?.label ?? rule.index.toUpperCase();
+ case 'nd': return pairName(rule.bands) ?? `(${rule.bands[0]} − ${rule.bands[1]}) / (${rule.bands[0]} + ${rule.bands[1]})`;
+ case 'band': return `${rule.band} (${BAND_NAMES[rule.band] ?? 'band'})`;
+ case 'brightness': return 'brightness';
+ case 'colour': return 'colour';
+ case 'radar': return POLARISATIONS.find((entry) => entry.id === rule.polarisation)?.label ?? 'VV';
+ case 'class': return 'ground';
+ default: return rule.measure;
+ }
+}
+
+const sideName = (on) => (on === 'a' ? 'A' : 'B');
+
+/** A rule as a clause: "NDVI dropped by 0.25 or more", "ground on B is water". */
+export function describeRule(rule) {
+ const quantity = quantityLabel(rule);
+ if (rule.measure === 'class') {
+ const names = rule.classes.map((id) => CLASS_NAMES[id] ?? id);
+ const list = names.length > 1 ? `${names.slice(0, -1).join(', ')} or ${names.at(-1)}` : names[0] ?? 'nothing';
+ return `ground on ${sideName(rule.on)} ${rule.op === 'not' ? 'is not' : 'is'} ${list}`;
+ }
+ const around = rule.around ? ` against the ground within ${rule.around} m` : '';
+ const value = (v, signed = false) => formatValue(rule, v, { signed });
+ if (rule.on !== 'change') {
+ const on = `${quantity} on ${sideName(rule.on)}`;
+ if (rule.op === 'between') return `${on} between ${value(rule.value)} and ${value(rule.upper)}${around}`;
+ if (rule.around) return `${on} at ${rule.op === 'ge' ? 'least' : 'most'} ${value(rule.value, true)}${around}`;
+ return `${on} at ${rule.op === 'ge' ? 'least' : 'most'} ${value(rule.value)}`;
+ }
+ if (rule.measure === 'colour') {
+ if (rule.op === 'between') return `colour moved by between ${value(rule.value)} and ${value(rule.upper)}${around}`;
+ return `colour moved by ${rule.op === 'ge' ? 'at least' : 'at most'} ${value(rule.value)}${around}`;
+ }
+ const size = (v) => formatValue(rule, Math.abs(v));
+ if (rule.op === 'moved') return `${quantity} moved by ${size(rule.value)} or more either way${around}`;
+ if (rule.op === 'between') return `${quantity} changed by between ${value(rule.value, true)} and ${value(rule.upper, true)}${around}`;
+ if (rule.op === 'le' && rule.value <= 0) return `${quantity} dropped by ${size(rule.value)} or more${around}`;
+ if (rule.op === 'ge' && rule.value >= 0) return `${quantity} rose by ${size(rule.value)} or more${around}`;
+ return `${quantity} changed by ${rule.op === 'ge' ? 'at least' : 'at most'} ${value(rule.value, true)}${around}`;
+}
+
+/** The whole analyzer as one sentence, for "Reads as" and a default description. */
+export function describeRecipe(recipe, { clouds = true } = {}) {
+ const clauses = (recipe?.rules ?? []).map(describeRule);
+ if (!clauses.length) return '';
+ const joiner = recipe.match === 'any' ? 'or' : 'and';
+ const list = clauses.length > 1 ? `${clauses.slice(0, -1).join(', ')} ${joiner} ${clauses.at(-1)}` : clauses[0];
+ const sky = clouds && !readsRadar(recipe) && recipe.parameters?.ignore_clouds ? ', outside cloud' : '';
+ const text = `Keeps ground where ${list}${sky}.`;
+ return text.charAt(0).toUpperCase() + text.slice(1);
+}
+
+/** A candidate's reading, from its analyzer's signal rule. */
+export function describeReading(recipe, measure) {
+ const index = signalOf(recipe);
+ if (index < 0 || !measure) return '';
+ const rule = recipe.rules[index];
+ const quantity = quantityLabel(rule);
+ if (rule.on === 'change' && rule.measure !== 'colour' && Number.isFinite(measure.before)) {
+ const change = formatValue(rule, measure.signed, { signed: true });
+ return `${quantity} ${formatValue(rule, measure.before)} → ${formatValue(rule, measure.after)} (${change}${rule.around ? ' against its ground' : ''})`;
+ }
+ if (!Number.isFinite(measure.value)) return '';
+ const shown = formatValue(rule, measure.value, { signed: !!rule.around });
+ return rule.around ? `${quantity} ${shown} against its ground` : `${quantity} ${shown}`;
+}
+
+/** The engine's parameter defaults, which a recipe starts from. */
+export const DEFAULT_PARAMETERS = Object.freeze({
+ sensitivity: 60, min_area: 0, max_area: 0, cleanup: 0, smoothing: 0, index: 'ndvi', direction: 'both',
+ sar_ground: 'any', ignore_clouds: true, ignore_shadows: true, cloud_margin: 5, merge_metres: 0, shape: 'any',
+});
+
+/** A new analyzer of your own: one change rule, at the medium size. */
+export function newRecipe(methods = []) {
+ const sizes = methods.find((entry) => entry.id === 'rules')?.sizes;
+ return {
+ id: 'custom', name: '', description: '', phenomenon: 'Candidate', method: 'rules',
+ parameters: { ...DEFAULT_PARAMETERS, ...(sizes?.medium ?? {}) },
+ colour: '#f6a81a', style: 'both', rules: [newRule('index', 'change')], match: 'all', checks: [],
+ };
+}
+
+/**
+ * Difference's index reading as an analyzer of your own: the same index, the
+ * same line, the same way it moved, the same cleanup. Difference counts its
+ * cloud margin in metres; Detect grows its mask in 10 m pixels.
+ */
+export function fromDifference(settings) {
+ const index = INDICES.find((entry) => entry.id === settings.index) ?? INDICES[0];
+ const threshold = Number(indexThreshold(settings.sensitivity).toFixed(2));
+ const classes = settings.classes ?? [];
+ const loss = classes.includes('loss') && !classes.includes('gain');
+ const gain = classes.includes('gain') && !classes.includes('loss');
+ const rule = newRule('index', 'change', { index: index.id });
+ const tuned = loss ? { op: 'le', value: -threshold } : gain ? { op: 'ge', value: threshold } : { op: 'moved', value: threshold };
+ const way = loss ? index.loss : gain ? index.gain : `${index.label} change`;
+ return {
+ id: 'custom', name: `${index.label}: ${way}`, description: '', phenomenon: way, method: 'rules',
+ parameters: {
+ ...DEFAULT_PARAMETERS,
+ min_area: Math.max(0, Number(settings.min_area) || 0),
+ cleanup: Math.min(3, Math.max(0, Math.round(settings.cleanup ?? 0))),
+ smoothing: Math.min(3, Math.max(0, Math.round(settings.smoothing ?? 0))),
+ ignore_clouds: !!settings.ignore_clouds,
+ ignore_shadows: !!settings.ignore_shadows,
+ cloud_margin: Math.min(10, Math.max(0, Math.round((settings.cloud_margin ?? 0) / 10))),
+ },
+ colour: '#f6a81a', style: 'both', rules: [{ ...rule, ...tuned }], match: 'all', checks: [],
+ };
+}
+
+function rgb(hex) {
+ const value = parseInt(hex.slice(1), 16);
+ return [(value >> 16) & 255, (value >> 8) & 255, value & 255];
+}
+
+/**
+ * The preview mask painted in the rules' colours: each shown rule lays its
+ * pixels in its colour, later ones over earlier, and a hovered rule alone,
+ * brighter. `bits` is one byte a pixel, the engine's mask.
+ */
+export function paintMask(bits, { shown = [], hover = null, colours = RULE_COLOURS, alpha = 110 } = {}) {
+ const out = new Uint8ClampedArray(bits.length * 4);
+ const order = hover === null ? shown.map((on, i) => (on ? i : -1)).filter((i) => i >= 0) : [hover];
+ const tints = colours.map(rgb);
+ const strength = hover === null ? alpha : 190;
+ for (let p = 0; p < bits.length; p++) {
+ const value = bits[p];
+ if (!value) continue;
+ for (const i of order) {
+ if (!(value & (1 << i))) continue;
+ const [r, g, b] = tints[i % tints.length];
+ out[p * 4] = r; out[p * 4 + 1] = g; out[p * 4 + 2] = b; out[p * 4 + 3] = strength;
+ }
+ }
+ return out;
+}
+
+/** A share of the measured ground, as the funnel prints it. */
+export function formatShare(share) {
+ if (!Number.isFinite(share)) return '–';
+ const percent = share * 100;
+ if (percent === 0) return '0 %';
+ if (percent < 0.1) return '< 0.1 %';
+ return `${percent < 10 ? percent.toFixed(1) : Math.round(percent)} %`;
+}
+
+// -- checks ---------------------------------------------------------------------------
+
+/** JSON with its keys sorted, so the same recipe always reads the same. */
+function canonical(value) {
+ if (Array.isArray(value)) return `[${value.map(canonical).join(',')}]`;
+ if (value && typeof value === 'object') {
+ return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${canonical(value[key])}`).join(',')}}`;
+ }
+ return JSON.stringify(value);
+}
+
+/**
+ * A short digest of what a reading depends on: the rules, how they combine
+ * and the parameters. A check's result keeps the one it was read with, so a
+ * result from rules changed since shows as stale rather than as an answer.
+ */
+export function signature(recipe) {
+ const text = canonical({ rules: recipe?.rules ?? [], match: recipe?.match ?? 'all', parameters: recipe?.parameters ?? {} });
+ let hash = 0x811c9dc5;
+ for (let i = 0; i < text.length; i++) {
+ hash ^= text.charCodeAt(i);
+ hash = Math.imul(hash, 0x01000193) >>> 0;
+ }
+ return hash.toString(36);
+}
+
+/** A check of the view on screen and the passes shown, with no marks yet. */
+export function newCheck({ name, a, b, bounds }) {
+ const id = `check-${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`;
+ return { id, name, a: { ...a }, b: { ...b }, bounds: { ...bounds }, marks: [], result: null };
+}
+
+/**
+ * A check with one more mark. Its view grows to hold the mark, and its last
+ * result goes, since it answered for the marks it had.
+ */
+export function withMark(check, point, expect) {
+ const [lon, lat] = point;
+ const bounds = {
+ west: Math.min(check.bounds.west, lon - 0.002), south: Math.min(check.bounds.south, lat - 0.002),
+ east: Math.max(check.bounds.east, lon + 0.002), north: Math.max(check.bounds.north, lat + 0.002),
+ };
+ return { ...check, bounds, marks: [...check.marks, { point: [lon, lat], expect }], result: null };
+}
+
+export function withoutMark(check, index) {
+ return { ...check, marks: check.marks.filter((_, i) => i !== index), result: null };
+}
+
+/** Mark by mark, whether it came out as expected, from the last result. */
+export function markOutcomes(check) {
+ const covered = check.result?.covered ?? [];
+ return check.marks.map((mark, i) => (covered.length ? covered[i] === (mark.expect === 'found') : null));
+}
+
+/**
+ * Where a check stands: 'pass' when every mark came out as it should,
+ * 'fail' when one did not, 'counted' for a check with no marks, 'stale' when
+ * its last result was read with other rules, 'unrun' when it has none.
+ */
+export function checkState(check, current) {
+ const result = check.result;
+ if (!result) return 'unrun';
+ if (result.signature !== current) return 'stale';
+ if (!check.marks.length) return 'counted';
+ return markOutcomes(check).every(Boolean) ? 'pass' : 'fail';
+}
+
+/** A check's last result in a few words: "2 of 2 found · none flagged". */
+export function describeOutcome(check, current) {
+ const state = checkState(check, current);
+ if (state === 'unrun') return 'Not run yet';
+ if (state === 'stale') return 'Not rerun since the rules changed';
+ if (state === 'counted') return `${check.result.count} candidate${check.result.count === 1 ? '' : 's'}`;
+ const outcomes = markOutcomes(check);
+ const found = check.marks.map((mark, i) => [mark, outcomes[i]]).filter(([mark]) => mark.expect === 'found');
+ const empty = check.marks.map((mark, i) => [mark, outcomes[i]]).filter(([mark]) => mark.expect === 'empty');
+ const parts = [];
+ if (found.length) parts.push(`${found.filter(([, ok]) => ok).length} of ${found.length} found`);
+ if (empty.length) {
+ const flagged = empty.filter(([, ok]) => !ok).length;
+ parts.push(flagged ? `${flagged} of ${empty.length} flagged` : empty.length === 1 ? 'stayed empty' : 'all stayed empty');
+ }
+ return parts.join(' · ');
+}
+
+/** Every check of a recipe counted by where it stands. */
+export function checksSummary(recipe) {
+ const current = signature(recipe);
+ const states = (recipe?.checks ?? []).map((check) => checkState(check, current));
+ const count = (state) => states.filter((entry) => entry === state).length;
+ return { total: states.length, pass: count('pass'), fail: count('fail'), counted: count('counted'),
+ waiting: count('stale') + count('unrun') };
+}
+
+/** The summary as the library prints it under an analyzer. */
+export function describeChecks(recipe) {
+ const { total, pass, fail, waiting } = checksSummary(recipe);
+ if (!total) return '';
+ const head = `${total} check${total === 1 ? '' : 's'}`;
+ if (fail) return `${head} · ${fail} fail${fail === 1 ? 's' : ''}`;
+ if (waiting === total) return `${head} · not run`;
+ if (pass && !waiting) return `${head} · all pass`;
+ return `${head} · ${pass} pass`;
+}
+
+// -- layers ---------------------------------------------------------------------------
+
+const firstOf = (wanted, ids) => wanted.find((id) => ids.includes(id));
+
+/**
+ * The Copernicus layer that shows best what a rule reads: vegetation in NDVI,
+ * burns and heat in short-wave infrared, water and hulls in false colour, among
+ * the layers the configuration offers.
+ */
+export function suggestedLayer(rule, layers = []) {
+ const ids = layers.map((layer) => layer.id);
+ const fallback = ids.includes('TRUE_COLOR') ? 'TRUE_COLOR' : ids[0] ?? 'TRUE_COLOR';
+ if (!rule) return fallback;
+ const swir = ['B11', 'B12'];
+ const nir = ['B05', 'B06', 'B07', 'B08', 'B8A'];
+ let wanted = ['TRUE_COLOR'];
+ if (rule.measure === 'index') {
+ wanted = {
+ ndvi: ['NDVI', 'FALSE_COLOR'], nbr: ['SWIR', 'MOISTURE_INDEX'], ndwi: ['NDWI', 'FALSE_COLOR'],
+ mndwi: ['NDWI', 'FALSE_COLOR'], ndbi: ['FALSE_COLOR_URBAN', 'SWIR'], bsi: ['SWIR', 'FALSE_COLOR_URBAN'],
+ }[rule.index] ?? wanted;
+ } else if (rule.measure === 'nd' || rule.measure === 'band') {
+ const bands = ruleBands(rule);
+ wanted = bands.some((band) => swir.includes(band)) ? ['SWIR', 'FALSE_COLOR']
+ : bands.some((band) => nir.includes(band)) ? ['FALSE_COLOR', 'NDVI'] : ['TRUE_COLOR'];
+ } else if (rule.measure === 'class') {
+ wanted = ['SCENE_CLASSIFICATION', 'TRUE_COLOR'];
+ }
+ return firstOf(wanted, ids) ?? fallback;
+}
diff --git a/frontend/src/lib/map/analyzerRules.test.js b/frontend/src/lib/map/analyzerRules.test.js
new file mode 100644
index 0000000..2105775
--- /dev/null
+++ b/frontend/src/lib/map/analyzerRules.test.js
@@ -0,0 +1,243 @@
+import { describe, expect, it } from 'vitest';
+import {
+ DEFAULT_PARAMETERS, KEPT_BIT, MEASURED_BIT, describeReading, describeRecipe, describeRule, formatShare,
+ formatValue, fromDifference, newRecipe, newRule, opsFor, paintMask, productCount, recipeBands,
+ recipeCapability, recipeProblem, retarget, scaleOf, signalOf, toEngine,
+ checkState, checksSummary, describeChecks, describeOutcome, markOutcomes, newCheck, signature, withMark, withoutMark,
+} from './analyzerRules.js';
+import { changeSettings } from './changeAssist.js';
+
+const METHODS = [
+ { id: 'rules', single: false, clouds: true, sensor: 'sentinel2', frames: 4, sizes: { medium: { min_area: 2000, cleanup: 1 } }, rules: true },
+ { id: 'sar-change', single: false, clouds: false, sensor: 'sentinel1', frames: 4, sizes: { medium: { smoothing: 2 } }, smoothing_m: 45 },
+ { id: 'vessels', single: true, clouds: true, sensor: 'sentinel2', frames: 2 },
+];
+
+const recipe = (...rules) => ({ ...newRecipe(METHODS), rules });
+
+describe('a new rule', () => {
+ it('starts on the published line for what it measures', () => {
+ expect(newRule('index', 'change')).toMatchObject({ op: 'le', value: -0.25, index: 'ndvi' });
+ expect(newRule('index', 'change', { index: 'nbr' })).toMatchObject({ op: 'le', value: -0.27 });
+ expect(newRule('index', 'b', { index: 'mndwi' })).toMatchObject({ op: 'ge', value: 0 });
+ expect(newRule('radar', 'change')).toMatchObject({ op: 'moved', value: 3 });
+ // a colour distance and a ground class only make sense one way
+ expect(newRule('colour', 'b').on).toBe('change');
+ expect(newRule('class', 'change')).toMatchObject({ on: 'b', op: 'is', classes: ['water'] });
+ // a line named outright is the line it keeps
+ expect(newRule('index', 'change', { value: -0.3 })).toMatchObject({ op: 'le', value: -0.3 });
+ expect(newRule('index', 'b', { index: 'nbr', op: 'le', value: 0.1 })).toMatchObject({ op: 'le', value: 0.1 });
+ });
+
+ it('carries every field the engine model spells', () => {
+ expect(Object.keys(newRule()).sort()).toEqual(
+ ['around', 'band', 'bands', 'classes', 'index', 'measure', 'on', 'op', 'polarisation', 'upper', 'value']);
+ });
+
+ it('moves to the new quantity’s line when what or when changes, and keeps the rest', () => {
+ const loss = newRule('index', 'change');
+ expect(retarget(loss, { on: 'a' })).toMatchObject({ on: 'a', op: 'ge', value: 0.4 });
+ expect(retarget(loss, { measure: 'band' })).toMatchObject({ measure: 'band', op: 'moved', value: 0.05 });
+ const tuned = retarget(loss, { value: -0.4 });
+ expect(tuned.value).toBe(-0.4);
+ expect(retarget(tuned, { op: 'between' }).upper).toBeGreaterThan(-0.4);
+ expect(retarget(tuned, { op: 'moved' }).value).toBe(0.4);
+ expect(retarget(newRule('index', 'b'), { measure: 'class' })).toMatchObject({ on: 'b', op: 'is' });
+ });
+
+ it('offers only the comparisons that mean something', () => {
+ expect(opsFor(newRule('index', 'b')).map(([id]) => id)).toEqual(['ge', 'le', 'between']);
+ expect(opsFor(newRule('index', 'change')).map(([id]) => id)).toContain('moved');
+ expect(opsFor(newRule('class', 'b')).map(([id]) => id)).toEqual(['is', 'not']);
+ });
+});
+
+describe('values and scales', () => {
+ it('shows reflectance in percent and keeps the engine in fractions', () => {
+ const band = newRule('band', 'b');
+ expect(scaleOf(band)).toMatchObject({ factor: 100, suffix: '%', min: 0, max: 100 });
+ expect(formatValue(band, 0.253)).toBe('25.3%');
+ expect(toEngine(band, 25.3)).toBe(0.253);
+ const change = newRule('index', 'change');
+ expect(formatValue(change, -0.312, { signed: true })).toBe('−0.31');
+ expect(formatValue(change, 0.1, { signed: true })).toBe('+0.10');
+ expect(formatValue(newRule('radar', 'b'), -4)).toBe('−4.0 dB');
+ expect(formatValue(change, null)).toBe('–');
+ });
+});
+
+describe('what a recipe reads', () => {
+ it('counts the bands and the requests its rules cost', () => {
+ const built = recipe(newRule('index', 'change', { index: 'bsi' }), newRule('band', 'b', { band: 'B12' }));
+ expect(recipeBands(built)).toEqual(['B02', 'B04', 'B08', 'B11', 'B12']);
+ expect(productCount(built)).toBe(2);
+ expect(recipeCapability(built, METHODS)).toMatchObject({ single: false, sensor: 'sentinel2', clouds: true, frames: 6 });
+ });
+
+ it('reads one date when every rule is on B, and radar when a rule is', () => {
+ const present = recipe(newRule('band', 'b'));
+ expect(recipeCapability(present, METHODS)).toMatchObject({ single: true, frames: 2 });
+ const radar = recipe(newRule('radar', 'change'));
+ expect(recipeCapability(radar, METHODS)).toMatchObject({
+ sensor: 'sentinel1', clouds: false, smoothing_m: 45, sizes: { medium: { smoothing: 2 } } });
+ // a built-in keeps what the catalogue says of its method
+ expect(recipeCapability({ method: 'vessels' }, METHODS)).toBe(METHODS[2]);
+ });
+
+ it('says why it cannot run before the engine has to', () => {
+ expect(recipeProblem(recipe())).toMatch(/Add a rule/);
+ expect(recipeProblem(recipe(newRule('index', 'change'), newRule('radar', 'change')))).toMatch(/two satellites/);
+ expect(recipeProblem(recipe({ ...newRule('nd', 'b'), bands: ['B08', 'B08'] }))).toMatch(/two different bands/);
+ const wide = recipe(...['B01', 'B03', 'B05', 'B07'].map((first, i) => newRule('nd', 'b', { bands: [first, ['B02', 'B04', 'B06', 'B8A'][i]] })));
+ expect(recipeProblem(wide, { max_bands: 6 })).toMatch(/at most 6 bands/);
+ expect(recipeProblem(recipe(newRule()))).toBe('');
+ });
+
+ it('ranks by the first rule that measures something', () => {
+ expect(signalOf(recipe(newRule('class', 'b'), newRule('index', 'change')))).toBe(1);
+ expect(signalOf(recipe(newRule('class', 'b')))).toBe(-1);
+ });
+});
+
+describe('the words', () => {
+ it('reads each rule as a clause', () => {
+ expect(describeRule(newRule('index', 'change'))).toBe('NDVI dropped by 0.25 or more');
+ expect(describeRule(newRule('index', 'change', { index: 'mndwi' }))).toBe('MNDWI rose by 0.25 or more');
+ expect(describeRule(newRule('index', 'a'))).toBe('NDVI on A at least 0.40');
+ expect(describeRule(newRule('band', 'b', { band: 'B12' }))).toBe('B12 (short-wave 2.2 µm) on B at least 25.0%');
+ expect(describeRule({ ...newRule('band', 'b'), around: 150, value: 0.08 }))
+ .toBe('B08 (near infrared) on B at least +8.0% against the ground within 150 m');
+ expect(describeRule({ ...newRule('class', 'b'), classes: ['water', 'bare'], op: 'not' }))
+ .toBe('ground on B is not water or bare ground');
+ expect(describeRule(newRule('nd', 'b', { bands: ['B8A', 'B11'] }))).toMatch(/^NDMI on B/);
+ expect(describeRule(newRule('radar', 'change'))).toBe('VV moved by 3.0 dB or more either way');
+ });
+
+ it('reads the whole analyzer as one sentence', () => {
+ const built = recipe(newRule('index', 'change'), newRule('index', 'a'));
+ expect(describeRecipe(built)).toBe('Keeps ground where NDVI dropped by 0.25 or more and NDVI on A at least 0.40, outside cloud.');
+ expect(describeRecipe({ ...built, match: 'any' })).toMatch(/or NDVI on A/);
+ });
+
+ it('words a candidate from its signal rule', () => {
+ const built = recipe(newRule('class', 'b'), newRule('index', 'change'));
+ expect(describeReading(built, { before: 0.81, after: 0.12, signed: -0.69 })).toBe('NDVI 0.81 → 0.12 (−0.69)');
+ expect(describeReading(recipe(newRule('band', 'b')), { value: 0.31 })).toBe('B08 (near infrared) 31.0%');
+ expect(describeReading(recipe(newRule('class', 'b')), { value: 1 })).toBe('');
+ });
+
+ it('prints the funnel’s shares without false precision', () => {
+ expect(formatShare(0)).toBe('0 %');
+ expect(formatShare(0.0004)).toBe('< 0.1 %');
+ expect(formatShare(0.0123)).toBe('1.2 %');
+ expect(formatShare(0.5)).toBe('50 %');
+ });
+});
+
+describe('from Difference', () => {
+ it('turns an index reading into the same rule, cleanup and sky', () => {
+ const settings = changeSettings({ method: 'index', index: 'nbr', sensitivity: 50, classes: ['loss'],
+ min_area: 400, cleanup: 2, smoothing: 4, ignore_clouds: true, ignore_shadows: true, cloud_margin: 50 });
+ const built = fromDifference(settings);
+ expect(built.method).toBe('rules');
+ expect(built.rules[0]).toMatchObject({ measure: 'index', index: 'nbr', on: 'change', op: 'le' });
+ expect(built.rules[0].value).toBeLessThan(0);
+ expect(built.parameters).toMatchObject({ min_area: 400, cleanup: 2, smoothing: 3, ignore_clouds: true, cloud_margin: 5 });
+ expect(built.name).toBe('NBR: Burnt');
+ expect(fromDifference({ ...settings, classes: ['gain', 'loss', 'changed'] }).rules[0].op).toBe('moved');
+ expect(Object.keys(built.parameters).sort()).toEqual(Object.keys(DEFAULT_PARAMETERS).sort());
+ });
+});
+
+describe('the preview mask', () => {
+ it('paints each shown rule in its colour and a hovered one alone', () => {
+ const bits = new Uint8Array([0, 1 << MEASURED_BIT, 0b1 | (1 << MEASURED_BIT), 0b11 | (1 << KEPT_BIT)]);
+ const colours = ['#ff0000', '#00ff00'];
+ const both = paintMask(bits, { shown: [true, true], colours });
+ expect([...both.slice(0, 4)]).toEqual([0, 0, 0, 0]);
+ expect([...both.slice(4, 8)]).toEqual([0, 0, 0, 0]); // measured, nothing passed
+ expect([...both.slice(8, 11)]).toEqual([255, 0, 0]);
+ expect([...both.slice(12, 15)]).toEqual([0, 255, 0]); // the later rule on top
+ const first = paintMask(bits, { shown: [true, false], colours });
+ expect([...first.slice(12, 15)]).toEqual([255, 0, 0]);
+ const hovered = paintMask(bits, { shown: [true, true], hover: 0, colours });
+ expect(hovered[15]).toBeGreaterThan(both[15]);
+ expect([...hovered.slice(12, 15)]).toEqual([255, 0, 0]);
+ });
+});
+
+describe('layers', () => {
+ it('suggests the layer that shows what a rule reads, among those on offer', async () => {
+ const { suggestedLayer } = await import('./analyzerRules.js');
+ const offered = ['TRUE_COLOR', 'FALSE_COLOR', 'SWIR', 'NDVI'].map((id) => ({ id }));
+ expect(suggestedLayer(newRule('index', 'change'), offered)).toBe('NDVI');
+ expect(suggestedLayer(newRule('index', 'change', { index: 'nbr' }), offered)).toBe('SWIR');
+ expect(suggestedLayer(newRule('index', 'b', { index: 'mndwi' }), offered)).toBe('FALSE_COLOR');
+ expect(suggestedLayer(newRule('band', 'b', { band: 'B12' }), offered)).toBe('SWIR');
+ expect(suggestedLayer(newRule('colour', 'change'), offered)).toBe('TRUE_COLOR');
+ expect(suggestedLayer(newRule('class', 'b'), offered)).toBe('TRUE_COLOR');
+ expect(suggestedLayer(newRule('index', 'b', { index: 'mndwi' }), [...offered, { id: 'NDWI' }])).toBe('NDWI');
+ expect(suggestedLayer(null, offered)).toBe('TRUE_COLOR');
+ });
+});
+
+describe('checks', () => {
+ const place = { west: 2, south: 48, east: 2.02, north: 48.02 };
+ const pass = (date) => ({ provider: 'sentinel2', date, layer: 'SWIR' });
+
+ it('reads the same signature whatever order the recipe’s keys come in', () => {
+ const built = recipe(newRule('index', 'change'));
+ const reordered = { ...built, parameters: Object.fromEntries(Object.entries(built.parameters).reverse()),
+ rules: built.rules.map((rule) => Object.fromEntries(Object.entries(rule).reverse())) };
+ expect(signature(reordered)).toBe(signature(built));
+ expect(signature(built)).toMatch(/^[0-9a-z]{1,32}$/);
+ // what reads differently signs differently; the name does not read at all
+ expect(signature({ ...built, match: 'any' })).not.toBe(signature(built));
+ expect(signature({ ...built, rules: [{ ...built.rules[0], value: -0.3 }] })).not.toBe(signature(built));
+ expect(signature({ ...built, name: 'Renamed' })).toBe(signature(built));
+ });
+
+ it('keeps the view and passes it was saved on, and grows to hold a mark', () => {
+ const check = newCheck({ name: 'Here', a: pass('2023-08-08'), b: pass('2023-08-13'), bounds: place });
+ expect(check.id).toMatch(/^[a-zA-Z0-9_-]{1,48}$/);
+ expect(check).toMatchObject({ name: 'Here', marks: [], result: null, b: { date: '2023-08-13', layer: 'SWIR' } });
+ const marked = withMark({ ...check, result: { signature: 'x', count: 1, covered: [] } }, [2.05, 48.01], 'empty');
+ expect(marked.marks).toEqual([{ point: [2.05, 48.01], expect: 'empty' }]);
+ expect(marked.bounds.east).toBeGreaterThan(2.05);
+ expect(marked.result).toBe(null); // it answered for the marks it had
+ expect(withoutMark(marked, 0).marks).toEqual([]);
+ });
+
+ it('says where each check stands, and when its answer is out of date', () => {
+ const built = recipe(newRule('index', 'change'));
+ const current = signature(built);
+ const base = { ...newCheck({ name: 'Here', a: pass('2023-08-08'), b: pass('2023-08-13'), bounds: place }),
+ marks: [{ point: [2.01, 48.01], expect: 'found' }, { point: [2.015, 48.01], expect: 'found' },
+ { point: [2.005, 48.005], expect: 'empty' }] };
+ const read = (covered, count = 3, sign = current) => ({ ...base, result: { signature: sign, count, covered } });
+ expect(checkState(base, current)).toBe('unrun');
+ expect(describeOutcome(base, current)).toBe('Not run yet');
+ expect(checkState(read([true, true, false]), current)).toBe('pass');
+ expect(describeOutcome(read([true, true, false]), current)).toBe('2 of 2 found · stayed empty');
+ expect(checkState(read([true, false, true]), current)).toBe('fail');
+ expect(describeOutcome(read([true, false, true]), current)).toBe('1 of 2 found · 1 of 1 flagged');
+ expect(markOutcomes(read([true, false, true]))).toEqual([true, false, false]);
+ expect(checkState(read([true, true, false], 3, 'old'), current)).toBe('stale');
+ const counted = { ...base, marks: [], result: { signature: current, count: 12, covered: [] } };
+ expect(checkState(counted, current)).toBe('counted');
+ expect(describeOutcome(counted, current)).toBe('12 candidates');
+ });
+
+ it('sums up an analyzer’s checks for the library', () => {
+ const built = recipe(newRule('index', 'change'));
+ const current = signature(built);
+ const check = (covered, sign = current) => ({ id: 'c', name: 'c', a: pass('2023-08-08'), b: pass('2023-08-13'),
+ bounds: place, marks: [{ point: [2.01, 48.01], expect: 'found' }], result: covered ? { signature: sign, count: 1, covered } : null });
+ expect(describeChecks(built)).toBe('');
+ expect(describeChecks({ ...built, checks: [check(null), check(null)] })).toBe('2 checks · not run');
+ expect(describeChecks({ ...built, checks: [check([true]), check([true])] })).toBe('2 checks · all pass');
+ expect(describeChecks({ ...built, checks: [check([true]), check([false])] })).toBe('2 checks · 1 fails');
+ expect(describeChecks({ ...built, checks: [check([true]), check([true], 'old')] })).toBe('2 checks · 1 pass');
+ expect(checksSummary({ ...built, checks: [check([true]), check(null)] })).toMatchObject({ total: 2, pass: 1, waiting: 1 });
+ });
+});
diff --git a/frontend/src/lib/map/analyzers.js b/frontend/src/lib/map/analyzers.js
index 6ad5276..9433857 100644
--- a/frontend/src/lib/map/analyzers.js
+++ b/frontend/src/lib/map/analyzers.js
@@ -1,4 +1,6 @@
/** Geographic analyzer inputs have no dependency on a screen or camera. */
+import { describeReading, isRules, readsRadar } from './analyzerRules.js';
+
export const clone = (value) => JSON.parse(JSON.stringify(value));
export function zoneMarks(zones) {
@@ -66,6 +68,16 @@ export function describeMeasure(template, measure, index = '') {
return missing ? '' : text;
}
+/**
+ * A candidate's reading in words, whatever made it: a built-in's catalogue
+ * template, or the first measured rule of an analyzer of your own.
+ */
+export function readingOf(recipe, methods, measure) {
+ if (isRules(recipe)) return describeReading(recipe, measure);
+ const method = (methods ?? []).find((entry) => entry.id === recipe?.method);
+ return describeMeasure(method?.measure, measure, recipe?.parameters?.index);
+}
+
export const STRENGTHS = { weak: 'Weak', clear: 'Clear', strong: 'Strong' };
/** Which of Small, Medium and Large the parameters are, or '' once tuned by hand. */
@@ -220,6 +232,7 @@ export function analyzerLock(entry, catalogue) {
if (!entry || !catalogue) return '';
if (catalogue.copernicus_key === false) return 'Needs a free Copernicus key';
const method = catalogue.methods?.find((candidate) => candidate.id === entry.method);
- if (method?.sensor === 'sentinel1' && !catalogue.radar_layer) return 'Needs the Sentinel-1 layer';
+ const radar = isRules(entry) ? readsRadar(entry) : method?.sensor === 'sentinel1';
+ if (radar && !catalogue.radar_layer) return 'Needs the Sentinel-1 layer';
return '';
}
diff --git a/frontend/src/lib/map/basemap.js b/frontend/src/lib/map/basemap.js
index 4346759..cc9653a 100644
--- a/frontend/src/lib/map/basemap.js
+++ b/frontend/src/lib/map/basemap.js
@@ -25,6 +25,8 @@ import { tileTemplate as nightTemplate } from './nightlights.js';
const DEFAULT_SUBDOMAINS = ['a', 'b', 'c'];
const IMAGERY = 'basemap-imagery';
+/** A second picture of the same ground, laid just over the first (`setAlternate`). */
+const ALTERNATE = 'basemap-alternate';
/**
* What can be laid over the imagery, in the order they stack — first is
@@ -179,7 +181,7 @@ export function overlaySources(overlay, params) {
}
/** Ours, so the first layer that is not is where the basemap stops. */
-const OWNED = new Set([IMAGERY, ...OVERLAYS.flatMap(overlayLayers)]);
+const OWNED = new Set([IMAGERY, ALTERNATE, ...OVERLAYS.flatMap(overlayLayers)]);
/**
* Where a provider's tiles are fetched from.
@@ -281,6 +283,9 @@ export function createBasemaps(engine, hooks = {}) {
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
+ let alternate = null; // `${providerId}@${cell}` of the second picture, when there is one
+ let alternateMetered = null;
+ let alternateOn = false;
// 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.
@@ -309,9 +314,10 @@ export function createBasemaps(engine, hooks = {}) {
}
function onSourceData(event) {
- if (!metered || event.sourceId !== IMAGERY || !event.isSourceLoaded) return;
+ if (!event.isSourceLoaded) return;
// every visible tile is in, so what the proxy counted is now final
- onMeteredTiles(metered);
+ const billed = event.sourceId === IMAGERY ? metered : event.sourceId === ALTERNATE ? alternateMetered : null;
+ if (billed) onMeteredTiles(billed);
}
map.on('sourcedata', onSourceData);
@@ -341,7 +347,8 @@ export function createBasemaps(engine, hooks = {}) {
dropTiles();
capZoom(provider);
map.addSource(IMAGERY, rasterSource(provider, providerId, cell));
- map.addLayer({ id: IMAGERY, type: 'raster', source: IMAGERY }, lowestOverlay());
+ map.addLayer({ id: IMAGERY, type: 'raster', source: IMAGERY },
+ map.getLayer(ALTERNATE) ? ALTERNATE : lowestOverlay());
live = `${providerId}@${cell}`;
if (provider.meter) {
metered = provider;
@@ -466,6 +473,44 @@ export function createBasemaps(engine, hooks = {}) {
}
},
+ /**
+ * Lay a second picture of the same ground just over the imagery, or take it
+ * off with a null provider. It is drawn transparent until `showAlternate`,
+ * so blinking between the two flips a paint property and never reloads a
+ * tile: both pictures stay loaded the whole time. A widget basemap has no
+ * tiles to lay, so it is refused.
+ */
+ setAlternate(provider, providerId, cell) {
+ const key = provider && !provider.widget ? `${providerId}@${cell}` : null;
+ if (key === alternate) return;
+ if (map.getLayer(ALTERNATE)) map.removeLayer(ALTERNATE);
+ if (map.getSource(ALTERNATE)) map.removeSource(ALTERNATE);
+ alternate = key;
+ alternateMetered = null;
+ if (!key) return;
+ map.addSource(ALTERNATE, rasterSource(provider, providerId, cell));
+ map.addLayer({
+ id: ALTERNATE,
+ type: 'raster',
+ source: ALTERNATE,
+ paint: {
+ 'raster-opacity': alternateOn ? 1 : 0,
+ 'raster-opacity-transition': { duration: 0, delay: 0 },
+ 'raster-fade-duration': 0,
+ },
+ }, lowestOverlay());
+ if (provider.meter) {
+ alternateMetered = provider;
+ onMeteredTiles(provider);
+ }
+ },
+
+ /** Show the second picture over the first, or let the first through again. */
+ showAlternate(on) {
+ alternateOn = Boolean(on);
+ if (map.getLayer(ALTERNATE)) map.setPaintProperty(ALTERNATE, 'raster-opacity', alternateOn ? 1 : 0);
+ },
+
/**
* 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.
diff --git a/frontend/src/lib/map/basemap.test.js b/frontend/src/lib/map/basemap.test.js
index 5294d20..7f52d4e 100644
--- a/frontend/src/lib/map/basemap.test.js
+++ b/frontend/src/lib/map/basemap.test.js
@@ -151,6 +151,10 @@ describe('the layers on a map', () => {
},
getLayer: (id) => layers.find((l) => l.id === id),
getLayersOrder: () => layers.map((l) => l.id),
+ setPaintProperty: (id, name, value) => {
+ const layer = layers.find((l) => l.id === id);
+ layer.paint = { ...layer.paint, [name]: value };
+ },
setMaxZoom: (...args) => calls.setMaxZoom.push(args),
on: (...args) => calls.on.push(args),
off: (...args) => calls.off.push(args),
@@ -200,6 +204,36 @@ describe('the layers on a map', () => {
});
});
+ it('lays a second picture over the first and flips it without a reload', async () => {
+ // Detect blinks pass A against pass B: both stay loaded, only the paint moves
+ await withStubbedGoogle(async ({ createBasemaps }) => {
+ const map = stubMap();
+ const onMeteredTiles = vi.fn();
+ const basemaps = createBasemaps(stubEngine(map), { onMeteredTiles });
+ basemaps.show(SENTINEL, 'sentinel2~TRUE_COLOR~2026-09-21~2026-09-21~CC100', 512);
+ basemaps.setOverlay('boundaries', true);
+ basemaps.setAlternate({ ...SENTINEL, meter: 'copernicus' }, 'sentinel2~TRUE_COLOR~2026-09-08~2026-09-08~CC100', 512);
+ const order = map.layers.map((l) => l.id);
+ expect(order.slice(0, 2)).toEqual(['basemap-imagery', 'basemap-alternate']);
+ expect(order.length).toBeGreaterThan(2); // the borders stay over both pictures
+ const second = map.sources.get('basemap-alternate');
+ expect(second.tiles[0]).toContain('2026-09-08');
+ expect(map.getLayer('basemap-alternate').paint['raster-opacity']).toBe(0);
+ expect(onMeteredTiles).toHaveBeenCalled();
+ basemaps.showAlternate(true);
+ expect(map.getLayer('basemap-alternate').paint['raster-opacity']).toBe(1);
+ basemaps.showAlternate(false);
+ basemaps.setAlternate({ ...SENTINEL, meter: 'copernicus' }, 'sentinel2~TRUE_COLOR~2026-09-08~2026-09-08~CC100', 512);
+ expect(map.sources.get('basemap-alternate')).toBe(second);
+ // a new basemap still goes under the second picture
+ basemaps.show(ESRI, ESRI.id, 256);
+ expect(map.layers.map((l) => l.id).slice(0, 2)).toEqual(['basemap-imagery', 'basemap-alternate']);
+ basemaps.setAlternate(null);
+ expect(map.getLayer('basemap-alternate')).toBe(undefined);
+ expect(map.sources.has('basemap-alternate')).toBe(false);
+ });
+ });
+
it('caps the view at what the provider can serve', async () => {
// capture sizing reads the view zoom against the provider maximum, and a
// shallower provider asked past its ceiling answers with a placard
diff --git a/frontend/src/lib/map/compareExport.js b/frontend/src/lib/map/compareExport.js
index 99050e6..2a5e44f 100644
--- a/frontend/src/lib/map/compareExport.js
+++ b/frontend/src/lib/map/compareExport.js
@@ -24,6 +24,7 @@ import {
toMercator,
} from './groundFrame.js';
import { CHANGE_PALETTES } from './changeAssist.js';
+import { fileDate } from './pictureDate.js';
const clamp = (value, min, max) => Math.min(max, Math.max(min, value));
const INK = '#f3f4f6';
@@ -33,12 +34,47 @@ 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);
+/**
+ * What an exported comparison is called: its title, then the dates of its two
+ * pictures, which say what the file shows. When neither picture is dated, the
+ * moment of the export stands in, so the name still tells two exports apart.
+ *
+ * @param {string} [title]
+ * @param {{ a?: string | null, b?: string | null }} [dates] each a day or a UTC instant
+ * @param {Date} [at]
+ */
+export function comparisonFilename(title = '', { a = null, b = null } = {}, at = new Date()) {
const stem = String(title).trim().replace(/[\\/:*?"<>|#%]+/g, ' ').replace(/\s+/g, ' ').slice(0, 80);
+ const first = fileDate(a);
+ const second = fileDate(b);
+ if (first || second) {
+ const dates = `${first || 'undated'}_${second || 'undated'}`;
+ return stem ? `${stem} ${dates}` : `compare-${dates}`;
+ }
+ const stamp = at.toISOString().replace(/[^0-9]/g, '').slice(0, 12);
return stem ? `${stem} ${stamp}` : `compare-${stamp || 'undated'}`;
}
+/**
+ * The dates a saved comparison files for its two pictures, as form fields.
+ *
+ * Two instants rather than a range: the image does not say anything happened
+ * between them. A date its provider only estimated goes with `exact: false`.
+ *
+ * @param {{ a?: object, b?: object }} dates each side's `pictureDate()` reading
+ * @returns {Array<[string, string]>}
+ */
+export function pictureDateFields(dates) {
+ const fields = [];
+ for (const side of ['a', 'b']) {
+ const picture = dates?.[side] ?? {};
+ if (!picture.imageryWhen) continue;
+ fields.push([`imagery_${side}`, picture.imageryWhen]);
+ if (picture.imageryExact === false) fields.push([`imagery_${side}_exact`, 'false']);
+ }
+ return fields;
+}
+
function canvasOf(width, height, makeCanvas) {
const canvas = makeCanvas ? makeCanvas() : document.createElement('canvas');
canvas.width = Math.max(1, Math.round(width));
diff --git a/frontend/src/lib/map/compareExport.test.js b/frontend/src/lib/map/compareExport.test.js
index 5d3ad54..e78f6e7 100644
--- a/frontend/src/lib/map/compareExport.test.js
+++ b/frontend/src/lib/map/compareExport.test.js
@@ -4,6 +4,7 @@ import {
canvasBlob,
captureProjection,
comparisonFilename,
+ pictureDateFields,
composeComparison,
scaleBarLength,
} from './compareExport.js';
@@ -211,10 +212,28 @@ describe('comparison export', () => {
expect(scaleBarLength(3.7, 120).metres).toBe(500);
});
- it('names the file after the comparison and a stable UTC minute', () => {
+ it('names the file after the comparison and the dates of its two pictures', () => {
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');
+ const dates = { a: '2024-05-03', b: '2026-09-02T05:42:10Z' };
+ expect(comparisonFilename('Harbour', dates, at)).toBe('Harbour 2024-05-03_2026-09-02T0542Z');
+ expect(comparisonFilename('', dates, at)).toBe('compare-2024-05-03_2026-09-02T0542Z');
+ expect(comparisonFilename('', { b: '2026-09-02' }, at)).toBe('compare-undated_2026-09-02');
+ });
+
+ it('files each dated picture, and says which date was only estimated', () => {
+ expect(pictureDateFields({
+ a: { imageryWhen: '2024-05-03', imageryExact: false },
+ b: { imageryWhen: '2026-09-02T05:42:10Z', imageryExact: true },
+ })).toEqual([
+ ['imagery_a', '2024-05-03'], ['imagery_a_exact', 'false'], ['imagery_b', '2026-09-02T05:42:10Z'],
+ ]);
+ expect(pictureDateFields({ a: { imageryWhen: null }, b: {} })).toEqual([]);
+ });
+
+ it('falls back to a stable UTC minute when neither picture is dated', () => {
+ 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');
});
});
diff --git a/frontend/src/lib/map/contextMenu.js b/frontend/src/lib/map/contextMenu.js
index 828acdd..28ca509 100644
--- a/frontend/src/lib/map/contextMenu.js
+++ b/frontend/src/lib/map/contextMenu.js
@@ -12,6 +12,7 @@
*/
import { COORD_FORMATS, formatCoords } from '../coords.js';
import { mapLinks } from '../maplinks.js';
+import { TOOL_LABELS } from '../workspaces.js';
const FORMAT_LABELS = { dd: 'DD', dms: 'DMS', mgrs: 'MGRS' };
@@ -36,6 +37,7 @@ export function copyRows(lat, lon, preferred = 'dd') {
export const ACTIONS = [
{ id: 'lookup', label: 'What is here?', icon: 'search' },
{ id: 'place', label: 'Save place here…', icon: 'pin' },
+ { id: 'candidate', label: 'Add candidate here', icon: 'plus' },
{ id: 'measure', label: 'Measure from here', icon: 'ruler' },
{ id: 'sky', label: 'Sun and moon from here', icon: 'sun' },
{ id: 'history', label: 'Imagery history here', icon: 'clock' },
@@ -45,15 +47,27 @@ export const ACTIONS = [
/**
* The acts a tool can actually perform, in the order above.
*
- * Satellite offers all of them; Compare has no sun panel and no measure rail,
- * so it asks for the subset it can honour rather than showing rows that do
- * nothing. The order stays the list's, not the caller's, so the menu reads the
- * same wherever it opens.
+ * Satellite has no run to add a candidate to, Compare has no sun panel and no
+ * measure rail, and Detect has neither the sun nor the imagery history, so each
+ * asks for the subset it can honour rather than showing rows that do nothing.
+ * The order stays the list's, not the caller's, so the menu reads the same
+ * wherever it opens.
*/
export function actionsFor(ids) {
return ACTIONS.filter((action) => ids.includes(action.id));
}
+/** The app's map tabs, each able to open on a point another one was showing. */
+export const MAP_TOOLS = ['satellite', 'compare', 'detect'];
+
+/**
+ * The other map tabs a point can be opened in, under their tabs' own names:
+ * the first rows of Open in…, above the maps outside the app.
+ */
+export function otherMapTools(current) {
+ return MAP_TOOLS.filter((id) => id !== current).map((id) => ({ id, label: TOOL_LABELS[id] }));
+}
+
/** The external maps, opened on the clicked point at the current zoom. */
export function openRows(lat, lon, zoom) {
const round = (value) => Number(value.toFixed(6));
diff --git a/frontend/src/lib/map/contextMenu.test.js b/frontend/src/lib/map/contextMenu.test.js
index 97fee8b..d9ce936 100644
--- a/frontend/src/lib/map/contextMenu.test.js
+++ b/frontend/src/lib/map/contextMenu.test.js
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest';
-import { ACTIONS, actionsFor, copyRows, nextFocus, openRows, placeMenu, placeSubmenu } from './contextMenu.js';
+import { ACTIONS, actionsFor, copyRows, nextFocus, openRows, otherMapTools, placeMenu, placeSubmenu } from './contextMenu.js';
describe('copying the point', () => {
it('offers every format the app writes, the analyst’s own first', () => {
@@ -25,6 +25,7 @@ describe('what the menu offers', () => {
expect(ACTIONS.map((action) => action.id)).toEqual([
'lookup',
'place',
+ 'candidate',
'measure',
'sky',
'history',
@@ -42,6 +43,12 @@ describe('what the menu offers', () => {
expect(actionsFor(['nothing-here'])).toEqual([]);
});
+ it('opens the point in the other map tabs, under the names their tabs show', () => {
+ expect(otherMapTools('satellite')).toEqual([{ id: 'compare', label: 'Compare' }, { id: 'detect', label: 'Detect' }]);
+ expect(otherMapTools('detect').map((tool) => tool.id)).toEqual(['satellite', 'compare']);
+ expect(otherMapTools('compare').map((tool) => tool.label)).toEqual(['Satellite', 'Detect']);
+ });
+
it('opens the external maps on the clicked point, at the current zoom', () => {
const links = openRows(48.85837123456, 2.29448123456, 18);
const google = links.find((link) => link.id === 'google');
diff --git a/frontend/src/lib/map/detectReview.js b/frontend/src/lib/map/detectReview.js
index bbc134c..1d9fe9f 100644
--- a/frontend/src/lib/map/detectReview.js
+++ b/frontend/src/lib/map/detectReview.js
@@ -1,3 +1,5 @@
+import { orientedExtent } from '../measure.js';
+
export function pinDefaults(candidate, single) {
return {
title: `${candidate.phenomenon} · ${candidate.coordinates[1].toFixed(4)}, ${candidate.coordinates[0].toFixed(4)}`.slice(0, 120),
@@ -5,6 +7,56 @@ export function pinDefaults(candidate, single) {
};
}
+/**
+ * How big a candidate is: the long and short sides of its footprint, in metres,
+ * turned to fit it. A ship on the diagonal is measured along its hull, where the
+ * box squared to north would call it wider than it is long. A result older than
+ * footprints is measured on its box; a manual point has nothing to measure.
+ */
+export function candidateSize(candidate) {
+ const [west, south, east, north] = candidate?.bbox ?? [];
+ const shape = candidate?.geometry ?? (candidate?.bbox
+ ? { type: 'Polygon', coordinates: [[[west, south], [east, south], [east, north], [west, north]]] }
+ : null);
+ if (!shape || shape.type === 'Point') return null;
+ const polygons = shape.type === 'Polygon' ? [shape.coordinates] : shape.coordinates;
+ return orientedExtent(polygons.flatMap((polygon) => polygon[0] ?? []).map(([lon, lat]) => ({ lat, lon })));
+}
+
+/**
+ * The review queue in the order asked. The run already lists it strongest
+ * first; largest first goes by length, so the big hulls come up before the
+ * skiffs, and a manual point, which has no outline, by its one pixel. Equal
+ * sizes keep the run's order.
+ */
+export function orderCandidates(rows, order = 'strength') {
+ if (order !== 'size') return rows;
+ const key = (row) => candidateSize(row)?.length ?? Math.sqrt(row.area || 0);
+ return rows.map((row) => [key(row), row]).sort((a, b) => b[0] - a[0]).map(([, row]) => row);
+}
+
+/**
+ * The two passes a candidate was read between: its own, else its area's, else
+ * the run's. A detector that reads one pass has the same picture twice.
+ */
+export function candidatePair(candidate, run) {
+ const ready = (pair) => pair.status === 'ready';
+ const area = run?.area_runs?.find((pair) => ready(pair) && pair.area_id === candidate?.area_id)
+ ?? run?.area_runs?.find(ready);
+ return {
+ a: candidate?.sources?.a ?? area?.a ?? run?.input?.a ?? null,
+ b: candidate?.sources?.b ?? area?.b ?? run?.input?.b ?? null,
+ };
+}
+
+/** Where a blink is worth having: two dated passes of one Copernicus archive, not one pass twice. */
+export function blinkable(pair) {
+ const { a, b } = pair ?? {};
+ if (!a?.date || !b?.date || a.provider !== b.provider) return false;
+ if (b.provider !== 'sentinel2' && b.provider !== 'sentinel1') return false;
+ return a.date !== b.date || (a.time ?? '') !== (b.time ?? '');
+}
+
export function candidatePaths(geometry, project) {
if (!geometry || geometry.type === 'Point') return '';
const polygons = geometry.type === 'Polygon' ? [geometry.coordinates] : geometry.coordinates;
diff --git a/frontend/src/lib/map/detectReview.test.js b/frontend/src/lib/map/detectReview.test.js
index 088d21c..20cdaf9 100644
--- a/frontend/src/lib/map/detectReview.test.js
+++ b/frontend/src/lib/map/detectReview.test.js
@@ -1,5 +1,7 @@
import { describe, expect, it } from 'vitest';
-import { HIGH_RESOLUTION, candidatePaths, comparePairFor, pinDefaults } from './detectReview.js';
+import {
+ HIGH_RESOLUTION, blinkable, candidatePair, candidatePaths, candidateSize, comparePairFor, orderCandidates, pinDefaults,
+} from './detectReview.js';
const candidate = { phenomenon: 'Change', coordinates: [2, 48], geometry: { type: 'Polygon', coordinates: [] } };
describe('Detect review', () => {
@@ -17,6 +19,77 @@ describe('Detect review', () => {
});
});
+describe('how big a candidate is', () => {
+ // Pixels about 9.2 m across at 14.8° N: a hull of five of them on the diagonal.
+ const step = 0.0000858;
+ const pixel = (i) => [[[42.95 + i * step, 14.8 + i * step], [42.95 + (i + 1) * step, 14.8 + i * step],
+ [42.95 + (i + 1) * step, 14.8 + (i + 1) * step], [42.95 + i * step, 14.8 + (i + 1) * step],
+ [42.95 + i * step, 14.8 + i * step]]];
+ const diagonal = { type: 'MultiPolygon', coordinates: [0, 1, 2, 3, 4].map(pixel) };
+
+ it('measures a footprint along its hull rather than its north-up box', () => {
+ const { length, width } = candidateSize({ geometry: diagonal });
+ // five pixels corner to corner, and one pixel's diagonal across
+ expect(length).toBeGreaterThan(60);
+ expect(length).toBeLessThan(70);
+ expect(width).toBeGreaterThan(12);
+ expect(width).toBeLessThan(15);
+ });
+
+ it('falls back to the box of a result older than footprints, and has nothing for a point', () => {
+ const boxed = candidateSize({ bbox: [2, 48, 2.001, 48.001] });
+ expect(boxed.length).toBeCloseTo(111.3, 0);
+ expect(boxed.width).toBeCloseTo(74.5, 0);
+ expect(candidateSize({ geometry: { type: 'Point', coordinates: [2, 48] }, bbox: [2, 48, 2.001, 48.001] })).toBe(null);
+ expect(candidateSize(undefined)).toBe(null);
+ });
+
+ it('walks the queue largest first when asked, keeping the run order otherwise', () => {
+ const rows = [
+ { id: 'strong-small', geometry: { type: 'MultiPolygon', coordinates: [pixel(0)] }, area: 85 },
+ { id: 'point', geometry: { type: 'Point', coordinates: [2, 48] }, area: 85 },
+ { id: 'weak-long', geometry: diagonal, area: 425 },
+ ];
+ expect(orderCandidates(rows)).toBe(rows);
+ expect(orderCandidates(rows, 'size').map((row) => row.id)).toEqual(['weak-long', 'strong-small', 'point']);
+ expect(rows.map((row) => row.id)).toEqual(['strong-small', 'point', 'weak-long']);
+ });
+});
+
+describe('the two passes behind a candidate', () => {
+ const optical = (date) => ({ provider: 'sentinel2', date, layer: 'TRUE_COLOR', maxcc: 30 });
+ const radar = (date, time) => ({ provider: 'sentinel1', date, time });
+ const run = {
+ input: { a: optical('2026-01-01'), b: optical('2026-01-09') },
+ area_runs: [
+ { area_id: 'north', status: 'failed', a: optical('2026-02-01'), b: optical('2026-02-09') },
+ { area_id: 'south', status: 'ready', a: optical('2026-03-01'), b: optical('2026-03-09') },
+ { area_id: 'east', status: 'ready', a: optical('2026-04-01'), b: optical('2026-04-09') },
+ ],
+ };
+
+ it('reads the candidate’s own pair, then its area’s, then the run’s', () => {
+ const own = { a: optical('2026-05-01'), b: optical('2026-05-11') };
+ expect(candidatePair({ sources: own, area_id: 'east' }, run)).toEqual(own);
+ expect(candidatePair({ area_id: 'east' }, run).b.date).toBe('2026-04-09');
+ // an area that failed has no pair to lend, so the first one read does
+ expect(candidatePair({ area_id: 'north' }, run).a.date).toBe('2026-03-01');
+ expect(candidatePair(null, { input: run.input })).toEqual(run.input);
+ });
+
+ it('blinks two dated passes of one archive, never one pass twice', () => {
+ expect(blinkable({ a: optical('2026-09-08'), b: optical('2026-09-21') })).toBe(true);
+ expect(blinkable({ a: radar('2026-09-10', '02:06:40'), b: radar('2026-09-22', '02:06:41') })).toBe(true);
+ // one day, two radar passes of the day
+ expect(blinkable({ a: radar('2026-09-22', '02:06:41'), b: radar('2026-09-22', '14:10:02') })).toBe(true);
+ // a detector that reads one pass
+ expect(blinkable({ a: optical('2026-09-21'), b: optical('2026-09-21') })).toBe(false);
+ expect(blinkable({ a: optical('2026-09-08'), b: radar('2026-09-21', '02:06:41') })).toBe(false);
+ expect(blinkable({ a: { provider: 'esri-wayback', release: 1 }, b: { provider: 'esri-wayback', release: 2 } })).toBe(false);
+ expect(blinkable({ a: null, b: optical('2026-09-21') })).toBe(false);
+ });
+});
+
describe('a candidate opened in Compare', () => {
const found = (sources, extra = {}) => ({ phenomenon: 'Burn scar', coordinates: [44.1, 15.3], sources, ...extra });
const optical = (date) => ({ provider: 'sentinel2', date, layer: 'TRUE_COLOR', maxcc: 30 });
diff --git a/frontend/src/lib/map/engine.js b/frontend/src/lib/map/engine.js
index d8b373c..5276b43 100644
--- a/frontend/src/lib/map/engine.js
+++ b/frontend/src/lib/map/engine.js
@@ -10,6 +10,7 @@
* Three of the engine's own defaults are turned off on purpose, and each one is
* a gesture the tool already owns: right-drag flags a grid cell, shift-drag and
* middle-drag turn the map, and the view is flat until the 3D map earns a pitch.
+ * The keyboard turn is the tool's too, so the engine's is switched off below.
*/
// `MapLibreMap` rather than the `Map` alias: shadowing the global here is
// exactly the sort of thing that reads fine until someone needs a Map.
@@ -127,6 +128,10 @@ export async function createMapEngine(container, { view, imperial = false } = {}
'bottom-left'
);
map.scrollZoom.setWheelZoomRate(WHEEL_ZOOM_RATE);
+ // Shift and an arrow turn the map from the window (lib/map/gestures.js), a
+ // whole step at a time; the engine's own turn would add a second one when
+ // the map has focus. The bare arrows still pan.
+ map.keyboard.disableRotation();
// A source cannot be added before the style is up, and `basemap.js` adds one
// as soon as this returns.
await map.once('load');
diff --git a/frontend/src/lib/map/facade.js b/frontend/src/lib/map/facade.js
index ac170ba..ee46caf 100644
--- a/frontend/src/lib/map/facade.js
+++ b/frontend/src/lib/map/facade.js
@@ -209,8 +209,16 @@ export function mapFacade(map, container) {
getZoom: () => viewZoom(map.getZoom()),
setView: ({ lat, lon }, zoom) => map.jumpTo({ center: [lon, lat], zoom: engineZoom(zoom) }),
+ /**
+ * A whole camera in one jump, turn included: one move and one settle, where
+ * `setView` then `setBearing` would settle once on the old heading first.
+ */
+ setCamera: ({ lat, lon, zoom, bearing = 0 }) =>
+ map.jumpTo({ center: [lon, lat], zoom: engineZoom(zoom), bearing: -normalizeBearing(bearing) }),
setZoom: (zoom) => map.setZoom(engineZoom(zoom)),
setBearing: (deg) => map.setBearing(-normalizeBearing(deg)),
+ /** How deep this map goes right now, in app zoom: its basemap's ceiling. */
+ maxZoom: () => viewZoom(map.getMaxZoom()),
/** Never animated: a rotation pans the map once per pointer move. */
panBy: (dx, dy) => map.panBy([dx, dy], { duration: 0 }),
fitBounds,
diff --git a/frontend/src/lib/map/facade.test.js b/frontend/src/lib/map/facade.test.js
index 52304c0..ab322e4 100644
--- a/frontend/src/lib/map/facade.test.js
+++ b/frontend/src/lib/map/facade.test.js
@@ -154,6 +154,21 @@ describe('the map façade keeps the engine on its own side', () => {
expect(map.calls.setZoom).toEqual([[17]]);
});
+ it('takes a whole camera in one jump, the turn in the engine’s sign', () => {
+ const map = stubMap();
+ const facade = mapFacade(map);
+ facade.setCamera({ lat: 1, lon: 2, zoom: 16, bearing: 37 });
+ facade.setCamera({ lat: 3, lon: 4, zoom: 12 });
+ expect(map.calls.jumpTo).toEqual([
+ [{ center: [2, 1], zoom: 15, bearing: -37 }],
+ [{ center: [4, 3], zoom: 11, bearing: -0 }],
+ ]);
+ });
+
+ it('reports the ceiling in app zoom', () => {
+ expect(mapFacade(stubMap({ getMaxZoom: () => 17 })).maxZoom()).toBe(18);
+ });
+
it('never animates a pan: it re-pins a grabbed point mid-gesture', () => {
const map = stubMap();
mapFacade(map).panBy(3, -7);
diff --git a/frontend/src/lib/map/gestures.js b/frontend/src/lib/map/gestures.js
index ac56385..b3a21fe 100644
--- a/frontend/src/lib/map/gestures.js
+++ b/frontend/src/lib/map/gestures.js
@@ -7,15 +7,17 @@
* gesture starts; the pointer bookkeeping and everything that touches the map
* live here, so a gesture is written once and re-aimed at the next engine once.
*
+ * The keyboard turn lives here too, so every map answers the same keys.
+ *
* Both starters take the `mousedown` that began the gesture, own it (no engine
* pan, no browser middle-click autoscroll), and track the rest on the window —
* a drag that leaves the map still finishes, which is what makes a marquee
* pulled past the edge behave.
*/
-import { dragBearing, pivotPanOffset } from '../satRotate.js';
+import { beyondGuide, keyTurn, pivotPanOffset, sweepDelta, turnBearing } from '../turn.js';
-/** px to leave the pivot before the reference spoke is fixed. */
-const ROTATE_DEADZONE = 8;
+/** px the pointer may wander and a middle press still be a click. */
+const CLICK_SLOP = 4;
/** Where in the map container an event landed. */
function containerPoint(engine, event) {
@@ -72,15 +74,19 @@ export function startRectDrag(engine, event, { ratio = null, onChange, onDone }
}
/**
- * Grab a point and turn the map around it.
+ * Grab a point and turn the map around it, like a wheel.
+ *
+ * The map turns by the angle the pointer sweeps about the grabbed point, read
+ * outside the guide circle only (`lib/turn.js`), with Ctrl laying it on whole
+ * steps. A map rotates about its centre, so after each bearing change the
+ * grabbed geographic point is panned back under where it was grabbed.
+ * `onPivot` is handed that point in container px, for the circle the tool
+ * draws there.
*
- * A map rotates about its centre, so after each bearing change the grabbed
- * geographic point is panned back under the cursor — which is what pins it
- * exactly where it was grabbed. `onPivot` is handed the grabbed point in
- * container px, for the target the tool draws there.
+ * A middle click that never moved puts north back up.
*
* @param {object} engine the façade from `engine.js`
- * @param {MouseEvent} event the middle-button mousedown that starts it
+ * @param {MouseEvent} event the mousedown that starts it
* @param {object} opts
* @param {(pivot: object) => void} [opts.onPivot]
* @param {() => void} [opts.onEnd]
@@ -91,21 +97,22 @@ export function startRotateDrag(engine, event, { onPivot, onEnd } = {}) {
const grab = containerPoint(engine, event);
const pinned = engine.containerPointToLatLng(grab); // the location held still
const startBearing = engine.camera().bearing;
- const startScreen = { x: event.clientX, y: event.clientY };
+ const pivot = { x: event.clientX, y: event.clientY };
+ const clicked = event.button === 1;
onPivot?.(grab);
- let spoke = null; // reference direction, fixed once out of the deadzone
+ let moved = false;
+ let last = null; // the last point outside the circle, null while inside
+ let swept = 0;
- const move = (moved) => {
- if (spoke === null) {
- if (Math.hypot(moved.clientX - startScreen.x, moved.clientY - startScreen.y) < ROTATE_DEADZONE) {
- return;
- }
- spoke = { x: moved.clientX, y: moved.clientY };
- return;
- }
- engine.setBearing(
- dragBearing(startBearing, startScreen, spoke, { x: moved.clientX, y: moved.clientY })
- );
+ const move = (event) => {
+ const at = { x: event.clientX, y: event.clientY };
+ if (!moved && Math.hypot(at.x - pivot.x, at.y - pivot.y) >= CLICK_SLOP) moved = true;
+ const out = beyondGuide(pivot, at);
+ const delta = out && last ? sweepDelta(pivot, last, at) : 0;
+ last = out ? at : null;
+ if (!delta) return;
+ swept += delta;
+ engine.setBearing(turnBearing(startBearing, swept, { stepped: event.ctrlKey || event.metaKey }));
const now = engine.latLngToContainerPoint(pinned);
const [dx, dy] = pivotPanOffset(grab, now);
if (dx || dy) engine.panBy(dx, dy);
@@ -114,9 +121,46 @@ export function startRotateDrag(engine, event, { onPivot, onEnd } = {}) {
const up = () => {
window.removeEventListener('mousemove', move);
window.removeEventListener('mouseup', up);
+ if (!moved && clicked) engine.setBearing(0);
onEnd?.();
};
window.addEventListener('mousemove', move);
window.addEventListener('mouseup', up);
}
+
+/**
+ * Start a turn if this press is one: the middle button, or Shift and the left
+ * one where the tool lets Shift turn. True when it started.
+ *
+ * @param {object} engine the façade from `engine.js`
+ * @param {MouseEvent} event
+ * @param {object} [opts]
+ * @param {boolean} [opts.shift] whether Shift-drag turns here
+ * @param {(pivot: object) => void} [opts.onPivot]
+ * @param {() => void} [opts.onEnd]
+ */
+export function turnFromPress(engine, event, { shift = true, onPivot, onEnd } = {}) {
+ const shiftDrag = shift && event.button === 0 && event.shiftKey;
+ if (event.button !== 1 && !shiftDrag) return false;
+ startRotateDrag(engine, event, { onPivot, onEnd });
+ return true;
+}
+
+/**
+ * Turn the map from the keyboard: Shift and an arrow (`keyTurn`). True when the
+ * key was a turn and has been spent. A key a focused control already took, or
+ * one typed into a field, is left alone.
+ *
+ * @param {object} engine the façade from `engine.js`
+ * @param {KeyboardEvent} event
+ */
+export function turnFromKey(engine, event) {
+ if (!engine || event.defaultPrevented) return false;
+ if (event.target?.closest?.('input, textarea, select, [contenteditable="true"]')) return false;
+ const turn = keyTurn(event, engine.camera().bearing);
+ if (!turn) return false;
+ event.preventDefault();
+ engine.setBearing(turn.to);
+ return true;
+}
diff --git a/frontend/src/lib/map/gestures.test.js b/frontend/src/lib/map/gestures.test.js
index 28fac39..a22d152 100644
--- a/frontend/src/lib/map/gestures.test.js
+++ b/frontend/src/lib/map/gestures.test.js
@@ -1,6 +1,6 @@
// @vitest-environment happy-dom
import { afterEach, describe, expect, it, vi } from 'vitest';
-import { startRectDrag, startRotateDrag } from './gestures.js';
+import { startRectDrag, startRotateDrag, turnFromKey, turnFromPress } from './gestures.js';
/** The façade, as far as the gestures reach into it. */
function stubEngine({ bearing = 0 } = {}) {
@@ -114,24 +114,61 @@ describe('grabbing a point and turning', () => {
expect(onPivot).toHaveBeenCalledWith({ x: 200, y: 200 });
});
- it('ignores a nudge, so a click does not spin the map', () => {
- const engine = stubEngine();
+ it('holds inside the guide circle, so a press does not spin the map', () => {
+ const engine = stubEngine({ bearing: 40 });
startRotateDrag(engine, press(1, 240, 220));
- drag(244, 224); // ~5.7 px, inside the deadzone
+ drag(250, 220);
+ drag(240, 235); // a big angle about the pivot, but all inside the circle
expect(engine.bearings).toEqual([]);
});
- it('turns once out of the deadzone, taking that direction as the reference', () => {
+ it('turns by the angle swept about the grabbed point, like a wheel', () => {
const engine = stubEngine({ bearing: 30 });
startRotateDrag(engine, press(1, 240, 220));
- drag(340, 220); // leaves the deadzone: this direction is 0 of the sweep
+ drag(340, 220); // out of the circle, due east: the wheel is taken here
expect(engine.bearings).toEqual([]);
- drag(240, 320); // a quarter turn from the reference spoke
- expect(engine.bearings).toHaveLength(1);
- expect(engine.bearings[0] - 30).toBeCloseTo(90, 6);
+ drag(310.71, 290.71); // south-east
+ drag(240, 320); // due south: a quarter turn clockwise
+ expect(engine.bearings.at(-1)).toBeCloseTo(120, 1);
+ });
+
+ it('keeps turning the same way all round the circle, and past a full turn', () => {
+ // a whole clockwise circle, in eighths: every step adds, none takes back
+ const engine = stubEngine({ bearing: 10 });
+ startRotateDrag(engine, press(1, 240, 220));
+ const steps = 12;
+ for (let i = 0; i <= steps; i += 1) {
+ const a = (i / 8) * 2 * Math.PI;
+ drag(240 + 100 * Math.cos(a), 220 + 100 * Math.sin(a));
+ }
+ const swept = engine.bearings.map((b, i) => (i ? b - engine.bearings[i - 1] : 0));
+ expect(swept.slice(1).every((d) => d > 0 || d < -300)).toBe(true); // only the 360 → 0 wrap goes down
+ expect(engine.bearings.at(-1)).toBeCloseTo((10 + 540) % 360, 6); // a turn and a half
+ });
+
+ it('picks the turn up without a jump after passing through the circle', () => {
+ const engine = stubEngine({ bearing: 0 });
+ startRotateDrag(engine, press(1, 240, 220));
+ drag(340, 220);
+ drag(240, 320); // +90
+ const before = engine.bearings.at(-1);
+ drag(245, 225); // back in the middle: holds
+ drag(140, 220); // out again, due west: taken as the new start, no jump
+ expect(engine.bearings.at(-1)).toBe(before);
+ drag(240, 120); // west to north: another quarter clockwise
+ expect(engine.bearings.at(-1)).toBeCloseTo(180, 6);
});
- it('pans the grabbed location back under the cursor after every turn', () => {
+ it('lays the turn on whole steps while Ctrl is held', () => {
+ const engine = stubEngine();
+ startRotateDrag(engine, press(1, 240, 220));
+ drag(340, 220);
+ const a = (24 * Math.PI) / 180;
+ window.dispatchEvent(new window.MouseEvent('mousemove', { clientX: 240 + 100 * Math.cos(a), clientY: 220 + 100 * Math.sin(a), ctrlKey: true }));
+ expect(engine.bearings.at(-1)).toBe(30); // 24° → 30
+ });
+
+ it('pans the grabbed location back under where it was grabbed after every turn', () => {
// the map rotates about its centre, so without this the point drifts away
const engine = stubEngine();
startRotateDrag(engine, press(1, 240, 220));
@@ -140,15 +177,79 @@ describe('grabbing a point and turning', () => {
expect(engine.pans).toEqual([[6, -3]]); // what the stub projection displaced
});
- it('says when the turn is over', () => {
+ it('puts north back up on a middle click that never turned', () => {
+ const engine = stubEngine({ bearing: 75 });
+ startRotateDrag(engine, press(1, 240, 220));
+ release();
+ expect(engine.bearings).toEqual([0]);
+ });
+
+ it('leaves the bearing alone on a Shift click, or once a turn happened', () => {
+ const shift = stubEngine({ bearing: 75 });
+ startRotateDrag(shift, press(0, 240, 220));
+ release();
+ expect(shift.bearings).toEqual([]);
+ const turned = stubEngine({ bearing: 75 });
+ startRotateDrag(turned, press(1, 240, 220));
+ drag(340, 220);
+ drag(240, 320);
+ release();
+ expect(turned.bearings.at(-1)).not.toBe(0);
+ });
+
+ it('says when the turn is over, and stops listening', () => {
const onEnd = vi.fn();
- startRotateDrag(stubEngine(), press(1), { onEnd });
+ startRotateDrag(stubEngine(), press(0), { onEnd });
release();
expect(onEnd).toHaveBeenCalledTimes(1);
const engine = stubEngine();
- startRotateDrag(engine, press(1, 240, 220), {});
+ startRotateDrag(engine, press(0, 240, 220), {});
release();
drag(600, 600);
expect(engine.bearings).toEqual([]);
});
});
+
+describe('which presses turn', () => {
+ it('takes the middle button, and Shift with the left one', () => {
+ expect(turnFromPress(stubEngine(), press(1))).toBe(true);
+ release();
+ expect(turnFromPress(stubEngine(), { ...press(0), shiftKey: true })).toBe(true);
+ release();
+ });
+
+ it('leaves a plain left press, and Shift where the tool keeps it', () => {
+ expect(turnFromPress(stubEngine(), press(0))).toBe(false);
+ expect(turnFromPress(stubEngine(), { ...press(0), shiftKey: true }, { shift: false })).toBe(false);
+ expect(turnFromPress(stubEngine(), { ...press(2), shiftKey: true })).toBe(false);
+ });
+});
+
+describe('turning from the keyboard', () => {
+ const keydown = (key, init = {}) => new window.KeyboardEvent('keydown', { key, shiftKey: true, cancelable: true, ...init });
+
+ it('steps with Shift and the side arrows, and puts north up with Shift and up', () => {
+ const engine = stubEngine({ bearing: 0 });
+ const event = keydown('ArrowRight');
+ expect(turnFromKey(engine, event)).toBe(true);
+ expect(event.defaultPrevented).toBe(true);
+ expect(engine.bearings).toEqual([15]);
+ expect(turnFromKey(stubEngine({ bearing: 200 }), keydown('ArrowUp'))).toBe(true);
+ });
+
+ it('leaves a key a control already took, or one typed into a field', () => {
+ const engine = stubEngine();
+ const taken = keydown('ArrowLeft');
+ taken.preventDefault();
+ expect(turnFromKey(engine, taken)).toBe(false);
+ const input = document.createElement('input');
+ document.body.append(input);
+ const typed = keydown('ArrowLeft');
+ input.dispatchEvent(typed);
+ expect(turnFromKey(engine, typed)).toBe(false);
+ input.remove();
+ expect(turnFromKey(engine, keydown('ArrowLeft', { shiftKey: false }))).toBe(false);
+ expect(turnFromKey(null, keydown('ArrowLeft'))).toBe(false);
+ expect(engine.bearings).toEqual([]);
+ });
+});
diff --git a/frontend/src/lib/map/layerDates.js b/frontend/src/lib/map/layerDates.js
index 7cc3fdd..28cd2c0 100644
--- a/frontend/src/lib/map/layerDates.js
+++ b/frontend/src/lib/map/layerDates.js
@@ -3,14 +3,17 @@
*
* A layer's features carry a day, `date: 'YYYY-MM-DD'`, when their source dated
* them (`engine/maplayers.py`): every GeoConfirmed event, a KML placemark with a
- * TimeStamp, a GPX waypoint. The filter is a period, `{ start, end }`, either
- * bound '' for open, compared as days on the map (`addedLayer.js`) and counted
- * here.
+ * TimeStamp, a GPX waypoint. A feature that spans several days also carries its
+ * last one, `date_end`: a KML TimeSpan, or a Detect change read between two
+ * passes. The filter is a period, `{ start, end }`, either bound '' for open, and
+ * a feature is in it when the days it spans meet the period, compared on the map
+ * (`addedLayer.js`) and counted here.
*
* **Indexed once per snapshot, then asked cheaply.** A layer holds up to a
- * hundred thousand features and the strip is redrawn on every drag, so the days
- * are sorted once per group and every question after that — how many in this
- * bar, how many in this period — is two binary searches per group.
+ * hundred thousand features and the strip is redrawn on every drag, so the first
+ * and last days are sorted once per group and every question after that — how
+ * many in this bar, how many in this period — is two binary searches per group:
+ * those that start by the period's end, less those that ended before it began.
*/
const DAY_MS = 86_400_000;
@@ -38,28 +41,41 @@ export function dayLabel(iso) {
return `${date.getUTCDate()} ${MONTHS[date.getUTCMonth()]} ${date.getUTCFullYear()}`;
}
+/** The days one feature spans, both included, or null when it states none. */
+export function featureDays(properties) {
+ const start = dayNumber(properties?.date);
+ if (start === null) return null;
+ const end = dayNumber(properties?.date_end);
+ return { start, end: end !== null && end > start ? end : start };
+}
+
/**
- * Every dated feature's day, sorted per group, or null for a layer with none.
+ * Every dated feature's first and last day, sorted per group, or null for a
+ * layer with none.
*
* @param {{ features?: object[] } | null} collection
- * @returns {{ first: number, last: number, groups: Map<string, Int32Array> } | null}
+ * @returns {{ first: number, last: number,
+ * groups: Map<string, { starts: Int32Array, ends: Int32Array }> } | null}
*/
export function indexDates(collection) {
const lists = new Map();
let first = Infinity;
let last = -Infinity;
for (const feature of collection?.features ?? []) {
- const day = dayNumber(feature?.properties?.date);
- if (day === null) continue;
+ const days = featureDays(feature?.properties);
+ if (days === null) continue;
const group = feature.properties.category ?? '';
- if (!lists.has(group)) lists.set(group, []);
- lists.get(group).push(day);
- if (day < first) first = day;
- if (day > last) last = day;
+ if (!lists.has(group)) lists.set(group, { starts: [], ends: [] });
+ lists.get(group).starts.push(days.start);
+ lists.get(group).ends.push(days.end);
+ if (days.start < first) first = days.start;
+ if (days.end > last) last = days.end;
}
if (!lists.size) return null;
const groups = new Map();
- for (const [group, days] of lists) groups.set(group, Int32Array.from(days).sort());
+ for (const [group, { starts, ends }] of lists) {
+ groups.set(group, { starts: Int32Array.from(starts).sort(), ends: Int32Array.from(ends).sort() });
+ }
return { first, last, groups };
}
@@ -75,9 +91,9 @@ function lowerBound(sorted, value) {
return low;
}
-/** How many of a sorted list fall on days `from` to `to`, both included. */
-function between(sorted, from, to) {
- return lowerBound(sorted, to + 1) - lowerBound(sorted, from);
+/** How many of a group's features meet days `from` to `to`, both included. */
+function between({ starts, ends }, from, to) {
+ return lowerBound(starts, to + 1) - lowerBound(ends, from);
}
/**
@@ -117,7 +133,8 @@ function steps(first, last, size) {
return out;
}
-/** How many features of the groups not switched off fall in each bar. */
+/** How many features of the groups not switched off meet each bar. A feature
+ * spanning several bars counts in each, since it may belong to any of them. */
export function histogram(index, hidden = [], edges = []) {
if (!index) return edges.map(() => 0);
const off = new Set(hidden);
@@ -157,14 +174,14 @@ export function within(index, hidden = [], period = null) {
return { total, byGroup };
}
-/** Whether one day is inside a period. An undated feature is outside any. */
-export function inPeriod(iso, period) {
+/** Whether a feature's days meet a period. An undated feature is outside any. */
+export function inPeriod(properties, period) {
if (!active(period)) return true;
- const day = dayNumber(iso);
- if (day === null) return false;
+ const days = featureDays(properties);
+ if (days === null) return false;
const from = dayNumber(period.start);
const to = dayNumber(period.end);
- return (from === null || day >= from) && (to === null || day <= to);
+ return (from === null || days.end >= from) && (to === null || days.start <= to);
}
/**
diff --git a/frontend/src/lib/map/layerDates.test.js b/frontend/src/lib/map/layerDates.test.js
index 361a6fa..4dd6ca4 100644
--- a/frontend/src/lib/map/layerDates.test.js
+++ b/frontend/src/lib/map/layerDates.test.js
@@ -121,10 +121,10 @@ describe('a period', () => {
});
it('keeps an undated feature out, and keeps everything in when there is no period', () => {
- expect(inPeriod('', { start: '2026-09-01', end: '' })).toBe(false);
- expect(inPeriod('', null)).toBe(true);
- expect(inPeriod('2026-09-05', { start: '2026-09-01', end: '2026-09-05' })).toBe(true);
- expect(inPeriod('2026-09-06', { start: '2026-09-01', end: '2026-09-05' })).toBe(false);
+ expect(inPeriod({}, { start: '2026-09-01', end: '' })).toBe(false);
+ expect(inPeriod({}, null)).toBe(true);
+ expect(inPeriod({ date: '2026-09-05' }, { start: '2026-09-01', end: '2026-09-05' })).toBe(true);
+ expect(inPeriod({ date: '2026-09-06' }, { start: '2026-09-01', end: '2026-09-05' })).toBe(false);
});
it('dragged back out to both edges is no period at all', () => {
@@ -146,3 +146,41 @@ describe('a period', () => {
});
});
});
+
+describe('a feature that spans days', () => {
+ // A change Detect read between two passes, and a KML TimeSpan: each may have
+ // happened on any day it spans, so a period meeting any of them holds it.
+ const SPANS = {
+ type: 'FeatureCollection',
+ features: [
+ { ...at('2026-09-01'), properties: { name: 'change', category: 'Detect', date: '2026-09-01', date_end: '2026-09-11' } },
+ at('2026-09-20', 'Detect'),
+ ],
+ };
+ const index = indexDates(SPANS);
+
+ it('runs the strip to the last day it spans', () => {
+ expect(isoDay(index.first)).toBe('2026-09-01');
+ expect(isoDay(index.last)).toBe('2026-09-20');
+ });
+
+ it('is in any period that meets it, and in no period past it', () => {
+ const change = SPANS.features[0].properties;
+ expect(inPeriod(change, { start: '2026-09-05', end: '2026-09-06' })).toBe(true);
+ expect(inPeriod(change, { start: '2026-09-11', end: '' })).toBe(true);
+ expect(inPeriod(change, { start: '2026-09-12', end: '' })).toBe(false);
+ expect(within(index, [], { start: '2026-09-05', end: '2026-09-06' }).total).toBe(1);
+ expect(within(index, [], { start: '2026-09-12', end: '2026-09-30' }).total).toBe(1);
+ });
+
+ it('counts in every bar it meets', () => {
+ const counts = histogram(index, [], bars(index.first, index.last));
+ expect(counts.slice(0, 11)).toEqual(Array(11).fill(1));
+ expect(counts[11]).toBe(0);
+ });
+
+ it('ignores an end that is not after its start', () => {
+ const odd = indexDates({ features: [{ ...at('2026-09-05'), properties: { category: 'x', date: '2026-09-05', date_end: '2026-09-01' } }] });
+ expect(odd.first).toBe(odd.last);
+ });
+});
diff --git a/frontend/src/lib/map/pictureDate.js b/frontend/src/lib/map/pictureDate.js
new file mode 100644
index 0000000..287bb84
--- /dev/null
+++ b/frontend/src/lib/map/pictureDate.js
@@ -0,0 +1,45 @@
+/**
+ * When the picture on a map surface was taken, as the case records it.
+ *
+ * A capture and a saved comparison file the date of the pixels they show. Two
+ * providers name it outright: a Sentinel-1 pass (its day and UTC time) and a
+ * pinned Sentinel-2 day. Esri and Wayback only estimate it from their metadata,
+ * so their date is kept with `exact: false`, which the Time panel shows as `~`.
+ */
+
+const DAY = /^\d{4}-\d{2}-\d{2}$/;
+const TIME = /^([01]\d|2[0-3]):[0-5]\d:[0-5]\d$/;
+
+/**
+ * @param {{ radarPass?: { date: string, time?: string } | null, pinnedDay?: string | null,
+ * estimated?: string | null }} shown
+ * @returns {{ imageryDate: string | null, imageryExact: boolean, imageryWhen: string | null }}
+ * `imageryDate` is the day, as a capture shows it; `imageryWhen` adds a radar
+ * pass's time as a UTC instant.
+ */
+export function pictureDate({ radarPass = null, pinnedDay = null, estimated = null } = {}) {
+ if (radarPass?.date && DAY.test(radarPass.date)) {
+ const when = TIME.test(radarPass.time ?? '') ? `${radarPass.date}T${radarPass.time}Z` : radarPass.date;
+ return { imageryDate: radarPass.date, imageryExact: true, imageryWhen: when };
+ }
+ if (pinnedDay && DAY.test(pinnedDay)) {
+ return { imageryDate: pinnedDay, imageryExact: true, imageryWhen: pinnedDay };
+ }
+ if (estimated && DAY.test(estimated)) {
+ return { imageryDate: estimated, imageryExact: false, imageryWhen: estimated };
+ }
+ return { imageryDate: null, imageryExact: true, imageryWhen: null };
+}
+
+/**
+ * A picture's date as a filename can carry it: the day, and a radar pass's hour
+ * and minute when it has one, since two passes can share a day. No colon, which
+ * Windows refuses.
+ *
+ * @param {string | null | undefined} when a day or a UTC instant
+ */
+export function fileDate(when) {
+ const match = /^(\d{4}-\d{2}-\d{2})(?:T(\d{2}):(\d{2}):\d{2}Z)?$/.exec(String(when ?? ''));
+ if (!match) return '';
+ return match[2] ? `${match[1]}T${match[2]}${match[3]}Z` : match[1];
+}
diff --git a/frontend/src/lib/map/pictureDate.test.js b/frontend/src/lib/map/pictureDate.test.js
new file mode 100644
index 0000000..4c6d329
--- /dev/null
+++ b/frontend/src/lib/map/pictureDate.test.js
@@ -0,0 +1,34 @@
+import { describe, expect, it } from 'vitest';
+import { fileDate, pictureDate } from './pictureDate.js';
+
+describe('the date a map picture was taken', () => {
+ it('names a radar pass to the second, and exactly', () => {
+ expect(pictureDate({ radarPass: { date: '2026-09-02', time: '05:42:10' } })).toEqual({
+ imageryDate: '2026-09-02', imageryExact: true, imageryWhen: '2026-09-02T05:42:10Z',
+ });
+ });
+
+ it('takes a pinned Sentinel-2 day as the acquisition itself', () => {
+ expect(pictureDate({ pinnedDay: '2026-08-30', estimated: '2020-01-01' })).toEqual({
+ imageryDate: '2026-08-30', imageryExact: true, imageryWhen: '2026-08-30',
+ });
+ });
+
+ it('keeps a provider estimate, marked as one', () => {
+ expect(pictureDate({ estimated: '2024-05-03' })).toMatchObject({ imageryDate: '2024-05-03', imageryExact: false });
+ });
+
+ it('states nothing it was not told', () => {
+ expect(pictureDate({})).toEqual({ imageryDate: null, imageryExact: true, imageryWhen: null });
+ expect(pictureDate({ estimated: 'last spring' }).imageryDate).toBeNull();
+ });
+});
+
+describe('a picture date in a filename', () => {
+ it('keeps the day, and a radar pass hour without a colon', () => {
+ expect(fileDate('2024-05-03')).toBe('2024-05-03');
+ expect(fileDate('2026-09-02T05:42:10Z')).toBe('2026-09-02T0542Z');
+ expect(fileDate('')).toBe('');
+ expect(fileDate(null)).toBe('');
+ });
+});
diff --git a/frontend/src/lib/map/sharedView.js b/frontend/src/lib/map/sharedView.js
new file mode 100644
index 0000000..5003988
--- /dev/null
+++ b/frontend/src/lib/map/sharedView.js
@@ -0,0 +1,105 @@
+/**
+ * One camera for the map tabs of a window.
+ *
+ * Satellite, Compare and Detect each keep a map of their own, and each stays
+ * mounted, hidden, while another tab shows. With the preference on (Settings →
+ * General, on out of the box) they look at the same ground: a map writes the
+ * window's camera each time it comes to rest, and a map tab that shows again
+ * takes that camera before anything else happens on it.
+ *
+ * A hidden map never moves. That is what keeps this quiet. Nothing copies a
+ * camera frame by frame (that is `cameraLink.js`, for the two maps Compare
+ * shows at once), a hidden map loads no tiles for ground nobody is looking
+ * at, and nothing a map reads on a move, a Sentinel date or a list of passes,
+ * goes out for a tab nobody opened. A map can still come to rest while
+ * hidden: a pan's glide outlasts a quick switch of tab, and a framing handed
+ * over from the Timeline lands once its places are read. That rest is where
+ * the analyst left it, so it is written, and the tab on screen follows it.
+ *
+ * The camera says which tab wrote it. A tab never takes back its own: nobody
+ * moved since, so it is already there, and a tab re-reading what it has just
+ * written in the middle of its own settling would fight it.
+ *
+ * **A map lands as deep as it goes.** Satellite at z20 on a provider that has
+ * the pixels, Detect on imagery that stops at z18: Detect lands short, and
+ * that landing is not news. Writing it back would pull Satellite out to 18 on
+ * the way back. So a settle on the shared spot at this map's own ceiling
+ * leaves the camera alone; a zoom the analyst makes there is still theirs.
+ *
+ * The chain in Satellite (`link.js`) carries this camera to other windows and
+ * to the extension's map panels while the preference is on, so every tab of
+ * the window follows them, not only Satellite.
+ */
+import { readable, samePlace, sameView } from './link.js';
+
+/**
+ * @param {string} tool this tab's id: 'satellite' | 'compare' | 'detect'
+ * @param {{ state: { tool: string, mapView: object | null }, enabled: () => boolean }} options
+ * `state` holds the window's camera (`uiState.mapView`) and which tab is on
+ * screen; `enabled` reads the preference.
+ */
+export function shareView(tool, { state, enabled }) {
+ /**
+ * This tab's map came to rest: that is where the window looks now, unless
+ * it is the shared camera as deep as this map goes.
+ *
+ * Kept with the preference off as well, so switching it on lines the tabs
+ * up on the last ground looked at rather than on an old one.
+ */
+ function settled(camera, ceiling = Infinity) {
+ if (!readable(camera)) return;
+ const shared = state.mapView;
+ if (
+ readable(shared) &&
+ samePlace(camera, shared) &&
+ Math.round(camera.zoom) === Math.round(Math.min(shared.zoom, ceiling))
+ ) {
+ return;
+ }
+ state.mapView = {
+ lat: camera.lat,
+ lon: camera.lon,
+ zoom: camera.zoom,
+ bearing: camera.bearing ?? 0,
+ by: tool,
+ };
+ }
+
+ return {
+ settled,
+
+ /**
+ * Where this tab should go now that it shows: the window's camera, when
+ * another map or the chain put it somewhere this one is not. Null to stay.
+ *
+ * A window with no camera yet takes this tab's. A map opened from its
+ * address or on the home view has not moved, so nothing has settled, and
+ * the next tab would otherwise open somewhere this one is not.
+ */
+ pending(camera) {
+ if (state.tool !== tool) return null;
+ const shared = state.mapView;
+ if (!readable(shared)) {
+ settled(camera);
+ return null;
+ }
+ if (!enabled() || shared.by === tool) return null;
+ if (camera && sameView(camera, shared)) return null;
+ return shared;
+ },
+
+ /** Where a map built now opens: the window's camera, or null for its own. */
+ opening() {
+ return enabled() && readable(state.mapView) ? state.mapView : null;
+ },
+
+ /**
+ * Whether another map tab, or the chain, left the window's camera. A tab
+ * arriving then follows it rather than framing ground of its own.
+ */
+ ledElsewhere() {
+ const shared = state.mapView;
+ return enabled() && readable(shared) && shared.by !== tool;
+ },
+ };
+}
diff --git a/frontend/src/lib/map/sharedView.test.js b/frontend/src/lib/map/sharedView.test.js
new file mode 100644
index 0000000..af8364c
--- /dev/null
+++ b/frontend/src/lib/map/sharedView.test.js
@@ -0,0 +1,122 @@
+import { describe, expect, it } from 'vitest';
+import { shareView } from './sharedView.js';
+
+const PLACE = { lat: 12.7615, lon: 43.6571, zoom: 16, bearing: 30 };
+
+function appWindow(tool = 'satellite', { on = true, mapView = null } = {}) {
+ const state = { tool, mapView };
+ const prefs = { on };
+ return { state, prefs, share: (name) => shareView(name, { state, enabled: () => prefs.on }) };
+}
+
+describe('writing the window camera', () => {
+ it('takes the settle of the map on screen, and says which tab wrote it', () => {
+ const { state, share } = appWindow('detect');
+ share('detect').settled(PLACE);
+ expect(state.mapView).toEqual({ ...PLACE, by: 'detect' });
+ });
+
+ it('takes the rest of a map a tab switch hid mid-glide', () => {
+ const { state, share } = appWindow('satellite');
+ share('compare').settled(PLACE);
+ expect(state.mapView).toEqual({ ...PLACE, by: 'compare' });
+ });
+
+ it('keeps the last ground looked at with the preference off, for when it comes back on', () => {
+ const { state, share } = appWindow('satellite', { on: false });
+ share('satellite').settled(PLACE);
+ expect(state.mapView).toEqual({ ...PLACE, by: 'satellite' });
+ });
+
+ it('does not write a map landing short of the shared zoom at its own ceiling', () => {
+ const shared = { ...PLACE, zoom: 20, by: 'satellite' };
+ const { state, share } = appWindow('detect', { mapView: shared });
+ share('detect').settled({ ...PLACE, zoom: 18 }, 18);
+ expect(state.mapView).toBe(shared);
+ });
+
+ it('writes a zoom made on the same spot below the ceiling', () => {
+ const shared = { ...PLACE, zoom: 20, by: 'satellite' };
+ const { state, share } = appWindow('detect', { mapView: shared });
+ share('detect').settled({ ...PLACE, zoom: 15 }, 18);
+ expect(state.mapView).toEqual({ ...PLACE, zoom: 15, by: 'detect' });
+ });
+
+ it('writes a turn made in place', () => {
+ const { state, share } = appWindow('compare', { mapView: { ...PLACE, by: 'satellite' } });
+ share('compare').settled({ ...PLACE, bearing: 90 });
+ expect(state.mapView).toEqual({ ...PLACE, bearing: 90, by: 'compare' });
+ });
+
+ it('leaves the camera alone when a tab settles where it already is', () => {
+ const shared = { ...PLACE, by: 'satellite' };
+ const { state, share } = appWindow('detect', { mapView: shared });
+ share('detect').settled({ ...PLACE, lat: PLACE.lat + 1e-7 });
+ expect(state.mapView).toBe(shared);
+ });
+});
+
+describe('taking the window camera', () => {
+ it('moves a tab that shows to where another map left the window', () => {
+ const shared = { ...PLACE, by: 'satellite' };
+ const { share } = appWindow('detect', { mapView: shared });
+ expect(share('detect').pending({ lat: 0, lon: 0, zoom: 3, bearing: 0 })).toBe(shared);
+ });
+
+ it('never hands a tab back its own camera', () => {
+ const { share } = appWindow('detect', { mapView: { ...PLACE, by: 'detect' } });
+ expect(share('detect').pending({ lat: 0, lon: 0, zoom: 3, bearing: 0 })).toBe(null);
+ });
+
+ it('follows the chain, which writes as nobody on the window', () => {
+ const shared = { ...PLACE, by: 'link' };
+ const { share } = appWindow('satellite', { mapView: shared });
+ expect(share('satellite').pending({ lat: 0, lon: 0, zoom: 3, bearing: 0 })).toBe(shared);
+ });
+
+ it('stays put when it is already there', () => {
+ const { share } = appWindow('compare', { mapView: { ...PLACE, by: 'satellite' } });
+ expect(share('compare').pending({ ...PLACE })).toBe(null);
+ });
+
+ it('asks a turned map to turn as well', () => {
+ const shared = { ...PLACE, by: 'satellite' };
+ const { share } = appWindow('compare', { mapView: shared });
+ expect(share('compare').pending({ ...PLACE, bearing: 0 })).toBe(shared);
+ });
+
+ it('gives a window with no camera yet the camera of the first map on screen', () => {
+ const { state, share } = appWindow('satellite');
+ expect(share('satellite').pending({ ...PLACE })).toBe(null);
+ expect(state.mapView).toEqual({ ...PLACE, by: 'satellite' });
+ // …which a hidden tab showing nothing yet does not do
+ const hidden = appWindow('compare');
+ hidden.share('satellite').pending({ ...PLACE });
+ expect(hidden.state.mapView).toBe(null);
+ });
+
+ it('moves nothing with the preference off, or for a tab that is not on screen', () => {
+ const shared = { ...PLACE, by: 'satellite' };
+ const off = appWindow('detect', { on: false, mapView: shared });
+ expect(off.share('detect').pending({ lat: 0, lon: 0, zoom: 3 })).toBe(null);
+ const hidden = appWindow('satellite', { mapView: shared });
+ expect(hidden.share('detect').pending({ lat: 0, lon: 0, zoom: 3 })).toBe(null);
+ });
+
+ it('says when another map left the window camera, which a tab arriving follows', () => {
+ const shared = { ...PLACE, by: 'satellite' };
+ expect(appWindow('detect', { mapView: shared }).share('detect').ledElsewhere()).toBe(true);
+ expect(appWindow('detect', { mapView: { ...PLACE, by: 'link' } }).share('detect').ledElsewhere()).toBe(true);
+ // its own camera, none yet, or the preference off: its own ground stands
+ expect(appWindow('detect', { mapView: { ...PLACE, by: 'detect' } }).share('detect').ledElsewhere()).toBe(false);
+ expect(appWindow('detect').share('detect').ledElsewhere()).toBe(false);
+ expect(appWindow('detect', { on: false, mapView: shared }).share('detect').ledElsewhere()).toBe(false);
+ });
+
+ it('opens a new map on the window camera, and only with the preference on', () => {
+ const shared = { ...PLACE, by: 'satellite' };
+ expect(appWindow('detect', { mapView: shared }).share('detect').opening()).toBe(shared);
+ expect(appWindow('detect', { on: false, mapView: shared }).share('detect').opening()).toBe(null);
+ expect(appWindow('detect').share('detect').opening()).toBe(null);
+ });
+});
diff --git a/frontend/src/lib/measure.js b/frontend/src/lib/measure.js
index 35031da..38ecb69 100644
--- a/frontend/src/lib/measure.js
+++ b/frontend/src/lib/measure.js
@@ -78,6 +78,68 @@ export function containsPoint(points, point) {
return inside;
}
+/** The convex hull of flat `[x, y]` points, counter-clockwise (monotone chain). */
+function convexHull(points) {
+ const sorted = [...points].sort((a, b) => a[0] - b[0] || a[1] - b[1]);
+ if (sorted.length < 3) return sorted;
+ const cross = (o, a, b) => (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]);
+ const half = (list) => {
+ const chain = [];
+ for (const point of list) {
+ while (chain.length >= 2 && cross(chain.at(-2), chain.at(-1), point) <= 0) chain.pop();
+ chain.push(point);
+ }
+ chain.pop();
+ return chain;
+ };
+ return [...half(sorted), ...half([...sorted].reverse())];
+}
+
+/**
+ * The long and short sides of the smallest rectangle around the points, in
+ * metres, turned to fit them rather than squared to north: a hull lying on the
+ * diagonal is as long as it is, not as long as the box around it.
+ *
+ * Worked flat about the points' middle, which at the size of a ship or a
+ * detection gives the answer the sphere does.
+ */
+export function orientedExtent(points) {
+ if (!points?.length) return null;
+ const lat0 = points.reduce((sum, point) => sum + point.lat, 0) / points.length;
+ const lon0 = points[0].lon;
+ const k = Math.cos(rad(lat0));
+ const flat = points.map((point) => [
+ rad(((point.lon - lon0 + 540) % 360) - 180) * k * R,
+ rad(point.lat - lat0) * R,
+ ]);
+ const hull = convexHull(flat);
+ if (hull.length < 3) {
+ const [a, b = a] = hull;
+ return { length: Math.hypot(b[0] - a[0], b[1] - a[1]), width: 0 };
+ }
+ let best = null;
+ for (let i = 0; i < hull.length; i++) {
+ const [ax, ay] = hull[i];
+ const [bx, by] = hull[(i + 1) % hull.length];
+ const edge = Math.hypot(bx - ax, by - ay);
+ if (!edge) continue;
+ const ux = (bx - ax) / edge;
+ const uy = (by - ay) / edge;
+ let [minU, maxU, minV, maxV] = [Infinity, -Infinity, Infinity, -Infinity];
+ for (const [x, y] of hull) {
+ const u = x * ux + y * uy;
+ const v = y * ux - x * uy;
+ minU = Math.min(minU, u);
+ maxU = Math.max(maxU, u);
+ minV = Math.min(minV, v);
+ maxV = Math.max(maxV, v);
+ }
+ const sides = [maxU - minU, maxV - minV];
+ if (!best || sides[0] * sides[1] < best[0] * best[1]) best = sides;
+ }
+ return { length: Math.max(...best), width: Math.min(...best) };
+}
+
/** Interior angle at `vertex` between the rays to `a` and `b`, in degrees. */
export function angleAt(a, vertex, b) {
const cosLat = Math.cos(rad(vertex.lat));
diff --git a/frontend/src/lib/measure.test.js b/frontend/src/lib/measure.test.js
index ddffd14..2d9ed94 100644
--- a/frontend/src/lib/measure.test.js
+++ b/frontend/src/lib/measure.test.js
@@ -9,6 +9,7 @@ import {
formatArea,
formatAngle,
destination,
+ orientedExtent,
} from './measure.js';
describe('haversine', () => {
@@ -188,3 +189,38 @@ describe('containsPoint', () => {
expect(containsPoint(quay, null)).toBe(false);
});
});
+
+describe('orientedExtent', () => {
+ // A 200 m hull, 30 m across, lying 30° off north off Hodeidah.
+ const centre = { lat: 14.8, lon: 42.95 };
+ const corner = (along, across) => destination(destination(centre, 30, along), 120, across);
+ const hull = [corner(100, 15), corner(100, -15), corner(-100, -15), corner(-100, 15)];
+
+ it('measures a turned shape along its own sides, not the box squared to north', () => {
+ const { length, width } = orientedExtent(hull);
+ expect(length).toBeCloseTo(200, 0);
+ expect(width).toBeCloseTo(30, 0);
+ // the north-up box around the same hull calls it four times as wide
+ const lons = hull.map((p) => p.lon);
+ const across = haversine({ lat: centre.lat, lon: Math.min(...lons) }, { lat: centre.lat, lon: Math.max(...lons) });
+ expect(across).toBeGreaterThan(4 * width);
+ });
+
+ it('reads the long side first whichever way the points run', () => {
+ const { length, width } = orientedExtent([...hull].reverse());
+ expect(length).toBeGreaterThan(width);
+ });
+
+ it('gives a line its length and nothing across, and a point nothing at all', () => {
+ const line = orientedExtent([corner(100, 0), corner(-100, 0)]);
+ expect(line.length).toBeCloseTo(200, 0);
+ expect(line.width).toBe(0);
+ expect(orientedExtent([centre])).toEqual({ length: 0, width: 0 });
+ expect(orientedExtent([])).toBe(null);
+ });
+
+ it('keeps a shape across the antimeridian its own size', () => {
+ const { length } = orientedExtent([{ lat: 0, lon: 179.9995 }, { lat: 0, lon: -179.9995 }]);
+ expect(length).toBeCloseTo(111, 0);
+ });
+});
diff --git a/frontend/src/lib/naming.js b/frontend/src/lib/naming.js
index 63014db..020946b 100644
--- a/frontend/src/lib/naming.js
+++ b/frontend/src/lib/naming.js
@@ -1,6 +1,6 @@
/**
- * Naming rules shared by everything the analyst saves under a name: inspect
- * sessions, proofs and post drafts.
+ * Naming rules shared by everything the analyst saves under a name: collages,
+ * proofs and post drafts.
*
* The rule is one line: **the name is the filename stem**. The human-readable
* text in the header becomes the file stem, with only cross-platform forbidden
@@ -16,7 +16,7 @@
export const MAX_SLUG = 68;
/** What a fresh item of each kind is called until the analyst renames it. */
-export const NAME_PREFIX = { session: 'Inspect', proof: 'Proof', draft: 'Post', note: 'Note' };
+export const NAME_PREFIX = { collage: 'Collage', proof: 'Proof', draft: 'Post', note: 'Note' };
/** Human-readable cross-platform filename stem — mirror of backend `slugify`. */
export function slugify(text, fallback) {
@@ -49,7 +49,7 @@ export function uniqueName(base, taken) {
}
/**
- * Name for a fresh item of `kind`: "Inspect 1", "Proof 1", … taking the lowest
+ * Name for a fresh item of `kind`: "Collage 1", "Proof 1", … taking the lowest
* free number so the case doesn't count past the gaps deletions leave behind.
*/
export function nextName(kind, taken) {
@@ -71,11 +71,11 @@ export function isDefaultName(name, kind) {
}
// Where each kind's spec lives, and the entity attribute that points at it.
-// These mirror `layout.session_rel` / `proof_spec_rel` / `draft_rel` — the
+// These mirror `layout.collage_rel` / `proof_spec_rel` / `draft_rel` — the
// specs are hidden inside the case folder, so a spec path is not the visible
// path of the work it describes (a proof's own file is `proofs/<name>.png`).
const SPEC_ATTR = {
- session: { dir: '.inspect/', attr: 'spec' },
+ collage: { dir: '.collages/', attr: 'spec' },
proof: { dir: 'proofs/.meta/', attr: 'spec' },
draft: { dir: '.drafts/', attr: 'draft' },
};
diff --git a/frontend/src/lib/naming.test.js b/frontend/src/lib/naming.test.js
index 8378527..925b695 100644
--- a/frontend/src/lib/naming.test.js
+++ b/frontend/src/lib/naming.test.js
@@ -6,14 +6,14 @@ import {
describe('slugify — mirrors the backend api/naming.slugify', () => {
it('preserves human text and replaces only forbidden filename characters', () => {
- expect(slugify('Inspect 1', 'session')).toBe('Inspect 1');
+ expect(slugify('Collage 1', 'collage')).toBe('Collage 1');
expect(slugify(' Rooftop! @ 12:30 ', 'proof')).toBe('Rooftop! @ 12_30');
expect(slugify('Café déjà', 'proof')).toBe('Café déjà');
});
it('falls back to the caller word when nothing survives, and caps the length', () => {
expect(slugify('', 'proof')).toBe('proof');
- expect(slugify('!!!', 'session')).toBe('!!!');
+ expect(slugify('!!!', 'collage')).toBe('!!!');
expect(slugify(null, 'draft')).toBe('draft');
expect(slugify('a'.repeat(200), 'proof')).toHaveLength(MAX_SLUG);
});
@@ -21,7 +21,7 @@ describe('slugify — mirrors the backend api/naming.slugify', () => {
describe('nextName — the default name of a fresh item', () => {
it('starts at 1 for each kind', () => {
- expect(nextName('session', [])).toBe('Inspect 1');
+ expect(nextName('collage', [])).toBe('Collage 1');
expect(nextName('proof', new Set())).toBe('Proof 1');
expect(nextName('draft', [])).toBe('Post 1');
});
@@ -32,7 +32,7 @@ describe('nextName — the default name of a fresh item', () => {
});
it('ignores names the analyst typed', () => {
- expect(nextName('session', ['Rooftop angle', 'Bridge'])).toBe('Inspect 1');
+ expect(nextName('collage', ['Rooftop angle', 'Bridge'])).toBe('Collage 1');
});
it('numbers a name that still slugs to a distinct filename', () => {
@@ -56,7 +56,7 @@ describe('isDefaultName — an assigned name is not a description', () => {
it('recognizes the names this app assigns', () => {
expect(isDefaultName('Proof 1', 'proof')).toBe(true);
expect(isDefaultName(' Proof 12 ', 'proof')).toBe(true);
- expect(isDefaultName('Inspect 3', 'session')).toBe(true);
+ expect(isDefaultName('Collage 3', 'collage')).toBe(true);
expect(isDefaultName('Post 2', 'draft')).toBe(true);
});
@@ -64,7 +64,7 @@ describe('isDefaultName — an assigned name is not a description', () => {
expect(isDefaultName('Rooftop angle', 'proof')).toBe(false);
expect(isDefaultName('Proof', 'proof')).toBe(false);
expect(isDefaultName('Proof 1 rooftop', 'proof')).toBe(false);
- expect(isDefaultName('Inspect 1', 'proof')).toBe(false); // right shape, wrong kind
+ expect(isDefaultName('Collage 1', 'proof')).toBe(false); // right shape, wrong kind
expect(isDefaultName(null, 'proof')).toBe(false);
});
});
@@ -73,7 +73,7 @@ describe('saved-item case queries', () => {
const entities = [
{ label: 'Rooftop', attrs: { spec: 'proofs/.meta/rooftop.json' } },
{ label: 'Bridge', attrs: { spec: 'proofs/.meta/bridge.json' } },
- { label: 'Angle', attrs: { spec: '.inspect/angle.json' } },
+ { label: 'Angle', attrs: { spec: '.collages/angle.json' } },
{ label: 'Thread', attrs: { draft: '.drafts/thread.json' } },
{ label: 'A place', attrs: { spec: 'places/x.json' } }, // filed, but not one of ours
{ label: 'No spec' },
@@ -82,32 +82,32 @@ describe('saved-item case queries', () => {
it('builds the spec path a filed entity actually carries', () => {
// The tools look an item up by this exact string to tell whether it is still
// filed, so it has to name the hidden folders the case really uses — a stale
- // `inspect/` matched nothing and warned "deleted" on every save.
- expect(specPath('session', 'angle')).toBe('.inspect/angle.json');
+ // `exports/` matched nothing and warned "deleted" on every save.
+ expect(specPath('collage', 'angle')).toBe('.collages/angle.json');
expect(specPath('proof', 'rooftop')).toBe('proofs/.meta/rooftop.json');
expect(specPath('draft', 'thread')).toBe('.drafts/thread.json');
// and the same string the filed entities carry, so a lookup by it hits
- for (const [kind, slug] of [['session', 'angle'], ['proof', 'rooftop'], ['draft', 'thread']]) {
+ for (const [kind, slug] of [['collage', 'angle'], ['proof', 'rooftop'], ['draft', 'thread']]) {
expect(entities.some((e) => e.attrs?.[specAttr(kind)] === specPath(kind, slug))).toBe(true);
}
});
it('names the attribute each kind stores its spec under', () => {
- expect(specAttr('session')).toBe('spec');
+ expect(specAttr('collage')).toBe('spec');
expect(specAttr('proof')).toBe('spec');
expect(specAttr('draft')).toBe('draft'); // posts are the odd one out
});
it('picks only the entities of the asked-for kind', () => {
expect(savedEntities(entities, 'proof').map((e) => e.label)).toEqual(['Rooftop', 'Bridge']);
- expect(savedEntities(entities, 'session').map((e) => e.label)).toEqual(['Angle']);
+ expect(savedEntities(entities, 'collage').map((e) => e.label)).toEqual(['Angle']);
expect(savedEntities(entities, 'draft').map((e) => e.label)).toEqual(['Thread']);
expect(savedEntities(undefined, 'proof')).toEqual([]);
});
it('lists the slugs (filename without its folder and .json)', () => {
expect(savedSlugs(entities, 'proof')).toEqual(new Set(['rooftop', 'bridge']));
- expect(savedSlugs(entities, 'session')).toEqual(new Set(['angle']));
+ expect(savedSlugs(entities, 'collage')).toEqual(new Set(['angle']));
expect(savedSlugs(entities, 'draft')).toEqual(new Set(['thread']));
});
@@ -133,7 +133,7 @@ describe('saved-item case queries', () => {
describe('every kind names its work the same way', () => {
it('has one prefix per kind and no other', () => {
// Notes joined the convention: their file is named after the title too,
- // so a fresh one is 'Note 1' the way a fresh session is 'Inspect 1'.
- expect(Object.keys(NAME_PREFIX).sort()).toEqual(['draft', 'note', 'proof', 'session']);
+ // so a fresh one is 'Note 1' the way a fresh collage is 'Collage 1'.
+ expect(Object.keys(NAME_PREFIX).sort()).toEqual(['collage', 'draft', 'note', 'proof']);
});
});
diff --git a/frontend/src/lib/navigate.js b/frontend/src/lib/navigate.js
index eab343a..2ddcf73 100644
--- a/frontend/src/lib/navigate.js
+++ b/frontend/src/lib/navigate.js
@@ -35,6 +35,13 @@ function specName(path) {
return path.split('/').pop().replace(/\.json$/, '');
}
+/** A saved comparison, from a Saved-panel row, reopened in Compare. */
+export function openComparison(row) {
+ if (!row?.session) return;
+ uiState.openCompare = row.session;
+ uiState.tool = 'compare';
+}
+
/** Tool a given entity type opens in (also gates the "Open in tool" button). */
export const ENTITY_TOOL = {
media: 'media',
@@ -42,6 +49,7 @@ export const ENTITY_TOOL = {
place: 'satellite',
post: 'post',
'inspect-session': 'inspect',
+ collage: 'collage',
'compare-session': 'compare',
'analysis-zones': 'detect',
'analysis-area': 'detect',
@@ -102,6 +110,12 @@ export function openEntity(entity) {
uiState.tool = 'inspect';
return;
}
+ if (entity.type === 'collage') {
+ const name = specName(entity.attrs?.spec);
+ if (name) uiState.openCollage = name;
+ uiState.tool = 'collage';
+ return;
+ }
if (entity.type === 'compare-session') {
const name = specName(entity.attrs?.spec);
if (name) uiState.openCompare = name;
@@ -190,6 +204,23 @@ export function gotoPoint(lat, lon) {
uiState.tool = 'satellite';
}
+/**
+ * Open another map tab on a point, at the zoom it was looked at.
+ *
+ * The right-click menu's Open in…: Satellite flies there, Compare and Detect
+ * move their camera and keep their own pictures and work. A fullscreen map is
+ * left first, or the tab it hands over to would open behind it.
+ */
+export function openMapAt(tool, { lat, lon, zoom }) {
+ if (!Number.isFinite(lat) || !Number.isFinite(lon)) return;
+ const at = { lat, lon, ...(Number.isFinite(zoom) ? { zoom } : {}) };
+ if (tool === 'satellite') uiState.gotoCoords = at;
+ else if (tool === 'compare' || tool === 'detect') uiState.lookAt = { tool, ...at };
+ else return;
+ if (globalThis.document?.fullscreenElement) void document.exitFullscreen?.().catch(() => {});
+ uiState.tool = tool;
+}
+
/**
* Open the Guide on whatever covers a tool.
*
diff --git a/frontend/src/lib/navigate.test.js b/frontend/src/lib/navigate.test.js
index 5f466a3..f28cca0 100644
--- a/frontend/src/lib/navigate.test.js
+++ b/frontend/src/lib/navigate.test.js
@@ -4,12 +4,13 @@ const post = vi.fn().mockResolvedValue({ path: '/cases/c1/azimut/media' });
vi.mock('./api.js', () => ({ api: { post: (...a) => post(...a), get: vi.fn() } }));
const { caseState, uiState } = await import('./state.svelte.js');
-const { gotoCapture, gotoPoint, openEntity, openGuide, openInReverseSearch, opensInFileManager } =
+const { gotoCapture, gotoPoint, openComparison, openEntity, openGuide, openInReverseSearch, openMapAt, opensInFileManager } =
await import('./navigate.js');
beforeEach(() => {
uiState.tool = 'media';
uiState.gotoCoords = null;
+ uiState.lookAt = null;
uiState.focusCapture = null;
uiState.openBoardEntity = null;
uiState.openCompare = null;
@@ -138,6 +139,32 @@ describe('gotoPoint', () => {
});
});
+describe('openMapAt', () => {
+ it('flies Satellite to the point, at the zoom it was looked at', () => {
+ openMapAt('satellite', { lat: 12.76, lon: 43.65, zoom: 15 });
+ expect(uiState.tool).toBe('satellite');
+ expect(uiState.gotoCoords).toEqual({ lat: 12.76, lon: 43.65, zoom: 15 });
+ expect(uiState.lookAt).toBeNull();
+ });
+
+ it('moves Compare and Detect there, and leaves their own pictures to them', () => {
+ openMapAt('compare', { lat: 12.76, lon: 43.65, zoom: 15 });
+ expect(uiState.tool).toBe('compare');
+ expect(uiState.lookAt).toEqual({ tool: 'compare', lat: 12.76, lon: 43.65, zoom: 15 });
+ expect(uiState.compareAt ?? null).toBeNull();
+ openMapAt('detect', { lat: 12.76, lon: 43.65 });
+ expect(uiState.tool).toBe('detect');
+ expect(uiState.lookAt).toEqual({ tool: 'detect', lat: 12.76, lon: 43.65 });
+ });
+
+ it('goes nowhere for a tab that is not a map, or a point it could not place', () => {
+ openMapAt('board', { lat: 12.76, lon: 43.65 });
+ openMapAt('detect', { lat: Number('north'), lon: 43.65 });
+ expect(uiState.tool).toBe('media');
+ expect(uiState.lookAt).toBeNull();
+ });
+});
+
describe('a file the app cannot display', () => {
const plan = { id: 'm1', type: 'media', attrs: { path: 'media/site plan.pdf', kind: 'file' } };
@@ -186,13 +213,20 @@ describe('reopening an artifact in its tool', () => {
expect(uiState.tool).toBe('post');
});
- it('names an inspect session by its spec file', () => {
+ it('names the Inspect work on a file by its spec file', () => {
openEntity({ type: 'inspect-session', attrs: { spec: '.inspect/Bridge pass.json' } });
expect(uiState.openInspect).toBe('Bridge pass');
expect(uiState.tool).toBe('inspect');
});
+ it('names a collage by its spec file', () => {
+ openEntity({ type: 'collage', attrs: { spec: '.collages/Harbour strip.json' } });
+
+ expect(uiState.openCollage).toBe('Harbour strip');
+ expect(uiState.tool).toBe('collage');
+ });
+
it('names a comparison session by its spec file', () => {
openEntity({ type: 'compare-session', attrs: { spec: 'comparisons/.meta/Harbour change.json' } });
@@ -208,3 +242,16 @@ describe('reopening an artifact in its tool', () => {
expect(uiState.tool).toBe('proof');
});
});
+
+describe('openComparison', () => {
+ it('reopens a saved comparison from its Saved row, by the name Compare knows it by', () => {
+ openComparison({ kind: 'comparison', session: 'Harbour reading' });
+ expect(uiState.openCompare).toBe('Harbour reading');
+ expect(uiState.tool).toBe('compare');
+ });
+
+ it('goes nowhere for a row that names no comparison', () => {
+ openComparison({ kind: 'capture' });
+ expect(uiState.tool).toBe('media');
+ });
+});
diff --git a/frontend/src/lib/satRotate.js b/frontend/src/lib/satRotate.js
deleted file mode 100644
index 4e19324..0000000
--- a/frontend/src/lib/satRotate.js
+++ /dev/null
@@ -1,34 +0,0 @@
-/**
- * Middle-drag map rotation for the Satellite tab — the same Google-Earth
- * "grab & turn" as the Frame viewer, but driving a map bearing.
- *
- * A map rotates about its centre, so to turn around an arbitrary grabbed point
- * we set the bearing and then pan the map so the grabbed location slides back
- * under the cursor. These two pure helpers hold the bits that are easy to get
- * subtly wrong (the swept-angle bearing and, above all, the *sign* of the
- * compensating pan); the map glue lives in the tool, over `lib/map`'s façade.
- */
-
-import { pointerAngleDeg } from './frameRotate.js';
-
-/**
- * New map bearing after sweeping the pointer around a fixed screen `pivot`,
- * from `start` to `cur` (all `{x, y}` in screen px). The turn tracks the angle
- * the cursor sweeps about the pivot — grab, then circle to rotate.
- */
-export function dragBearing(startBearing, pivot, start, cur) {
- const delta =
- pointerAngleDeg(pivot.x, pivot.y, cur.x, cur.y) -
- pointerAngleDeg(pivot.x, pivot.y, start.x, start.y);
- return startBearing + delta;
-}
-
-/**
- * The `[dx, dy]` to hand `panBy` so a pivot that a bearing change pushed from
- * `grab` to `now` (both container-pixel points) returns exactly under `grab`.
- * A `panBy(offset)` shifts every container point by `-offset`, so to move the
- * pivot by `grab - now` we pan by `now - grab`.
- */
-export function pivotPanOffset(grab, now) {
- return [now.x - grab.x, now.y - grab.y];
-}
diff --git a/frontend/src/lib/satRotate.test.js b/frontend/src/lib/satRotate.test.js
deleted file mode 100644
index 00ca76a..0000000
--- a/frontend/src/lib/satRotate.test.js
+++ /dev/null
@@ -1,43 +0,0 @@
-import { describe, it, expect } from 'vitest';
-import { dragBearing, pivotPanOffset } from './satRotate.js';
-
-const near = (a, b, eps = 1e-9) => Math.abs(a - b) < eps;
-
-describe('dragBearing', () => {
- const pivot = { x: 100, y: 100 };
-
- it('adds the swept angle to the starting bearing', () => {
- // start due east of the pivot, sweep to due south → +90° (screen, Y down)
- const b = dragBearing(30, pivot, { x: 200, y: 100 }, { x: 100, y: 200 });
- expect(near(b, 120)).toBe(true);
- });
-
- it('turns the other way when the sweep reverses', () => {
- // east → north is -90°
- const b = dragBearing(0, pivot, { x: 200, y: 100 }, { x: 100, y: 0 });
- expect(near(b, -90)).toBe(true);
- });
-
- it('is a no-op when the cursor has not moved off the reference spoke', () => {
- const b = dragBearing(42, pivot, { x: 160, y: 100 }, { x: 160, y: 100 });
- expect(near(b, 42)).toBe(true);
- });
-});
-
-describe('pivotPanOffset', () => {
- it('cancels the drift so panBy re-pins the pivot under the grab point', () => {
- // A pan shifts container points by -offset; panning by (now-grab) moves
- // the drifted pivot (now) back onto grab.
- const grab = { x: 120, y: 80 };
- const now = { x: 135, y: 60 };
- const [dx, dy] = pivotPanOffset(grab, now);
- expect([dx, dy]).toEqual([15, -20]);
- // apply the -offset shift a pan performs → pivot lands back on grab
- expect(now.x - dx).toBe(grab.x);
- expect(now.y - dy).toBe(grab.y);
- });
-
- it('is zero when the pivot did not drift', () => {
- expect(pivotPanOffset({ x: 10, y: 10 }, { x: 10, y: 10 })).toEqual([0, 0]);
- });
-});
diff --git a/frontend/src/lib/savedMarkers.js b/frontend/src/lib/savedMarkers.js
index 97ed019..b6956fb 100644
--- a/frontend/src/lib/savedMarkers.js
+++ b/frontend/src/lib/savedMarkers.js
@@ -9,6 +9,22 @@
* zoomed-out world map readable.
*/
+import { CAPTURE_KINDS } from './geoTree.js';
+
+/**
+ * The kind a mark is drawn as, from the kinds it holds.
+ *
+ * One kind draws as itself. A stack of imagery (captures, screenshots, saved
+ * comparisons, which the Saved panel files together under Captures) draws as a
+ * capture, so zooming out never turns three captures into a pin. A stack holding
+ * a place draws as the place.
+ */
+export function markKind(kinds) {
+ const list = [...(kinds ?? [])];
+ if (list.length === 1) return list[0];
+ return list.length && list.every((kind) => CAPTURE_KINDS.has(kind)) ? 'capture' : 'place';
+}
+
/** Decimal places to key on at a given map zoom.
*
* 5 decimals is about a metre: at street zoom only items at genuinely the same
@@ -60,15 +76,31 @@ export function groupSavedMarkers(rows, precision = 5) {
}));
}
+/** When an item's imagery was taken: a comparison is read by its later picture,
+ * and an estimate's `~` does not move it. */
+const imageryOf = (row) => String(row.imagery_date ?? row.imagery_b ?? '').replace(/~$/, '');
+
/** A stack's items ordered for the popup: by imagery date, newest first, so
* "what do I already have here?" reads as a timeline of the ground. Items
* with no imagery date fall to the end, ordered by when they were saved. */
export function stackOrder(items) {
return [...(items ?? [])].sort((a, b) => {
- const left = a.imagery_date ?? '';
- const right = b.imagery_date ?? '';
+ const left = imageryOf(a);
+ const right = imageryOf(b);
if (!left !== !right) return left ? -1 : 1; // dated imagery first
if (left !== right) return right.localeCompare(left);
return String(b.fetched_at ?? '').localeCompare(String(a.fetched_at ?? ''));
});
}
+
+/** A comparison's two pictures as a row writes them, an estimate keeping its `~`. */
+export function pairLabel(row) {
+ if (!row?.imagery_a && !row?.imagery_b) return '';
+ return `${row.imagery_a ?? 'undated'} → ${row.imagery_b ?? 'undated'}`;
+}
+
+/** How many images were kept in the case from a comparison, or '' for none. */
+export function keptLabel(row) {
+ const count = row?.kept?.length ?? 0;
+ return count ? `${count} image${count > 1 ? 's' : ''} kept` : '';
+}
diff --git a/frontend/src/lib/savedMarkers.test.js b/frontend/src/lib/savedMarkers.test.js
index da11326..d488050 100644
--- a/frontend/src/lib/savedMarkers.test.js
+++ b/frontend/src/lib/savedMarkers.test.js
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest';
-import { groupSavedMarkers, markerPrecision, stackOrder } from './savedMarkers.js';
+import { groupSavedMarkers, keptLabel, markKind, markerPrecision, pairLabel, stackOrder } from './savedMarkers.js';
const at = (id, lat, lon, extra = {}) => ({ id, kind: 'capture', lat, lon, ...extra });
@@ -86,6 +86,15 @@ describe('stackOrder', () => {
expect(ordered.map((i) => i.id)).toEqual(['b', 'c', 'a']);
});
+ it('dates a comparison by its later picture, an estimate included', () => {
+ const ordered = stackOrder([
+ { id: 'a', imagery_date: '2024-03' },
+ { id: 'cmp', kind: 'comparison', imagery_a: '2020-01-01~', imagery_b: '2025-06-01~' },
+ ]);
+
+ expect(ordered.map((i) => i.id)).toEqual(['cmp', 'a']);
+ });
+
it('sends undated items to the end, newest save first', () => {
const ordered = stackOrder([
{ id: 'a', fetched_at: '2026-01-01T00:00:00Z' },
@@ -96,3 +105,34 @@ describe('stackOrder', () => {
expect(ordered.map((i) => i.id)).toEqual(['b', 'c', 'a']);
});
});
+
+describe('a comparison row', () => {
+ it('writes its two pictures, an undated one said as such', () => {
+ expect(pairLabel({ imagery_a: '2024-05-03~', imagery_b: '2026-09-02' })).toBe('2024-05-03~ → 2026-09-02');
+ expect(pairLabel({ imagery_b: '2026-09-02' })).toBe('undated → 2026-09-02');
+ expect(pairLabel({ kind: 'capture' })).toBe('');
+ });
+
+ it('counts the images kept from it', () => {
+ expect(keptLabel({ kept: [{}, {}] })).toBe('2 images kept');
+ expect(keptLabel({ kept: [{}] })).toBe('1 image kept');
+ expect(keptLabel({ kept: [] })).toBe('');
+ });
+});
+
+describe('markKind', () => {
+ it('draws one kind as itself', () => {
+ expect(markKind(['comparison'])).toBe('comparison');
+ expect(markKind(['place'])).toBe('place');
+ });
+
+ it('draws a stack of imagery as a capture, however it was made', () => {
+ // zoomed out, three captures and a comparison nearby merge into one mark
+ expect(markKind(['capture', 'comparison'])).toBe('capture');
+ expect(markKind(['capture', 'screenshot', 'comparison'])).toBe('capture');
+ });
+
+ it('draws a stack holding a place as the place', () => {
+ expect(markKind(['capture', 'place'])).toBe('place');
+ });
+});
diff --git a/frontend/src/lib/state.svelte.js b/frontend/src/lib/state.svelte.js
index 1a624cb..cedadee 100644
--- a/frontend/src/lib/state.svelte.js
+++ b/frontend/src/lib/state.svelte.js
@@ -23,6 +23,7 @@ export const prefs = $state({
coordFormat: 'dd', // 'dd' | 'dms' | 'mgrs'
units: 'metric', // 'metric' | 'imperial'
homeView: { lat: 43, lon: 25, zoom: 3 }, // where Satellite opens
+ mapSync: true, // Satellite, Compare and Detect share one camera
detectView: { collapsed: false, basemap: 'esri-world-imagery', overlays: ['boundaries'], saved: true },
captureScaleNorth: false, // burn a scale bar and a north arrow into captures
postMention: '@GeoConfirmed', // handle a fresh post draft is addressed to
@@ -93,6 +94,7 @@ export function applyPrefs(s) {
if (s.coord_format) prefs.coordFormat = s.coord_format;
if (s.units) prefs.units = s.units;
if (s.home_view) prefs.homeView = s.home_view;
+ if (s.map_sync !== undefined) prefs.mapSync = s.map_sync;
if (s.detect_view) prefs.detectView = s.detect_view;
if (s.capture_scale_north !== undefined) prefs.captureScaleNorth = s.capture_scale_north;
if (s.post_mention !== undefined) prefs.postMention = s.post_mention; // '' = none
@@ -245,7 +247,8 @@ export const uiState = $state({
*/
reverseTarget: null,
focusMedia: null, // media path to highlight & scroll to in the Media Library
- openInspect: null, // inspect-session name to reopen in the Inspect tool
+ openInspect: null, // name of a file's Inspect work, reopened on that file
+ openCollage: null, // collage name to reopen in the Collage tool
openCompare: null, // compare-session name to reopen in the Compare tool
openAnalyzer: null, // saved Detect item stem to reopen without loading imagery
// Entity id the Board should open Details on. The graph-only types — a person,
@@ -296,6 +299,13 @@ export const uiState = $state({
* Coords & Sky, and never part of a capture, a proof or a case.
*/
mapPoint: null, // { lat, lon, zoom }
+ /**
+ * The window's camera, which Satellite, Compare and Detect share while
+ * `prefs.mapSync` is on (`lib/map/sharedView.js`): `{ lat, lon, zoom,
+ * bearing, by }`, where `by` is the tab that wrote it or 'link' for the
+ * chain. Session-only. A case switch leaves it: a camera is not case state.
+ */
+ mapView: null,
/**
* A pair of dated views of one point, handed to Compare from the map's own
* right-click menu: `{ lat, lon, zoom, a, b, title }`, where each side is the
@@ -304,6 +314,13 @@ export const uiState = $state({
* rather than on two empty panes. Consumed once, session-only.
*/
compareAt: null,
+ /**
+ * A point another map tab was asked to look at, from the right-click menu's
+ * Open in…: `{ tool: 'compare' | 'detect', lat, lon, zoom }`. That tab moves
+ * its camera there and keeps its own pictures and work; Satellite takes the
+ * same hand-off as `gotoCoords`. Consumed once, session-only.
+ */
+ lookAt: null,
focusCapture: null, // case-relative capture path selected from another workspace
// Satellite reference viewers: floating scratch windows holding a media image
// over the map to eyeball against the imagery. Session-only — never captured
@@ -560,6 +577,7 @@ function clearCaseHandoffs() {
uiState.focusMedia = null;
uiState.focusCapture = null;
uiState.openInspect = null;
+ uiState.openCollage = null;
uiState.openCompare = null;
uiState.openAnalyzer = null;
uiState.drawInGraph = null;
@@ -569,6 +587,7 @@ function clearCaseHandoffs() {
uiState.timelineRange = null;
uiState.mapTimelineRange = null;
uiState.gotoCoords = null;
+ uiState.lookAt = null;
uiState.skyAt = null;
uiState.refViewers = [];
}
diff --git a/frontend/src/lib/state.test.js b/frontend/src/lib/state.test.js
index 80a7079..9dfafe8 100644
--- a/frontend/src/lib/state.test.js
+++ b/frontend/src/lib/state.test.js
@@ -41,6 +41,7 @@ describe('closeCase', () => {
uiState.reverseTarget = { path: 'media/a.jpg', kind: 'image', label: 'a.jpg' };
uiState.focusMedia = 'media/a.jpg';
uiState.openInspect = 'session-a';
+ uiState.openCollage = 'collage-a';
uiState.openAnalyzer = 'runs-123456789abc';
uiState.drawInGraph = { label: 'A question' };
uiState.openBoardEntity = 'entity-a';
@@ -49,6 +50,7 @@ describe('closeCase', () => {
uiState.timelineRange = { from: '2026-01-01', to: '2026-02-01' };
uiState.mapTimelineRange = { from: '2026-01-01', to: '2026-02-01' };
uiState.gotoCoords = { lat: 1, lon: 2 };
+ uiState.lookAt = { tool: 'detect', lat: 1, lon: 2, zoom: 12 };
});
it('drops the open case', () => {
@@ -66,6 +68,7 @@ describe('closeCase', () => {
expect(uiState.reverseTarget).toBeNull();
expect(uiState.focusMedia).toBeNull();
expect(uiState.openInspect).toBeNull();
+ expect(uiState.openCollage).toBeNull();
expect(uiState.openAnalyzer).toBeNull();
expect(uiState.drawInGraph).toBeNull();
expect(uiState.openBoardEntity).toBeNull();
@@ -74,11 +77,18 @@ describe('closeCase', () => {
expect(uiState.timelineRange).toBeNull();
expect(uiState.mapTimelineRange).toBeNull();
expect(uiState.gotoCoords).toBeNull();
+ expect(uiState.lookAt).toBeNull();
expect(uiState.openNotebook).toBeNull();
expect(uiState.focusCapture).toBeNull();
expect(uiState.skyAt).toBeNull();
expect(uiState.refViewers).toEqual([]);
});
+
+ it('leaves the camera the map tabs share, which is not case state', () => {
+ uiState.mapView = { lat: 1, lon: 2, zoom: 12, bearing: 0, by: 'satellite' };
+ closeCase();
+ expect(uiState.mapView).toEqual({ lat: 1, lon: 2, zoom: 12, bearing: 0, by: 'satellite' });
+ });
});
describe('setSidebarWidth', () => {
@@ -154,6 +164,15 @@ describe('applyPrefs', () => {
applyPrefs({ signature_handle: '@example' });
expect(prefs.signatureHandle).toBe('@example');
});
+
+ it('shares one camera across the map tabs until Settings says otherwise', async () => {
+ const { applyPrefs, prefs } = await freshState();
+ expect(prefs.mapSync).toBe(true);
+ applyPrefs({ units: 'metric' });
+ expect(prefs.mapSync).toBe(true);
+ applyPrefs({ map_sync: false });
+ expect(prefs.mapSync).toBe(false);
+ });
});
describe('startup update check', () => {
@@ -340,6 +359,7 @@ describe('case request ownership', () => {
focusMedia: 'media/a.jpg',
focusCapture: 'media/crop.png',
openInspect: 'session-a',
+ openCollage: 'collage-a',
drawInGraph: { label: 'A question' },
openBoardEntity: 'entity-a',
openGraphEntity: 'entity-a',
@@ -347,6 +367,7 @@ describe('case request ownership', () => {
timelineRange: { from: '2026-01-01', to: '2026-02-01' },
mapTimelineRange: { from: '2026-01-01', to: '2026-02-01' },
gotoCoords: { lat: 1, lon: 2 },
+ lookAt: { tool: 'compare', lat: 1, lon: 2, zoom: 12 },
skyAt: { lat: 1, lon: 2, date: '2026-01-01', time: '12:00' },
refViewers: [{ id: 'v1' }],
};
diff --git a/frontend/src/lib/timeline.js b/frontend/src/lib/timeline.js
index 628ceaf..6753b53 100644
--- a/frontend/src/lib/timeline.js
+++ b/frontend/src/lib/timeline.js
@@ -521,6 +521,46 @@ function qualifierLabels(raw) {
return labels;
}
+const KIND_LABELS = {
+ captured: 'Captured',
+ published: 'Published',
+ imagery: 'Imagery',
+ 'imagery-a': 'Imagery A',
+ 'imagery-b': 'Imagery B',
+ collected: 'Collected',
+ added: 'Added to case',
+ filed: 'Filed in case',
+ claim: 'Claim',
+ taken: 'Taken',
+};
+
+/** What a temporal row's kind is called on the Time panel and the Timeline. */
+export function temporalKindLabel(kind) {
+ return KIND_LABELS[kind] ?? kind ?? '';
+}
+
+/**
+ * The span a change seen between two pictures happened in, as a Claim's date.
+ *
+ * Two UTC instants stay an exact range. Otherwise both are read as days, since a
+ * range does not mix a day with a time, and an estimate keeps its `~` on the end
+ * it belongs to. Empty when the two do not make a range.
+ *
+ * @param {string} first a picture's date, as the Time panel carries it
+ * @param {string} second the other picture's
+ */
+export function changeInterval(first, second) {
+ if (!first || !second) return '';
+ const instant = (value) => sortableTimestamp(value) && value.endsWith('Z');
+ const [a, b] = instant(first) && instant(second)
+ ? [first, second]
+ : [first, second].map((value) => value.replace(/T.*$/, ''));
+ const key = (value) => value.replace(/[~?%]$/, '');
+ if (key(a) === key(b)) return '';
+ const raw = key(a) < key(b) ? `${a}/${b}` : `${b}/${a}`;
+ return validateTemporalValue(raw).valid ? raw : '';
+}
+
export function formatTemporalValue(raw) {
const check = validateTemporalValue(raw ?? '');
if (!raw) return { ...check, label: 'Undated', qualifiers: [] };
diff --git a/frontend/src/lib/timeline.test.js b/frontend/src/lib/timeline.test.js
index 8c5924a..c2bc860 100644
--- a/frontend/src/lib/timeline.test.js
+++ b/frontend/src/lib/timeline.test.js
@@ -10,6 +10,7 @@ import {
bucketScale,
bucketSpan,
bucketWindow,
+ changeInterval,
densityScale,
densityTicks,
densityUnit,
@@ -33,6 +34,7 @@ import {
resizeTemporalRaw,
resizeWindow,
shiftWindow,
+ temporalKindLabel,
timeAtRatio,
validateTemporalValue,
windowInputValue,
@@ -535,3 +537,31 @@ describe('the window, as one reading', () => {
expect(resizeWindow('', '', 1000)).toEqual({ from: '', to: '' });
});
});
+
+describe('two dated pictures', () => {
+ it('date a change as the span between them, earliest first', () => {
+ expect(changeInterval('2024-05-03', '2026-09-02')).toBe('2024-05-03/2026-09-02');
+ expect(changeInterval('2026-09-02', '2024-05-03')).toBe('2024-05-03/2026-09-02');
+ });
+
+ it('keep two radar instants exact, and read a day beside a time as days', () => {
+ expect(changeInterval('2026-09-02T05:42:10Z', '2026-09-02T17:31:02Z'))
+ .toBe('2026-09-02T05:42:10Z/2026-09-02T17:31:02Z');
+ expect(changeInterval('2024-05-03', '2026-09-02T05:42:10Z')).toBe('2024-05-03/2026-09-02');
+ });
+
+ it('keep an estimate marked on its own end', () => {
+ expect(changeInterval('2024-05-03~', '2026-09-02')).toBe('2024-05-03~/2026-09-02');
+ });
+
+ it('make no span of one day or of a missing picture', () => {
+ expect(changeInterval('2026-09-02', '2026-09-02T05:42:10Z')).toBe('');
+ expect(changeInterval('', '2026-09-02')).toBe('');
+ });
+
+ it('name each picture on the Time panel', () => {
+ expect(temporalKindLabel('imagery-a')).toBe('Imagery A');
+ expect(temporalKindLabel('imagery-b')).toBe('Imagery B');
+ expect(temporalKindLabel('something-new')).toBe('something-new');
+ });
+});
diff --git a/frontend/src/lib/trash.js b/frontend/src/lib/trash.js
index 7cbbee8..63455c9 100644
--- a/frontend/src/lib/trash.js
+++ b/frontend/src/lib/trash.js
@@ -25,6 +25,7 @@ export const FILE_BACKED = new Set([
'proof',
'post',
'inspect-session',
+ 'collage',
'compare-session',
'analysis-zones',
'analysis-area',
diff --git a/frontend/src/lib/turn.js b/frontend/src/lib/turn.js
new file mode 100644
index 0000000..a169065
--- /dev/null
+++ b/frontend/src/lib/turn.js
@@ -0,0 +1,92 @@
+/**
+ * How a drag or a key turns a view: the maps' bearing and the Inspect frame.
+ *
+ * A drag is a wheel about the grabbed point: the view turns by the angle the
+ * pointer sweeps around it. That angle is only read outside a guide circle,
+ * because right next to the pivot a pixel is a huge angle and crossing it
+ * flips half a turn. Inside the circle the view holds, and leaving it again
+ * picks the turn up from there. Near north the view settles on north, and Ctrl
+ * lays the turn on whole steps.
+ *
+ * Angles are clockwise degrees, 0–360, which is the app's bearing.
+ */
+
+/** px from the pivot before the sweep is read: the guide circle's radius. */
+export const TURN_RADIUS = 30;
+
+/** A turn this close to north settles on north. */
+export const NORTH_SNAP = 3;
+
+/** One key press, and the grid Ctrl lays a drag on. */
+export const TURN_STEP = 15;
+
+/** 0–360, whatever the caller added up. */
+function wrap(deg) {
+ return ((deg % 360) + 360) % 360;
+}
+
+/** Whether `point` is out of the guide circle about `pivot`, where a sweep is read. */
+export function beyondGuide(pivot, point, radius = TURN_RADIUS) {
+ return Math.hypot(point.x - pivot.x, point.y - pivot.y) >= radius;
+}
+
+/**
+ * The signed angle swept about `pivot` from `from` to `to`, clockwise on
+ * screen (Y down) positive, and never more than half a turn: moves come a few
+ * pixels at a time, so the short way round is the way the hand went.
+ * Null when either point is inside the guide circle.
+ */
+export function sweepDelta(pivot, from, to, radius = TURN_RADIUS) {
+ if (!beyondGuide(pivot, from, radius) || !beyondGuide(pivot, to, radius)) return null;
+ const angle = (point) => (Math.atan2(point.y - pivot.y, point.x - pivot.x) * 180) / Math.PI;
+ const delta = angle(to) - angle(from);
+ return delta > 180 ? delta - 360 : delta <= -180 ? delta + 360 : delta;
+}
+
+/**
+ * Where a turn of `swept` degrees from `start` comes to rest.
+ *
+ * @param {number} start the angle when the pointer was grabbed
+ * @param {number} swept the angle turned since, unwrapped
+ * @param {object} [opts]
+ * @param {boolean} [opts.stepped] lay the result on whole `TURN_STEP`s
+ */
+export function turnBearing(start, swept, { stepped = false } = {}) {
+ const raw = wrap(start + swept);
+ if (stepped) return wrap(Math.round(raw / TURN_STEP) * TURN_STEP);
+ return Math.min(raw, 360 - raw) <= NORTH_SNAP ? 0 : raw;
+}
+
+/**
+ * The next whole step from `bearing` in direction `dir` (1 clockwise, -1 back).
+ * An angle between steps goes to the nearer one that way, so a few presses
+ * always land on a clean reading.
+ */
+export function stepBearing(bearing, dir) {
+ const at = wrap(bearing) / TURN_STEP;
+ const eps = 1e-9;
+ const next = dir > 0 ? Math.floor(at + eps) + 1 : Math.ceil(at - eps) - 1;
+ return wrap(next * TURN_STEP);
+}
+
+/**
+ * What a key asks of the turn: `{ to }` an angle, or null for a key it ignores.
+ * Shift and an arrow, with no other modifier: left and right step, up is north.
+ */
+export function keyTurn(event, bearing) {
+ if (!event.shiftKey || event.ctrlKey || event.metaKey || event.altKey) return null;
+ if (event.key === 'ArrowLeft') return { to: stepBearing(bearing, -1) };
+ if (event.key === 'ArrowRight') return { to: stepBearing(bearing, 1) };
+ if (event.key === 'ArrowUp') return { to: 0 };
+ return null;
+}
+
+/**
+ * The `[dx, dy]` to hand `panBy` so a pivot that a bearing change pushed from
+ * `grab` to `now` (both container-pixel points) returns exactly under `grab`.
+ * A `panBy(offset)` shifts every container point by `-offset`, so to move the
+ * pivot by `grab - now` we pan by `now - grab`.
+ */
+export function pivotPanOffset(grab, now) {
+ return [now.x - grab.x, now.y - grab.y];
+}
diff --git a/frontend/src/lib/turn.test.js b/frontend/src/lib/turn.test.js
new file mode 100644
index 0000000..1cc0d53
--- /dev/null
+++ b/frontend/src/lib/turn.test.js
@@ -0,0 +1,95 @@
+import { describe, it, expect } from 'vitest';
+import { beyondGuide, keyTurn, pivotPanOffset, stepBearing, sweepDelta, turnBearing, TURN_RADIUS } from './turn.js';
+
+const key = (k, mods = {}) => ({ key: k, shiftKey: true, ctrlKey: false, metaKey: false, altKey: false, ...mods });
+
+describe('sweepDelta', () => {
+ const pivot = { x: 100, y: 100 };
+
+ it('reads the angle swept about the pivot, clockwise positive', () => {
+ // east of the pivot to south of it is a quarter turn clockwise on screen
+ expect(sweepDelta(pivot, { x: 200, y: 100 }, { x: 100, y: 200 })).toBeCloseTo(90, 9);
+ expect(sweepDelta(pivot, { x: 200, y: 100 }, { x: 100, y: 0 })).toBeCloseTo(-90, 9);
+ });
+
+ it('keeps going the way the hand went across the back of the circle', () => {
+ // just past west, either side: a small step, not most of a turn back
+ expect(sweepDelta(pivot, { x: 0, y: 99 }, { x: 0, y: 101 })).toBeCloseTo(-2 * (180 / Math.PI) * Math.atan(1 / 100), 6);
+ expect(sweepDelta(pivot, { x: 0, y: 101 }, { x: 0, y: 99 })).toBeGreaterThan(0);
+ });
+
+ it('reads nothing inside the guide circle, where a pixel is a huge angle', () => {
+ expect(sweepDelta(pivot, { x: 110, y: 100 }, { x: 100, y: 110 })).toBeNull();
+ expect(sweepDelta(pivot, { x: 100 + TURN_RADIUS, y: 100 }, { x: 105, y: 100 })).toBeNull();
+ expect(beyondGuide(pivot, { x: 100 + TURN_RADIUS, y: 100 })).toBe(true);
+ expect(beyondGuide(pivot, { x: 100 + TURN_RADIUS - 1, y: 100 })).toBe(false);
+ });
+});
+
+describe('turnBearing', () => {
+ it('adds the angle swept, and wraps past a full turn', () => {
+ expect(turnBearing(30, 40)).toBeCloseTo(70, 9);
+ expect(turnBearing(350, 20)).toBeCloseTo(10, 9);
+ expect(turnBearing(10, -40)).toBeCloseTo(330, 9);
+ expect(turnBearing(0, 720 + 90)).toBeCloseTo(90, 9); // several turns of the wheel
+ });
+
+ it('settles on north when it comes close, from either side', () => {
+ expect(turnBearing(10, -8)).toBe(0);
+ expect(turnBearing(350, 8)).toBe(0);
+ expect(turnBearing(10, -6)).toBeCloseTo(4, 9); // just outside
+ });
+
+ it('lays the turn on whole steps when stepped', () => {
+ expect(turnBearing(0, 20, { stepped: true })).toBe(15);
+ expect(turnBearing(0, 24, { stepped: true })).toBe(30);
+ expect(turnBearing(10, -12, { stepped: true })).toBe(0); // -2° → 0, not 360
+ });
+});
+
+describe('stepBearing', () => {
+ it('moves a whole step from a clean reading', () => {
+ expect(stepBearing(0, 1)).toBe(15);
+ expect(stepBearing(0, -1)).toBe(345);
+ expect(stepBearing(345, 1)).toBe(0);
+ });
+
+ it('goes to the nearer step that way from an angle between steps', () => {
+ expect(stepBearing(7, 1)).toBe(15);
+ expect(stepBearing(7, -1)).toBe(0);
+ expect(stepBearing(29.9999999999, 1)).toBe(45); // float noise on 30 is 30
+ });
+});
+
+describe('keyTurn', () => {
+ it('reads Shift and the arrows: left and right step, up is north', () => {
+ expect(keyTurn(key('ArrowRight'), 0)).toEqual({ to: 15 });
+ expect(keyTurn(key('ArrowLeft'), 0)).toEqual({ to: 345 });
+ expect(keyTurn(key('ArrowUp'), 123)).toEqual({ to: 0 });
+ });
+
+ it('leaves bare arrows, other keys and other modifiers alone', () => {
+ expect(keyTurn(key('ArrowRight', { shiftKey: false }), 0)).toBeNull();
+ expect(keyTurn(key('ArrowDown'), 0)).toBeNull();
+ expect(keyTurn(key('e'), 0)).toBeNull();
+ expect(keyTurn(key('ArrowLeft', { ctrlKey: true }), 0)).toBeNull();
+ expect(keyTurn(key('ArrowLeft', { altKey: true }), 0)).toBeNull();
+ });
+});
+
+describe('pivotPanOffset', () => {
+ it('cancels the drift so panBy re-pins the pivot under the grab point', () => {
+ // A pan shifts container points by -offset; panning by (now-grab) moves
+ // the drifted pivot (now) back onto grab.
+ const grab = { x: 120, y: 80 };
+ const now = { x: 135, y: 60 };
+ const [dx, dy] = pivotPanOffset(grab, now);
+ expect([dx, dy]).toEqual([15, -20]);
+ expect(now.x - dx).toBe(grab.x);
+ expect(now.y - dy).toBe(grab.y);
+ });
+
+ it('is zero when the pivot did not drift', () => {
+ expect(pivotPanOffset({ x: 10, y: 10 }, { x: 10, y: 10 })).toEqual([0, 0]);
+ });
+});
diff --git a/frontend/src/lib/usage.js b/frontend/src/lib/usage.js
index 6dd1bee..13ea1c7 100644
--- a/frontend/src/lib/usage.js
+++ b/frontend/src/lib/usage.js
@@ -63,6 +63,9 @@ export const BLOCK_SHARE = 0.9;
* billed basemap. The live value is the user's `eco_max_zoom` setting. */
export const ECO_MAX_ZOOM = 15;
+/** Sentinel's own eco default, mirrored from `engine/tiles.py`. */
+export const SENTINEL_ECO_MAX_ZOOM = 7;
+
/** Where to watch the real counters and set caps, per provider. */
export const USAGE_LINKS = {
mapbox: 'https://console.mapbox.com/account/statistics/',
diff --git a/frontend/src/lib/usage.test.js b/frontend/src/lib/usage.test.js
index 3e524ef..9bf3272 100644
--- a/frontend/src/lib/usage.test.js
+++ b/frontend/src/lib/usage.test.js
@@ -154,10 +154,10 @@ describe('displayProviderId', () => {
it("a provider's own eco threshold wins over the global one", () => {
// Sentinel-2 caps at z14, so the global z15 would hide it at every zoom it
- // can serve; its own z11 keeps the useful z12-14 band alive.
- const s2 = { id: 'sentinel2', meter: 'sentinelhub', eco_max_zoom: 11 };
- expect(displayProviderId(s2, 11)).toBe('esri-world-imagery');
- expect(displayProviderId(s2, 12)).toBe('sentinel2');
+ // can serve; its own z7 keeps everything from z8 in alive.
+ const s2 = { id: 'sentinel2', meter: 'sentinelhub', eco_max_zoom: 7 };
+ expect(displayProviderId(s2, 7)).toBe('esri-world-imagery');
+ expect(displayProviderId(s2, 8)).toBe('sentinel2');
expect(displayProviderId(s2, 14)).toBe('sentinel2');
// the user's global setting doesn't drag it back under
expect(displayProviderId(s2, 14, { ecoMaxZoom: 15 })).toBe('sentinel2');
diff --git a/frontend/src/lib/workspaces.js b/frontend/src/lib/workspaces.js
index 5a138ca..7806d8e 100644
--- a/frontend/src/lib/workspaces.js
+++ b/frontend/src/lib/workspaces.js
@@ -43,7 +43,7 @@ export const HOME_WORKSPACE = {
/** The rail, in investigation order. */
export const WORKSPACES = [
{ id: 'collect', label: 'Sources', icon: 'download', tools: ['media', 'files', 'reverse'] },
- { id: 'examine', label: 'Examine', icon: 'inspect', tools: ['inspect'] },
+ { id: 'examine', label: 'Examine', icon: 'inspect', tools: ['inspect', 'collage'] },
{ id: 'map', label: 'Map', icon: 'satellite', tools: ['satellite', 'compare', 'detect', 'coordinates'] },
{ id: 'compose', label: 'Compose', icon: 'proof', tools: ['proof', 'post', 'notebook'] },
];
@@ -62,6 +62,7 @@ export const TOOL_LABELS = {
files: 'Files',
reverse: 'Reverse Search',
inspect: 'Inspect',
+ collage: 'Collage',
satellite: 'Satellite',
compare: 'Compare',
detect: 'Detect',
diff --git a/frontend/src/tools/Collage.render.svelte.test.js b/frontend/src/tools/Collage.render.svelte.test.js
new file mode 100644
index 0000000..fd50cf1
--- /dev/null
+++ b/frontend/src/tools/Collage.render.svelte.test.js
@@ -0,0 +1,293 @@
+// @vitest-environment happy-dom
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { flushSync, mount, unmount } from 'svelte';
+
+/**
+ * The Collage tool driven the way an analyst drives it: start a canvas, place a
+ * piece, rename it, export it. A collage is saved as it is made, so what these
+ * check is what reaches the server and when.
+ */
+
+const MEDIA = [
+ { path: 'media/roof.png', kind: 'image', title: 'Roof', filename: 'roof.png', thumbnail: 'media/.thumbs/r.jpg' },
+ { path: 'media/clip.mp4', kind: 'video', title: 'Convoy clip', filename: 'clip.mp4' },
+];
+let media = MEDIA;
+let works = [];
+const piece = (path) => ({
+ id: 'nd_1', frameId: null, save: { path, time: null, ops: [] }, w: 80, h: 60,
+ quad: [[0, 0], [80, 0], [80, 60], [0, 60]], frameOps: [], crop: null,
+});
+
+let collages = [];
+let saved = {};
+
+const get = vi.fn(async (path) => {
+ if (path === '/api/inspect/ops') return { filters: [], analyses: [] };
+ if (path === '/api/cases/case-a/media') return structuredClone(media);
+ if (path === '/api/cases/case-a/inspect/works') return structuredClone(works);
+ if (path.startsWith('/api/cases/case-a/inspect/works/')) {
+ throw Object.assign(new Error('nothing was inspected under that name'), { status: 404 });
+ }
+ if (path === '/api/cases/case-a/collages') return structuredClone(collages);
+ if (path.startsWith('/api/cases/case-a/collages/')) {
+ return structuredClone(saved[decodeURIComponent(path.split('/collages/')[1])]);
+ }
+ return {};
+});
+const post = vi.fn(async (path, body) => {
+ if (path === '/api/cases/case-a/collages') return { name: body.title, title: body.title };
+ return {};
+});
+vi.mock('../lib/api.js', () => ({ api: { get, post, put: vi.fn(), patch: vi.fn(), del: vi.fn() } }));
+
+// Reactive, so a change made elsewhere in the case can reach the open collage.
+const caseState = $state({ current: { id: 'case-a', folders: [] }, rev: 0 });
+const uiState = { tool: 'collage', openCollage: null, focusMedia: null };
+const toast = vi.fn();
+vi.mock('../lib/state.svelte.js', () => ({ caseState, uiState, toast, reloadCase: vi.fn(async () => {}) }));
+vi.mock('../lib/trash.js', () => ({ deletedToast: vi.fn() }));
+
+const { default: Collage } = await import('./Collage.svelte');
+const { workState } = await import('../lib/inspectWork.svelte.js');
+
+let live;
+let target;
+
+async function settle(ms = 0) {
+ if (ms) await new Promise((resolve) => setTimeout(resolve, ms));
+ for (let i = 0; i < 40; i += 1) await Promise.resolve();
+ flushSync();
+}
+
+const afterQuiet = () => settle(1000);
+const button = (text) => [...document.querySelectorAll('button')].find((b) => b.textContent.trim().startsWith(text));
+const collagePosts = () => post.mock.calls.filter(([path]) => path === '/api/cases/case-a/collages');
+
+async function start() {
+ target = document.createElement('div');
+ document.body.append(target);
+ live = mount(Collage, { target });
+ flushSync();
+ await settle();
+}
+
+beforeEach(() => {
+ collages = [];
+ saved = {};
+ media = MEDIA;
+ works = [];
+ post.mockClear();
+ toast.mockClear();
+ uiState.openCollage = null;
+ // A picture "loads" as soon as it is asked for, with a size to lay out.
+ vi.stubGlobal('Image', class {
+ naturalWidth = 80;
+ naturalHeight = 60;
+ set src(_value) {
+ setTimeout(() => this.onload?.(), 0);
+ }
+ });
+ globalThis.ResizeObserver ??= class { observe() {} disconnect() {} };
+});
+
+afterEach(() => {
+ if (live) unmount(live);
+ live = null;
+ target?.remove();
+ vi.unstubAllGlobals();
+});
+
+describe('a new collage', () => {
+ it('leaves the title to the tab, with no bar until a collage is open', async () => {
+ await start();
+
+ expect(target.querySelector('h2')).toBeNull();
+ expect(target.querySelector('.tool-header')).toBeNull();
+ button('New collage').click();
+ await settle();
+ expect(target.querySelector('.tool-header input[aria-label="Collage name"]')).not.toBeNull();
+ });
+
+ it('files nothing until a piece is placed', async () => {
+ collages = [{ name: 'Collage 1', title: 'Collage 1', pieces: 2 }];
+ await start();
+
+ button('New collage').click();
+ await settle();
+ await afterQuiet();
+
+ // named past the ones the case already holds
+ expect(target.querySelector('input[aria-label="Collage name"]').value).toBe('Collage 2');
+ expect(collagePosts()).toHaveLength(0);
+ });
+
+ it('is filed under its name once a case image is placed on it', async () => {
+ await start();
+ button('New collage').click();
+ await settle();
+
+ button('Images').click();
+ flushSync();
+ target.querySelector('.picker .thumb').click();
+ await settle(20);
+ await afterQuiet();
+
+ expect(collagePosts()).toHaveLength(1);
+ const [, body] = collagePosts()[0];
+ expect(body.name).toBeNull();
+ expect(body.title).toBe('Collage 1');
+ expect(body.spec.nodes).toHaveLength(1);
+ expect(body.spec.nodes[0].save).toEqual({ path: 'media/roof.png', time: null, ops: [] });
+ expect(body.spec.nodes[0]).not.toHaveProperty('url');
+ });
+});
+
+describe('an existing collage', () => {
+ beforeEach(() => {
+ collages = [{ name: 'Strip', title: 'Strip', pieces: 1 }];
+ saved.Strip = {
+ name: 'Strip', title: 'Strip',
+ spec: { width: 800, height: 400, transparent: true, nodes: [piece('media/roof.png')] },
+ };
+ });
+
+ it('opens from the list without writing anything', async () => {
+ await start();
+ button('Strip').click();
+ await settle(20);
+ await afterQuiet();
+
+ expect(target.querySelector('input[aria-label="Collage name"]').value).toBe('Strip');
+ expect(collagePosts()).toHaveLength(0);
+ });
+
+ it('refuses a rename onto a name another collage holds, and keeps its own', async () => {
+ post.mockImplementationOnce(async () => {
+ throw Object.assign(new Error('another collage already uses that name'), { status: 409 });
+ });
+ await start();
+ button('Strip').click();
+ await settle(20);
+
+ const input = target.querySelector('input[aria-label="Collage name"]');
+ input.value = 'Harbour';
+ input.dispatchEvent(new Event('input', { bubbles: true }));
+ input.dispatchEvent(new FocusEvent('blur'));
+ await settle(20);
+
+ expect(toast).toHaveBeenCalledWith('Another collage already uses that name', 'warn');
+ expect(input.value).toBe('Strip');
+ });
+
+ it('holds the export while a piece has lost its file', async () => {
+ saved.Strip.spec.nodes = [piece('media/gone.png')];
+ await start();
+ button('Strip').click();
+ await settle(20);
+
+ expect(target.textContent).toContain('1 piece lost its file. Remove it to save.');
+ const save = [...document.querySelectorAll('.save .btn-primary')][0];
+ expect(save.disabled).toBe(true);
+ expect(target.querySelector('.node.missing')).not.toBeNull();
+ });
+
+ it('shows a piece still rendering as loading, not as lost', async () => {
+ saved.Strip.spec.nodes = [{ ...piece('media/clip.mp4'), save: { path: 'media/clip.mp4', time: 2, ops: [] } }];
+ let finish;
+ vi.stubGlobal('fetch', vi.fn(() => new Promise((resolve) => (finish = resolve))));
+ URL.createObjectURL = vi.fn(() => 'blob:piece');
+ URL.revokeObjectURL = vi.fn();
+ await start();
+ button('Strip').click();
+ await settle(20);
+
+ const holder = target.querySelector('.node.placeholder');
+ expect(holder.classList.contains('missing')).toBe(false);
+ expect(holder.querySelector('.spinner')).not.toBeNull();
+ expect(target.textContent).not.toContain('lost its file');
+
+ finish(new Response(new Blob(['png'], { type: 'image/png' })));
+ await settle(20);
+ expect(target.querySelector('.node.placeholder')).toBeNull();
+ expect(target.querySelector('img.node').getAttribute('src')).toBe('blob:piece');
+ });
+
+ it('follows a piece whose file was renamed elsewhere', async () => {
+ await start();
+ button('Strip').click();
+ await settle(20);
+
+ // the rename rewrote the saved collage along with the file
+ media = [{ ...MEDIA[0], path: 'media/North roof.png', title: 'North roof' }, MEDIA[1]];
+ saved.Strip.spec.nodes = [piece('media/North roof.png')];
+ caseState.rev += 1;
+ await settle(20);
+
+ expect(target.querySelector('.node.missing')).toBeNull();
+ expect(target.textContent).not.toContain('lost its file');
+ });
+
+ it('marks a piece whose file was deleted elsewhere', async () => {
+ await start();
+ button('Strip').click();
+ await settle(20);
+
+ media = [MEDIA[1]];
+ caseState.rev += 1;
+ await settle(20);
+
+ expect(target.querySelector('.node.missing')).not.toBeNull();
+ expect(target.textContent).toContain('1 piece lost its file. Remove it to save.');
+ });
+
+ it('reopens from the sidebar by name', async () => {
+ uiState.openCollage = 'Strip';
+ await start();
+ await settle(20);
+
+ expect(target.querySelector('input[aria-label="Collage name"]').value).toBe('Strip');
+ expect(uiState.openCollage).toBeNull();
+ });
+});
+
+describe('frames from Inspect', () => {
+ const clipWork = { name: 'Convoy clip', title: 'Convoy clip', source: 'media/clip.mp4', frames: 2, kind: 'video' };
+
+ it('stops offering a work cleared in Inspect', async () => {
+ works = [clipWork];
+ await start();
+ button('New collage').click();
+ await settle();
+ expect(target.querySelector('.group-head').textContent).toContain('Convoy clip');
+
+ works = [];
+ workState.rev += 1;
+ await settle(20);
+
+ expect(target.querySelector('.group-head')).toBeNull();
+ });
+
+ it('lists a work under the name its file has now', async () => {
+ // a work that kept the name the file had before a rename
+ works = [{ ...clipWork, name: 'Old clip name', title: 'Old clip name' }];
+ await start();
+ button('New collage').click();
+ await settle();
+
+ expect(target.querySelector('.group-head .name').textContent).toBe('Convoy clip');
+ });
+
+ it('says so, rather than spinning, when a work is no longer there', async () => {
+ works = [clipWork];
+ await start();
+ button('New collage').click();
+ await settle();
+
+ target.querySelector('.group-head').click();
+ await settle(20);
+
+ expect(target.querySelector('.group .spinner')).toBeNull();
+ expect(target.querySelector('.group').textContent).toContain('No frames left here.');
+ });
+});
diff --git a/frontend/src/tools/Collage.svelte b/frontend/src/tools/Collage.svelte
new file mode 100644
index 0000000..b4bef66
--- /dev/null
+++ b/frontend/src/tools/Collage.svelte
@@ -0,0 +1,875 @@
+<script>
+ import { api } from '../lib/api.js';
+ import { fileUrl } from '../lib/fileUrl.js';
+ import { caseState, uiState, reloadCase, toast } from '../lib/state.svelte.js';
+ import {
+ uid, initialQuad, quadFromCropRect, collageBounds, COLLAGE_DEFAULT_SIZE,
+ } from '../lib/inspect.js';
+ import {
+ workState, collageSpec, collageSignature, missingPieces, isFiled,
+ } from '../lib/inspectWork.svelte.js';
+ import { nextName } from '../lib/naming.js';
+ import { createAutosave } from '../lib/autosave.svelte.js';
+ import { createHistory } from '../lib/history.js';
+ import { deletedToast } from '../lib/trash.js';
+ import Icon from '../components/Icon.svelte';
+ import Modal from '../components/Modal.svelte';
+ import ConfirmDialog from '../components/ConfirmDialog.svelte';
+ import CollageCanvas from './inspect/CollageCanvas.svelte';
+ import CollageMenu from './inspect/CollageMenu.svelte';
+ import PiecePicker from './inspect/PiecePicker.svelte';
+ import PieceCropModal from './inspect/PieceCropModal.svelte';
+ import SaveToCase from './inspect/SaveToCase.svelte';
+
+ // A collage lays out pieces from any number of files on one canvas: frames cut
+ // in Inspect, or images already in the case. It is a document of its own, saved
+ // as it is made (engine/inspectwork.py), and the picture it exports is media.
+
+ let mediaList = $state([]);
+ let works = $state([]);
+ let collages = $state([]);
+ let filters = $state([]);
+ let loadedFor = $state(null);
+ let listOpen = $state(false);
+ let deleting = $state(null); // the collage row a delete is being confirmed for
+ let exporting = $state(false);
+ let exportFolder = $state('');
+ let selectedIds = $state([]);
+ let cropPieceNode = $state(null);
+ let opening = $state(false);
+
+ const mediaPaths = $derived(new Set(mediaList.map((m) => m.path)));
+ const images = $derived(mediaList.filter((m) => m.kind === 'image'));
+ // A work is listed under its file's name as the file has it now, whatever the
+ // work itself is called.
+ const fileTitles = $derived(new Map(mediaList.map((m) => [m.path, m.title || m.filename])));
+ const pickerWorks = $derived(works.map((w) => ({ ...w, title: fileTitles.get(w.source) ?? w.title })));
+
+ // The open collage. `name` is the file it is saved under, absent until the
+ // first piece makes it worth filing.
+ const doc = $state({
+ open: false,
+ caseId: null,
+ name: null,
+ title: '',
+ width: COLLAGE_DEFAULT_SIZE.width,
+ height: COLLAGE_DEFAULT_SIZE.height,
+ background: '#12141c',
+ transparent: true,
+ nodes: [],
+ exported: null,
+ });
+ let docRun = 0;
+ const blobs = new Set();
+
+ const used = $derived.by(() => {
+ const counts = new Map();
+ for (const n of doc.nodes) if (n.frameId) counts.set(n.frameId, (counts.get(n.frameId) ?? 0) + 1);
+ return counts;
+ });
+ const lost = $derived(missingPieces(doc).length);
+ const exportedPath = $derived(
+ isFiled(doc.exported, collageSignature(doc), mediaPaths) ? doc.exported.path : null
+ );
+
+ // -- saving as it is made -----------------------------------------------------
+ let savedSignature = $state(null);
+ const signature = () => JSON.stringify(collageSpec(doc));
+
+ async function writeCollage(opts) {
+ if (!doc.open || opening) return;
+ const sig = signature();
+ if (sig === savedSignature) return;
+ // An empty new collage is not worth a file yet.
+ if (!doc.name && !doc.nodes.length) return;
+ const run = docRun;
+ const res = await api.post(
+ `/api/cases/${doc.caseId}/collages`,
+ { name: doc.name, title: doc.name ?? doc.title, spec: JSON.parse(sig) },
+ opts,
+ );
+ if (run !== docRun) return;
+ const first = !doc.name;
+ doc.name = res.name;
+ doc.title = res.title;
+ savedSignature = sig;
+ if (first) reloadCase(); // the sidebar lists the collage it just filed
+ }
+
+ const autosave = createAutosave({ write: () => writeCollage() });
+
+ $effect(() => {
+ const sig = signature();
+ if (!doc.open || opening || sig === savedSignature) return;
+ autosave.schedule();
+ });
+
+ $effect(() => {
+ if (uiState.tool !== 'collage') autosave.flush();
+ });
+ $effect(() => () => autosave.flush());
+
+ function onpagehide() {
+ if (autosave.pending) writeCollage({ keepalive: true }).catch(() => {});
+ }
+
+ const status = $derived.by(() => {
+ if (!doc.open || (!doc.name && !doc.nodes.length)) return '';
+ if (autosave.state.status === 'error') return 'error';
+ if (autosave.state.status === 'pending' || autosave.state.status === 'saving') return 'saving';
+ return 'saved';
+ });
+
+ // -- undo / redo ------------------------------------------------------------------
+ // Snapshots of the layout. A drag moves quads continuously; the debounced
+ // capture collapses it into one entry.
+ const history = createHistory();
+ let canUndo = $state(false);
+ let canRedo = $state(false);
+ let restoring = false; // plain: suppresses capture while a snapshot is put back
+ let historyTimer = null;
+ const layoutSnapshot = () =>
+ JSON.stringify({ width: doc.width, height: doc.height, nodes: doc.nodes });
+
+ function syncHistory() {
+ canUndo = history.canUndo;
+ canRedo = history.canRedo;
+ }
+
+ function anchorHistory() {
+ clearTimeout(historyTimer);
+ history.reset(layoutSnapshot());
+ syncHistory();
+ }
+
+ $effect(() => {
+ const json = layoutSnapshot();
+ if (restoring || !doc.open) return;
+ clearTimeout(historyTimer);
+ historyTimer = setTimeout(() => {
+ history.push(json);
+ syncHistory();
+ }, 350);
+ });
+
+ function applySnapshot(json) {
+ restoring = true;
+ const snap = JSON.parse(json);
+ doc.width = snap.width;
+ doc.height = snap.height;
+ doc.nodes = snap.nodes;
+ selectedIds = [];
+ // outlast the capture debounce so the restore itself is not recorded
+ setTimeout(() => (restoring = false), 400);
+ }
+
+ function undo() {
+ const json = history.undo();
+ if (json != null) applySnapshot(json);
+ syncHistory();
+ }
+
+ function redo() {
+ const json = history.redo();
+ if (json != null) applySnapshot(json);
+ syncHistory();
+ }
+
+ function onWindowKeydown(e) {
+ if (uiState.tool !== 'collage' || !doc.open) return;
+ const t = e.target;
+ if (['INPUT', 'TEXTAREA', 'SELECT'].includes(t.tagName) || t.isContentEditable) return;
+ if (!(e.ctrlKey || e.metaKey)) return;
+ const k = e.key.toLowerCase();
+ if (k === 'z') { e.preventDefault(); e.shiftKey ? redo() : undo(); }
+ else if (k === 'y') { e.preventDefault(); redo(); }
+ }
+
+ // -- the case ---------------------------------------------------------------------
+ async function ensureOps() {
+ if (filters.length) return;
+ const ops = await api.get('/api/inspect/ops');
+ filters = ops.filters.filter((f) => !['crop', 'rotate', 'remap'].includes(f.id));
+ }
+
+ async function refreshList(id = caseState.current?.id) {
+ if (!id) return;
+ try {
+ collages = await api.get(`/api/cases/${id}/collages`);
+ } catch {
+ collages = [];
+ }
+ }
+
+ async function refreshWorks(id = caseState.current?.id) {
+ if (!id) return;
+ try {
+ works = await api.get(`/api/cases/${id}/inspect/works`);
+ } catch {
+ works = [];
+ }
+ }
+
+ async function refresh(id = caseState.current?.id) {
+ if (!id) return;
+ mediaList = await api.get(`/api/cases/${id}/media`);
+ await Promise.all([refreshList(id), refreshWorks(id)]);
+ }
+
+ $effect(() => {
+ const id = caseState.current?.id;
+ caseState.rev;
+ if (id !== loadedFor) {
+ loadedFor = id;
+ mediaList = [];
+ collages = [];
+ works = [];
+ autosave.flush().finally(() => {
+ if (doc.caseId && doc.caseId !== caseState.current?.id) closeDoc();
+ });
+ if (id) {
+ ensureOps();
+ refresh(id);
+ }
+ } else if (id) {
+ refresh(id).then(recheckOpenDoc);
+ }
+ });
+
+ // A capture in Inspect adds frames the piece picker should offer.
+ $effect(() => {
+ workState.rev;
+ if (caseState.current?.id) refreshWorks();
+ });
+
+ /** A delete or a rename elsewhere may concern the open collage, or a file one of its pieces uses. */
+ function recheckOpenDoc() {
+ if (!doc.open || opening) return;
+ if (doc.name && !collages.some((c) => c.name === doc.name)) {
+ autosave.cancel();
+ toast(`The collage “${doc.title}” was deleted`, 'warn');
+ closeDoc();
+ return;
+ }
+ const gone = doc.nodes.filter((node) => !mediaPaths.has(node.save.path) && !node.missing);
+ if (!gone.length) return;
+ // A rename rewrites the saved collage to the file's new path and a delete does
+ // not, so reading it back tells the two apart.
+ if (doc.name && !autosave.pending) {
+ openCollage(doc.name);
+ return;
+ }
+ for (const node of gone) {
+ node.missing = true;
+ node.url = null;
+ }
+ }
+
+ $effect(() => {
+ if (uiState.tool === 'collage' && uiState.openCollage && caseState.current) {
+ const name = uiState.openCollage;
+ uiState.openCollage = null;
+ openCollage(name);
+ }
+ });
+
+ // -- opening ----------------------------------------------------------------------
+ function closeDoc() {
+ docRun += 1;
+ for (const url of blobs) URL.revokeObjectURL(url);
+ blobs.clear();
+ Object.assign(doc, {
+ open: false, caseId: null, name: null, title: '', ...COLLAGE_DEFAULT_SIZE,
+ background: '#12141c', transparent: true, nodes: [], exported: null,
+ });
+ savedSignature = null;
+ selectedIds = [];
+ cropPieceNode = null;
+ }
+
+ async function newCollage() {
+ listOpen = false;
+ await autosave.flush();
+ await refreshList();
+ closeDoc();
+ doc.open = true;
+ doc.caseId = caseState.current.id;
+ doc.title = nextName('collage', collages.map((c) => c.title));
+ savedSignature = signature();
+ anchorHistory();
+ }
+
+ async function openCollage(name) {
+ listOpen = false;
+ await autosave.flush();
+ await ensureOps();
+ closeDoc();
+ const run = docRun;
+ const caseId = caseState.current.id;
+ opening = true;
+ try {
+ // Which pieces lost their file is read off the media list, so it has to be in.
+ if (!mediaList.length) await refresh(caseId);
+ const saved = await api.get(`/api/cases/${caseId}/collages/${encodeURIComponent(name)}`);
+ if (run !== docRun) return;
+ const spec = saved.spec;
+ Object.assign(doc, {
+ open: true,
+ caseId,
+ name: saved.name,
+ title: saved.title,
+ width: spec.width ?? COLLAGE_DEFAULT_SIZE.width,
+ height: spec.height ?? COLLAGE_DEFAULT_SIZE.height,
+ background: spec.background ?? '#12141c',
+ transparent: spec.transparent ?? true,
+ exported: spec.exported ?? null,
+ nodes: (spec.nodes ?? []).map((n) => ({ ...n, url: null, baseUrl: null })),
+ });
+ savedSignature = signature();
+ anchorHistory();
+ renderPieces(run);
+ } catch (e) {
+ if (run === docRun) toast(e.message, 'danger');
+ } finally {
+ if (run === docRun) opening = false;
+ }
+ }
+
+ /**
+ * Pixels for every piece of a reopened collage, a few at a time so the canvas
+ * fills in as they land. `baseUrl` is the piece before its collage crop, which
+ * is what the crop editor draws on; a piece whose file is gone keeps its place
+ * and is marked, rather than dropped.
+ */
+ async function renderPieces(run) {
+ const queue = [];
+ for (const node of doc.nodes) {
+ if (mediaPaths.has(node.save.path)) queue.push(node);
+ else node.missing = true;
+ }
+ const next = async () => {
+ while (queue.length) {
+ const node = queue.shift();
+ try {
+ const frameOps = node.frameOps ?? node.save.ops ?? [];
+ const baseUrl = await pieceUrl(node.save.path, node.save.time, frameOps);
+ const url = node.crop ? await pieceUrl(node.save.path, node.save.time, node.save.ops) : baseUrl;
+ if (run !== docRun) return;
+ Object.assign(node, { baseUrl, url, frameOps });
+ } catch {
+ if (run === docRun) node.missing = true;
+ }
+ }
+ };
+ await Promise.all([next(), next(), next()]);
+ }
+
+ // -- pieces -----------------------------------------------------------------------
+ async function pieceUrl(path, time, ops = []) {
+ if (time == null && !ops.length) return fileUrl(doc.caseId, path);
+ const res = await fetch(`/api/cases/${doc.caseId}/inspect/render-preview`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ path, time: time ?? null, ops }),
+ });
+ if (!res.ok) {
+ let detail = 'render failed';
+ try {
+ detail = (await res.json()).detail;
+ } catch {
+ /* non-json */
+ }
+ throw new Error(detail);
+ }
+ const url = URL.createObjectURL(await res.blob());
+ blobs.add(url);
+ return url;
+ }
+
+ function imageSize(url) {
+ return new Promise((resolve) => {
+ const im = new Image();
+ im.onload = () => resolve({ w: im.naturalWidth, h: im.naturalHeight });
+ im.onerror = () => resolve({ w: 320, h: 240 });
+ im.src = url;
+ });
+ }
+
+ async function addPiece({ frameId, save }) {
+ const run = docRun;
+ try {
+ const url = await pieceUrl(save.path, save.time, save.ops);
+ const dim = await imageSize(url);
+ if (run !== docRun) return;
+ const off = 30 + (doc.nodes.length % 4) * 40;
+ const node = {
+ id: uid('nd'), frameId, url, baseUrl: url, w: dim.w, h: dim.h,
+ frameOps: save.ops, crop: null, save,
+ quad: initialQuad(dim.w, dim.h, doc.width * 0.5, off, off),
+ };
+ doc.nodes.push(node);
+ selectedIds = [node.id];
+ } catch (e) {
+ toast(e.message, 'danger');
+ }
+ }
+
+ // Re-render a piece with (or without) its crop, applied before the warp. The
+ // crop is relative to the uncropped snapshot, so re-cropping never compounds.
+ async function applyNodeCrop(node, crop) {
+ try {
+ const frameOps = node.frameOps ?? node.save?.ops ?? [];
+ const ops = crop ? [...frameOps, { op: 'crop', params: crop }] : [...frameOps];
+ const url = await pieceUrl(node.save.path, node.save.time, ops);
+ const dim = await imageSize(url);
+ // Keep the piece in place with the right proportions: back out to the
+ // full-image quad, then project the new crop rectangle onto it.
+ const prev = node.crop;
+ const baseQuad = prev
+ ? quadFromCropRect(node.quad, { x: -prev.x / prev.w, y: -prev.y / prev.h, w: 1 / prev.w, h: 1 / prev.h })
+ : node.quad;
+ node.quad = crop ? quadFromCropRect(baseQuad, crop) : baseQuad.map(([x, y]) => [x, y]);
+ Object.assign(node, { url, w: dim.w, h: dim.h, crop, save: { ...node.save, ops } });
+ } catch (e) {
+ toast(e.message, 'danger');
+ }
+ }
+
+ // Auto-stitch's panorama modes bake their warp into a piece's recipe, so the
+ // piece is re-derived from it, crop-free: whatever it showed is baked in now.
+ async function renderPiece(node, ops) {
+ const url = await pieceUrl(node.save.path, node.save.time, ops);
+ const dim = await imageSize(url);
+ Object.assign(node, {
+ url, baseUrl: url, w: dim.w, h: dim.h, frameOps: ops, crop: null, save: { ...node.save, ops },
+ });
+ }
+
+ function requestCrop(node, clear = false) {
+ if (node.missing) return;
+ if (clear) applyNodeCrop(node, null);
+ else cropPieceNode = node;
+ }
+
+ // -- naming -----------------------------------------------------------------------
+ // The field follows the collage's name, and goes back to it whenever a typed one
+ // is not taken: blank, refused, or abandoned with Escape.
+ let titleField = $state('');
+ $effect(() => {
+ titleField = doc.title;
+ });
+
+ async function commitTitle() {
+ const next = titleField.trim();
+ if (!next || next === doc.title) {
+ titleField = doc.title;
+ return;
+ }
+ if (!doc.name) {
+ doc.title = next; // the first save files it under this, numbered if taken
+ return;
+ }
+ await autosave.flush();
+ try {
+ const res = await api.post(`/api/cases/${doc.caseId}/collages`, {
+ name: doc.name, title: next, spec: collageSpec(doc),
+ });
+ doc.name = res.name;
+ doc.title = res.title;
+ savedSignature = signature();
+ refreshList();
+ reloadCase();
+ } catch (e) {
+ titleField = doc.title;
+ toast(e.status === 409 ? 'Another collage already uses that name' : e.message, 'warn');
+ }
+ }
+
+ function titleKey(e) {
+ if (e.key === 'Enter') e.currentTarget.blur();
+ else if (e.key === 'Escape') {
+ titleField = doc.title;
+ e.currentTarget.blur();
+ }
+ }
+
+ // -- export and delete ------------------------------------------------------------
+ async function exportCollage({ name, folder, note }) {
+ exporting = true;
+ exportFolder = folder ?? '';
+ const signatureNow = collageSignature(doc);
+ try {
+ // Always a transparent PNG of just the pieces, trimmed to their bounds: the
+ // size follows the layout, not a number typed somewhere.
+ const b = collageBounds(doc.nodes);
+ const nodes = doc.nodes.map((n) => ({ src: n.save, quad: n.quad.map(([x, y]) => [x - b.minX, y - b.minY]) }));
+ const res = await api.post(`/api/cases/${doc.caseId}/inspect/compose`, {
+ width: b.width, height: b.height, background: null, nodes, folder, label: name, notes: note,
+ });
+ if (res?.item?.path) doc.exported = { path: res.item.path, signature: signatureNow };
+ await reloadCase();
+ await refresh();
+ const dupe = res?.duplicate ? '. It matched media already in the case, which was renamed' : '';
+ toast(`Saved “${name}” to the case${dupe}`, 'ok');
+ } catch (e) {
+ toast(e.message, 'danger');
+ } finally {
+ exporting = false;
+ }
+ }
+
+ async function deleteCollage(row) {
+ deleting = null;
+ const caseId = caseState.current.id;
+ try {
+ if (doc.name === row.name) {
+ autosave.cancel();
+ closeDoc();
+ }
+ const result = await api.del(`/api/cases/${caseId}/collages/${encodeURIComponent(row.name)}`);
+ await refreshList();
+ await reloadCase();
+ deletedToast(caseId, result, row.title);
+ } catch (e) {
+ toast(e.message, 'danger');
+ }
+ }
+
+ function when(stamp) {
+ if (!stamp) return '';
+ const d = new Date(stamp);
+ return Number.isNaN(d.getTime()) ? '' : d.toLocaleDateString(undefined, { day: 'numeric', month: 'short', year: 'numeric' });
+ }
+</script>
+
+<svelte:window onkeydown={onWindowKeydown} {onpagehide} />
+
+{#snippet list()}
+ {#if collages.length}
+ <div class="rows">
+ {#each collages as row (row.name)}
+ <div class="row" class:current={row.name === doc.name}>
+ <button class="row-open" onclick={() => openCollage(row.name)}>
+ <Icon name="grid" size={15} />
+ <span class="row-title">{row.title}</span>
+ <span class="row-meta">
+ {row.pieces} piece{row.pieces === 1 ? '' : 's'}{when(row.updated_at) ? ` · ${when(row.updated_at)}` : ''}
+ </span>
+ </button>
+ <button class="btn btn-ghost btn-xs" onclick={() => (deleting = row)} aria-label="Delete collage" title="Delete collage">
+ <Icon name="trash" size={14} />
+ </button>
+ </div>
+ {/each}
+ </div>
+ {/if}
+{/snippet}
+
+<div class="tool">
+ {#if doc.open}
+ <div class="tool-header">
+ <input
+ class="input title-input"
+ bind:value={titleField}
+ onblur={commitTitle}
+ onkeydown={titleKey}
+ maxlength="200"
+ aria-label="Collage name"
+ />
+ {#if status === 'saving'}
+ <span class="status">Saving…</span>
+ {:else if status === 'saved'}
+ <span class="status"><Icon name="check" size={12} /> Saved</span>
+ {:else if status === 'error'}
+ <span class="status error" title={autosave.state.error}><Icon name="alert" size={12} /> Not saved</span>
+ <button class="btn btn-ghost btn-xs" onclick={() => autosave.flush()}>Retry</button>
+ {/if}
+ <div class="spacer"></div>
+ <button class="btn btn-ghost btn-sm" title="Undo (Ctrl+Z)" disabled={!canUndo} onclick={undo}>
+ <Icon name="undo" size={15} />
+ </button>
+ <button class="btn btn-ghost btn-sm" title="Redo (Ctrl+Shift+Z / Ctrl+Y)" disabled={!canRedo} onclick={redo}>
+ <Icon name="redo" size={15} />
+ </button>
+ <button class="btn btn-sm" onclick={() => { refreshList(); listOpen = true; }} title="Open another collage">
+ <Icon name="folderOpen" size={14} /> Collages
+ </button>
+ <button class="btn btn-sm" onclick={newCollage} title="Start an empty canvas">
+ <Icon name="plus" size={14} /> New
+ </button>
+ </div>
+ {/if}
+
+ {#if !caseState.current}
+ <div class="empty">
+ <Icon name="grid" size={40} />
+ <p>Open a case to lay out a collage.</p>
+ </div>
+ {:else if !doc.open}
+ <div class="start">
+ <div class="start-col">
+ <div class="start-head">
+ <div>
+ <h3>Collages</h3>
+ <p>Lay out frames and images on one canvas, then save the picture to the case.</p>
+ </div>
+ <button class="btn btn-primary" onclick={newCollage}><Icon name="plus" size={15} /> New collage</button>
+ </div>
+ {#if opening}
+ <span class="spinner" aria-label="Opening"></span>
+ {:else}
+ {@render list()}
+ {/if}
+ </div>
+ </div>
+ {:else}
+ <div class="workspace">
+ <div class="viewer">
+ <CollageCanvas collage={doc} bind:selectedIds {requestCrop} />
+ </div>
+ <aside class="panel">
+ <div class="section first">
+ <div class="section-head"><span><Icon name="plus" size={14} /> Add pieces</span></div>
+ <PiecePicker
+ caseId={doc.caseId}
+ {filters}
+ works={pickerWorks}
+ {images}
+ {used}
+ rev={workState.rev}
+ onadd={addPiece}
+ />
+ </div>
+ <div class="section">
+ <CollageMenu collage={doc} bind:selectedIds {requestCrop} {renderPiece} />
+ </div>
+ <div class="section">
+ <SaveToCase
+ defaultName={doc.title}
+ filedPath={exportedPath}
+ busy={exporting}
+ blocked={!doc.nodes.length
+ ? 'Add a piece first.'
+ : lost
+ ? `${lost} piece${lost === 1 ? '' : 's'} lost ${lost === 1 ? 'its' : 'their'} file. Remove ${lost === 1 ? 'it' : 'them'} to save.`
+ : ''}
+ hint="Saves only the pieces, on a transparent background, trimmed to their bounds."
+ bind:folder={exportFolder}
+ onsave={exportCollage}
+ />
+ </div>
+ </aside>
+ </div>
+ {/if}
+
+ {#if cropPieceNode}
+ <PieceCropModal
+ node={cropPieceNode}
+ onapply={(crop) => { applyNodeCrop(cropPieceNode, crop); cropPieceNode = null; }}
+ onclose={() => (cropPieceNode = null)}
+ />
+ {/if}
+
+ {#if listOpen}
+ <Modal title="Collages" width="480px" onclose={() => (listOpen = false)}>
+ {#if collages.length}
+ {@render list()}
+ {:else}
+ <p class="hint">No collage saved in this case yet.</p>
+ {/if}
+ </Modal>
+ {/if}
+
+ {#if deleting}
+ <ConfirmDialog
+ title="Delete this collage?"
+ message={`“${deleting.title}” goes to the Trash.`}
+ detail="A picture already saved from it stays in the Media Library."
+ confirmLabel="Delete"
+ tone="danger"
+ icon="trash"
+ onconfirm={() => deleteCollage(deleting)}
+ oncancel={() => (deleting = null)}
+ />
+ {/if}
+</div>
+
+<style>
+ .tool {
+ display: flex;
+ flex-direction: column;
+ height: 100%;
+ }
+ .tool-header {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ padding: 14px 16px 12px;
+ border-bottom: 1px solid var(--border);
+ flex-shrink: 0;
+ }
+ .title-input {
+ width: 260px;
+ }
+ .status {
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ color: var(--text-3);
+ font-size: var(--fs-xs);
+ }
+ .status.error {
+ color: var(--danger);
+ }
+ .spacer {
+ flex: 1;
+ }
+ .empty {
+ flex: 1;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ gap: 12px;
+ color: var(--text-3);
+ text-align: center;
+ }
+ /* The whole panel scrolls and the column sits centred in it, so the wheel works
+ over the margins and the scrollbar stays on the edge. */
+ .start {
+ flex: 1;
+ min-height: 0;
+ overflow: auto;
+ }
+ .start-col {
+ display: flex;
+ flex-direction: column;
+ gap: 16px;
+ max-width: 720px;
+ margin: 0 auto;
+ padding: 24px 20px;
+ }
+ .start-head {
+ display: flex;
+ align-items: flex-start;
+ justify-content: space-between;
+ gap: 16px;
+ }
+ .start-head h3 {
+ font-size: var(--fs-md);
+ font-weight: 700;
+ margin: 0 0 4px;
+ }
+ .start-head p {
+ margin: 0;
+ color: var(--text-3);
+ font-size: var(--fs-sm);
+ }
+ .rows {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ }
+ .row {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ }
+ .row-open {
+ flex: 1;
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ min-width: 0;
+ padding: 9px 11px;
+ text-align: left;
+ border: 1px solid var(--border);
+ border-radius: var(--r-md);
+ background: var(--bg-2);
+ color: var(--text-2);
+ }
+ .row-open:hover,
+ .row.current .row-open {
+ border-color: var(--accent);
+ }
+ .row-title {
+ flex: 1;
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ color: var(--text-1);
+ font-size: var(--fs-sm);
+ font-weight: 600;
+ }
+ .row-meta {
+ color: var(--text-3);
+ font-size: var(--fs-xs);
+ white-space: nowrap;
+ }
+ .spinner {
+ align-self: center;
+ width: 24px;
+ height: 24px;
+ border: 3px solid var(--border);
+ border-top-color: var(--accent);
+ border-radius: 50%;
+ animation: spin 0.7s linear infinite;
+ }
+ @keyframes spin {
+ to {
+ transform: rotate(360deg);
+ }
+ }
+ .workspace {
+ flex: 1;
+ display: flex;
+ min-height: 0;
+ }
+ .viewer {
+ flex: 1;
+ min-width: 0;
+ display: flex;
+ background: var(--bg-0);
+ overflow: hidden;
+ }
+ .panel {
+ width: 320px;
+ flex-shrink: 0;
+ border-left: 1px solid var(--border);
+ background: var(--bg-1);
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+ min-height: 0;
+ overflow: auto;
+ padding: 14px;
+ }
+ .section {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ border-top: 1px solid var(--border);
+ padding-top: 12px;
+ }
+ .section.first {
+ border-top: 0;
+ padding-top: 0;
+ }
+ .section-head {
+ display: flex;
+ align-items: center;
+ font-weight: 600;
+ font-size: var(--fs-sm);
+ }
+ .section-head span {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ }
+ .hint {
+ color: var(--text-3);
+ font-size: var(--fs-sm);
+ margin: 0;
+ }
+</style>
diff --git a/frontend/src/tools/Compare.pair.test.js b/frontend/src/tools/Compare.pair.test.js
index c5920c8..d3dcbc0 100644
--- a/frontend/src/tools/Compare.pair.test.js
+++ b/frontend/src/tools/Compare.pair.test.js
@@ -47,3 +47,31 @@ describe('Compare here', () => {
expect(compare).toContain('uiState.compareAt = null;');
});
});
+
+describe('an export kept in the case', () => {
+ it('is offered beside the copy on disk, and files the same image under its comparison', () => {
+ expect(compare).toContain('<input type="checkbox" bind:checked={keepInCase} />');
+ expect(compare).toContain('Also keep it in this case');
+ const keep = compare.slice(compare.indexOf('async function keepExport('));
+ expect(keep).toContain("form.append('spec', JSON.stringify(sessionSpec()));");
+ expect(keep).toContain('pictureDateFields(pictureDates())');
+ expect(keep).toContain('/compare/sessions/${encodeURIComponent(openedSession.name)}/images');
+ expect(compare).toContain("const kept = await keepExport(owner.id, 'png', blob);");
+ expect(compare).toContain('const kept = await keepExport(owner.id, animation, frameA, frameB);');
+ });
+
+ it('asks for a name first when the comparison was never saved, then exports', () => {
+ const run = compare.slice(compare.indexOf('async function runExport('));
+ expect(run).toContain('if (keepInCase && !openedSession) {');
+ expect(run).toContain('exportAfterSave = true;');
+ const save = compare.slice(compare.indexOf('async function performSessionSave('));
+ expect(save).toContain('await runExport();');
+ // cancelling the name cancels the export it was asked for
+ expect(compare).toContain('function closeSaveDialog() {');
+ });
+
+ it('reopens a saved comparison from its own card on the map', () => {
+ expect(compare).toContain("if (row?.kind === 'comparison' && row.session) requestOpenSession(row.session);");
+ expect(compare).toContain('onedit={editSaved}');
+ });
+});
diff --git a/frontend/src/tools/Compare.render.test.js b/frontend/src/tools/Compare.render.test.js
index 61b9c88..97cdb7c 100644
--- a/frontend/src/tools/Compare.render.test.js
+++ b/frontend/src/tools/Compare.render.test.js
@@ -113,12 +113,14 @@ const toast = vi.fn();
const ensureCase = vi.fn(async () => ({ id: 'case-a' }));
const reloadCase = vi.fn(async () => {});
const caseState = { current: { id: 'case-a' } };
-const uiState = { tool: 'compare', openCompare: null };
+// Reactive, so a tab switch wakes the effects that watch it.
+const { uiState } = await import('./detect/uistate.fixture.svelte.js');
+const prefs = { homeView: { lat: 48.8566, lon: 2.3522, zoom: 16 }, units: 'metric', mapSync: false };
vi.mock('../lib/state.svelte.js', () => ({
caseState,
ensureCase,
fmtCoords: (lat, lon) => `${lat.toFixed(5)}, ${lon.toFixed(5)}`,
- prefs: { homeView: { lat: 48.8566, lon: 2.3522, zoom: 16 }, units: 'metric' },
+ prefs,
prefsReady: Promise.resolve(),
reloadCase,
toast,
@@ -142,6 +144,8 @@ function fakeEngine(opening, container) {
container,
setBearing: vi.fn((bearing) => (camera.bearing = bearing)),
setView: vi.fn((view, zoom) => (camera = { ...camera, ...view, zoom })),
+ setCamera: vi.fn((next) => (camera = { lat: next.lat, lon: next.lon, zoom: next.zoom, bearing: next.bearing ?? 0 })),
+ maxZoom: vi.fn(() => 19),
syncView: vi.fn((view, zoom) => (camera = { ...camera, ...view, zoom })),
resize: vi.fn(),
snapshot: vi.fn(() => ({ width: 400, height: 300 })),
@@ -239,6 +243,13 @@ beforeEach(() => {
vi.clearAllMocks();
engines.length = 0;
releases = [];
+ uiState.tool = 'compare';
+ uiState.openCompare = null;
+ uiState.compareAt = null;
+ uiState.lookAt = null;
+ uiState.mapView = null;
+ uiState.mapPoint = null;
+ prefs.mapSync = false;
});
afterEach(() => {
@@ -666,6 +677,43 @@ describe('Compare', () => {
expect(drawn.some((path) => path.getAttribute('stroke-dasharray') === '8 6')).toBe(true);
});
+ it('opens the right-clicked point in Satellite or Detect, at the zoom it was read at', async () => {
+ await open();
+ await add('A');
+ await add('B');
+ engines[0].handlers.contextmenu({ lat: 43.3, lon: 5.4, x: 120, y: 90 });
+ flushSync();
+ button('Open in', target.querySelector('[role="menu"]')).click();
+ await settle();
+ const sub = target.querySelector('[role="menu"][aria-label="Open this point in"]');
+ const rows = [...sub.querySelectorAll('[role="menuitem"]')].map((row) => row.textContent.trim());
+ expect(rows.slice(0, 2)).toEqual(['Satellite', 'Detect']);
+ expect(rows).not.toContain('Compare');
+ button('Detect', sub).click();
+ flushSync();
+ expect(uiState.tool).toBe('detect');
+ expect(uiState.lookAt).toEqual({ tool: 'detect', lat: 43.3, lon: 5.4, zoom: 16 });
+ });
+
+ it('moves both maps to a point another tab asked about, and keeps its pictures', async () => {
+ releases = [{ release: 30, date: '2026-09-01' }, { release: 20, date: '2025-06-01' }];
+ uiState.lookAt = { tool: 'compare', lat: 12.76, lon: 43.65, zoom: 15 };
+ vi.useFakeTimers({ toFake: ['Date'] });
+ vi.setSystemTime(new Date('2026-09-23T12:00:00Z'));
+ try {
+ await openFresh();
+ } finally {
+ vi.useRealTimers();
+ }
+ expect(uiState.lookAt).toBe(null);
+ expect(engines).toHaveLength(2);
+ for (const engine of engines) {
+ expect(engine.camera()).toMatchObject({ lat: 12.76, lon: 43.65, zoom: 15 });
+ }
+ // the opening pair was still built: the point moved the camera, not the pictures
+ expect(target.querySelectorAll('.empty-slot')).toHaveLength(0);
+ });
+
it('saves a place on the right-clicked point without leaving the comparison', async () => {
await open();
await add('A');
@@ -776,3 +824,69 @@ describe('Compare', () => {
expect(target.querySelector('.badge')).toBeNull();
});
});
+
+describe('one camera for the map tabs', () => {
+ const SATELLITE = { lat: 12.7615, lon: 43.6571, zoom: 17, bearing: 30, by: 'satellite' };
+
+ /** The opening pair, both sides built: today's imagery against a year back. */
+ async function openPairOfMaps() {
+ releases = [{ release: 30, date: '2026-09-01' }, { release: 20, date: '2025-06-01' }];
+ vi.useFakeTimers({ toFake: ['Date'] });
+ vi.setSystemTime(new Date('2026-09-23T12:00:00Z'));
+ try {
+ await openFresh();
+ } finally {
+ vi.useRealTimers();
+ }
+ }
+
+ it('opens both maps where the other map tabs left the window', async () => {
+ prefs.mapSync = true;
+ uiState.mapView = { ...SATELLITE };
+ await openPairOfMaps();
+ expect(engines).toHaveLength(2);
+ for (const engine of engines) {
+ expect(engine.camera()).toMatchObject({ lat: SATELLITE.lat, lon: SATELLITE.lon, zoom: 17 });
+ }
+ });
+
+ it('writes where it comes to rest, for the other map tabs and for Coordinates', async () => {
+ prefs.mapSync = true;
+ await openPairOfMaps();
+ engines[0].handlers['view-settled']({ lat: 43.3, lon: 5.4, zoom: 15, bearing: 12 });
+ flushSync();
+ expect(uiState.mapView).toEqual({ lat: 43.3, lon: 5.4, zoom: 15, bearing: 12, by: 'compare' });
+ expect(uiState.mapPoint).toEqual({ lat: 43.3, lon: 5.4, zoom: 15 });
+ });
+
+ it('takes the window camera in one jump when it shows again', async () => {
+ prefs.mapSync = true;
+ await openPairOfMaps();
+ uiState.tool = 'satellite';
+ uiState.mapView = { ...SATELLITE };
+ flushSync();
+ expect(engines[0].setCamera).not.toHaveBeenCalled();
+ uiState.tool = 'compare';
+ flushSync();
+ // one map takes it; the camera link brings the other along
+ const took = engines.filter((engine) => engine.setCamera.mock.calls.length);
+ expect(took).toHaveLength(1);
+ expect(took[0].setCamera).toHaveBeenCalledWith(expect.objectContaining({ ...SATELLITE }));
+ });
+
+ it('keeps a saved comparison on the ground it was saved on', async () => {
+ prefs.mapSync = true;
+ await open();
+ button('Open', target).click();
+ await settle();
+ button('Harbour change', document.querySelector('[role="dialog"]')).click();
+ await settle();
+ uiState.tool = 'satellite';
+ uiState.mapView = { ...SATELLITE };
+ flushSync();
+ uiState.tool = 'compare';
+ flushSync();
+ for (const engine of engines) expect(engine.setCamera).not.toHaveBeenCalled();
+ expect(target.querySelector('.badge')).toBeNull();
+ });
+});
diff --git a/frontend/src/tools/Compare.svelte b/frontend/src/tools/Compare.svelte
index 514a11b..62f2d97 100644
--- a/frontend/src/tools/Compare.svelte
+++ b/frontend/src/tools/Compare.svelte
@@ -20,7 +20,8 @@
uiState,
} from '../lib/state.svelte.js';
import { saveRelation } from '../lib/relations.svelte.js';
- import { actionsFor } from '../lib/map/contextMenu.js';
+ import { actionsFor, otherMapTools } from '../lib/map/contextMenu.js';
+ import { openMapAt } from '../lib/navigate.js';
import {
COMPARE_LAYERS,
COMPARE_MODES,
@@ -41,6 +42,7 @@
canvasBlob,
comparisonFilename,
composeComparison,
+ pictureDateFields,
} from '../lib/map/compareExport.js';
import {
changeCompatibility,
@@ -64,7 +66,7 @@
destinationLabel,
readDestinations,
} from '../lib/exportDest.js';
- import { startRotateDrag } from '../lib/map/gestures.js';
+ import { turnFromKey, turnFromPress } from '../lib/map/gestures.js';
import {
askable as firmsAskable,
tileParams as firmsTileParams,
@@ -82,6 +84,7 @@
import { RADAR_ID, radarId } from '../lib/radar.js';
import Icon from '../components/Icon.svelte';
import Compass from '../components/Compass.svelte';
+ import TurnGuide from '../components/TurnGuide.svelte';
import ConfirmDialog from '../components/ConfirmDialog.svelte';
import ExportFolderPicker from '../components/ExportFolderPicker.svelte';
import Modal from '../components/Modal.svelte';
@@ -89,12 +92,14 @@
import ModeControl from './compare/ModeControl.svelte';
import SourceCard from './compare/SourceCard.svelte';
import DifferenceBar from './compare/DifferenceBar.svelte';
+ import { fromDifference } from '../lib/map/analyzerRules.js';
import PassStrip from './compare/PassStrip.svelte';
import CopernicusNeeded from '../components/CopernicusNeeded.svelte';
import { copernicusNeed } from '../lib/copernicusSetup.js';
import { stripArchive } from '../lib/map/passStrip.js';
import './mapdock.css';
import { linkCameras } from '../lib/map/cameraLink.js';
+ import { shareView } from '../lib/map/sharedView.js';
import { detectCaptures } from '../lib/map/changeCapture.js';
import { apply, compassAngle, cssMatrix, frameToFrame, fromMercator, screenToMercator } from '../lib/map/groundFrame.js';
import MapSurface from './satellite/MapSurface.svelte';
@@ -145,6 +150,10 @@
let openedSession = $state(null); // { name, title } | null
let savedSignature = $state(null);
let saveDialog = $state(false);
+ // Keeping an export files it under its comparison, which needs a name first:
+ // an export asked while unsaved opens the save dialog and runs once it is saved.
+ let keepInCase = $state(false);
+ let exportAfterSave = false;
let sessionDialog = $state(false);
let sessionBusy = $state(false);
let sessionList = $state([]);
@@ -392,7 +401,10 @@
await prefsReady;
if (gone) return;
home = { ...prefs.homeView };
- view = { ...home };
+ // Where the other map tabs left the window, when they share a camera.
+ const shared = share.opening();
+ view = shared ? { lat: shared.lat, lon: shared.lon, zoom: shared.zoom } : { ...home };
+ bearing = shared?.bearing ?? 0;
await loadProviders();
if (gone) return;
// A handoff from the map brings its own pair.
@@ -432,6 +444,12 @@
return `${Number(at.lat).toFixed(5)}, ${Number(at.lon).toFixed(5)}`;
}
+ /** A card's own action: a comparison reopens here, anything else is flown to. */
+ function editSaved(row) {
+ if (row?.kind === 'comparison' && row.session) requestOpenSession(row.session);
+ else openSaved(row);
+ }
+
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);
@@ -490,6 +508,10 @@
view = { lat: next.lat, lon: next.lon, zoom: next.zoom };
bearing = next.bearing ?? bearing;
invalidateChangeAssist();
+ // Where the map is, for Coordinates, and where the window looks: hidden
+ // too, when a pan's glide ends after a switch of tab.
+ uiState.mapPoint = { lat: next.lat, lon: next.lon, zoom: next.zoom };
+ share.settled(next, (which === 'a' ? a : b).engine?.maxZoom());
}
function onSurfaceBearing(which, next) {
@@ -593,20 +615,27 @@
{ 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, {
+ const down = (event) =>
+ turnFromPress(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());
});
+ // Shift and an arrow turn the pair, whether one map is up or both: the
+ // camera is shared, so turning the first turns the other.
+ $effect(() => {
+ if (uiState.tool !== 'compare' || !primeEngine) return;
+ const engine = primeEngine;
+ const onKey = (event) => turnFromKey(engine, event);
+ document.addEventListener('keydown', onKey);
+ return () => document.removeEventListener('keydown', onKey);
+ });
+
// 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(() => {
@@ -885,13 +914,25 @@
? 'Comparison and animated preview saved to My work'
: 'Comparison and preview saved to My work', 'ok');
}
+ if (exportAfterSave) {
+ exportAfterSave = false;
+ sessionBusy = false;
+ await runExport();
+ }
} catch (error) {
toast(`Could not save the comparison: ${error.message}`, 'danger', 6500);
} finally {
+ // an export waiting on this save runs above or not at all
+ exportAfterSave = false;
sessionBusy = false;
}
}
+ function closeSaveDialog() {
+ saveDialog = false;
+ exportAfterSave = false;
+ }
+
async function openSessionList() {
sessionDialog = true;
sessionBusy = true;
@@ -1013,6 +1054,45 @@
b.engine?.resize();
}
+ /**
+ * The camera this window's map tabs share (`lib/map/sharedView.js`), taken
+ * when this tab shows. One map takes it and the link brings the other along;
+ * with neither built, the camera they will open on moves.
+ *
+ * A saved comparison keeps the ground it was saved on: its camera is part of
+ * what was saved, and a pan made in another tab would leave it unsaved.
+ */
+ const share = shareView('compare', { state: uiState, enabled: () => prefs.mapSync });
+
+ $effect(() => {
+ uiState.mapView;
+ if (uiState.tool !== 'compare' || !home) return;
+ untrack(() => {
+ if (openedSession) return;
+ const engine = a.engine ?? b.engine;
+ const next = share.pending(engine ? engine.camera() : { ...view, bearing });
+ if (!next) return;
+ if (engine) engine.setCamera(next);
+ else {
+ view = { lat: next.lat, lon: next.lon, zoom: next.zoom };
+ bearing = next.bearing ?? 0;
+ }
+ });
+ });
+
+ // Another map tab asked to look here: the camera goes, the two pictures stay.
+ // A surface not built yet opens on `view`; one already up is moved.
+ $effect(() => {
+ const asked = uiState.lookAt;
+ if (uiState.tool !== 'compare' || asked?.tool !== 'compare' || !home) return;
+ untrack(() => {
+ uiState.lookAt = null;
+ const zoom = Number.isFinite(asked.zoom) ? asked.zoom : view.zoom;
+ view = { lat: asked.lat, lon: asked.lon, zoom };
+ for (const target of [a, b]) target.engine?.setView(view, zoom);
+ });
+ });
+
$effect(() => {
if (uiState.tool !== 'compare' || !uiState.compareAt || !imagery.providers.length) return;
const pair = uiState.compareAt;
@@ -1179,6 +1259,19 @@
changeTimer = setTimeout(() => void refreshChangeAssist({ fetch: false }), 180);
}
+ /** Difference's index reading, kept as an analyzer of your own in Detect. */
+ async function saveAsAnalyzer() {
+ try {
+ const saved = await api.post('/api/compare/analyzers', fromDifference(changeOptions));
+ toast(`${saved.name} is in your Detect analyzers`, 'ok', 7000, {
+ label: 'Open in Detect',
+ onClick: () => { uiState.openAnalyzer = `analyzer:${saved.id}`; uiState.tool = 'detect'; },
+ });
+ } catch (error) {
+ toast(error.message, 'danger');
+ }
+ }
+
async function refreshChangeAssist({ fetch = true } = {}) {
if (!difference || !changeStatus.ok) return;
if (!changeStatus.methods.includes(changeOptions.method)) { changeError = 'Choose a compatible method'; return; }
@@ -1394,6 +1487,7 @@
const pointActions = $derived(
actionsFor(both ? ['lookup', 'place', 'measure'] : ['lookup', 'place'])
);
+ const pointTools = otherMapTools('compare');
function onMapContextMenu(side, at) {
pointLookupSeq += 1;
@@ -1431,6 +1525,8 @@
await tick();
(side === 'a' ? canvasA : canvasB)?.startFrom([point.lon, point.lat]);
toast('Click the far end of the measure', 'info', 4000);
+ } else if (id === 'goto') {
+ openMapAt(value, { ...point, zoom: view.zoom });
}
}
@@ -1675,8 +1771,21 @@
return canvasBlob(compose(sources, { renderChangeMap }));
}
+ /** When each picture on screen was taken, as the surfaces that drew them say. */
+ function pictureDates() {
+ return { a: a.surface?.provenance?.() ?? {}, b: b.surface?.provenance?.() ?? {} };
+ }
+
+ /** The export's name: the comparison's, then the two pictures' dates. */
+ function exportName() {
+ const { a: first, b: second } = pictureDates();
+ return comparisonFilename(sessionName, { a: first.imageryWhen, b: second.imageryWhen });
+ }
+
async function saveWorkingPreview(caseId, name) {
const form = new FormData();
+ // The saved image files the date of each picture it shows, as a capture does.
+ for (const [field, value] of pictureDateFields(pictureDates())) form.append(field, value);
if (mode === 'blink') {
const renderChangeMap = await exportedChange();
const sources = await exportSources();
@@ -1708,6 +1817,35 @@
toast(`${action}: ${error.message}`, 'danger', 7000);
}
+ /**
+ * File the export just written as an image of this comparison in the case.
+ * It carries the reading on screen, not the saved one, since that is what it
+ * shows. Answers what the toast adds, and says so itself when it fails: the
+ * copy on disk is already written either way.
+ */
+ async function keepExport(caseId, format, imageA, imageB = null) {
+ if (!keepInCase || !openedSession) return '';
+ const form = new FormData();
+ form.append('image_a', imageA, 'comparison-a.png');
+ if (imageB) form.append('image_b', imageB, 'comparison-b.png');
+ form.append('format', format);
+ form.append('interval', String(blinkInterval));
+ form.append('filename', exportName());
+ form.append('spec', JSON.stringify(sessionSpec()));
+ for (const [field, value] of pictureDateFields(pictureDates())) form.append(field, value);
+ try {
+ await api.post(
+ `/api/cases/${caseId}/compare/sessions/${encodeURIComponent(openedSession.name)}/images`,
+ form,
+ );
+ await reloadCase();
+ return ' and kept in the case';
+ } catch (error) {
+ toast(`Exported, but not kept in the case: ${error.message}`, 'warn', 7000);
+ return '';
+ }
+ }
+
async function exportPng() {
if (outputBusy) return;
outputBusy = 'png';
@@ -1715,12 +1853,15 @@
const owner = await ensureCase();
const blob = await comparisonBlob();
const result = await api.post(`/api/cases/${owner.id}/plates`, {
- filename: comparisonFilename(),
+ filename: exportName(),
format: 'png',
png: await blobBase64(blob),
+ // Named by its pictures' dates, which another comparison of the pair shares.
+ overwrite: false,
});
+ const kept = await keepExport(owner.id, 'png', blob);
rightPanel = null;
- toast(`${result.file} written to ${destinationLabel(result.path)}`, 'ok', 5200, {
+ toast(`${result.file} written to ${destinationLabel(result.path)}${kept}`, 'ok', 5200, {
label: 'Show',
onClick: () => showExports(),
});
@@ -1745,10 +1886,11 @@
form.append('image_b', frameB, 'comparison-b.png');
form.append('animation', animation);
form.append('interval', String(blinkInterval));
- form.append('filename', comparisonFilename());
+ form.append('filename', exportName());
const result = await api.post(`/api/cases/${owner.id}/compare/gif`, form);
+ const kept = await keepExport(owner.id, animation, frameA, frameB);
rightPanel = null;
- toast(`${result.file} written to ${destinationLabel(result.path)}`, 'ok', 5200, {
+ toast(`${result.file} written to ${destinationLabel(result.path)}${kept}`, 'ok', 5200, {
label: 'Show',
onClick: () => showExports(),
});
@@ -1760,6 +1902,11 @@
}
async function runExport() {
+ if (keepInCase && !openedSession) {
+ exportAfterSave = true;
+ saveDialog = true;
+ return;
+ }
if (exportKind === 'png') await exportPng();
else await exportGif(exportKind);
}
@@ -1994,6 +2141,7 @@
zoom={view.zoom}
format={prefs.coordFormat}
actions={pointActions}
+ tools={pointTools}
lookup={pointMenu.lookup}
onpick={onPointMenu}
onclose={closePointMenu}
@@ -2006,7 +2154,7 @@
caseId={caseState.current?.id}
coords={savedCoords}
onopen={openSaved}
- onedit={openSaved}
+ onedit={editSaved}
onrefresh={reloadCase}
/>
{/if}
@@ -2032,7 +2180,7 @@
editVertices={true} {annotationSide} {bearing} turnable={true} onchange={setAnnotations} />
{/if}
{#if rotating?.which === 'a'}
- <div class="rotate-pivot" style:left={`${rotating.x}px`} style:top={`${rotating.y}px`} aria-hidden="true"></div>
+ <TurnGuide x={rotating.x} y={rotating.y} />
{/if}
</div>
{:else}
@@ -2087,6 +2235,7 @@
zoom={view.zoom}
format={prefs.coordFormat}
actions={pointActions}
+ tools={pointTools}
lookup={pointMenu.lookup}
onpick={onPointMenu}
onclose={closePointMenu}
@@ -2099,7 +2248,7 @@
caseId={caseState.current?.id}
coords={savedCoords}
onopen={openSaved}
- onedit={openSaved}
+ onedit={editSaved}
onrefresh={reloadCase}
/>
{/if}
@@ -2120,7 +2269,7 @@
editVertices={true} {annotationSide} {bearing} turnable={true} onchange={setAnnotations} />
{/if}
{#if rotating?.which === 'b'}
- <div class="rotate-pivot" style:left={`${rotating.x}px`} style:top={`${rotating.y}px`} aria-hidden="true"></div>
+ <TurnGuide x={rotating.x} y={rotating.y} />
{/if}
</div>
{:else}
@@ -2197,7 +2346,7 @@
<DifferenceBar bind:settings={changeOptions} status={changeStatus} result={changeResult}
busy={changeBusy} error={changeError}
stale={!!changeResult && changeRenderedKey !== detectionKey}
- onrun={() => refreshChangeAssist()} onzone={visitZone} />
+ onrun={() => refreshChangeAssist()} onzone={visitZone} onanalyzer={saveAsAnalyzer} />
{/if}
</div>
{/if}
@@ -2241,6 +2390,16 @@
<button class="link" onclick={() => (exportPicker = true)}>Change…</button>
</div>
+ <label class="keep-choice">
+ <input type="checkbox" bind:checked={keepInCase} />
+ <span>
+ <strong>Also keep it in this case</strong>
+ <small>{openedSession
+ ? `Filed under ${openedSession.title}, with its dates and point.`
+ : 'Saves the comparison first, then files the image under it.'}</small>
+ </span>
+ </label>
+
{#if hasWidget}
<p class="panel-note"><Icon name="info" size={13} /> Google pixels are captured through the Azimut Capture extension.</p>
{/if}
@@ -2351,7 +2510,7 @@
{/if}
{#if saveDialog}
- <Modal title="Save comparison" onclose={() => (saveDialog = false)} width="440px">
+ <Modal title="Save comparison" onclose={closeSaveDialog} width="440px">
<div class="save-form">
<label>Name
<!-- svelte-ignore a11y_autofocus -->
@@ -2359,7 +2518,7 @@
</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" onclick={closeSaveDialog}>Cancel</button>
<button class="btn btn-primary" disabled={!sessionName.trim() || sessionBusy} onclick={performSessionSave}>
{sessionBusy ? 'Saving…' : 'Save comparison'}
</button>
@@ -2677,25 +2836,6 @@
.swipe-line:active .swipe-handle {
transform: translate(-50%, -50%) scale(.98);
}
- .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; }
@@ -2750,6 +2890,11 @@
.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; }
+ .keep-choice { display: grid; grid-template-columns: auto minmax(0, 1fr); align-items: flex-start; gap: 9px; padding-top: 13px; border-top: 1px solid var(--border); cursor: pointer; }
+ .keep-choice span,
+ .keep-choice small { display: block; }
+ .keep-choice strong { color: var(--text-1); font-size: var(--fs-sm); }
+ .keep-choice small { margin-top: 2px; color: var(--text-3); font-size: var(--fs-xs); line-height: 1.35; }
.destination strong { overflow: hidden; color: var(--text-2); font-size: var(--fs-xs); text-overflow: ellipsis; white-space: nowrap; }
.destination-actions { display: flex; align-items: center; justify-content: flex-end; gap: 12px; }
.link { color: var(--accent); font-size: var(--fs-xs); }
diff --git a/frontend/src/tools/Detect.render.test.js b/frontend/src/tools/Detect.render.test.js
index 5aac74b..bbaf8d5 100644
--- a/frontend/src/tools/Detect.render.test.js
+++ b/frontend/src/tools/Detect.render.test.js
@@ -13,12 +13,16 @@ const ANALYZERS = {
custom: [],
methods: [{ id: 'vessels', label: 'Vessels: infrared contrast over water', single: true, clouds: true,
sizes: { medium: { min_area: 250, max_area: 150000, cleanup: 0, smoothing: 0, merge_metres: 50 } },
- measure: '{value}× brighter than the water around it' }],
+ measure: '{value}× brighter than the water around it' },
+ { id: 'surface', label: 'Any reflectance change', single: false, clouds: true, sizes: {},
+ measure: 'Reflectance moved by {value}%' }],
max_tiles: 4096, max_results: 2000, grid: [13, 512],
};
const PROVIDERS = [{ id: 'esri-world-imagery', label: 'Esri World Imagery', kind: 'tiles' },
{ id: 'osm', label: 'OpenStreetMap', kind: 'tiles' }, { id: 'sentinel2', label: 'Copernicus Sentinel-2', kind: 'tiles' }];
const WATCH = 'abcdef123456';
+const RUN = '123456789abc';
+const PAIR_RUN = 'fedcba987654';
const area = [{ id: 'z1', name: 'Anchorage', kind: 'rect', points: [[42.9, 14.84], [42.97, 14.78]] }];
const get = vi.fn(async (path) => {
@@ -35,6 +39,24 @@ const get = vi.fn(async (path) => {
recipe: structuredClone(ANALYZERS.builtins[0]), a: { provider: 'sentinel2', date: '2026-09-01' },
b: { provider: 'sentinel2', date: '' }, offline: false, date_rule: 'latest_previous', followup_id: null };
}
+ if (path === `/api/cases/case-a/analysis/runs/${RUN}`) {
+ const pass = { provider: 'sentinel2', date: '2026-09-06' };
+ return { id: RUN, title: 'Anchorage sweep', status: 'ready', progress: 1, total: 1, count: 0,
+ engine_version: 2, results: [], area_runs: [{ area_id: 'z1', status: 'ready', a: pass, b: pass }],
+ input: { title: 'Anchorage sweep', zones: area, recipe: structuredClone(ANALYZERS.builtins[0]), note: '',
+ a: pass, b: pass, offline: false, date_rule: 'manual', followup_id: null } };
+ }
+ if (path === `/api/cases/case-a/analysis/runs/${PAIR_RUN}`) {
+ const a = { provider: 'sentinel2', date: '2026-09-08', layer: 'TRUE_COLOR', maxcc: 30 };
+ const b = { ...a, date: '2026-09-21' };
+ const recipe = { ...structuredClone(ANALYZERS.builtins[0]), id: 'change', method: 'surface', phenomenon: 'Surface change' };
+ return { id: PAIR_RUN, title: 'Earthworks', status: 'ready', progress: 1, total: 1, count: 1, engine_version: 2,
+ results: [{ id: '0-1', area_id: 'z1', coordinates: [42.95, 14.81], bbox: [42.95, 14.81, 42.951, 14.811],
+ area: 900, margin: 2, strength: 'clear', measure: { signed: -8 }, review: 'new', phenomenon: 'Surface change',
+ parts: [], sources: { a, b } }],
+ area_runs: [{ area_id: 'z1', status: 'ready', a, b }],
+ input: { title: 'Earthworks', zones: area, recipe, note: '', a, b, offline: false, date_rule: 'manual', followup_id: null } };
+ }
if (path.startsWith('/api/cases/case-a/analysis/')) return [];
if (path.startsWith('/api/settings')) return { usage: {}, month: '2026-09' };
return {};
@@ -62,13 +84,29 @@ vi.mock('../lib/state.svelte.js', () => ({
const engines = [];
function fakeEngine(view) {
let camera = { ...view, bearing: 0 };
+ const handlers = {};
+ // A jump and a framing come to rest inside the call, as the engine's do when
+ // they are not animated.
+ const settle = () => handlers['view-settled']?.forEach((handler) => handler({ ...camera }));
const engine = {
- on: vi.fn(() => () => {}),
+ handlers,
+ on: vi.fn((name, handler) => {
+ (handlers[name] ??= new Set()).add(handler);
+ return () => handlers[name].delete(handler);
+ }),
camera: vi.fn(() => ({ ...camera })),
getZoom: vi.fn(() => camera.zoom),
+ maxZoom: vi.fn(() => 18),
setView: vi.fn((next, zoom) => { camera = { ...camera, ...next, zoom }; }),
+ setCamera: vi.fn((next) => {
+ camera = { lat: next.lat, lon: next.lon, zoom: Math.min(next.zoom, 18), bearing: next.bearing ?? 0 };
+ settle();
+ }),
setBearing: vi.fn(),
- fitBounds: vi.fn(),
+ fitBounds: vi.fn((box) => {
+ camera = { ...camera, lat: (box.north + box.south) / 2, lon: (box.east + box.west) / 2 };
+ settle();
+ }),
viewBounds: vi.fn(() => ({ west: 42.9, south: 14.78, east: 42.97, north: 14.84 })),
latLngToContainerPoint: vi.fn(({ lat, lon }) => ({ x: lon * 10, y: lat * 10 })),
containerPointToLatLng: vi.fn(({ x, y }) => ({ lat: y, lon: x })),
@@ -88,9 +126,12 @@ vi.mock('../lib/map/engine.js', () => ({
}));
const showBasemap = vi.fn();
const setOverlay = vi.fn();
+const setAlternate = vi.fn();
+const showAlternate = vi.fn();
vi.mock('../lib/map/basemap.js', () => ({
OVERLAY_IDS: ['boundaries', 'roads', 'labels'],
- createBasemaps: vi.fn(() => ({ show: showBasemap, setOverlay, setZoomCeiling: vi.fn(), dispose: vi.fn() })),
+ createBasemaps: vi.fn(() => ({ show: showBasemap, setOverlay, setAlternate, showAlternate,
+ setZoomCeiling: vi.fn(), dispose: vi.fn() })),
}));
const { default: Detect } = await import('./Detect.svelte');
@@ -114,7 +155,12 @@ beforeEach(() => {
engines.length = 0;
uiState.tool = 'detect';
uiState.openAnalyzer = null;
+ uiState.lookAt = null;
+ uiState.gotoCoords = null;
+ uiState.mapView = null;
+ uiState.mapPoint = null;
prefs.detectView = undefined;
+ prefs.mapSync = false;
});
afterEach(() => {
if (live) unmount(live);
@@ -167,15 +213,17 @@ describe('Detect', () => {
);
grab({ button: 0 });
flushSync();
- expect(target.querySelector('.rotate-pivot')).toBe(null); // a plain drag pans
+ expect(target.querySelector('.turn-guide')).toBe(null); // a plain drag pans
grab({ button: 1 });
flushSync();
- expect(target.querySelector('.rotate-pivot')).not.toBe(null);
- window.dispatchEvent(new MouseEvent('mousemove', { bubbles: true, clientX: 500, clientY: 200 }));
+ expect(target.querySelector('.turn-guide')).not.toBe(null);
+ // a quarter of the wheel, swept outside its circle
+ window.dispatchEvent(new MouseEvent('mousemove', { bubbles: true, clientX: 500, clientY: 300 }));
+ window.dispatchEvent(new MouseEvent('mousemove', { bubbles: true, clientX: 400, clientY: 400 }));
window.dispatchEvent(new MouseEvent('mouseup', { bubbles: true }));
flushSync();
expect(engines[0].setBearing).toHaveBeenCalled();
- expect(target.querySelector('.rotate-pivot')).toBe(null);
+ expect(target.querySelector('.turn-guide')).toBe(null);
});
it('keeps the drawn areas in the map\'s own layer list', async () => {
@@ -242,4 +290,286 @@ describe('Detect', () => {
expect(uiState.openAnalyzer).toBe(null);
expect(get).toHaveBeenCalledWith(`/api/cases/case-a/analysis/followups/${WATCH}`);
});
+
+ const rightClick = (at) => {
+ engines[0].on.mock.calls.find(([name]) => name === 'contextmenu')[1](at);
+ flushSync();
+ return target.querySelector('[role="menu"][aria-label="This point"]');
+ };
+ /** The measure canvas, once the ruler is up: the one layer taking the pointer. */
+ const drawingCanvas = () => {
+ const canvas = target.querySelector('.annotation-canvas.drawing');
+ canvas.getBoundingClientRect = () => ({ left: 0, top: 0, width: 800, height: 600 });
+ return canvas;
+ };
+ // The fake engine puts a degree of longitude on every pixel across and a degree
+ // of latitude on every pixel down.
+ const press = (canvas, type, x, y) => canvas.dispatchEvent(new PointerEvent(type,
+ { bubbles: true, clientX: x, clientY: y, button: 0, pointerId: 1 }));
+
+ it('opens a menu on a right-click, with the acts Detect can honour', async () => {
+ await open();
+ const menu = rightClick({ lat: 14.81, lon: 42.95, x: 200, y: 150 });
+ expect(menu).not.toBe(null);
+ for (const text of ['DD', 'What is here?', 'Measure from here', 'Centre the map here', 'Compare here…', 'Open in…']) {
+ expect(menu.textContent).toContain(text);
+ }
+ // no sun panel, no imagery history, and no run open to add a candidate to
+ for (const text of ['Sun and moon', 'Imagery history', 'Save place', 'Add candidate here']) {
+ expect(menu.textContent).not.toContain(text);
+ }
+ button('Centre the map here').click(); flushSync();
+ expect(engines[0].setView).toHaveBeenLastCalledWith({ lat: 14.81, lon: 42.95 }, 12);
+ expect(target.querySelector('[role="menu"]')).toBe(null);
+ // opening it asked nothing of anyone
+ expect(post).not.toHaveBeenCalled();
+ expect(get.mock.calls.some(([path]) => path.includes('/geo/'))).toBe(false);
+ });
+
+ it('opens the point in Satellite or Compare from the menu, at the zoom it was looked at', async () => {
+ await open();
+ rightClick({ lat: 14.81, lon: 42.95, x: 200, y: 150 });
+ starts('Open in').click(); await settle();
+ const sub = target.querySelector('[role="menu"][aria-label="Open this point in"]');
+ const rows = [...sub.querySelectorAll('[role="menuitem"]')].map((row) => row.textContent.trim());
+ // the other map tabs first, then the maps outside the app
+ expect(rows.slice(0, 2)).toEqual(['Satellite', 'Compare']);
+ expect(rows).not.toContain('Detect');
+ expect(rows.length).toBeGreaterThan(3);
+ button('Satellite').click(); flushSync();
+ expect(uiState.tool).toBe('satellite');
+ expect(uiState.gotoCoords).toEqual({ lat: 14.81, lon: 42.95, zoom: 12 });
+ });
+
+ it('looks where another map tab asked, over the case\'s landing frame', async () => {
+ uiState.lookAt = { tool: 'detect', lat: 12.7615, lon: 43.6571, zoom: 15 };
+ await open();
+ expect(uiState.lookAt).toBe(null);
+ expect(engines[0].setView).toHaveBeenLastCalledWith({ lat: 12.7615, lon: 43.6571 }, 15);
+ // the areas the case watches arrived too, and did not take the camera back
+ const frames = engines[0].fitBounds.mock.invocationCallOrder;
+ const looked = engines[0].setView.mock.invocationCallOrder.at(-1);
+ expect(frames.every((order) => order < looked)).toBe(true);
+ });
+
+ it('opens the same menu from a right-click on an area drawn over the map', async () => {
+ await open();
+ const outline = target.querySelector('.detect-areas polygon');
+ const press = new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: 42.95, clientY: 14.81 });
+ outline.dispatchEvent(press);
+ flushSync();
+ // the browser's own menu is kept away, and the point is the ground under the press
+ // (the fake engine reads a container pixel as a degree)
+ expect(press.defaultPrevented).toBe(true);
+ const menu = target.querySelector('[role="menu"][aria-label="This point"]');
+ expect(menu.textContent).toContain('42.95');
+ expect(menu.textContent).toContain('14.81');
+ });
+
+ it('adds a candidate from the menu, inside an area of the run under review', async () => {
+ await open();
+ uiState.openAnalyzer = `runs-${RUN}`;
+ flushSync();
+ await settle();
+ // outside the run's ground there is nothing to add it to
+ expect(rightClick({ lat: 10, lon: 10, x: 10, y: 10 }).textContent).not.toContain('Add candidate here');
+ const menu = rightClick({ lat: 14.81, lon: 42.95, x: 200, y: 150 });
+ expect(menu.textContent).toContain('Add candidate here');
+ // one pass read twice has nothing to blink
+ expect(labelled('Blink A and B')).toBe(null);
+ post.mockResolvedValueOnce({ id: 'manual-1', origin: 'manual', area_id: 'z1', coordinates: [42.95, 14.81],
+ geometry: { type: 'Point', coordinates: [42.95, 14.81] }, bbox: [42.95, 14.81, 42.9501, 14.8101],
+ area: 90, margin: 0, measure: {}, review: 'new', phenomenon: 'Manual candidate', parts: [] });
+ button('Add candidate here').click();
+ await settle();
+ expect(post).toHaveBeenCalledWith(`/api/cases/case-a/analysis/runs/${RUN}/results`,
+ { area_id: 'z1', geometry: { type: 'Point', coordinates: [42.95, 14.81] } });
+ expect(target.textContent).toContain('Manual candidate · Manual');
+ });
+
+ it('hides what the detection draws, and blinks A against B in the same map', async () => {
+ vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval'] });
+ try {
+ await open();
+ uiState.openAnalyzer = `runs-${PAIR_RUN}`;
+ flushSync();
+ await settle();
+ expect(target.querySelector('.detect-areas')).not.toBe(null);
+ labelled('Hide the candidates and areas').click(); flushSync();
+ expect(target.querySelector('.detect-areas')).toBe(null);
+ expect(target.querySelector('.analysis-overlay')).toBe(null);
+ window.dispatchEvent(new KeyboardEvent('keydown', { key: 'h' })); flushSync();
+ expect(target.querySelector('.detect-areas')).not.toBe(null);
+
+ labelled('Blink A and B').click(); flushSync(); await settle();
+ const chip = target.querySelector('[aria-label="Blinking A and B"]');
+ // B is the pass on the map; A is laid over it, loaded and transparent
+ expect(chip.textContent).toContain('B');
+ expect(chip.textContent).toContain('2026-09-21');
+ expect(setAlternate).toHaveBeenLastCalledWith(
+ expect.objectContaining({ id: 'sentinel2' }), expect.stringContaining('2026-09-08'), expect.any(Number)
+ );
+ expect(showBasemap).toHaveBeenLastCalledWith(
+ expect.objectContaining({ id: 'sentinel2' }), expect.stringContaining('2026-09-21'), expect.any(Number)
+ );
+ // Compare's normal speed: A shows, then B again
+ vi.advanceTimersByTime(800); flushSync();
+ expect(chip.textContent).toContain('2026-09-08');
+ expect(showAlternate).toHaveBeenLastCalledWith(true);
+ vi.advanceTimersByTime(800); flushSync();
+ expect(showAlternate).toHaveBeenLastCalledWith(false);
+ labelled('Stop blinking').click(); flushSync();
+ expect(labelled('Blink A and B').getAttribute('aria-pressed')).toBe('false');
+ expect(setAlternate).toHaveBeenLastCalledWith(null, '', 256);
+ // B, the key, starts it again from the review
+ window.dispatchEvent(new KeyboardEvent('keydown', { key: 'b' })); flushSync();
+ expect(labelled('Blink A and B').getAttribute('aria-pressed')).toBe('true');
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('measures a length from the ruler, and drops a selected measure with Delete', async () => {
+ await open();
+ const ruler = labelled('Measure');
+ expect(ruler.getAttribute('aria-pressed')).toBe('false');
+ ruler.click(); flushSync();
+ expect(ruler.getAttribute('aria-pressed')).toBe('true');
+ expect(target.textContent).toContain('Drag from one end to the other');
+ const canvas = drawingCanvas();
+ press(canvas, 'pointerdown', 40, 14);
+ press(canvas, 'pointermove', 43, 14);
+ press(canvas, 'pointerup', 43, 14);
+ flushSync();
+ // one measure, labelled with its length, and the ruler put down so it can be adjusted
+ expect(target.querySelector('.annotation-canvas .mark text')?.textContent).toMatch(/^\d+(\.\d)? km$/);
+ expect(ruler.getAttribute('aria-pressed')).toBe('false');
+ expect(labelled('Clear measures')).not.toBe(null);
+ window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Delete' })); flushSync();
+ expect(target.querySelector('.annotation-canvas .mark text')).toBe(null);
+ expect(labelled('Clear measures')).toBe(null);
+ // M picks the ruler up, Escape puts it down
+ window.dispatchEvent(new KeyboardEvent('keydown', { key: 'm' })); flushSync();
+ expect(ruler.getAttribute('aria-pressed')).toBe('true');
+ document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true })); flushSync();
+ expect(ruler.getAttribute('aria-pressed')).toBe('false');
+ });
+
+ it('starts a measure on the right-clicked point, finished by the next click', async () => {
+ await open();
+ rightClick({ lat: 14, lon: 40, x: 400, y: 140 });
+ button('Measure from here').click(); await settle();
+ expect(labelled('Measure').getAttribute('aria-pressed')).toBe('true');
+ expect(target.textContent).toContain('Click the far end');
+ press(drawingCanvas(), 'pointerdown', 42, 14);
+ flushSync();
+ expect(target.querySelector('.annotation-canvas .mark text')?.textContent).toMatch(/km$/);
+ expect(labelled('Clear measures')).not.toBe(null);
+ labelled('Clear measures').click(); flushSync();
+ expect(target.querySelector('.annotation-canvas .mark text')).toBe(null);
+ });
+});
+
+describe('one camera for the map tabs', () => {
+ // Satellite left the window at z20, deeper than this map's imagery goes.
+ const SATELLITE = { lat: 12.7615, lon: 43.6571, zoom: 20, bearing: 30, by: 'satellite' };
+ const AREAS = { lat: (14.84 + 14.78) / 2, lon: (42.97 + 42.9) / 2 };
+
+ it('writes where it comes to rest, for the other map tabs and for Coordinates', async () => {
+ prefs.mapSync = true;
+ await open();
+ engines[0].handlers['view-settled'].forEach((handler) => handler({ lat: 15, lon: 43, zoom: 14, bearing: 12 }));
+ flushSync();
+ expect(uiState.mapView).toEqual({ lat: 15, lon: 43, zoom: 14, bearing: 12, by: 'detect' });
+ expect(uiState.mapPoint).toEqual({ lat: 15, lon: 43, zoom: 14 });
+ });
+
+ it('takes the window camera when it shows again, never while another tab does', async () => {
+ prefs.mapSync = true;
+ await open();
+ uiState.tool = 'satellite';
+ uiState.mapView = { ...SATELLITE };
+ flushSync();
+ expect(engines[0].setCamera).not.toHaveBeenCalled();
+ uiState.tool = 'detect';
+ flushSync();
+ expect(engines[0].setCamera).toHaveBeenLastCalledWith(expect.objectContaining({ ...SATELLITE }));
+ // it landed at its own ceiling, which leaves Satellite's z20 standing
+ expect(uiState.mapView).toMatchObject({ zoom: 20, by: 'satellite' });
+ expect(uiState.mapPoint).toEqual({ lat: SATELLITE.lat, lon: SATELLITE.lon, zoom: 18 });
+ });
+
+ it('keeps a run under review where it is', async () => {
+ prefs.mapSync = true;
+ await open();
+ uiState.openAnalyzer = `runs-${PAIR_RUN}`;
+ flushSync();
+ await settle();
+ uiState.tool = 'satellite';
+ uiState.mapView = { ...SATELLITE };
+ flushSync();
+ uiState.tool = 'detect';
+ flushSync();
+ expect(engines[0].setCamera).not.toHaveBeenCalled();
+ });
+
+ it('stays on its own ground with the preference off', async () => {
+ await open();
+ uiState.tool = 'satellite';
+ uiState.mapView = { ...SATELLITE };
+ flushSync();
+ uiState.tool = 'detect';
+ flushSync();
+ expect(engines[0].setCamera).not.toHaveBeenCalled();
+ });
+
+ it('holds a framing asked for while another tab shows until this one does', async () => {
+ await open();
+ const framed = engines[0].fitBounds.mock.calls.length;
+ uiState.tool = 'satellite';
+ uiState.openAnalyzer = `followups-${WATCH}`;
+ flushSync();
+ await settle();
+ // a hidden map has no size to fit the routine's ground to
+ expect(engines[0].fitBounds).toHaveBeenCalledTimes(framed);
+ uiState.tool = 'detect';
+ flushSync();
+ expect(engines[0].fitBounds).toHaveBeenCalledTimes(framed + 1);
+ });
+
+ it('arrives where Satellite was rather than on the ground the case watches', async () => {
+ // First visit to the case's Detect, after a walk around Satellite.
+ prefs.mapSync = true;
+ uiState.mapView = { ...SATELLITE };
+ await open();
+ const { createMapEngine } = await import('../lib/map/engine.js');
+ expect(createMapEngine).toHaveBeenCalledWith(
+ expect.anything(), expect.objectContaining({ view: { lat: SATELLITE.lat, lon: SATELLITE.lon, zoom: 20 } })
+ );
+ expect(engines[0].fitBounds).not.toHaveBeenCalled();
+ expect(engines[0].camera()).toMatchObject({ lat: SATELLITE.lat, lon: SATELLITE.lon });
+ expect(uiState.mapView).toMatchObject({ by: 'satellite' });
+ });
+
+ it('still lands on the watched ground when no other map has been looked at', async () => {
+ prefs.mapSync = true;
+ await open();
+ expect(engines[0].fitBounds).toHaveBeenCalledTimes(1);
+ expect(engines[0].camera()).toMatchObject(AREAS);
+ expect(uiState.mapView).toMatchObject({ ...AREAS, by: 'detect' });
+ });
+
+ it('holds a landing asked for while another tab shows until this one does', async () => {
+ // Built while another tab shows, as after a case switch, and with no other
+ // map looked at: the areas arrive with no map on screen to fit them to.
+ prefs.mapSync = true;
+ uiState.tool = 'satellite';
+ await open();
+ expect(engines[0].fitBounds).not.toHaveBeenCalled();
+ uiState.tool = 'detect';
+ flushSync();
+ await settle();
+ expect(engines[0].fitBounds).toHaveBeenCalledTimes(1);
+ expect(engines[0].camera()).toMatchObject(AREAS);
+ });
});
diff --git a/frontend/src/tools/Detect.svelte b/frontend/src/tools/Detect.svelte
index 0de8b8b..96a7b2f 100644
--- a/frontend/src/tools/Detect.svelte
+++ b/frontend/src/tools/Detect.svelte
@@ -11,29 +11,43 @@
*
* Nothing here fetches imagery on its own beyond the basemap the map shows.
* Starting a run, and looking a pass up, are the acts that reach Copernicus.
+ *
+ * The ruler over the map is for the thing on it: how long a hull is, how far
+ * a wake runs. Its measures are a scratch aid, gone with the session.
*/
import { onMount, tick, untrack } from 'svelte';
import { api } from '../lib/api.js';
- import { caseState, prefs, prefsReady, toast, uiState } from '../lib/state.svelte.js';
- import { marksToZones, viewZone, zoneMarks, zoneRing } from '../lib/map/analyzers.js';
+ import { caseState, dismissToast, prefs, prefsReady, toast, uiState } from '../lib/state.svelte.js';
+ import { marksToZones, sourceLabel, viewZone, zoneMarks, zoneRing } from '../lib/map/analyzers.js';
+ import { blinkable } from '../lib/map/detectReview.js';
+ import { DEFAULT_BLINK_INTERVAL } from '../lib/map/compare.js';
import { createImageryState } from './satellite/state/imagery.svelte.js';
import { createSentinelState } from './satellite/state/sentinel.svelte.js';
import { createRadarState } from './satellite/state/radar.svelte.js';
import { RADAR_ID, passLabel } from '../lib/radar.js';
import { copernicusNeed } from '../lib/copernicusSetup.js';
+ import { actionsFor, otherMapTools } from '../lib/map/contextMenu.js';
+ import { openMapAt } from '../lib/navigate.js';
+ import { shareView } from '../lib/map/sharedView.js';
+ import { COMPARE_SOURCES, comparePair } from '../lib/map/comparePair.js';
import CopernicusNeeded from '../components/CopernicusNeeded.svelte';
import MapSurface from './satellite/MapSurface.svelte';
+ import MapContextMenu from './satellite/MapContextMenu.svelte';
import PlaceSearch from './satellite/PlaceSearch.svelte';
import ImageryChip from './satellite/ImageryChip.svelte';
import MapLayers from './satellite/MapLayers.svelte';
import Compass from '../components/Compass.svelte';
+ import TurnGuide from '../components/TurnGuide.svelte';
import Icon from '../components/Icon.svelte';
import { createWaybackState } from './satellite/state/wayback.svelte.js';
- import { startRotateDrag } from '../lib/map/gestures.js';
+ import { turnFromKey, turnFromPress } from '../lib/map/gestures.js';
import AnnotationCanvas from './compare/AnnotationCanvas.svelte';
import AnalysisOverlay from './detect/AnalysisOverlay.svelte';
import DetectAreas from './detect/DetectAreas.svelte';
import DetectPanel from './detect/DetectPanel.svelte';
+ import CheckMarks from './detect/CheckMarks.svelte';
+ import RuleLayers from './detect/RuleLayers.svelte';
+ import RuleProbe from './detect/RuleProbe.svelte';
import './mapdock.css';
const SENTINEL = 'sentinel2';
@@ -58,9 +72,10 @@
const wayback = createWaybackState({ api, place: () => view });
const s1 = createRadarState({ api, place: () => view, onBilled: () => imagery.refreshUsage() });
const shown = $derived(imagery.displayed(providerId, view.zoom, { ...s2.variant, release: wayback.release, pass: s1.pass }));
- /** The metered archives are on the map only while a pass is being read. */
+ /** The metered archives. Any of them can be put on the map from its chip, with
+ * its Copernicus layer and day, but none is remembered as the basemap: Detect
+ * opens on free imagery every time. */
const PASSES = [SENTINEL, RADAR_ID];
- const selectableImagery = $derived({ ...imagery, providers: imagery.providers.filter((p) => readingPass || !PASSES.includes(p.id)) });
const layerRows = $derived([
...[['boundaries', 'Borders'], ['labels', 'Labels'], ['roads', 'Roads'], ['railway', 'Railways'],
['power', 'Power lines'], ['seamarks', 'Seamarks'], ['gpstraces', 'GPS traces']].map(([id, label]) => ({
@@ -94,8 +109,70 @@
let highlight = $state([]);
let manual = $state(null);
let manualTool = $state('select');
+ // An analyzer of your own being built: its preview, and what the map shows
+ // of it (AnalyzerBuilder). The map is its bench while it is open, so saved
+ // work and watched areas step aside.
+ let builder = $state(null);
+ // The builder offers the configuration's Copernicus layers by name; the list
+ // is the app's own catalogue until the instance has been asked, so reading
+ // it spends nothing.
+ let layersAsked = false;
+ $effect(() => {
+ if (!builder || layersAsked || s2.layers.length) return;
+ layersAsked = true;
+ untrack(() => s2.loadLayers(false, true));
+ });
+ const previewLayer = $derived(builder?.preview?.ready ? [{
+ id: 'builder-preview', visible: true,
+ input: { recipe: { colour: builder.colour, style: builder.style } },
+ results: builder.preview.candidates.map((row) => ({ ...row, review: 'new', phenomenon: builder.phenomenon })),
+ }] : []);
$effect(() => { manualTool = manual?.kind === 'polygon' ? 'polygon' : 'select'; });
+ // The ruler: measures drawn over the map, one armed at a time.
+ let measures = $state([]);
+ let measureTool = $state('select');
+ let selectedMeasure = $state(null);
+ let measureCanvas = $state(null);
+ /** A measure started from the right-click menu, which only wants its far end. */
+ let trailing = $state(false);
+ const measuring = $derived(measureTool === 'measure');
+ $effect(() => { if (!measuring) trailing = false; });
+ // One tool holds the pointer at a time: drawing an area or a candidate puts
+ // the ruler down, and taking the ruler up lets go of both.
+ $effect(() => {
+ if (drawing !== 'select' || manual) untrack(() => { measureTool = 'select'; });
+ });
+
+ // The review's eye and blink. The eye takes what the detection draws off the
+ // imagery; the blink lays pass A over pass B in the same map and flips it at
+ // Compare's normal speed, both pictures loaded, so nothing reloads mid-blink.
+ let bare = $state(false);
+ let blinking = $state(false);
+ let reviewPair = $state(null);
+ let showingA = $state(false);
+ const blinkPair = $derived(blinking && blinkable(reviewPair) ? reviewPair : null);
+ const alternate = $derived.by(() => {
+ if (!blinkPair) return null;
+ const { a } = blinkPair;
+ const other = a.provider === RADAR_ID
+ ? imagery.displayed(RADAR_ID, view.zoom, { pass: { date: a.date, time: a.time ?? '', orbit: a.orbit ?? '' } })
+ : imagery.displayed(SENTINEL, view.zoom, { ...s2.variant, from: a.date, to: a.date });
+ // Zoomed out of the archive, or past the month's budget, both sides fall
+ // back to the same stand-in, and blinking that against itself says nothing.
+ return other.provider && other.provider.id === shown.provider?.id ? other : null;
+ });
+ $effect(() => {
+ const pair = blinkPair;
+ if (!pair) return;
+ untrack(() => showDate(pair.b));
+ const timer = setInterval(() => (showingA = !showingA), DEFAULT_BLINK_INTERVAL);
+ return () => {
+ clearInterval(timer);
+ showingA = false;
+ };
+ });
+
const marks = $derived(zoneMarks(zones));
const mapDate = $derived(s2.date || '');
const passChip = $derived(providerId === RADAR_ID ? passLabel(s1.pass) : mapDate);
@@ -121,7 +198,10 @@
savedVisible = saved?.saved ?? true;
prefsLoaded = true;
home = { ...prefs.homeView };
- view = { ...home };
+ // Where the other map tabs left the window, when they share a camera.
+ const shared = share.opening();
+ view = shared ? { lat: shared.lat, lon: shared.lon, zoom: shared.zoom } : { ...home };
+ bearing = shared?.bearing ?? 0;
try {
await imagery.loadProviders();
} catch {
@@ -153,30 +233,165 @@
});
// The same turn as Satellite and Compare: a middle-drag, or shift and the
- // left button, turns the map about the point that was grabbed. Detect had
- // the compass without the gesture, so north could be reset and never left.
+ // left button, turns the map about the point that was grabbed.
let rotating = $state(null);
$effect(() => {
if (!element || !engine) return;
const surface = element;
- const down = (event) => {
- const shiftDrag = event.button === 0 && event.shiftKey;
- if (event.button !== 1 && !shiftDrag) return;
- startRotateDrag(engine, event, {
+ const down = (event) =>
+ turnFromPress(engine, event, {
onPivot: (point) => (rotating = point),
onEnd: () => (rotating = null),
});
- };
surface.addEventListener('mousedown', down, true);
return () => surface.removeEventListener('mousedown', down, true);
});
- function toggleDock(event) {
- if (uiState.tool !== 'detect' || event.repeat || event.key !== ']' || event.ctrlKey || event.metaKey || event.altKey
+ function onKey(event) {
+ if (uiState.tool !== 'detect') return;
+ // held down, the turn keeps going
+ if (turnFromKey(engine, event)) return;
+ if (event.repeat || event.ctrlKey || event.metaKey || event.altKey
|| event.target?.closest?.('input, textarea, select, [contenteditable="true"]')) return;
+ if (event.key === ']') collapsed = !collapsed;
+ else if (event.key.toLowerCase() === 'm') toggleMeasure();
+ else if ((event.key === 'Delete' || event.key === 'Backspace') && selectedMeasure) dropMeasure(selectedMeasure);
+ else return;
+ event.preventDefault();
+ }
+
+ function armMeasure() {
+ drawing = 'select';
+ manual = null;
+ measureTool = 'measure';
+ }
+ function toggleMeasure() {
+ if (measuring) measureTool = 'select';
+ else armMeasure();
+ }
+ function dropMeasure(id) {
+ measures = measures.filter((mark) => mark.id !== id);
+ if (selectedMeasure === id) selectedMeasure = null;
+ }
+ function clearMeasures() {
+ measures = [];
+ selectedMeasure = null;
+ }
+
+ // --- the right-click menu: acts on the point under the cursor -------------
+ //
+ // Satellite's menu, cut down to what Detect can honour: there is no sun panel
+ // and no imagery history here, and a place is kept by pinning a candidate. A
+ // run under review adds a candidate where the point falls in one of its
+ // areas, which is how a hull the detector missed joins the queue.
+ let pointMenu = $state(null); // { lat, lon, x, y, frame, lookup, areaId }
+ let pointLookupSeq = 0;
+ const compareSources = $derived(
+ COMPARE_SOURCES.filter((source) => !source.provider || imagery.find(source.provider))
+ );
+ const pointActions = $derived(
+ actionsFor(pointMenu?.areaId ? ['lookup', 'candidate', 'measure', 'centre'] : ['lookup', 'measure', 'centre'])
+ );
+ const pointTools = otherMapTools('detect');
+
+ function onMapContextMenu(at) {
+ pointLookupSeq += 1;
+ pointMenu = {
+ ...at,
+ frame: { width: element?.clientWidth ?? 0, height: element?.clientHeight ?? 0 },
+ lookup: null,
+ areaId: panel?.candidateAreaAt(at) ?? null,
+ };
+ }
+
+ /**
+ * A right-click on a candidate, an area or a measure is a right-click on the
+ * ground under it. Those are drawn over the map rather than in it, so the
+ * engine never hears the press, and the browser's own menu opened instead,
+ * right where a hull under review sits.
+ */
+ function onOverlayMenu(event) {
+ if (!engine || !element || !event.target?.closest?.('.analysis-overlay, .detect-areas, .annotation-canvas')) return;
event.preventDefault();
- collapsed = !collapsed;
+ const box = element.getBoundingClientRect();
+ const x = event.clientX - box.left;
+ const y = event.clientY - box.top;
+ const at = engine.containerPointToLatLng({ x, y });
+ onMapContextMenu({ lat: at.lat, lon: ((at.lon + 540) % 360) - 180, x, y });
+ }
+
+ function closePointMenu() {
+ pointLookupSeq += 1;
+ pointMenu = null;
+ }
+
+ async function onPointMenu(id, value) {
+ const at = pointMenu;
+ if (!at || !engine) return;
+ const point = { lat: at.lat, lon: at.lon };
+ if (id === 'lookup') return lookUpPoint(point);
+ closePointMenu();
+ if (id === 'copy') {
+ try {
+ await navigator.clipboard.writeText(value);
+ toast('Coordinates copied', 'ok', 1600);
+ } catch {
+ toast('The browser refused the clipboard', 'warn');
+ }
+ } else if (id === 'candidate') {
+ await panel?.addCandidate(at.areaId, { type: 'Point', coordinates: [point.lon, point.lat] });
+ } else if (id === 'measure') {
+ armMeasure();
+ await tick();
+ measureCanvas?.startFrom([point.lon, point.lat]);
+ trailing = true;
+ } else if (id === 'centre') {
+ engine.setView(point, engine.getZoom());
+ } else if (id === 'compare') {
+ await comparePoint(point, value);
+ } else if (id === 'goto') {
+ openMapAt(value, { ...point, zoom: engine.getZoom() });
+ }
+ }
+
+ /** "What is here?": the geocoder's name for the point, shown in the menu itself. */
+ async function lookUpPoint(point) {
+ const mine = ++pointLookupSeq;
+ pointMenu = { ...pointMenu, lookup: { busy: true } };
+ try {
+ const answer = await api.get(`/api/geo/reverse?lat=${point.lat}&lon=${point.lon}`);
+ if (mine !== pointLookupSeq || !pointMenu) return;
+ pointMenu = { ...pointMenu, lookup: { text: answer.display_name || 'No name for this point' } };
+ } catch (error) {
+ if (mine !== pointLookupSeq || !pointMenu) return;
+ pointMenu = { ...pointMenu, lookup: { error: `Lookup failed: ${error.message}` } };
+ }
+ }
+
+ /** Open Compare on the last two pictures of this point, as Satellite's menu does. */
+ async function comparePoint(point, source) {
+ const name = COMPARE_SOURCES.find((entry) => entry.id === source)?.label ?? 'the archive';
+ const waiting = toast(`Asking ${name} for the last two pictures…`, 'info', 0);
+ try {
+ const zoom = engine.getZoom();
+ const pair = await comparePair(api, source, { ...point, zoom });
+ uiState.compareAt = { ...point, zoom, ...pair };
+ uiState.tool = 'compare';
+ } catch (error) {
+ toast(error.message, 'warn', 6000);
+ } finally {
+ dismissToast(waiting);
+ }
}
+
+ // The menu is pinned to a screen point, so a zoom or a pan leaves it pointing
+ // at somewhere else. A drag already closes it by pressing outside; the wheel
+ // does not, so the settled view does.
+ $effect(() => {
+ if (!engine || !pointMenu) return;
+ return engine.on('view-settled', closePointMenu);
+ });
function leavePass() {
+ blinking = false;
readingPass = false;
providerId = chosenBasemap;
}
@@ -209,17 +424,67 @@
}
/** A framing asked for before the map engine existed, run once it does: the
- * case's areas usually arrive first. */
+ * case's areas usually arrive first. Likewise one asked for while another tab
+ * shows, as a new case's areas are: a hidden map has no size to fit them to,
+ * and the landing is for the analyst arriving here, so it waits for that. */
let waitingFrame = $state(null);
$effect(() => {
- if (!engine || !waitingFrame) return;
- const shapes = waitingFrame;
- untrack(() => { waitingFrame = null; frame(shapes); });
+ if (!engine || !waitingFrame || uiState.tool !== 'detect') return;
+ const { shapes, landing } = waitingFrame;
+ untrack(() => { waitingFrame = null; frame(shapes, { landing }); });
+ });
+
+ /**
+ * The camera this window's map tabs share (`lib/map/sharedView.js`), taken
+ * when this tab shows. A candidate under review keeps the map on it: the
+ * analyst stepping out to look at the ground around it comes back to it.
+ */
+ const share = shareView('detect', { state: uiState, enabled: () => prefs.mapSync });
+ let reviewing = $state(false);
+
+ $effect(() => {
+ uiState.mapView;
+ if (uiState.tool !== 'detect' || !ready) return;
+ untrack(() => {
+ if (reviewing) return;
+ const next = share.pending(engine.camera());
+ if (next) engine.setCamera(next);
+ });
+ });
+
+ /** Where the map is, for Coordinates, and where the window looks: hidden
+ * too, when a pan's glide ends after a switch of tab. */
+ function onSettled(camera) {
+ uiState.mapPoint = { lat: camera.lat, lon: camera.lon, zoom: camera.zoom };
+ share.settled(camera, engine?.maxZoom());
+ }
+
+ /**
+ * A point another map tab asked Detect to look at. It wins over the case's
+ * landing frame, which can arrive after it: the analyst came here for that
+ * point, not for the areas the case happens to watch.
+ */
+ let pointAsked = false;
+ $effect(() => {
+ caseState.current?.id;
+ pointAsked = false;
+ });
+ $effect(() => {
+ const asked = uiState.lookAt;
+ if (uiState.tool !== 'detect' || asked?.tool !== 'detect' || !engine) return;
+ untrack(() => {
+ uiState.lookAt = null;
+ pointAsked = true;
+ engine.setView({ lat: asked.lat, lon: asked.lon }, Number.isFinite(asked.zoom) ? asked.zoom : engine.getZoom());
+ });
});
/** Frame a whole set of areas: opening a routine should show all of it. */
- function frame(shapes) {
- if (!engine?.fitBounds) { waitingFrame = shapes; return; }
+ function frame(shapes, { landing = false } = {}) {
+ // The case's landing gives way to a point asked for, and to a camera another
+ // map tab left the window on: arriving from there, that is the ground in hand.
+ if (landing && (pointAsked || share.ledElsewhere())) return;
+ if (!engine?.fitBounds || uiState.tool !== 'detect') { waitingFrame = { shapes, landing }; return; }
const points = shapes.flatMap((zone) => zoneRing(zone));
if (!points.length) return;
const xs = points.map(([lon]) => lon);
@@ -272,10 +537,11 @@
}
</script>
-<svelte:window onkeydown={toggleDock} />
+<svelte:window onkeydown={onKey} />
<div class="detect-tool">
<div class="stage">
- <div class="surface-shell">
+ <!-- svelte-ignore a11y_no_static_element_interactions -->
+ <div class="surface-shell" oncontextmenu={onOverlayMenu}>
<div class="search cmp-glass">
<PlaceSearch
bind:value={searchText}
@@ -288,16 +554,49 @@
/>
</div>
<div class="map-choices">
- <ImageryChip imagery={selectableImagery} bind:providerId {s2} {wayback} {s1} {shown} />
+ <ImageryChip {imagery} bind:providerId {s2} {wayback} {s1} {shown} />
<div class="layer-picker cmp-glass">
<MapLayers rows={layerRows} bind:open={layersOpen} />
</div>
- {#if readingPass}
+ {#if builder?.pass?.b || builder?.pass?.a}
+ <!-- The builder's passes under its preview: A, B or both blinking, and back to the basemap. -->
+ {@const pass = builder.pass}
+ {@const onScreen = pass.showing === 'blink' ? (showingA ? 'a' : 'b') : pass.showing}
+ <div class="pass-chip bench-bar cmp-glass" role="group" aria-label="Passes under the preview">
+ {#each [['a', 'A'], ['b', 'B']] as [id, letter] (id)}
+ {#if pass[id]}
+ <button class="cmp-letter {id}" class:dim={onScreen !== id} aria-pressed={pass.showing === id}
+ title={`Show pass ${letter}, ${pass[id]}`} onclick={() => panel?.showPass(id)}>{letter}</button>
+ {/if}
+ {/each}
+ {#if pass.blink}
+ <button class="blink" class:on={pass.showing === 'blink'} aria-pressed={pass.showing === 'blink'}
+ title="Flip between A and B" onclick={() => panel?.showPass(pass.showing === 'blink' ? 'b' : 'blink')}>Blink</button>
+ {/if}
+ {#if onScreen === 'a' || onScreen === 'b'}<span class="mono">{pass[onScreen]}</span>{/if}
+ <button class="cmp-icon" title="Back to the basemap" aria-label="Back to the basemap"
+ onclick={() => panel?.showPass('basemap')}><Icon name="x" size={12} /></button>
+ </div>
+ {:else if blinkPair}
+ <!-- Which of the two is on screen, in Compare's letters and colours. -->
+ <div class="pass-chip blink-chip cmp-glass" role="group" aria-label="Blinking A and B">
+ <span class="cmp-letter" class:a={showingA} class:b={!showingA}>{showingA ? 'A' : 'B'}</span>
+ <span class="mono">{sourceLabel(showingA ? blinkPair.a : blinkPair.b)}</span>
+ <button class="cmp-icon" title="Stop blinking" aria-label="Stop blinking" onclick={() => (blinking = false)}><Icon name="x" size={12} /></button>
+ </div>
+ {:else if readingPass}
<button class="pass-chip cmp-glass" title="Return to your basemap" aria-label="Leave pass imagery" onclick={leavePass}>{passChip} <Icon name="x" size={12} /></button>
{/if}
<!-- Which way is up: the same reading every other map in the app shows,
which Detect lost when it turned the surface's own chrome off. -->
<Compass {bearing} onbearing={(deg) => engine?.setBearing(deg)} />
+ <div class="ruler cmp-glass">
+ <button class="cmp-icon" class:on={measuring} aria-pressed={measuring} aria-label="Measure"
+ title="Measure a length (M)" onclick={toggleMeasure}><Icon name="ruler" size={15} /></button>
+ {#if measures.length}
+ <button class="cmp-icon" aria-label="Clear measures" title="Clear measures" onclick={clearMeasures}><Icon name="trash" size={14} /></button>
+ {/if}
+ </div>
</div>
{#if home}
<MapSurface
@@ -318,18 +617,41 @@
{home}
resetToHome={false}
imperial={prefs.units === 'imperial'}
- armed={drawing !== 'select' ? 'selecting' : null}
+ armed={measuring ? 'measuring' : drawing !== 'select' || builder?.pinning ? 'selecting' : null}
onclick={({ lon, lat }) => {
if (manual?.kind === 'point') void panel?.addManual({ type: 'Point', coordinates: [lon, lat] });
+ else if (builder?.pinning && !measuring) panel?.pinAt({ lon, lat });
+ else if (builder && !measuring) void panel?.probeAt({ lon, lat });
}}
controlsTop={98}
+ {alternate}
+ alternateOn={showingA}
onusage={() => imagery.refreshUsage()}
+ onviewsettled={onSettled}
+ oncontextmenu={onMapContextMenu}
/>
- {#if savedVisible && layers.some((layer) => layer.visible)}
+ {#if builder}
+ <RuleLayers {engine} {element} preview={builder.preview} shown={builder.shown} hover={builder.hover}
+ colours={builder.colours} />
+ {#if previewLayer.length}
+ <AnalysisOverlay {engine} layers={previewLayer} onpick={(_, id) => {
+ const row = builder.preview.candidates.find((candidate) => candidate.id === id);
+ if (row) void panel?.probeAt({ lon: row.coordinates[0], lat: row.coordinates[1] });
+ }} />
+ {/if}
+ {#if builder.marks.length || builder.ground}
+ <CheckMarks {engine} marks={builder.marks} ground={builder.ground} />
+ {/if}
+ {#if builder.probe}
+ <RuleProbe {engine} probe={builder.probe} rules={builder.rules} colours={builder.colours}
+ width={element?.clientWidth ?? 0} height={element?.clientHeight ?? 0} onclose={() => panel?.closeProbe()}
+ onmark={(expect) => panel?.markProbe(expect)} markTarget={builder.checking} canMark={builder.canMark} />
+ {/if}
+ {:else if savedVisible && !bare && layers.some((layer) => layer.visible)}
<AnalysisOverlay {engine} {layers} selected={selectedResult} active={!manual}
onpick={(run, result) => panel?.pick(run, result)} />
{/if}
- {#if areaGroups.length && !manual}
+ {#if areaGroups.length && !manual && !bare && !builder}
<DetectAreas {engine} groups={areaGroups} {highlight} onpick={(id) => panel?.openArea(id)} />
{/if}
{#if manual?.kind === 'polygon'}
@@ -341,22 +663,50 @@
void panel?.addManual({ type: 'Polygon', coordinates: [[...ring, ring[0]]] });
}
}} />
- {:else if showZones && !manual}
+ {:else if showZones && !manual && !bare && !builder}
<AnnotationCanvas annotations={marks} {engine} letter="a" editVertices={true} edgeOnly={true}
bind:tool={drawing} bind:selectedId={selectedZone} colour="#38bdf8" fillOpacity={0.08}
onchange={(next) => (zones = marksToZones(next, zones))} />
{/if}
+ <!-- Over the areas, so a measure started inside one takes the press. -->
+ <AnnotationCanvas bind:this={measureCanvas} annotations={measures} {engine} letter="a" units={prefs.units}
+ editVertices={true} bind:tool={measureTool} bind:selectedId={selectedMeasure} colour="#f5a623"
+ strokeWidth={2} stampSize={14} onchange={(next) => (measures = next)} />
+ {#if pointMenu}
+ <MapContextMenu
+ at={pointMenu}
+ frame={pointMenu.frame}
+ zoom={view.zoom}
+ format={prefs.coordFormat}
+ actions={pointActions}
+ tools={pointTools}
+ lookup={pointMenu.lookup}
+ {compareSources}
+ onpick={onPointMenu}
+ onclose={closePointMenu}
+ />
+ {/if}
{:else}
<div class="loading">Reading your preferences…</div>
{/if}
{#if rotating}
- <div class="rotate-pivot" style:left={`${rotating.x}px`} style:top={`${rotating.y}px`} aria-hidden="true"></div>
+ <TurnGuide x={rotating.x} y={rotating.y} />
{/if}
{#if needs}
<div class="need-over">
<CopernicusNeeded need={needs} tool="Detect" />
</div>
{/if}
+ {#if measuring}
+ <div class="manual-chip cmp-glass">{trailing ? 'Click the far end' : 'Drag from one end to the other'}
+ <button class="cmp-icon" aria-label="Stop measuring" title="Stop measuring (Esc)" onclick={() => (measureTool = 'select')}><Icon name="x" size={13} /></button>
+ </div>
+ {/if}
+ {#if builder?.pinning}
+ <div class="manual-chip cmp-glass">{builder.pinning === 'found' ? 'Click where a candidate should be found' : 'Click where none should be'}
+ <button class="cmp-icon" aria-label="Stop dropping pins" title="Stop dropping pins" onclick={() => panel?.pinMode(null)}><Icon name="x" size={13} /></button>
+ </div>
+ {/if}
{#if manual}
<div class="manual-chip cmp-glass">{manual.kind === 'point' ? 'Click the candidate on the map' : 'Click corners; Enter finishes'}
<button class="cmp-icon" aria-label="Cancel adding candidate" title="Cancel adding candidate" onclick={() => (manual = null)}><Icon name="x" size={13} /></button>
@@ -377,6 +727,10 @@
bind:selectedResult
bind:areaGroups
bind:highlight
+ bind:bare
+ bind:blinking
+ bind:reviewing
+ onpair={(pair) => (reviewPair = pair)}
{opening}
onopened={() => (opening = null)}
onfocus={focus}
@@ -384,6 +738,12 @@
onusecurrentview={useCurrentView}
onshow={showDate}
onleavepass={leavePass}
+ bind:builder
+ onblink={(pair) => { reviewPair = pair; blinking = !!pair; }}
+ viewBounds={() => engine?.viewBounds?.() ?? null}
+ mapView={view}
+ passLayers={s2.layers}
+ onfly={({ lon, lat, zoom, bounds }) => (bounds ? engine?.fitBounds(bounds, { padding: 40 }) : engine?.setView({ lon, lat }, zoom))}
/>
</div>
</div>
@@ -403,6 +763,15 @@
.layer-picker :global(.sub-head) { display: flex; align-items: center; gap: 6px; width: 100%; min-height: 22px; font-size: var(--fs-xs); color: var(--text-2); }
.layer-picker :global(.count) { margin-left: auto; color: var(--text-3); }
.layer-picker :global(.layers) { min-width: 190px; margin-top: 8px; }
+ .ruler { display: flex; padding: 2px; }
+ .blink-chip { padding: 2px 2px 2px 4px; }
+ .bench-bar { gap: 4px; padding: 2px 2px 2px 4px; }
+ .bench-bar .cmp-letter { cursor: pointer; }
+ .bench-bar .cmp-letter.dim { opacity: 0.4; }
+ .bench-bar .blink { padding: 2px 7px; border-radius: var(--r-sm); color: var(--text-2); font-size: var(--fs-xs); }
+ .bench-bar .blink.on { color: var(--accent); background: var(--accent-soft); }
+ .bench-bar .cmp-icon { width: 22px; height: 22px; }
+ .blink-chip .cmp-icon { width: 22px; height: 22px; }
.pass-chip { display: flex; align-items: center; gap: 8px; padding: 4px 8px; font-size: var(--fs-xs); }
/* Over the map and under its own controls, which stay usable around it. */
.need-over {
@@ -416,25 +785,6 @@
}
.manual-chip { position: absolute; bottom: 36px; left: 12px; z-index: 650; display: flex; align-items: center; padding: 4px 8px; font-size: var(--fs-xs); }
/* The point a turn is happening about, drawn as Satellite and Compare draw it. */
- .rotate-pivot {
- position: absolute;
- z-index: 570;
- width: 34px;
- height: 34px;
- transform: translate(-50%, -50%);
- border: 1px solid rgb(255 255 255 / 0.92);
- border-radius: 50%;
- pointer-events: none;
- box-shadow: 0 0 0 1px rgb(0 0 0 / 0.7), inset 0 0 0 8px rgb(0 0 0 / 0.25);
- }
- .rotate-pivot::before,
- .rotate-pivot::after {
- content: '';
- position: absolute;
- background: rgb(255 255 255 / 0.92);
- }
- .rotate-pivot::before { left: 50%; top: 5px; bottom: 5px; width: 1px; }
- .rotate-pivot::after { top: 50%; left: 5px; right: 5px; height: 1px; }
.stage { display: flex; flex: 1; min-height: 0; }
/* The surface itself is a flex child (`.map-wrap`), so this has to be a flex
container or the map lands with no height at all. */
diff --git a/frontend/src/tools/Files.svelte b/frontend/src/tools/Files.svelte
index 1d52be1..ca8e5bd 100644
--- a/frontend/src/tools/Files.svelte
+++ b/frontend/src/tools/Files.svelte
@@ -42,7 +42,8 @@
const TYPE_ICON = {
media: 'image', capture: 'satellite', note: 'note', proof: 'proof',
- post: 'post', place: 'pin', 'inspect-session': 'inspect', 'compare-session': 'compare', bookmark: 'link',
+ post: 'post', place: 'pin', 'inspect-session': 'inspect', collage: 'grid', 'compare-session': 'compare',
+ bookmark: 'link',
};
const VIDEO_EXTS = new Set(['mp4', 'mov', 'webm', 'mkv', 'avi', 'm4v']);
diff --git a/frontend/src/tools/Inspector.render.svelte.test.js b/frontend/src/tools/Inspector.render.svelte.test.js
new file mode 100644
index 0000000..54dae0f
--- /dev/null
+++ b/frontend/src/tools/Inspector.render.svelte.test.js
@@ -0,0 +1,332 @@
+// @vitest-environment happy-dom
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { flushSync, mount, unmount } from 'svelte';
+
+/**
+ * Inspect driven the way an analyst drives it: open a file, change something,
+ * come back to it. The work is saved as it is made, so what these check is what
+ * reaches the server and when.
+ */
+
+const MEDIA = [
+ { path: 'media/roof.png', kind: 'image', title: 'Roof', filename: 'roof.png', entity_id: 'e_roof', source: { type: 'upload' } },
+ { path: 'media/clip.mp4', kind: 'video', title: 'Convoy clip', filename: 'clip.mp4', entity_id: 'e_clip', source: { type: 'download' } },
+];
+let media = MEDIA;
+const OPS = {
+ filters: [
+ { id: 'brightness', label: 'Brightness', params: [{ name: 'value', default: 1, min: 0, max: 2, step: 0.05 }], css: 'brightness({v})' },
+ ],
+ analyses: [],
+};
+const frame = (id, time) => ({
+ id, path: 'media/clip.mp4', time, adjust: { brightness: 1 }, crop: null, sourceOps: [], rotation: 0, w: 640, h: 360, filed: null,
+});
+
+let saved = {};
+let works = [];
+
+const get = vi.fn(async (path) => {
+ if (path === '/api/inspect/ops') return structuredClone(OPS);
+ if (path === '/api/cases/case-a/media') return structuredClone(media);
+ if (path === '/api/cases/case-a/inspect/works') return structuredClone(works);
+ if (path.startsWith('/api/cases/case-a/inspect/probe')) {
+ return path.includes('clip') ? { kind: 'video', duration: 20, fps: 25, width: 640, height: 360 } : { kind: 'image', width: 80, height: 60 };
+ }
+ if (path.startsWith('/api/cases/case-a/inspect/work?path=')) {
+ const file = decodeURIComponent(path.split('path=')[1]);
+ return { work: saved[file] ? structuredClone(saved[file]) : null };
+ }
+ if (path.startsWith('/api/cases/case-a/inspect/works/')) {
+ const name = decodeURIComponent(path.split('/works/')[1]);
+ const found = Object.values(saved).find((w) => w.name === name);
+ if (!found) throw Object.assign(new Error('nothing was inspected under that name'), { status: 404 });
+ return structuredClone(found);
+ }
+ return {};
+});
+const put = vi.fn(async (path, body) => ({ name: body.path.includes('roof') ? 'Roof' : 'Convoy clip', title: 'x' }));
+const post = vi.fn(async () => ({ saved: [] }));
+const del = vi.fn(async () => ({ status: 'deleted', deleted: ['e_work'], trash: 'g_1' }));
+const patch = vi.fn();
+vi.mock('../lib/api.js', () => ({ api: { get, put, post, del, patch } }));
+
+// Reactive, so a change made elsewhere in the case can reach the open file.
+const caseState = $state({ current: { id: 'case-a', folders: [] }, rev: 0 });
+const uiState = { tool: 'inspect', inspectPath: null, openInspect: null, focusMedia: null };
+const toast = vi.fn();
+const reloadCase = vi.fn(async () => {});
+vi.mock('../lib/state.svelte.js', () => ({ caseState, uiState, toast, reloadCase }));
+vi.mock('../lib/navigate.js', () => ({ openInReverseSearch: vi.fn() }));
+const deletedToast = vi.fn();
+vi.mock('../lib/trash.js', () => ({ deletedToast }));
+
+const { default: Inspector } = await import('./Inspector.svelte');
+const { workState } = await import('../lib/inspectWork.svelte.js');
+
+let live;
+let target;
+
+async function settle(ms = 0) {
+ if (ms) await new Promise((resolve) => setTimeout(resolve, ms));
+ for (let i = 0; i < 40; i += 1) await Promise.resolve();
+ flushSync();
+}
+
+/** Past the autosave's quiet period, so a pending save has run. */
+const afterQuiet = () => settle(1000);
+
+async function start() {
+ target = document.createElement('div');
+ document.body.append(target);
+ live = mount(Inspector, { target });
+ flushSync();
+ await settle();
+}
+
+async function openFile(title) {
+ const card = [...target.querySelectorAll('.card')].find((c) => c.textContent.includes(title));
+ card.click();
+ await settle();
+ await settle(10);
+}
+
+const button = (text) => [...document.querySelectorAll('button')].find((b) => b.textContent.trim().startsWith(text));
+
+beforeEach(() => {
+ saved = {};
+ works = [];
+ media = MEDIA;
+ get.mockClear();
+ put.mockClear();
+ del.mockClear();
+ patch.mockReset();
+ toast.mockClear();
+ reloadCase.mockClear();
+ deletedToast.mockClear();
+ uiState.openInspect = null;
+ vi.stubGlobal('fetch', vi.fn(async () => new Response(new Blob(['png'], { type: 'image/png' }))));
+ URL.createObjectURL = vi.fn(() => `blob:${Math.random()}`);
+ URL.revokeObjectURL = vi.fn();
+ globalThis.ResizeObserver ??= class { observe() {} disconnect() {} };
+});
+
+afterEach(() => {
+ if (live) unmount(live);
+ live = null;
+ target?.remove();
+ vi.unstubAllGlobals();
+});
+
+describe('opening a file', () => {
+ it('lists every image and video to open, with no session to start first', async () => {
+ await start();
+
+ expect(target.textContent).toContain('Open a file');
+ expect([...target.querySelectorAll('.card .title')].map((t) => t.textContent)).toEqual(['Roof', 'Convoy clip']);
+ expect(button('New session')).toBeUndefined();
+ });
+
+ it('leaves the title to the tab, with no bar until a file is open', async () => {
+ await start();
+
+ expect(target.querySelector('h2')).toBeNull();
+ expect(target.querySelector('.tool-header')).toBeNull();
+ await openFile('Roof');
+ expect(target.querySelector('.tool-header .file-name').value).toBe('Roof');
+ });
+
+ it('files nothing for a file that was only looked at', async () => {
+ await start();
+ await openFile('Roof');
+ await afterQuiet();
+
+ expect(target.querySelector('.file-name').value).toBe('Roof');
+ expect(put).not.toHaveBeenCalled();
+ expect(target.querySelector('.status')).toBeNull();
+ });
+});
+
+describe('leaving a file', () => {
+ it('goes back to the file list, writing what was pending first', async () => {
+ await start();
+ await openFile('Roof');
+ button('Duplicate').click();
+ flushSync();
+
+ target.querySelector('button[aria-label="Close file"]').click();
+ await settle(10);
+
+ expect(put).toHaveBeenCalledTimes(1);
+ expect(target.textContent).toContain('Open a file');
+ expect(target.querySelector('.file-name')).toBeNull();
+ });
+
+ it('opens another file from the header without going back to the list', async () => {
+ await start();
+ await openFile('Roof');
+
+ button('Change file').click();
+ flushSync();
+ const modal = document.querySelector('[role="dialog"]');
+ [...modal.querySelectorAll('.card')].find((c) => c.textContent.includes('Convoy clip')).click();
+ await settle(10);
+
+ expect(target.querySelector('.file-name').value).toBe('Convoy clip');
+ expect(document.querySelector('[role="dialog"]')).toBeNull();
+ });
+});
+
+describe('saving as it is made', () => {
+ it('files the work once the edits stop, and says it is saved', async () => {
+ await start();
+ await openFile('Roof');
+
+ button('Duplicate').click();
+ flushSync();
+ button('Duplicate').click();
+ flushSync();
+ await afterQuiet();
+
+ expect(put).toHaveBeenCalledTimes(1);
+ const [path, body] = put.mock.calls[0];
+ expect(path).toBe('/api/cases/case-a/inspect/work');
+ expect(body.path).toBe('media/roof.png');
+ expect(body.spec.frames).toHaveLength(3);
+ expect(body.spec.frames.every((f) => !('url' in f))).toBe(true);
+ expect(target.querySelector('.status').textContent).toContain('Saved');
+ });
+});
+
+describe('coming back to a file', () => {
+ it('puts its frames back in the strip without writing anything', async () => {
+ saved['media/clip.mp4'] = {
+ name: 'Convoy clip',
+ title: 'Convoy clip',
+ spec: { source: { path: 'media/clip.mp4', kind: 'video' }, videoAdjust: {}, videoRotation: 0, frames: [frame('fr_a', 2), frame('fr_b', 5.5)], activeFrameId: null },
+ };
+ works = [{ name: 'Convoy clip', title: 'Convoy clip', source: 'media/clip.mp4', frames: 2, kind: 'video' }];
+ await start();
+
+ expect(target.querySelector('h4').textContent).toBe('Worked on');
+ await openFile('Convoy clip');
+ await afterQuiet();
+
+ const tiles = [...target.querySelectorAll('.strip .tile')];
+ expect(tiles).toHaveLength(3);
+ expect(tiles[0].textContent).toContain('Video');
+ expect(target.querySelector('button[aria-label="Frame 2 at 0:05.5"]')).not.toBeNull();
+ expect(put).not.toHaveBeenCalled();
+ });
+
+ it('reopens a work from the sidebar on the file it belongs to', async () => {
+ saved['media/clip.mp4'] = {
+ name: 'Convoy clip',
+ title: 'Convoy clip',
+ spec: { source: { path: 'media/clip.mp4', kind: 'video' }, frames: [frame('fr_a', 2)], activeFrameId: 'fr_a' },
+ };
+ uiState.openInspect = 'Convoy clip';
+ await start();
+ await settle(20);
+
+ expect(target.querySelector('.file-name').value).toBe('Convoy clip');
+ expect(uiState.openInspect).toBeNull();
+ });
+});
+
+describe('clearing a work', () => {
+ it('sends it to the Trash, with the way back, and leaves the file open', async () => {
+ saved['media/clip.mp4'] = {
+ name: 'Convoy clip',
+ title: 'Convoy clip',
+ spec: { source: { path: 'media/clip.mp4', kind: 'video' }, frames: [frame('fr_a', 2)], activeFrameId: null },
+ };
+ await start();
+ await openFile('Convoy clip');
+
+ button('Clear work').click();
+ flushSync();
+ const confirm = [...document.querySelectorAll('button')].filter((b) => b.textContent.trim() === 'Clear work').pop();
+ delete saved['media/clip.mp4'];
+ const rev = workState.rev;
+ confirm.click();
+ await settle(20);
+
+ expect(del).toHaveBeenCalledWith('/api/cases/case-a/inspect/work?path=media%2Fclip.mp4');
+ // Collage stops offering its frames, and the sidebar drops it
+ expect(workState.rev).toBeGreaterThan(rev);
+ expect(reloadCase).toHaveBeenCalled();
+ expect(deletedToast).toHaveBeenCalledWith('case-a', expect.objectContaining({ trash: 'g_1' }), 'Convoy clip');
+ expect(target.querySelector('.file-name').value).toBe('Convoy clip');
+ expect(target.querySelectorAll('.strip .tile')).toHaveLength(1);
+ });
+});
+
+describe('renaming the file', () => {
+ const renamed = { path: 'media/North roof.png', kind: 'image', title: 'North roof', filename: 'North roof.png', entity_id: 'e_roof' };
+ const field = () => target.querySelector('input[aria-label="File name"]');
+
+ function type(value) {
+ field().value = value;
+ field().dispatchEvent(new Event('input', { bubbles: true }));
+ }
+
+ it('renames it from the header, writing what was pending first, and stays on it', async () => {
+ await start();
+ await openFile('Roof');
+ patch.mockImplementation(async () => {
+ media = [renamed, MEDIA[1]];
+ const { entity_id: _id, ...answer } = renamed; // the route answers without it
+ return answer;
+ });
+ button('Duplicate').click();
+ flushSync();
+
+ type('North roof');
+ field().dispatchEvent(new FocusEvent('blur'));
+ await settle(20);
+
+ expect(patch).toHaveBeenCalledWith('/api/cases/case-a/media', { path: 'media/roof.png', title: 'North roof' });
+ expect(put.mock.invocationCallOrder[0]).toBeLessThan(patch.mock.invocationCallOrder[0]);
+ expect(get).toHaveBeenCalledWith('/api/cases/case-a/inspect/work?path=media%2FNorth%20roof.png');
+ expect(field().value).toBe('North roof');
+ expect(reloadCase).toHaveBeenCalled();
+ });
+
+ it('leaves the name as it was on Escape', async () => {
+ await start();
+ await openFile('Roof');
+
+ type('Something else');
+ field().dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }));
+ field().dispatchEvent(new FocusEvent('blur'));
+ await settle();
+
+ expect(field().value).toBe('Roof');
+ expect(patch).not.toHaveBeenCalled();
+ });
+
+ it('follows the open file when it is renamed elsewhere', async () => {
+ await start();
+ await openFile('Roof');
+
+ media = [renamed, MEDIA[1]];
+ caseState.rev += 1;
+ await settle(20);
+
+ expect(field().value).toBe('North roof');
+ expect(toast).not.toHaveBeenCalled();
+ });
+
+ it('closes the open file when it is deleted elsewhere', async () => {
+ await start();
+ await openFile('Roof');
+
+ media = [MEDIA[1]];
+ caseState.rev += 1;
+ await settle(20);
+
+ expect(toast).toHaveBeenCalledWith('“Roof” was deleted from the case', 'warn');
+ expect(field()).toBeNull();
+ });
+});
diff --git a/frontend/src/tools/Inspector.svelte b/frontend/src/tools/Inspector.svelte
index bccc204..0d1f489 100644
--- a/frontend/src/tools/Inspector.svelte
+++ b/frontend/src/tools/Inspector.svelte
@@ -1,623 +1,403 @@
<script>
import { api } from '../lib/api.js';
import { fileUrl } from '../lib/fileUrl.js';
- import { fetchAllEntities, lookupEntity } from '../lib/catalog.js';
- import { matchesTerms } from '../lib/folderBrowse.js';
import { caseState, uiState, reloadCase, toast } from '../lib/state.svelte.js';
import {
- adjustDefaults, buildFrameOps, previewStyle, uid, videoSeed, initialQuad, VIDEO_ADJUST_IDS,
- collageBounds, quadFromCropRect, cropImgStyle, cropAspect, styleText, hasVideoEdits,
- normalizeRightAngleRotation, rotationOps, sourceStem, frameSaveNames, autoSaveNames, saveNameOf,
- newCollage, COLLAGE_DEFAULT_SIZE,
+ adjustDefaults, buildFrameOps, previewStyle, uid, videoSeed, VIDEO_ADJUST_IDS,
+ hasVideoEdits, normalizeRightAngleRotation, rotationOps, sourceStem, frameSaveNames,
} from '../lib/inspect.js';
import {
- isDefaultName, nextName, savedSlugs, savedTitles, savedTitle, slugify, specAttr, specPath,
- } from '../lib/naming.js';
- import { createHistory } from '../lib/history.js';
+ workState, workSpec, isPristine, frameSignature, videoSignature, isFiled,
+ } from '../lib/inspectWork.svelte.js';
+ import { createAutosave } from '../lib/autosave.svelte.js';
import { deletedToast } from '../lib/trash.js';
import { openInReverseSearch } from '../lib/navigate.js';
- import { IDENTITY, matrixCss, rotateAbout, isIdentity, matrixAngleDeg, pointerAngleDeg } from '../lib/frameRotate.js';
import Icon from '../components/Icon.svelte';
- import SearchInput from '../components/SearchInput.svelte';
- import FolderBrowser from '../components/FolderBrowser.svelte';
+ import Modal from '../components/Modal.svelte';
import ConfirmDialog from '../components/ConfirmDialog.svelte';
- import CropBox from './inspect/CropBox.svelte';
- import SelectionMenu from './inspect/SelectionMenu.svelte';
+ import SourcePicker from '../components/SourcePicker.svelte';
+ import FrameStrip from './inspect/FrameStrip.svelte';
+ import FrameViewer from './inspect/FrameViewer.svelte';
import FrameMenu from './inspect/FrameMenu.svelte';
- import CollageCanvas from './inspect/CollageCanvas.svelte';
- import CollageMenu from './inspect/CollageMenu.svelte';
- import SaveGallery from './inspect/SaveGallery.svelte';
- import SaveMenu from './inspect/SaveMenu.svelte';
- import PieceCropModal from './inspect/PieceCropModal.svelte';
+ import VideoMenu from './inspect/VideoMenu.svelte';
import VideoPlayer from './inspect/VideoPlayer.svelte';
- // Inspect keeps edits in session state until the Save tab renders them at full
- // resolution and commits selected outputs to the case.
- const TAB_META = {
- selection: { label: 'Selection', icon: 'video' },
- frame: { label: 'Frame', icon: 'image' },
- collage: { label: 'Collage', icon: 'layers' },
- save: { label: 'Save', icon: 'save' },
- };
- const SOURCE_FILTERS = [
- { id: 'all', label: 'All' },
- { id: 'image', label: 'Images' },
- { id: 'video', label: 'Video' },
- { id: 'capture', label: 'Captures' },
- { id: 'frame', label: 'Frames' },
- { id: 'collage', label: 'Collages' },
- ];
+ // Inspect works on one file at a time: a video to cut frames from, or an image
+ // to read closely. What is done to it is its work, one per file, kept as it is
+ // made (engine/inspectwork.py): opening the file again is how it is reopened.
+ // Nothing reaches the Media Library until Save to case files an output.
let mediaList = $state([]);
- let sourceQuery = $state('');
- let sourceFilter = $state('all');
- let sourceModalOpen = $state(false);
- let sourceBrowserOpen = $state(false);
- let sourceBrowsePath = $state('');
- let sourceBrowseSelection = $state(null);
- let openSourceAfterDiscard = $state(false);
- const inspectableMedia = $derived(mediaList.filter((m) => m.kind === 'image' || m.kind === 'video'));
- const filteredSourceMedia = $derived(
- sourceFilter === 'all' ? inspectableMedia : inspectableMedia.filter((m) => sourceCategory(m) === sourceFilter)
- );
- const pickableMedia = $derived(
- sourceQuery.trim() ? filteredSourceMedia.filter((m) => matchesSourceName(m, sourceQuery)) : filteredSourceMedia
- );
- const sourceBrowserEntries = $derived(
- filteredSourceMedia.map((m) => ({ ...m, id: m.path, attrs: { folder: m.folder ?? '' } }))
- );
+ let works = $state([]);
let loadedFor = $state(null);
let filters = $state([]);
let analyses = $state([]);
let probeInfo = $state(null);
+ let pickerOpen = $state(false);
+ let opening = $state(false);
+ let clearConfirm = $state(false);
+ let saving = $state(null); // 'video', 'all' or a frame id while its save runs
+ let saveFolder = $state(''); // where the last save went, offered for the next
+
+ const inspectable = $derived(mediaList.filter((m) => m.kind === 'image' || m.kind === 'video'));
+ const mediaPaths = $derived(new Set(mediaList.map((m) => m.path)));
+ const titleByPath = $derived(new Map(mediaList.map((m) => [m.path, m.title])));
- let activeTab = $state('selection');
- let collageSelectedIds = $state([]);
- let cropPieceNode = $state(null);
- // Backend-composited Save thumbnails keyed by collage id: { sig, url }.
- let collagePreviews = $state({});
- let saving = $state(false);
- // Keep names outside the derived `savables` list so slider changes preserve input.
- const saveUi = $state({ selected: {}, folder: '', names: {}, touched: {}, baseName: '', note: '' });
- // The header name controls the session filename; `openedSession` stores its slug.
- let sessionName = $state('');
- let openedSession = $state(null);
- const sessionModal = $state({ open: false, list: [], busy: false });
- let sessionQuery = $state('');
- let sessionBrowserOpen = $state(false);
- let sessionBrowsePath = $state('');
- let sessionBrowseSelection = $state(null);
- const visibleSessions = $derived(
- sessionQuery.trim() ? sessionModal.list.filter((s) => matchesSessionQuery(s, sessionQuery)) : sessionModal.list
- );
- const sessionBrowserEntries = $derived(
- sessionModal.list.map((s) => ({ ...s, id: s.name, attrs: { folder: s.folder ?? '' } }))
- );
- let discardConfirm = $state(false);
- // Loading can be slow because each frame and collage node is rendered in sequence.
- let sessionLoading = $state(false);
-
- // A session can hold several collages and edits one at a time; this is the
- // live one (reset on source / case change).
- const _firstCollage = newCollage('Collage 1');
- // Bumped every time the session is cleared, so work started against the old
- // one can tell it is stale (`resetSession`, `capture`).
- let sessionRun = 0;
- const session = $state({
+ // The open file's work. `caseId` is captured with it, so a save still pending
+ // when the case changes lands in the case it was made in.
+ const work = $state({
+ caseId: null,
source: null,
+ name: null,
videoAdjust: {},
videoRotation: 0,
+ videoFiled: null,
frames: [],
activeFrameId: null,
- collages: [_firstCollage],
- activeCollageId: _firstCollage.id,
- saved: {},
- });
-
- const activeCollage = $derived(
- session.collages.find((c) => c.id === session.activeCollageId) ?? session.collages[0] ?? null
- );
-
- // ---- collage undo / redo --------------------------------------------------
- // Snapshot history over the collages (quads, pieces, crops). A drag mutates
- // node.quad continuously; the debounced capture collapses it into one entry.
- const collageHistory = createHistory();
- let collageCanUndo = $state(false);
- let collageCanRedo = $state(false);
- let collageHistBusy = false; // plain (untracked): suppresses capture while restoring
- let collageHistTimer = null;
-
- const collageSnapshot = () => JSON.stringify(session.collages);
-
- function syncCollageHist() {
- collageCanUndo = collageHistory.canUndo;
- collageCanRedo = collageHistory.canRedo;
- }
-
- function anchorCollageHistory() {
- clearTimeout(collageHistTimer);
- collageHistory.reset(collageSnapshot());
- syncCollageHist();
- }
-
- $effect(() => {
- const json = collageSnapshot(); // reads every collage field → tracked
- if (collageHistBusy) return;
- clearTimeout(collageHistTimer);
- collageHistTimer = setTimeout(() => {
- collageHistory.push(json);
- syncCollageHist();
- }, 350);
- });
-
- function applyCollageSnapshot(json) {
- collageHistBusy = true;
- session.collages = JSON.parse(json);
- if (!session.collages.some((c) => c.id === session.activeCollageId)) {
- session.activeCollageId = session.collages[0]?.id ?? null;
- }
- collageSelectedIds = [];
- // outlast the capture debounce so the restore itself is not re-recorded
- setTimeout(() => (collageHistBusy = false), 400);
- }
-
- function undoCollage() {
- const json = collageHistory.undo();
- if (json != null) applyCollageSnapshot(json);
- syncCollageHist();
- }
-
- function redoCollage() {
- const json = collageHistory.redo();
- if (json != null) applyCollageSnapshot(json);
- syncCollageHist();
- }
-
- // ---- keyboard: collage undo + frame-accurate video stepping ----------------
- const frameDur = $derived(probeInfo?.fps ? 1 / probeInfo.fps : 1 / 30);
-
- function stepVideo(delta) {
- const duration = probeInfo?.duration ?? Infinity;
- shared.seekTo = Math.min(Math.max((shared.currentTime ?? 0) + delta, 0), duration);
- }
-
- function toggleVideoPlayback() {
- if (!videoEl) return;
- if (videoEl.paused) videoEl.play().catch(() => {});
- else videoEl.pause();
- }
-
- function onWindowKeydown(e) {
- if (uiState.tool !== 'inspect') return;
- const t = e.target;
- if (['INPUT', 'TEXTAREA', 'SELECT'].includes(t.tagName) || t.isContentEditable) return;
- if (e.ctrlKey || e.metaKey) {
- if (activeTab !== 'collage') return;
- const k = e.key.toLowerCase();
- if (k === 'z') { e.preventDefault(); e.shiftKey ? redoCollage() : undoCollage(); }
- else if (k === 'y') { e.preventDefault(); redoCollage(); }
- return;
- }
- // Frame tab: Enter applies the crop (→ committed preview), Esc leaves editing.
- if (activeTab === 'frame' && cropEditing) {
- if (e.key === 'Enter') { e.preventDefault(); commitCrop(); }
- else if (e.key === 'Escape') { e.preventDefault(); cancelCrop(); }
- return;
- }
- // Selection tab: ←/→ step one frame (Shift = 1s), ,/. mpv-style aliases
- if (activeTab !== 'selection' || session.source?.kind !== 'video') return;
- if (e.key === 'ArrowLeft') { e.preventDefault(); stepVideo(e.shiftKey ? -1 : -frameDur); }
- else if (e.key === 'ArrowRight') { e.preventDefault(); stepVideo(e.shiftKey ? 1 : frameDur); }
- else if (e.key === ',') { e.preventDefault(); stepVideo(-frameDur); }
- else if (e.key === '.') { e.preventDefault(); stepVideo(frameDur); }
- else if (e.key === ' ') { e.preventDefault(); toggleVideoPlayback(); }
- }
-
- // keep-alive: tools stay mounted when another tab is shown — silence the video
- $effect(() => {
- if (uiState.tool !== 'inspect') videoEl?.pause();
});
- // viewer bridge (video seek + crop overlay), mirrors the old shared object
- const shared = $state({ currentTime: 0, seekTo: null, cropMode: false });
- let videoEl = $state();
- // Frame-tab viewer: wheel-zoom toward the pointer, left-drag pans, middle-drag
- // turns the view (Google-Earth style, around the grabbed point). Zoom/pan/
- // rotate are *view only* — never saved — so turning just helps read the frame.
- // The rotation is an affine matrix in the stage's own space (see frameRotate.js);
- // `frameAspect` is the crop aspect lock, shared with the right-panel controls.
- let frameZoom = $state(1);
- let framePan = $state({ x: 0, y: 0 });
- let frameRotMatrix = $state(IDENTITY); // accumulated view rotation (stage-local)
- let rotating = $state(false); // a middle-drag turn is in progress
- let rotatePivot = $state({ x: 0, y: 0 }); // target indicator, viewport-local px
- let frameStageEl = $state(); // rotated stage (image + crop overlay)
- let frameZoomEl = $state(); // zoom/pan layer — reference box for screen→local
- let frameViewportEl = $state(); // outer viewport — reference box for the indicator
- let frameAspect = $state(null);
- // Crop has two modes: *editing* (original image + draggable box) and, once
- // applied (Enter / Apply), a committed *preview* showing the cropped result.
- // Re-opening crop (button or double-click) goes back to editing the original.
- let cropEditing = $state(false);
- let cropBefore = null; // the crop editing opened on — what Escape puts back
- let frameOrientationBusy = $state(false);
+ // Bumped whenever the open file changes, so a render or a capture that returns
+ // afterwards can tell it belongs to a file no longer open.
+ let openRun = 0;
+ // Every preview blob this file made. A duplicated frame shares its original's,
+ // so they are freed together when the file closes rather than one at a time.
+ const blobs = new Set();
const videoFilters = $derived(filters.filter((f) => VIDEO_ADJUST_IDS.includes(f.id)));
- const tabs = $derived(
- session.source?.kind === 'video' ? ['selection', 'frame', 'collage', 'save'] : ['frame', 'save']
- );
- const activeFrame = $derived(session.frames.find((f) => f.id === session.activeFrameId) ?? null);
+ const isVideo = $derived(work.source?.kind === 'video');
+ const activeFrame = $derived(work.frames.find((f) => f.id === work.activeFrameId) ?? null);
+ const selected = $derived(activeFrame ? activeFrame.id : isVideo ? 'video' : null);
const framePreview = $derived(activeFrame ? previewStyle(filters, activeFrame.adjust) : { filter: '', transform: '' });
- const videoPreview = $derived(previewStyle(videoFilters, session.videoAdjust));
- const videoRotation = $derived(normalizeRightAngleRotation(session.videoRotation));
- const videoQuarterTurn = $derived(Math.abs(videoRotation) === 90);
- const videoPreviewTransform = $derived(
+ const videoPreview = $derived(previewStyle(videoFilters, work.videoAdjust));
+ const videoRotation = $derived(normalizeRightAngleRotation(work.videoRotation));
+ const videoTransform = $derived(
[videoPreview.transform, videoRotation ? `rotate(${videoRotation}deg)` : ''].filter(Boolean).join(' ')
);
+ const videoEdited = $derived(isVideo && hasVideoEdits(videoFilters, work.videoAdjust, videoRotation));
+
+ // A frame carries only the path it was cut from, so the title is looked back up:
+ // without it every frame of a download is named after the download's filename.
+ const stemFor = (path) => sourceStem({ path, title: titleByPath.get(path) ?? work.source?.title });
+ const frameNames = $derived.by(() => {
+ const names = frameSaveNames(work.frames.map((f) => ({ stem: stemFor(f.path), time: f.time })));
+ return new Map(work.frames.map((f, i) => [f.id, names[i]]));
+ });
+ const filedIds = $derived(
+ new Set(work.frames.filter((f) => isFiled(f.filed, frameSignature(filters, f), mediaPaths)).map((f) => f.id))
+ );
+ const videoFiled = $derived(
+ isFiled(work.videoFiled, videoSignature(videoFilters, work.videoAdjust, videoRotation), mediaPaths)
+ );
- // A frame carries the path it was cut from and nothing else, so the title has
- // to be looked back up: without this, every frame of a downloaded video is named
- // after the download's filename instead of what the analyst called it.
- const titleByPath = $derived(new Map(mediaList.map((m) => [m.path, m.title])));
- const stemFor = (path, item = null) =>
- sourceStem({ ...item, path, title: titleByPath.get(path) ?? item?.title });
+ // -- saving as it is made ---------------------------------------------------
+ let savedSignature = $state(null);
+ const signature = () => JSON.stringify(workSpec(work));
+ const pristine = $derived(!work.source || isPristine(work, filters, videoFilters));
- const savables = $derived.by(() => {
- const out = [];
- const cid = caseState.current?.id;
- const stem = stemFor(session.source?.path, session.source);
- if (session.source?.kind === 'video' && hasVideoEdits(videoFilters, session.videoAdjust, videoRotation)) {
- const t = session.source.thumbnail ? fileUrl(cid, session.source.thumbnail) : null;
- out.push({
- key: 'video', kind: 'video', defaultName: `${stem} (enhanced)`, thumb: t,
- filter: videoPreview.filter, transform: videoPreviewTransform,
- saved: !!session.saved.video,
- });
- }
- // Named as a set, not one by one: a frame only needs sub-second digits when
- // another frame in the tray lands in the same second.
- const frameNames = frameSaveNames(
- session.frames.map((fr) => ({ stem: stemFor(fr.path), time: fr.time })),
- );
- for (const [i, fr] of session.frames.entries()) {
- out.push({
- key: `frame:${fr.id}`, kind: 'frame', frame: fr, thumb: fr.url,
- defaultName: frameNames[i],
- filter: previewStyle(filters, fr.adjust).filter,
- saved: !!session.saved[`frame:${fr.id}`],
- });
- }
- let colN = 0;
- for (const cl of session.collages) {
- colN += 1;
- if (!cl.nodes.length) continue;
- out.push({
- key: `collage:${cl.id}`, kind: 'collage', defaultName: cl.name || `Collage ${colN}`,
- thumb: null, collage: cl, preview: collagePreviews[cl.id]?.url ?? null,
- saved: !!session.saved[`collage:${cl.id}`],
- });
+ async function writeWork(opts) {
+ if (!work.source || opening) return;
+ const sig = signature();
+ if (sig === savedSignature) return;
+ // Looking at a file files nothing; the first real change is what does.
+ if (!work.name && isPristine(work, filters, videoFilters)) return;
+ const path = work.source.path;
+ const res = await api.put(`/api/cases/${work.caseId}/inspect/work`, { path, spec: JSON.parse(sig) }, opts);
+ if (work.source?.path === path) {
+ const first = !work.name;
+ work.name = res.name;
+ savedSignature = sig;
+ if (first) reloadCase(); // the sidebar lists the work it just filed
}
- return out;
- });
-
- // Every field carries real, editable text — never a placeholder to guess at.
- // Fields the user has not touched follow the base name; the ones they typed in
- // are theirs and stay put.
- //
- // A collage keeps its name in the session (session.collages[].name), not in
- // saveUi — that is the one name the Collage tab and the Save tab share, so a
- // rename in either place shows up in the other.
- const saveName = (it) => (it.kind === 'collage' ? (it.collage.name ?? '') : (saveUi.names[it.key] ?? ''));
- function setSaveName(it, value) {
- if (it.kind === 'collage') it.collage.name = value;
- else saveUi.names[it.key] = value;
- saveUi.touched[it.key] = true;
- saveUi.selected[it.key] = true;
+ workState.rev += 1;
}
- $effect(() => {
- const auto = autoSaveNames(savables, saveUi.baseName);
- savables.forEach((it, i) => {
- if (saveUi.touched[it.key]) return;
- if (it.kind === 'collage') it.collage.name = auto[i];
- else saveUi.names[it.key] = auto[i];
- });
- });
+ const autosave = createAutosave({ write: () => writeWork() });
- // -- lifecycle ------------------------------------------------------------
$effect(() => {
- const id = caseState.current?.id;
- caseState.rev; // refetch when media changes elsewhere (e.g. Media Library upload/delete)
- if (id !== loadedFor) {
- loadedFor = id;
- mediaList = [];
- resetSession();
- if (id) refresh(id);
- } else if (id) {
- refresh(id);
- }
+ const sig = signature();
+ if (!work.source || opening || sig === savedSignature) return;
+ autosave.schedule();
});
+ // Leaving the tool, or the page, is a moment to write rather than wait.
$effect(() => {
- if (uiState.tool === 'inspect' && uiState.inspectPath && mediaList.length) {
- const target = mediaList.find((m) => m.path === uiState.inspectPath);
- uiState.inspectPath = null;
- if (target) select(target);
+ if (uiState.tool !== 'inspect') {
+ autosave.flush();
+ videoEl?.pause();
}
});
+ $effect(() => () => autosave.flush());
- // reopen a saved session from the sidebar (like proofs/posts)
- $effect(() => {
- if (uiState.tool === 'inspect' && uiState.openInspect && mediaList.length) {
- const name = uiState.openInspect;
- uiState.openInspect = null;
- openSession(name);
- }
- });
+ function onpagehide() {
+ if (autosave.pending) writeWork({ keepalive: true }).catch(() => {});
+ }
- $effect(() => {
- if (shared.seekTo != null && videoEl) {
- videoEl.currentTime = shared.seekTo;
- shared.seekTo = null;
- }
+ const status = $derived.by(() => {
+ if (!work.source || (!work.name && pristine)) return '';
+ if (autosave.state.status === 'error') return 'error';
+ if (autosave.state.status === 'pending' || autosave.state.status === 'saving') return 'saving';
+ return 'saved';
});
+ // -- the case -----------------------------------------------------------------
async function ensureOps() {
if (filters.length) return;
const ops = await api.get('/api/inspect/ops');
- // `crop` is driven by the interactive box; `rotate` is a view-only tilt in
- // the Frame tab (never baked); `remap` is solved by auto-stitch — none of the
- // three belongs in the slider pipeline.
+ // `crop` is the interactive box, `rotate` a view-only turn and `remap` what
+ // auto-stitch solves: none of the three belongs in the slider pipeline.
const solved = ['crop', 'rotate', 'remap'];
filters = ops.filters.filter((f) => !solved.includes(f.id));
analyses = ops.analyses;
}
+ async function refreshWorks(id = caseState.current?.id) {
+ if (!id) return;
+ try {
+ works = await api.get(`/api/cases/${id}/inspect/works`);
+ } catch {
+ works = [];
+ }
+ }
+
async function refresh(id = caseState.current?.id) {
if (!id) return;
mediaList = await api.get(`/api/cases/${id}/media`);
+ await refreshWorks(id);
}
- // A delete anywhere else in the app lands here: this workspace may be sitting
- // on a subject, or on a saved session, that no longer exists.
- //
- // The saved session is the dangerous half — a session cannot outlive its
- // subject, so deleting the subject deletes the session (ONTOLOGY §3). Left
- // bound, the next Save would silently write the deleted session back. Drop the
- // binding instead: Save then files a new one, deliberately.
- let sourceGone = $state(false);
$effect(() => {
const id = caseState.current?.id;
- caseState.rev; // re-check after a delete elsewhere
- const sessionName = openedSession?.name;
- const path = session.source?.path;
- if (!id) {
- sourceGone = false;
- return;
+ caseState.rev; // a delete, an import or a restore elsewhere
+ if (id !== loadedFor) {
+ loadedFor = id;
+ mediaList = [];
+ works = [];
+ // A save still pending goes to the case it was made in, then the file closes.
+ autosave.flush().finally(() => {
+ if (work.caseId && work.caseId !== caseState.current?.id) closeFile();
+ });
+ if (id) refresh(id);
+ } else if (id) {
+ refresh(id).then(recheckOpenFile);
}
- let live = true;
- (async () => {
- if (sessionName) {
- const bound = await lookupEntity(id, specAttr('session'), specPath('session', sessionName));
- if (live && !bound && openedSession?.name === sessionName) {
- openedSession = null;
- toast('The saved session was deleted. Saving now creates a new one', 'warn');
- }
- }
- if (path) {
- const ent = await lookupEntity(id, 'path', path);
- if (live) sourceGone = !ent;
- } else if (live) {
- sourceGone = false;
- }
- })();
- return () => {
- live = false;
- };
});
- // Every saved session in this case, read off the filed entities: the slugs to
- // catch a name already taken, the names so a fresh session reads apart.
- let sessionEntities = $state([]);
- $effect(() => {
- const id = caseState.current?.id;
- caseState.rev; // refresh after a save or a delete anywhere else
- if (!id) {
- sessionEntities = [];
+ /**
+ * Whatever changed elsewhere may concern the open file. A renamed one is followed
+ * to its new path. A deleted file takes its work with it, so there is nothing
+ * left to keep open. A restore may have brought back the work of a file shown
+ * here with nothing done to it yet, and that work is what should be on screen
+ * rather than be written over.
+ */
+ async function recheckOpenFile() {
+ if (!work.source || opening) return;
+ if (!mediaPaths.has(work.source.path)) {
+ // Renamed elsewhere: the same file under a new path, with its work moved along.
+ const moved = work.source.entity_id && mediaList.find((m) => m.entity_id === work.source.entity_id);
+ if (moved) {
+ open(moved);
+ return;
+ }
+ autosave.cancel();
+ toast(`“${work.source.title || work.source.filename}” was deleted from the case`, 'warn');
+ closeFile();
return;
}
- let live = true;
- fetchAllEntities(id, { types: ['inspect-session'] })
- .then((list) => {
- if (!live) return;
- sessionEntities = list;
- // The name was assigned before the case's sessions were known. Renumber
- // it now rather than letting a fresh workspace collide on its first save.
- if (!openedSession && isDefaultName(sessionName, 'session')) {
- sessionName = nextName('session', savedTitles(sessionEntities, 'session'));
- }
- })
- .catch(() => { if (live) sessionEntities = []; });
- return () => { live = false; };
- });
-
- const takenSlugs = () => savedSlugs(sessionEntities, 'session');
-
- function openSourceDialog() {
- sourceQuery = '';
- sourceFilter = 'all';
- sourceBrowserOpen = false;
- sourceBrowsePath = '';
- sourceBrowseSelection = null;
- sourceModalOpen = true;
- }
-
- function matchesSourceName(item, query) {
- return matchesTerms(item.title || item.filename || '', query);
- }
-
- function sourceCategory(item) {
- const source = item.source ?? {};
- if (source.type === 'satellite' || source.type === 'screenshot') return 'capture';
- if (source.op === 'collage') return 'collage';
- if (source.op === 'frame' || source.op === 'adjust') return 'frame';
- return item.kind;
- }
-
- function matchesSessionQuery(session, query) {
- return matchesTerms([session.title, session.name, session.source].filter(Boolean).join('\n'), query);
- }
-
- function openSourceBrowser() {
- sourceQuery = '';
- sourceBrowsePath = '';
- sourceBrowseSelection = null;
- sourceBrowserOpen = true;
- }
-
- function toggleSourceBrowser() {
- if (sourceBrowserOpen) {
- sourceBrowserOpen = false;
- return;
+ if (!work.name && pristine && works.some((w) => w.source === work.source.path)) {
+ open(work.source);
}
- openSourceBrowser();
}
- function setSourceFilter(filter) {
- sourceFilter = filter;
- sourceBrowsePath = '';
- sourceBrowseSelection = null;
- }
-
- function openSourceFolder(path) {
- sourceBrowsePath = path;
- sourceBrowseSelection = null;
+ // -- opening a file -----------------------------------------------------------
+ function closeFile() {
+ openRun += 1;
+ for (const url of blobs) URL.revokeObjectURL(url);
+ blobs.clear();
+ work.caseId = null;
+ work.source = null;
+ work.name = null;
+ work.videoAdjust = {};
+ work.videoRotation = 0;
+ work.videoFiled = null;
+ work.frames = [];
+ work.activeFrameId = null;
+ savedSignature = null;
+ probeInfo = null;
+ shared.currentTime = 0;
+ shared.cropMode = false;
+ cropEditing = false;
+ cropBefore = null;
+ frameAspect = null;
}
- function confirmSourceBrowser() {
- const item = sourceBrowserEntries.find((m) => m.path === sourceBrowseSelection);
- if (item) selectNewSource(item);
+ async function open(item) {
+ pickerOpen = false;
+ await autosave.flush();
+ await ensureOps();
+ closeFile();
+ const run = openRun;
+ const caseId = caseState.current?.id;
+ opening = true;
+ work.caseId = caseId;
+ work.source = item;
+ try {
+ const [probe, saved] = await Promise.all([
+ api.get(`/api/cases/${caseId}/inspect/probe?path=${encodeURIComponent(item.path)}`).catch(() => ({ kind: item.kind })),
+ api.get(`/api/cases/${caseId}/inspect/work?path=${encodeURIComponent(item.path)}`).then((r) => r.work),
+ ]);
+ if (run !== openRun) return;
+ probeInfo = probe;
+ if (saved) restore(saved, run);
+ else seed();
+ savedSignature = signature();
+ } catch (e) {
+ if (run === openRun) {
+ toast(e.message, 'danger');
+ closeFile();
+ }
+ } finally {
+ if (run === openRun) opening = false;
+ }
}
- function selectSourceBrowser(item, confirm = false) {
- sourceBrowseSelection = item.path;
- if (confirm) selectNewSource(item);
+ /** Back to the file list. Nothing is lost: what is pending is written first. */
+ async function leave() {
+ await autosave.flush();
+ closeFile();
+ refreshWorks();
}
- function openSessionBrowser() {
- sessionBrowsePath = '';
- sessionBrowseSelection = null;
- sessionBrowserOpen = true;
- }
+ // -- renaming the file -----------------------------------------------------------
+ // The field follows the file's name, and goes back to it when the one typed is
+ // blank or abandoned with Escape. A rename moves the file on disk, and the work
+ // with it, so the file is reopened under its new path.
+ const fileLabel = $derived(work.source ? work.source.title || work.source.filename : '');
+ let nameField = $state('');
+ let renaming = $state(false);
+ $effect(() => {
+ nameField = fileLabel;
+ });
- function toggleSessionBrowser() {
- if (sessionBrowserOpen) {
- sessionBrowserOpen = false;
+ async function commitName() {
+ const source = work.source;
+ const typed = nameField.trim();
+ if (!source || renaming || !typed || typed === fileLabel) {
+ nameField = fileLabel;
return;
}
- openSessionBrowser();
- }
-
- function openSessionFolder(path) {
- sessionBrowsePath = path;
- sessionBrowseSelection = null;
+ renaming = true;
+ try {
+ await autosave.flush();
+ if (autosave.state.status === 'error') throw new Error('The work is not saved yet. Retry, then rename the file');
+ const at = shared.currentTime;
+ const renamed = await api.patch(`/api/cases/${work.caseId}/media`, { path: source.path, title: typed });
+ await open({ ...source, ...renamed });
+ if (at) shared.seekTo = at;
+ reloadCase();
+ } catch (e) {
+ nameField = fileLabel;
+ toast(e.message, 'danger');
+ } finally {
+ renaming = false;
+ }
}
- function confirmSessionBrowser() {
- if (sessionBrowseSelection) openSession(sessionBrowseSelection);
+ function nameKey(e) {
+ if (e.key === 'Enter') e.currentTarget.blur();
+ else if (e.key === 'Escape') {
+ nameField = fileLabel;
+ e.currentTarget.blur();
+ }
}
- function selectSessionBrowser(session, confirm = false) {
- sessionBrowseSelection = session.name;
- if (confirm) openSession(session.name);
+ /** A file with nothing done to it: a video waits for frames, an image is its own. */
+ function seed() {
+ work.videoAdjust = adjustDefaults(videoFilters);
+ if (!isVideo) {
+ const frame = makeFrame(work.source.path, null);
+ frame.url = fileUrl(work.caseId, work.source.path);
+ work.frames = [frame];
+ work.activeFrameId = frame.id;
+ }
}
- function startNewSession() {
- if (session.source) {
- openSourceAfterDiscard = true;
- discardConfirm = true;
+ function restore(saved, run) {
+ const spec = saved.spec;
+ work.name = saved.name;
+ work.videoAdjust = { ...adjustDefaults(videoFilters), ...(spec.videoAdjust ?? {}) };
+ work.videoRotation = normalizeRightAngleRotation(spec.videoRotation);
+ work.videoFiled = spec.videoFiled ?? null;
+ work.frames = (spec.frames ?? []).map((f) => ({ ...f, adjust: { ...adjustDefaults(filters), ...(f.adjust ?? {}) }, url: null }));
+ if (!isVideo && !work.frames.length) {
+ seed();
return;
}
- openSourceDialog();
- }
-
- function resetSession() {
- // Everything still in flight against the session being cleared belongs to a
- // document that no longer exists. `session` is one object mutated in place,
- // so a pending render has no way to notice on its own (see `capture`).
- sessionRun += 1;
- for (const fr of session.frames) if (fr.url?.startsWith('blob:')) URL.revokeObjectURL(fr.url);
- session.source = null;
- session.videoAdjust = {};
- session.videoRotation = 0;
- session.frames = [];
- session.activeFrameId = null;
- const c0 = newCollage('Collage 1');
- session.collages = [c0];
- session.activeCollageId = c0.id;
- for (const p of Object.values(collagePreviews)) if (p?.url) URL.revokeObjectURL(p.url);
- collagePreviews = {};
- session.saved = {};
- saveUi.selected = {};
- saveUi.folder = '';
- saveUi.names = {};
- saveUi.touched = {};
- saveUi.baseName = '';
- saveUi.note = '';
- openedSession = null;
- sessionName = nextName('session', savedTitles(sessionEntities, 'session'));
- savedSignature = null;
- collageSelectedIds = [];
- shared.currentTime = 0;
- shared.cropMode = false;
- frameZoom = 1;
- framePan = { x: 0, y: 0 };
- frameRotMatrix = IDENTITY;
- rotating = false;
- frameAspect = null;
- cropEditing = false;
- cropBefore = null;
- anchorCollageHistory();
+ work.activeFrameId = work.frames.some((f) => f.id === spec.activeFrameId)
+ ? spec.activeFrameId
+ : isVideo ? null : work.frames[0].id;
+ renderFrames(run);
}
- async function select(item) {
- await ensureOps();
- resetSession();
- session.source = item;
- try {
- probeInfo = await api.get(
- `/api/cases/${caseState.current.id}/inspect/probe?path=${encodeURIComponent(item.path)}`
- );
- } catch {
- probeInfo = { kind: item.kind };
- }
- if (item.kind === 'video') {
- session.videoAdjust = adjustDefaults(videoFilters);
- activeTab = 'selection';
- } else {
- const frame = makeFrame(item.path, null, fileUrl(caseState.current.id, item.path));
- session.frames.push(frame);
- session.activeFrameId = frame.id;
- activeTab = 'frame';
- }
+ /** Previews for a reopened work, a few at a time so the strip fills in as they land. */
+ async function renderFrames(run) {
+ const queue = [...work.frames];
+ const next = async () => {
+ while (queue.length) {
+ const frame = queue.shift();
+ try {
+ const url = await frameUrl(frame);
+ if (run !== openRun) return;
+ frame.url = url;
+ if (!frame.w || !frame.h) Object.assign(frame, await imageSize(url));
+ } catch {
+ if (run === openRun) frame.missing = true;
+ }
+ }
+ };
+ await Promise.all([next(), next(), next()]);
}
- async function selectNewSource(item) {
- sourceModalOpen = false;
- await select(item);
+ /** The pixels a frame is edited over: its source, turned. Adjust and crop are previewed on top. */
+ function frameUrl(frame) {
+ const ops = [...(frame.sourceOps ?? []), ...rotationOps(frame.rotation)];
+ if (frame.time == null && !ops.length) return Promise.resolve(fileUrl(work.caseId, frame.path));
+ return renderUrl(frame.path, frame.time, ops);
}
- function makeFrame(path, time, url) {
+ function makeFrame(path, time) {
return {
- id: uid('fr'), path, time, url,
+ id: uid('fr'), path, time, url: null,
adjust: adjustDefaults(filters), crop: null, sourceOps: [], rotation: 0,
- w: probeInfo?.width, h: probeInfo?.height,
+ w: probeInfo?.width, h: probeInfo?.height, filed: null,
};
}
- // Render a recipe (video frame / image + ops) to a PNG, no filing.
+ // Handoffs: a file sent from the Media Library or Reverse Search, and a work
+ // reopened from the sidebar, which is reopened on its file.
+ $effect(() => {
+ if (uiState.tool === 'inspect' && uiState.inspectPath && mediaList.length) {
+ const target = mediaList.find((m) => m.path === uiState.inspectPath);
+ uiState.inspectPath = null;
+ if (target) open(target);
+ }
+ });
+
+ $effect(() => {
+ if (uiState.tool === 'inspect' && uiState.openInspect && mediaList.length) {
+ const name = uiState.openInspect;
+ uiState.openInspect = null;
+ api.get(`/api/cases/${caseState.current.id}/inspect/works/${encodeURIComponent(name)}`)
+ .then((saved) => {
+ const target = mediaList.find((m) => m.path === saved.spec?.source?.path);
+ if (target) open(target);
+ })
+ .catch((e) => toast(e.message, 'warn'));
+ }
+ });
+
+ // -- rendering ------------------------------------------------------------------
async function renderBlob(path, time, ops = []) {
- const res = await fetch(`/api/cases/${caseState.current.id}/inspect/render-preview`, {
+ const res = await fetch(`/api/cases/${work.caseId}/inspect/render-preview`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ path, time: time ?? null, ops }),
@@ -635,22 +415,9 @@
}
async function renderUrl(path, time, ops = []) {
- return URL.createObjectURL(await renderBlob(path, time, ops));
- }
-
- /**
- * Hand a tray frame to Reverse Search as it reads here — turned, adjusted and
- * cropped — without filing it. The crop is usually the subject, and an engine
- * matches a subject better than the whole picture it sits in.
- */
- async function reverseFrame(frame) {
- try {
- const blob = await renderBlob(frame.path, frame.time, buildFrameOps(filters, frame));
- const name = session.source?.title || session.source?.filename || frame.path.split('/').pop();
- openInReverseSearch({ blob, label: frame.time != null ? `${name} · t=${frame.time.toFixed(2)}s` : name });
- } catch (e) {
- toast(e.message, 'danger');
- }
+ const url = URL.createObjectURL(await renderBlob(path, time, ops));
+ blobs.add(url);
+ return url;
}
function imageSize(url) {
@@ -662,646 +429,300 @@
});
}
- // -- true-to-export collage thumbnails (Save tab) -------------------------
- // The Save picker shows the *actual* composited PNG (backend warp), not the
- // CSS approximation. Signature = the pieces' recipes+quads, so we only re-render
- // when a layout really changed.
- const collageSig = (cl) => JSON.stringify(cl.nodes.map((n) => [n.save, n.quad]));
-
- async function buildCollagePreview(cl, sig, cid) {
- try {
- const b = collageBounds(cl.nodes);
- const nodes = cl.nodes.map((n) => ({
- src: n.save, quad: n.quad.map(([x, y]) => [x - b.minX, y - b.minY]),
- }));
- const res = await fetch(`/api/cases/${cid}/inspect/compose-preview`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ width: b.width, height: b.height, background: null, nodes }),
- });
- if (!res.ok) return;
- const url = URL.createObjectURL(await res.blob());
- const prev = collagePreviews[cl.id];
- if (prev?.url) URL.revokeObjectURL(prev.url);
- collagePreviews[cl.id] = { sig, url };
- } catch {
- /* leave the CSS fallback in place */
- }
- }
-
- $effect(() => {
- if (activeTab !== 'save') return;
- const cid = caseState.current?.id;
- if (!cid) return;
- for (const cl of session.collages) {
- if (!cl.nodes.length) continue;
- const sig = collageSig(cl);
- if (collagePreviews[cl.id]?.sig === sig) continue;
- buildCollagePreview(cl, sig, cid);
- }
- });
-
- // -- frame capture (Selection) -------------------------------------------
- async function capture(time) {
- // The render and the measurement below are two round trips, and a slow video
- // leaves room to discard the session or pick another source in between. The
- // frame that lands is evidence, so a stale one must be dropped rather than
- // pushed into whatever document is open by then.
- const run = sessionRun;
- try {
- const sourceOps = rotationOps(videoRotation);
- const url = await renderUrl(session.source.path, time, sourceOps);
- const frame = makeFrame(session.source.path, time, url);
- const dim = await imageSize(url);
- if (run !== sessionRun) {
- if (url.startsWith('blob:')) URL.revokeObjectURL(url);
- return;
- }
- frame.sourceOps = sourceOps;
- frame.w = dim.w;
- frame.h = dim.h;
- // frames captured from a tuned video inherit those gear adjustments
- frame.adjust = videoSeed(filters, session.videoAdjust);
- session.frames.push(frame);
- session.activeFrameId = frame.id;
- toast('Frame added to tray. Not saved yet', 'ok');
- } catch (e) {
- if (run === sessionRun) toast(e.message, 'danger');
- }
- }
-
- // Collage pieces are snapshots frozen at add-time: the modified image is baked
- // now and later frame edits never change it (deliberate — see SPEC).
- async function addToCollage(frame) {
- const cl = activeCollage;
- if (!cl) return;
+ /**
+ * Hand a frame to Reverse Search as it reads here, turned, adjusted and cropped,
+ * without filing it. The crop is usually the subject, and an engine matches a
+ * subject better than the whole picture it sits in.
+ */
+ async function reverseFrame(frame) {
try {
- const ops = buildFrameOps(filters, frame);
- const url = await renderUrl(frame.path, frame.time, ops);
- const dim = await imageSize(url);
- const count = cl.nodes.length;
- const off = 30 + (count % 4) * 40;
- const quad = initialQuad(dim.w, dim.h, cl.width * 0.5, off, off);
- const node = {
- id: uid('nd'), frameId: frame.id, url, baseUrl: url, w: dim.w, h: dim.h,
- frameOps: ops, crop: null,
- save: { path: frame.path, time: frame.time ?? null, ops }, quad,
- };
- cl.nodes.push(node);
- collageSelectedIds = [node.id];
+ const blob = await renderBlob(frame.path, frame.time, buildFrameOps(filters, frame));
+ const name = work.source?.title || work.source?.filename || frame.path.split('/').pop();
+ openInReverseSearch({ blob, label: frame.time != null ? `${name} · t=${frame.time.toFixed(2)}s` : name });
} catch (e) {
toast(e.message, 'danger');
}
}
- // Re-render a collage piece with (or without) its crop, applied before the
- // warp. Keeps baseUrl (uncropped snapshot) so the crop editor never compounds.
- async function applyNodeCrop(node, crop) {
+ // -- frames -----------------------------------------------------------------------
+ async function capture(time) {
+ // Two round trips, long enough on a slow video to switch file in between. The
+ // frame is evidence, so a late one is dropped rather than put in another file.
+ const run = openRun;
try {
- const frameOps = node.frameOps ?? node.save?.ops ?? [];
- const ops = crop ? [...frameOps, { op: 'crop', params: crop }] : [...frameOps];
- const url = await renderUrl(node.save.path, node.save.time, ops);
+ const sourceOps = rotationOps(videoRotation);
+ const url = await renderUrl(work.source.path, time, sourceOps);
const dim = await imageSize(url);
- // Reshape the quad so the cropped image keeps correct proportions and
- // stays in place. Derive the *full-image* quad from the current one (a
- // crop stored on the node is relative to the base image, so re-cropping
- // never compounds), then re-project the new crop rectangle onto it.
- const prev = node.crop;
- const baseQuad = prev
- ? quadFromCropRect(node.quad, { x: -prev.x / prev.w, y: -prev.y / prev.h, w: 1 / prev.w, h: 1 / prev.h })
- : node.quad;
- node.quad = crop ? quadFromCropRect(baseQuad, crop) : baseQuad.map(([x, y]) => [x, y]);
- // the previous blob URL stays alive: an undo may restore a snapshot that
- // still points at it (bounded leak, reclaimed on session reset/reload)
- node.url = url;
- node.w = dim.w;
- node.h = dim.h;
- node.crop = crop;
- node.save = { ...node.save, ops };
+ if (run !== openRun) return;
+ const frame = makeFrame(work.source.path, time);
+ Object.assign(frame, { url, sourceOps, w: dim.w, h: dim.h });
+ // frames cut from an adjusted clip start from its adjustments
+ frame.adjust = videoSeed(filters, work.videoAdjust);
+ work.frames.push(frame);
} catch (e) {
- toast(e.message, 'danger');
+ if (run === openRun) toast(e.message, 'danger');
}
}
- // Re-derive a collage piece's pixels for a new op pipeline — auto-stitch's
- // panorama modes bake their warp into the recipe, so the piece the analyst sees
- // is the piece the backend will export. A crop rect is relative to the piece's
- // own snapshot, and that snapshot has just changed underneath it, so the
- // re-derived piece starts crop-free: whatever it was showing is now baked in.
- async function renderPiece(node, ops) {
- const url = await renderUrl(node.save.path, node.save.time, ops);
- const dim = await imageSize(url);
- node.url = url;
- node.baseUrl = url;
- node.w = dim.w;
- node.h = dim.h;
- node.frameOps = ops;
- node.crop = null;
- node.save = { ...node.save, ops };
+ function select(id) {
+ cropEditing = false;
+ cropBefore = null;
+ shared.cropMode = false;
+ work.activeFrameId = id === 'video' ? null : id;
}
- // Open the piece crop editor, or clear the crop directly (clear=true).
- function requestCrop(node, clear = false) {
- if (clear) {
- applyNodeCrop(node, null);
- } else {
- cropPieceNode = node;
- }
+ function removeFrame(id) {
+ const index = work.frames.findIndex((f) => f.id === id);
+ if (index === -1) return;
+ const [frame] = work.frames.splice(index, 1);
+ if (work.activeFrameId === id) {
+ const neighbour = work.frames[Math.min(index, work.frames.length - 1)];
+ work.activeFrameId = neighbour?.id ?? null;
+ }
+ const run = openRun;
+ toast('Frame removed', 'info', 6000, {
+ label: 'Undo',
+ onClick: () => {
+ if (run !== openRun || work.frames.some((f) => f.id === frame.id)) return;
+ work.frames.splice(Math.min(index, work.frames.length), 0, frame);
+ work.activeFrameId = frame.id;
+ },
+ });
}
- function removeFrame(id) {
- const fr = session.frames.find((f) => f.id === id);
- if (fr?.url?.startsWith('blob:')) URL.revokeObjectURL(fr.url);
- session.frames = session.frames.filter((f) => f.id !== id);
- // collage pieces are independent snapshots — they stay.
- delete session.saved[`frame:${id}`];
- if (session.activeFrameId === id) session.activeFrameId = session.frames[0]?.id ?? null;
+ function duplicateFrame(frame) {
+ const index = work.frames.findIndex((f) => f.id === frame.id);
+ const copy = {
+ ...$state.snapshot(frame),
+ id: uid('fr'),
+ adjust: { ...frame.adjust },
+ filed: null,
+ };
+ work.frames.splice(index + 1, 0, copy);
+ select(copy.id);
}
+ let rotationBusy = $state(false);
async function setFrameRotation(angle) {
const frame = activeFrame;
- if (!frame || frameOrientationBusy) return;
+ if (!frame || rotationBusy) return;
const rotation = normalizeRightAngleRotation(angle);
- frameOrientationBusy = true;
+ rotationBusy = true;
try {
- const url = await renderUrl(frame.path, frame.time, [
- ...(frame.sourceOps ?? []),
- ...rotationOps(rotation),
- ]);
+ const url = await frameUrl({ ...frame, rotation });
const dim = await imageSize(url);
- if (!session.frames.includes(frame)) {
- URL.revokeObjectURL(url);
- return;
- }
- const oldUrl = frame.url;
- frame.url = url;
- frame.rotation = rotation;
- frame.w = dim.w;
- frame.h = dim.h;
- if (oldUrl?.startsWith('blob:')) URL.revokeObjectURL(oldUrl);
+ if (!work.frames.includes(frame)) return;
+ Object.assign(frame, { url, rotation, w: dim.w, h: dim.h });
} catch (e) {
toast(e.message, 'danger');
} finally {
- frameOrientationBusy = false;
+ rotationBusy = false;
}
}
- // -- frame viewer: zoom / pan / straighten (Frame tab) -------------------
- // Reset the view whenever the active frame changes.
- $effect(() => {
- session.activeFrameId; // track
- frameZoom = 1;
- framePan = { x: 0, y: 0 };
- frameRotMatrix = IDENTITY;
- frameAspect = null;
- cropEditing = false;
- cropBefore = null;
- shared.cropMode = false;
- });
+ // -- crop: editing shows the original with a box; applying shows the result ------
+ let cropEditing = $state(false);
+ let cropBefore = null; // the crop editing opened on, which Escape puts back
+ let frameAspect = $state(null);
- // Enter crop editing (original + box); arm a fresh draw if there's no box yet.
function beginCrop() {
if (!activeFrame) return;
cropBefore = activeFrame.crop ? { ...activeFrame.crop } : null;
cropEditing = true;
if (!activeFrame.crop) shared.cropMode = true;
}
- // Apply the crop → drop back to the committed preview of the cropped result.
function commitCrop() {
cropEditing = false;
shared.cropMode = false;
cropBefore = null;
}
- // Escape leaves crop editing the way it found it: the box drawn since
- // `beginCrop` is dropped rather than applied. Escape committing was the one
- // key in the tool that made a change the analyst was backing out of.
+ // Escape leaves crop editing the way it found it: a box drawn since beginCrop is
+ // dropped rather than applied.
function cancelCrop() {
if (activeFrame) activeFrame.crop = cropBefore;
- cropEditing = false;
- shared.cropMode = false;
- cropBefore = null;
+ commitCrop();
}
- // Wheel zooms toward the pointer (never below the fitted size); at 1× the pan
- // snaps back to centre so the image can't drift off.
- function frameWheel(e) {
- if (!activeFrame) return;
- e.preventDefault();
- const r = e.currentTarget.getBoundingClientRect();
- const px = e.clientX - r.left;
- const py = e.clientY - r.top;
- const cX = r.width / 2;
- const cY = r.height / 2;
- const old = frameZoom;
- const next = Math.min(Math.max(old * (e.deltaY > 0 ? 0.9 : 1.1), 1), 8);
- if (next === 1) {
- frameZoom = 1;
- framePan = { x: 0, y: 0 };
- return;
+ // -- video --------------------------------------------------------------------------
+ // The bridge between the player and its panel: where the clip is, where to seek,
+ // and whether the frame viewer is drawing a crop box.
+ const shared = $state({ currentTime: 0, seekTo: null, cropMode: false });
+ let videoEl = $state();
+ const frameDur = $derived(probeInfo?.fps ? 1 / probeInfo.fps : 1 / 30);
+
+ $effect(() => {
+ if (shared.seekTo != null && videoEl) {
+ videoEl.currentTime = shared.seekTo;
+ shared.seekTo = null;
}
- // keep the point under the pointer fixed (transform-origin is the centre)
- const ratio = next / old;
- framePan = {
- x: px - (px - (cX + framePan.x)) * ratio - cX,
- y: py - (py - (cY + framePan.y)) * ratio - cY,
- };
- frameZoom = next;
- }
+ });
- function resetFrameView() {
- frameZoom = 1;
- framePan = { x: 0, y: 0 };
- frameRotMatrix = IDENTITY;
+ function stepVideo(delta) {
+ const duration = probeInfo?.duration ?? Infinity;
+ shared.seekTo = Math.min(Math.max((shared.currentTime ?? 0) + delta, 0), duration);
}
- const frameViewDirty = $derived(
- frameZoom !== 1 || framePan.x !== 0 || framePan.y !== 0 || !isIdentity(frameRotMatrix)
- );
- const frameAngle = $derived(Math.round(matrixAngleDeg(frameRotMatrix)));
-
- // Middle-drag turns the *view* (never saved), Google-Earth style: a stylised
- // target marks the exact point you grabbed and the image spins around it as you
- // move the mouse — the turn follows the angle the cursor sweeps about that
- // pivot. The rotation is kept as a matrix in the stage's own space, so it
- // composes on top of any prior zoom / pan / rotate: every new grab pivots from
- // wherever you click, with no jump, no matter what the view already looks like.
- const ROTATE_DEADZONE = 8; // px to move off the pivot before a spoke is fixed
- function frameRotateStart(e) {
- if (!activeFrame || !frameStageEl || !frameZoomEl || !frameViewportEl) return;
- // The zoom/pan layer carries only translate + scale (no rotation), so its
- // on-screen box gives a clean screen→local map — read it live so the pivot is
- // correct whatever the current zoom/pan is. offsetLeft/Top place the stage's
- // origin (its transform-origin, 0 0) within that layer, unaffected by rotation.
- const layer = frameZoomEl.getBoundingClientRect();
- const vp = frameViewportEl.getBoundingClientRect();
- const px = (e.clientX - layer.left) / frameZoom - frameStageEl.offsetLeft;
- const py = (e.clientY - layer.top) / frameZoom - frameStageEl.offsetTop;
- const base = frameRotMatrix; // freeze the accumulated rotation for this gesture
- const pivotX = e.clientX;
- const pivotY = e.clientY;
- rotatePivot = { x: e.clientX - vp.left, y: e.clientY - vp.top };
- rotating = true;
- let startAngle = null; // the reference spoke, fixed once the cursor leaves the deadzone
- const move = (ev) => {
- if (startAngle === null) {
- if (Math.hypot(ev.clientX - pivotX, ev.clientY - pivotY) < ROTATE_DEADZONE) return;
- startAngle = pointerAngleDeg(pivotX, pivotY, ev.clientX, ev.clientY);
- return;
- }
- const delta = pointerAngleDeg(pivotX, pivotY, ev.clientX, ev.clientY) - startAngle;
- frameRotMatrix = rotateAbout(base, px, py, delta);
- };
- const up = () => {
- rotating = false;
- window.removeEventListener('pointermove', move);
- window.removeEventListener('pointerup', up);
- };
- window.addEventListener('pointermove', move);
- window.addEventListener('pointerup', up);
+ function onWindowKeydown(e) {
+ if (uiState.tool !== 'inspect' || !work.source || pickerOpen) return;
+ const t = e.target;
+ if (['INPUT', 'TEXTAREA', 'SELECT'].includes(t.tagName) || t.isContentEditable) return;
+ if (e.ctrlKey || e.metaKey) return;
+ if (activeFrame && cropEditing) {
+ if (e.key === 'Enter') { e.preventDefault(); commitCrop(); }
+ else if (e.key === 'Escape') { e.preventDefault(); cancelCrop(); }
+ return;
+ }
+ // On the video: ←/→ step one frame (Shift = 1 s), with mpv's , and . as aliases.
+ if (selected !== 'video') return;
+ if (e.key === 'ArrowLeft') { e.preventDefault(); stepVideo(e.shiftKey ? -1 : -frameDur); }
+ else if (e.key === 'ArrowRight') { e.preventDefault(); stepVideo(e.shiftKey ? 1 : frameDur); }
+ else if (e.key === ',') { e.preventDefault(); stepVideo(-frameDur); }
+ else if (e.key === '.') { e.preventDefault(); stepVideo(frameDur); }
+ else if (e.key === ' ' && videoEl) {
+ e.preventDefault();
+ if (videoEl.paused) videoEl.play().catch(() => {});
+ else videoEl.pause();
+ }
}
- // Kill the browser's middle-click auto-scroll so a turn doesn't also pan-scroll.
- function frameMouseDown(e) {
- if (e.button === 1) e.preventDefault();
+ // -- save to case: the one step that files media ------------------------------------
+ function dupeNote(results) {
+ const dupes = results.filter((r) => r?.duplicate).length;
+ if (!dupes) return '';
+ return dupes === 1 ? '. It matched media already in the case, which was renamed' : `. ${dupes} matched media already in the case and were renamed`;
}
- // Left-drag on the image pans the view.
- function framePanStart(e) {
- const sx = e.clientX;
- const sy = e.clientY;
- const ox = framePan.x;
- const oy = framePan.y;
- const move = (ev) => {
- framePan = { x: ox + ev.clientX - sx, y: oy + ev.clientY - sy };
- };
- const up = () => {
- window.removeEventListener('pointermove', move);
- window.removeEventListener('pointerup', up);
- };
- window.addEventListener('pointermove', move);
- window.addEventListener('pointerup', up);
+ async function afterFiling() {
+ await reloadCase();
+ await refresh();
}
- function frameViewportDown(e) {
- if (e.button === 1) {
- e.preventDefault();
- if (!cropEditing) frameRotateStart(e); // keep the crop box un-rotated
- return;
- }
- if (e.button !== 0 || shared.cropMode || cropEditing) return; // crop box owns drags
- e.preventDefault(); // stop the browser's native image-drag ghost
- framePanStart(e);
+ async function saveFrames(frames, { folder, note, names }) {
+ const cid = work.caseId;
+ const items = frames.map((f, i) => ({
+ path: f.path, time: f.time ?? null, ops: buildFrameOps(filters, f), label: names[i],
+ }));
+ const res = await api.post(`/api/cases/${cid}/inspect/save-frames`, { items, folder, notes: note });
+ const saved = res?.saved ?? [];
+ frames.forEach((f, i) => {
+ const path = saved[i]?.item?.path;
+ if (path) f.filed = { path, signature: frameSignature(filters, f) };
+ });
+ await afterFiling();
+ return saved;
}
- // -- save (the only gate that files entities) ----------------------------
- async function saveSelected() {
- const cid = caseState.current.id;
- const folder = saveUi.folder?.trim() || null;
- const chosen = savables.filter((it) => saveUi.selected[it.key]);
- if (!chosen.length) return;
- const note = saveUi.note?.trim() || null;
- const nameOf = (item) => saveNameOf(item, saveName(item));
- // A save can land on media the case already holds (re-saving an unchanged
- // collage is the common one). The name still applies, but the toast has to
- // say no new file appeared, or the count looks wrong in the library.
- let dupes = 0;
- saving = true;
+ async function saveFrame(frame, { name, folder, note }) {
+ saving = frame.id;
+ saveFolder = folder ?? '';
try {
- const frameItems = chosen
- .filter((it) => it.kind === 'frame')
- .map((it) => ({
- path: it.frame.path,
- time: it.frame.time ?? null,
- ops: buildFrameOps(filters, it.frame),
- label: nameOf(it),
- }));
- if (frameItems.length) {
- const res = await api.post(`/api/cases/${cid}/inspect/save-frames`, {
- items: frameItems, folder, notes: note,
- });
- dupes += (res?.saved ?? []).filter((r) => r.duplicate).length;
- for (const it of chosen) if (it.kind === 'frame') session.saved[it.key] = true;
- }
- const videoItem = chosen.find((it) => it.kind === 'video');
- if (videoItem) {
- const res = await api.post(`/api/cases/${cid}/inspect/enhance-video`, {
- path: session.source.path, params: session.videoAdjust, rotation: videoRotation, folder,
- label: nameOf(videoItem), notes: note,
- });
- if (res?.duplicate) dupes += 1;
- session.saved.video = true;
- }
- for (const it of chosen.filter((c) => c.kind === 'collage')) {
- // A collage is always a transparent PNG of just the pieces, trimmed to
- // their bounds — the export size follows the layout, not a manual value.
- const cl = it.collage;
- const b = collageBounds(cl.nodes);
- const nodes = cl.nodes.map((n) => ({
- src: n.save, // frozen snapshot recipe (path/time/ops)
- quad: n.quad.map(([x, y]) => [x - b.minX, y - b.minY]),
- }));
- const res = await api.post(`/api/cases/${cid}/inspect/compose`, {
- width: b.width,
- height: b.height,
- background: null,
- nodes, folder,
- label: nameOf(it), notes: note,
- });
- if (res?.duplicate) dupes += 1;
- session.saved[it.key] = true;
- }
- await reloadCase();
- await refresh();
- saveUi.selected = {};
- saveUi.names = {};
- saveUi.touched = {};
- const dupeNote = dupes
- ? `. ${dupes} matched existing media and ${dupes === 1 ? 'was' : 'were'} renamed`
- : '';
- toast(`Saved ${chosen.length} item${chosen.length === 1 ? '' : 's'} to the case${dupeNote}`, 'ok');
+ const saved = await saveFrames([frame], { folder, note, names: [name] });
+ toast(`Saved “${name}” to the case${dupeNote(saved)}`, 'ok');
} catch (e) {
toast(e.message, 'danger');
} finally {
- saving = false;
+ saving = null;
}
}
- // -- saveable sessions (persist the whole workspace, reopen later) --------
- function sessionSpec() {
- return {
- source: { path: session.source.path, kind: session.source.kind },
- videoAdjust: { ...session.videoAdjust },
- videoRotation,
- activeFrameId: session.activeFrameId,
- frames: session.frames.map((f) => ({
- id: f.id, path: f.path, time: f.time, adjust: { ...f.adjust }, crop: f.crop,
- sourceOps: f.sourceOps ?? [], rotation: normalizeRightAngleRotation(f.rotation),
- w: f.w, h: f.h,
- })),
- activeCollageId: session.activeCollageId,
- collages: session.collages.map((cl) => ({
- id: cl.id, name: cl.name, width: cl.width, height: cl.height,
- background: cl.background, transparent: cl.transparent,
- nodes: cl.nodes.map((n) => ({
- id: n.id, frameId: n.frameId, save: n.save, w: n.w, h: n.h, quad: n.quad,
- frameOps: n.frameOps ?? n.save.ops, crop: n.crop ?? null,
- })),
- })),
- };
- }
-
- // The "unsaved" badge compares what a save would write against what the last
- // one wrote. Deriving it costs one stringify per change, which beats setting a
- // dirty flag at each of the dozens of places that mutate the workspace — and
- // it can't drift out of step with them.
- let savedSignature = $state(null);
- const signature = () => JSON.stringify([sessionName.trim(), sessionSpec()]);
- const sessionDirty = $derived(session.source ? signature() !== savedSignature : false);
-
- async function openLoadDialog() {
- sessionModal.busy = true;
- sessionQuery = '';
- sessionBrowserOpen = false;
- sessionBrowsePath = '';
- sessionBrowseSelection = null;
- sessionModal.open = true;
+ async function saveAllFrames() {
+ const frames = work.frames.filter((f) => !filedIds.has(f.id) && f.url);
+ if (!frames.length) return;
+ saving = 'all';
try {
- const sessions = await api.get(`/api/cases/${caseState.current.id}/inspect/sessions`);
- try {
- const entities = await fetchAllEntities(caseState.current.id, { types: ['inspect-session'] });
- const folders = new Map(
- entities.map((entity) => [
- (entity.attrs?.spec ?? '').replace(/^inspect\//, '').replace(/\.json$/, ''),
- entity.attrs?.folder ?? '',
- ])
- );
- sessionModal.list = sessions.map((session) => ({ ...session, folder: folders.get(session.name) ?? '' }));
- } catch {
- sessionModal.list = sessions;
- }
+ const saved = await saveFrames(frames, {
+ folder: saveFolder || null, note: null, names: frames.map((f) => frameNames.get(f.id)),
+ });
+ toast(`Saved ${frames.length} frames to the case${dupeNote(saved)}`, 'ok');
} catch (e) {
toast(e.message, 'danger');
} finally {
- sessionModal.busy = false;
- }
- }
-
- // Saving writes under the name in the header. When that name is free the
- // backend just renames the bound session onto it; when another session holds
- // it, only an unbound workspace may take it, and only after this asks.
- let overwritePrompt = $state(null);
- let savingSession = $state(false);
-
- async function saveSession() {
- const title = sessionName.trim();
- if (!title || savingSession || !session.source) return;
- const slug = slugify(title, 'session');
- if (!openedSession && takenSlugs().has(slug)) {
- overwritePrompt = { slug };
- return;
+ saving = null;
}
- return performSessionSave();
}
- async function performSessionSave() {
- const title = sessionName.trim();
- savingSession = true;
+ async function saveVideo({ name, folder, note }) {
+ saving = 'video';
+ saveFolder = folder ?? '';
+ const signatureNow = videoSignature(videoFilters, work.videoAdjust, videoRotation);
try {
- const res = await api.post(`/api/cases/${caseState.current.id}/inspect/sessions`, {
- rename_from: openedSession?.name ?? null, title, spec: sessionSpec(),
+ const res = await api.post(`/api/cases/${work.caseId}/inspect/enhance-video`, {
+ path: work.source.path, params: work.videoAdjust, rotation: videoRotation, folder,
+ label: name, notes: note,
});
- sessionName = res.title;
- openedSession = { name: res.name, title: res.title };
- savedSignature = signature();
- await reloadCase();
- toast('Session saved. Reopen it from the sidebar', 'ok');
+ if (res?.item?.path) work.videoFiled = { path: res.item.path, signature: signatureNow };
+ await afterFiling();
+ toast(`Saved “${name}” to the case${dupeNote([res])}`, 'ok');
} catch (e) {
toast(e.message, 'danger');
} finally {
- savingSession = false;
- overwritePrompt = null;
+ saving = null;
}
}
- async function openSession(name) {
- sessionLoading = true;
- sessionModal.open = false;
- try {
- await ensureOps();
- if (!mediaList.length) await refresh();
- let spec;
+ // -- clearing -------------------------------------------------------------------------
+ async function clearWork() {
+ clearConfirm = false;
+ autosave.cancel();
+ const source = work.source;
+ const caseId = work.caseId;
+ if (work.name) {
try {
- spec = await api.get(`/api/cases/${caseState.current.id}/inspect/sessions/${name}`);
+ const result = await api.del(`/api/cases/${caseId}/inspect/work?path=${encodeURIComponent(source.path)}`);
+ deletedToast(caseId, result, work.name);
} catch (e) {
toast(e.message, 'danger');
return;
}
- resetSession();
- const src = mediaList.find((m) => m.path === spec.source.path) ?? spec.source;
- session.source = src;
- try {
- probeInfo = await api.get(
- `/api/cases/${caseState.current.id}/inspect/probe?path=${encodeURIComponent(src.path)}`
- );
- } catch {
- probeInfo = { kind: src.kind };
- }
- session.videoAdjust = spec.videoAdjust ?? adjustDefaults(videoFilters);
- session.videoRotation = normalizeRightAngleRotation(spec.videoRotation);
- for (const f of spec.frames ?? []) {
- try {
- const sourceOps = f.sourceOps ?? [];
- const rotation = normalizeRightAngleRotation(f.rotation);
- const url = await renderUrl(f.path, f.time, [...sourceOps, ...rotationOps(rotation)]);
- session.frames.push({ ...f, sourceOps, rotation, url });
- } catch {
- /* skip a frame whose source is gone */
- }
- }
- session.activeFrameId = spec.activeFrameId ?? session.frames[0]?.id ?? null;
- // Back-compat: older sessions stored a single `collage`; newer ones an array.
- const specCollages = spec.collages ?? (spec.collage ? [spec.collage] : []);
- const collages = [];
- for (const sc of specCollages) {
- const nodes = [];
- for (const n of sc.nodes ?? []) {
- try {
- // frameOps = the snapshot without the collage crop; baseUrl feeds the
- // crop editor, url is the (possibly cropped) piece shown on the canvas.
- const frameOps = n.frameOps ?? n.save.ops ?? [];
- const crop = n.crop ?? null;
- const baseUrl = await renderUrl(n.save.path, n.save.time, frameOps);
- const url = crop ? await renderUrl(n.save.path, n.save.time, n.save.ops) : baseUrl;
- nodes.push({ ...n, frameOps, crop, baseUrl, url });
- } catch {
- /* skip a node whose source is gone */
- }
- }
- collages.push({
- id: sc.id ?? uid('cl'),
- name: sc.name ?? `Collage ${collages.length + 1}`,
- width: sc.width ?? COLLAGE_DEFAULT_SIZE.width,
- height: sc.height ?? COLLAGE_DEFAULT_SIZE.height,
- background: sc.background ?? '#12141c',
- transparent: sc.transparent ?? false,
- nodes,
- });
- }
- if (!collages.length) collages.push(newCollage('Collage 1'));
- session.collages = collages;
- session.activeCollageId =
- collages.find((c) => c.id === spec.activeCollageId)?.id ?? collages[0].id;
- openedSession = { name, title: spec.title || name };
- sessionName = openedSession.title;
- savedSignature = signature();
- activeTab = src.kind === 'video' ? 'selection' : 'frame';
- anchorCollageHistory();
- } finally {
- sessionLoading = false;
- }
- }
-
- function discardSession() {
- resetSession();
- discardConfirm = false;
- if (openSourceAfterDiscard) {
- openSourceAfterDiscard = false;
- openSourceDialog();
- }
- }
-
- function cancelDiscard() {
- discardConfirm = false;
- openSourceAfterDiscard = false;
- }
-
- async function deleteSession(name) {
- try {
- const caseId = caseState.current.id;
- const session = sessionModal.list.find((item) => item.name === name);
- const result = await api.del(`/api/cases/${caseId}/inspect/sessions/${name}`);
- sessionModal.list = sessionModal.list.filter((s) => s.name !== name);
- if (openedSession?.name === name) openedSession = null;
- await reloadCase();
- deletedToast(caseId, result, session?.title ?? name);
- } catch (e) {
- toast(e.message, 'danger');
}
+ await open(source);
+ // Collage offers this work's frames, and the sidebar lists the work itself.
+ workState.rev += 1;
+ reloadCase();
}
</script>
-<svelte:window onkeydown={onWindowKeydown} />
+<svelte:window onkeydown={onWindowKeydown} {onpagehide} />
<div class="tool">
- <div class="tool-header">
- <h2>Inspect</h2>
- {#if session.source}
- <input class="input title-input" bind:value={sessionName} maxlength="200" aria-label="Session name" />
- {#if sessionDirty}<span class="badge">unsaved</span>{/if}
- {/if}
- <div class="spacer"></div>
- {#if caseState.current}
- <button class="btn btn-sm" onclick={openLoadDialog} title="Reopen a saved session">
- <Icon name="folderOpen" size={14} /> Open session
- </button>
- <button class="btn btn-sm" onclick={startNewSession} title="Start from case media">
- <Icon name="plus" size={14} /> New session
- </button>
- {#if session.source}
- <button class="btn btn-sm" onclick={() => (discardConfirm = true)} title="Clear this workspace">
- <Icon name="reset" size={14} /> Discard
+ {#if work.source}
+ <div class="tool-header">
+ <span class="file">
+ <Icon name={isVideo ? 'video' : 'image'} size={14} />
+ <input
+ class="input file-name"
+ dir="auto"
+ bind:value={nameField}
+ onblur={commitName}
+ onkeydown={nameKey}
+ disabled={renaming}
+ maxlength="200"
+ aria-label="File name"
+ title="Rename the file"
+ />
+ </span>
+ {#if status === 'saving'}
+ <span class="status">Saving…</span>
+ {:else if status === 'saved'}
+ <span class="status"><Icon name="check" size={12} /> Saved</span>
+ {:else if status === 'error'}
+ <span class="status error" title={autosave.state.error}><Icon name="alert" size={12} /> Not saved</span>
+ <button class="btn btn-ghost btn-xs" onclick={() => autosave.flush()}>Retry</button>
+ {/if}
+ <div class="spacer"></div>
+ {#if work.name || !pristine}
+ <button class="btn btn-ghost btn-sm" onclick={() => (clearConfirm = true)} title="Send this file's frames and edits to the Trash">
+ <Icon name="reset" size={14} /> Clear work
</button>
{/if}
- <button
- class="btn btn-ok btn-sm"
- disabled={!session.source || savingSession || !sessionName.trim()}
- onclick={saveSession}
- title="Save this workspace under its name"
- >
- <Icon name="save" size={14} /> {savingSession ? 'Saving…' : 'Save session'}
+ <button class="btn btn-sm" onclick={() => (pickerOpen = true)} title="Open another image or video">
+ <Icon name="folderOpen" size={14} /> Change file
</button>
- {/if}
- </div>
+ <button class="btn btn-ghost btn-sm" onclick={leave} title="Back to the file list" aria-label="Close file">
+ <Icon name="x" size={15} />
+ </button>
+ </div>
+ {/if}
{#if !caseState.current}
<div class="empty">
@@ -1309,370 +730,133 @@
<p>Open a case and add media to start inspecting.</p>
<button class="btn" onclick={() => (uiState.tool = 'media')}>Go to Media Library</button>
</div>
- {:else if sessionLoading}
- <div class="empty">
- <span class="spinner"></span>
- <p>Loading session…</p>
- </div>
- {:else if !session.source}
- <div class="empty">
- <Icon name="inspect" size={40} />
- <h3>Start a session</h3>
- <p>Start a session to choose media.</p>
- <button class="btn" onclick={startNewSession}>
- <Icon name="plus" size={15} /> New session
- </button>
- </div>
- {:else}
- {#if sourceGone}
- <!-- The subject was deleted out from under this workspace. Everything
- already captured stays on screen and can still be saved; only what
- needs to re-read the original is out of reach. -->
- <div class="gone-banner">
- <Icon name="alert" size={14} />
- <span>
- <strong>{session.source.filename ?? session.source.path}</strong> was deleted from the
- case. What you already captured is still here, but new frames and re-renders can't be
- made from it.
- </span>
+ {:else if !work.source}
+ {#if inspectable.length === 0}
+ <div class="empty">
+ <Icon name="inspect" size={40} />
+ <p>Add an image or a video to the case to inspect it.</p>
+ <button class="btn" onclick={() => (uiState.tool = 'media')}>Go to Media Library</button>
+ </div>
+ {:else}
+ <div class="start">
+ <div class="start-col">
+ <div class="start-head">
+ <h3>Open a file</h3>
+ <p>Frames and edits are kept with the file, so opening it again picks up where you left off.</p>
+ </div>
+ <SourcePicker media={inspectable} {works} caseId={caseState.current.id} onpick={open} />
+ </div>
</div>
{/if}
- <div class="tabbar">
- {#each tabs as t (t)}
- <button class="tab" class:active={activeTab === t} onclick={() => (activeTab = t)}>
- <Icon name={TAB_META[t].icon} size={15} /> {TAB_META[t].label}
- </button>
- {/each}
- {#if activeTab === 'collage'}
- <div class="tab-spacer"></div>
- <button class="btn btn-ghost btn-sm" title="Undo (Ctrl+Z)" disabled={!collageCanUndo} onclick={undoCollage}>
- <Icon name="undo" size={15} />
- </button>
- <button class="btn btn-ghost btn-sm" title="Redo (Ctrl+Shift+Z / Ctrl+Y)" disabled={!collageCanRedo} onclick={redoCollage}>
- <Icon name="redo" size={15} />
- </button>
- {/if}
- </div>
-
+ {:else}
<div class="workspace">
- <div class="viewer" class:pad={activeTab !== 'collage' && activeTab !== 'save'}>
- {#if activeTab === 'selection'}
- <VideoPlayer
- bind:video={videoEl}
- src={fileUrl(caseState.current?.id, session.source.path)}
- filter={videoPreview.filter}
- transform={videoPreviewTransform}
- quarterTurn={videoQuarterTurn}
- duration={probeInfo?.duration ?? 0}
- currentTime={shared.currentTime}
- ontimeupdate={(time) => (shared.currentTime = time)}
- />
- {:else if activeTab === 'frame'}
- {#if activeFrame}
- <!-- svelte-ignore a11y_no_static_element_interactions -->
- <div
- class="frame-viewport"
- class:cropping={shared.cropMode}
- class:pannable={!shared.cropMode && !cropEditing}
- class:rotating
- bind:this={frameViewportEl}
- onwheel={frameWheel}
- onmousedown={frameMouseDown}
- onpointerdown={frameViewportDown}
- onauxclick={(e) => e.preventDefault()}
- ondblclick={beginCrop}
- >
- <div
- class="zoom-layer"
- bind:this={frameZoomEl}
- style:transform={`translate(${framePan.x}px, ${framePan.y}px) scale(${frameZoom})`}
- >
- <!-- View-only rotation pivots around the grabbed point; never saved. -->
- <div
- class="img-stage"
- bind:this={frameStageEl}
- style:transform={matrixCss(frameRotMatrix)}
- style:transform-origin="0 0"
- >
- {#if activeFrame.crop && !cropEditing}
- <!-- committed crop: show the cropped region -->
- <div class="crop-view" style:--ar={cropAspect(activeFrame.crop, activeFrame.w, activeFrame.h) ?? 1}>
- <img
- src={activeFrame.url}
- alt="frame"
- draggable="false"
- style={styleText(cropImgStyle(activeFrame.crop))}
- style:filter={framePreview.filter}
- style:transform={framePreview.transform}
- />
- </div>
- {:else}
- <img src={activeFrame.url} alt="frame" draggable="false" style:filter={framePreview.filter} style:transform={framePreview.transform} />
- <CropBox
- bind:crop={activeFrame.crop}
- bind:draw={shared.cropMode}
- aspect={frameAspect}
- natW={activeFrame.w}
- natH={activeFrame.h}
- />
- {/if}
- </div>
- </div>
- {#if rotating}
- <!-- "target" pivot marker: sits at the grabbed point, fixed on
- screen while the image turns around it -->
- <div class="rotate-pivot" style:left={`${rotatePivot.x}px`} style:top={`${rotatePivot.y}px`} aria-hidden="true">
- <svg width="40" height="40" viewBox="0 0 40 40">
- <circle class="ring" cx="20" cy="20" r="15" />
- <circle class="dot" cx="20" cy="20" r="1.5" />
- </svg>
- </div>
- {/if}
- <div class="view-ctl">
- {#if cropEditing}
- <span class="zoom-hint">drag to crop · Enter applies · Esc cancels</span>
- <button class="btn btn-sm" onclick={commitCrop} title="Apply the crop (Enter)">
- <Icon name="check" size={14} /> Apply
- </button>
- {:else if frameViewDirty}
- {#if frameZoom !== 1}<span class="zoom-val">{Math.round(frameZoom * 100)}%</span>{/if}
- {#if frameAngle !== 0}<span class="zoom-val">{frameAngle}°</span>{/if}
- <button class="btn btn-ghost btn-sm" onclick={resetFrameView} title="Reset zoom / pan / rotation">
- <Icon name="eye" size={14} /> Fit
- </button>
- {:else}
- <span class="zoom-hint">scroll zoom · drag pan · middle-drag turns · double-click crop</span>
- {/if}
- </div>
- </div>
- {:else}
+ <div class="stage">
+ <div class="viewer" class:pad={selected !== 'video'}>
+ {#if opening}
+ <span class="spinner" aria-label="Opening"></span>
+ {:else if selected === 'video'}
+ <VideoPlayer
+ bind:video={videoEl}
+ src={fileUrl(work.caseId, work.source.path)}
+ filter={videoPreview.filter}
+ transform={videoTransform}
+ quarterTurn={Math.abs(videoRotation) === 90}
+ duration={probeInfo?.duration ?? 0}
+ currentTime={shared.currentTime}
+ ontimeupdate={(time) => (shared.currentTime = time)}
+ />
+ {:else if activeFrame?.url}
+ <FrameViewer
+ frame={activeFrame}
+ preview={framePreview}
+ aspect={frameAspect}
+ {cropEditing}
+ bind:cropMode={shared.cropMode}
+ onbegincrop={beginCrop}
+ oncommitcrop={commitCrop}
+ />
+ {:else if activeFrame?.missing}
<div class="hint-mid">
- <Icon name="image" size={34} />
- <p>No frame selected. Capture frames in the Selection tab.</p>
+ <Icon name="alert" size={30} />
+ <p>This frame could not be rendered from its file.</p>
</div>
+ {:else}
+ <span class="spinner" aria-label="Rendering"></span>
{/if}
- {:else if activeTab === 'collage'}
- <CollageCanvas collage={activeCollage} bind:selectedIds={collageSelectedIds} {requestCrop} />
- {:else if activeTab === 'save'}
- <SaveGallery {savables} {saveUi} {saveName} {setSaveName} />
+ </div>
+ {#if !opening && (isVideo || work.frames.length > 1)}
+ <FrameStrip
+ source={work.source}
+ sourceThumb={work.source.thumbnail ? fileUrl(work.caseId, work.source.thumbnail) : null}
+ frames={work.frames}
+ {selected}
+ {filters}
+ {filedIds}
+ removable={isVideo || work.frames.length > 1}
+ savingAll={saving === 'all'}
+ onselect={select}
+ onremove={removeFrame}
+ onsaveall={saveAllFrames}
+ />
{/if}
</div>
<aside class="panel">
- {#if activeTab === 'selection'}
- <SelectionMenu {probeInfo} {shared} {videoFilters} {session} {capture} />
- {:else if activeTab === 'frame'}
- <FrameMenu
- {session} {filters} {analyses} {activeFrame} {shared} {removeFrame}
- bind:cropAspect={frameAspect} bind:cropEditing {beginCrop} {commitCrop}
- setRotation={setFrameRotation} rotationBusy={frameOrientationBusy}
- setActive={(id) => (session.activeFrameId = id)}
- reverse={reverseFrame}
- />
- {:else if activeTab === 'collage'}
- <CollageMenu
- {session} {filters} bind:selectedIds={collageSelectedIds}
- {addToCollage} {requestCrop} {renderPiece}
- onRename={(cl) => (saveUi.touched[`collage:${cl.id}`] = true)}
+ {#if opening}
+ <p class="hint">Opening…</p>
+ {:else if selected === 'video'}
+ <VideoMenu
+ {probeInfo} {shared} {videoFilters} {work} {capture}
+ {videoEdited}
+ videoSave={{
+ defaultName: `${stemFor(work.source.path)} (enhanced)`,
+ filedPath: videoFiled ? work.videoFiled.path : null,
+ busy: saving === 'video',
+ onsave: saveVideo,
+ }}
+ bind:folder={saveFolder}
/>
- {:else if activeTab === 'save'}
- <SaveMenu {savables} {saveUi} {saving} save={saveSelected} />
+ {:else if activeFrame}
+ {#key activeFrame.id}
+ <FrameMenu
+ frame={activeFrame} {filters} {analyses} {shared}
+ bind:cropAspect={frameAspect} bind:cropEditing {beginCrop} {commitCrop}
+ setRotation={setFrameRotation} {rotationBusy}
+ reverse={reverseFrame}
+ onduplicate={duplicateFrame}
+ frameSave={{
+ defaultName: frameNames.get(activeFrame.id),
+ filedPath: filedIds.has(activeFrame.id) ? activeFrame.filed.path : null,
+ busy: saving === activeFrame.id || saving === 'all',
+ blocked: activeFrame.url ? '' : 'The frame is still rendering.',
+ onsave: (opts) => saveFrame(activeFrame, opts),
+ }}
+ bind:folder={saveFolder}
+ />
+ {/key}
{/if}
</aside>
</div>
{/if}
- {#if cropPieceNode}
- <PieceCropModal
- node={cropPieceNode}
- onapply={(crop) => { applyNodeCrop(cropPieceNode, crop); cropPieceNode = null; }}
- onclose={() => (cropPieceNode = null)}
- />
+ {#if pickerOpen && caseState.current}
+ <Modal title="Open a file" width="720px" onclose={() => (pickerOpen = false)}>
+ <SourcePicker media={inspectable} {works} caseId={caseState.current.id} current={work.source?.path} onpick={open} />
+ </Modal>
{/if}
- {#if discardConfirm}
+ {#if clearConfirm}
<ConfirmDialog
- title="Discard this session?"
- message="This clears the current workspace."
- detail={openedSession ? 'This does not delete the saved session, only the unsaved changes in this workspace.' : 'Anything not saved yet will be lost.'}
- confirmLabel="Discard"
+ title="Clear the work on this file?"
+ message="Its frames and edits go to the Trash."
+ detail="Media already saved to the case stays where it is."
+ confirmLabel="Clear work"
tone="danger"
icon="reset"
- onconfirm={discardSession}
- oncancel={cancelDiscard}
- />
- {/if}
-
- {#if overwritePrompt}
- <ConfirmDialog
- title="Overwrite this session?"
- message={`“${savedTitle(sessionEntities, 'session', overwritePrompt.slug)}” is already saved in this case.`}
- detail="Saving replaces its workspace. Rename this session to keep both."
- confirmLabel="Overwrite"
- tone="danger"
- icon="check"
- onconfirm={performSessionSave}
- oncancel={() => (overwritePrompt = null)}
+ onconfirm={clearWork}
+ oncancel={() => (clearConfirm = false)}
/>
{/if}
-
- {#if sourceModalOpen}
- <!-- svelte-ignore a11y_click_events_have_key_events -->
- <!-- svelte-ignore a11y_no_static_element_interactions -->
- <div class="modal-back" onclick={() => (sourceModalOpen = false)} role="presentation">
- <!-- svelte-ignore a11y_click_events_have_key_events -->
- <!-- svelte-ignore a11y_no_noninteractive_element_interactions -->
- <div class="modal source-modal" onclick={(e) => e.stopPropagation()} role="dialog" aria-modal="true" aria-labelledby="new-session-title" tabindex="-1">
- <div class="modal-head">
- <h3 id="new-session-title">New session</h3>
- <button class="btn btn-ghost btn-xs" onclick={() => (sourceModalOpen = false)} aria-label="Close" title="Close">
- <Icon name="x" size={15} />
- </button>
- </div>
-
- <div class="picker-search">
- <SearchInput bind:value={sourceQuery} placeholder="Search names…" width="100%" />
- <button class="btn btn-ghost btn-sm browse-btn" title="Browse folders" onclick={toggleSourceBrowser}>…</button>
- </div>
-
- {#if inspectableMedia.length === 0}
- <p class="modal-hint">Add an image or video to start an Inspect session.</p>
- <div class="modal-actions">
- <button class="btn btn-sm" onclick={() => (sourceModalOpen = false)}>Cancel</button>
- <button class="btn btn-primary btn-sm" onclick={() => { sourceModalOpen = false; uiState.tool = 'media'; }}>
- Go to Media Library
- </button>
- </div>
- {:else}
- <div class="source-filters" aria-label="Media type">
- {#each SOURCE_FILTERS as filter (filter.id)}
- <button
- class="btn btn-ghost btn-sm"
- class:active={sourceFilter === filter.id}
- aria-pressed={sourceFilter === filter.id}
- onclick={() => setSourceFilter(filter.id)}
- >
- {filter.label}
- </button>
- {/each}
- </div>
-
- {#if sourceBrowserOpen}
- <FolderBrowser
- entries={sourceBrowserEntries}
- path={sourceBrowsePath}
- rootLabel="Case media"
- selectedId={sourceBrowseSelection}
- matches={(m) => matchesSourceName(m, sourceQuery)}
- emptyText="This folder has no matching media."
- icon={(m) => (m.kind === 'video' ? 'video' : 'image')}
- label={(m) => m.title || m.filename}
- onnavigate={openSourceFolder}
- onselect={(m) => selectSourceBrowser(m)}
- onconfirm={(m) => selectSourceBrowser(m, true)}
- />
- <div class="modal-actions">
- <button class="btn btn-primary btn-sm" disabled={!sourceBrowseSelection} onclick={confirmSourceBrowser}>Open selected</button>
- </div>
- {:else}
- {#if pickableMedia.length === 0}
- <p class="modal-hint">No media matches this filter.</p>
- {:else}
- <div class="source-list">
- {#each pickableMedia as m (m.path)}
- <button class="source-open" onclick={() => selectNewSource(m)}>
- <div class="source-thumb">
- {#if m.thumbnail}
- <img src={fileUrl(caseState.current.id, m.thumbnail)} alt="" loading="lazy" />
- {:else}
- <Icon name={m.kind === 'video' ? 'video' : 'image'} size={22} />
- {/if}
- </div>
- <span class="source-copy">
- <span class="source-title">{m.title || m.filename}</span>
- <span class="source-meta">
- {sourceCategory(m)}{m.folder ? ` · ${m.folder}` : ''}
- </span>
- </span>
- </button>
- {/each}
- </div>
- {/if}
- {/if}
- {/if}
- </div>
- </div>
- {/if}
-
- {#if sessionModal.open}
- <!-- svelte-ignore a11y_click_events_have_key_events -->
- <!-- svelte-ignore a11y_no_static_element_interactions -->
- <div class="modal-back" onclick={() => (sessionModal.open = false)} role="presentation">
- <!-- svelte-ignore a11y_click_events_have_key_events -->
- <!-- svelte-ignore a11y_no_noninteractive_element_interactions -->
- <div class="modal" onclick={(e) => e.stopPropagation()} role="dialog" aria-modal="true" tabindex="-1">
- <div class="modal-head">
- <h3>Open session</h3>
- <button class="btn btn-ghost btn-xs" onclick={() => (sessionModal.open = false)} aria-label="Close" title="Close">
- <Icon name="x" size={15} />
- </button>
- </div>
-
- {#if sessionBrowserOpen}
- <div class="picker-search">
- <SearchInput bind:value={sessionQuery} placeholder="Search sessions…" width="100%" />
- <button class="btn btn-ghost btn-sm browse-btn" title="Show session list" onclick={toggleSessionBrowser}>…</button>
- </div>
- <FolderBrowser
- entries={sessionBrowserEntries}
- path={sessionBrowsePath}
- rootLabel="Sessions"
- selectedId={sessionBrowseSelection}
- matches={(s) => matchesSessionQuery(s, sessionQuery)}
- emptyText="This folder has no matching sessions."
- icon={() => 'inspect'}
- label={(s) => s.title}
- onnavigate={openSessionFolder}
- onselect={(s) => selectSessionBrowser(s)}
- onconfirm={(s) => selectSessionBrowser(s, true)}
- />
- <div class="modal-actions">
- <button class="btn btn-primary btn-sm" disabled={!sessionBrowseSelection} onclick={confirmSessionBrowser}>Open selected</button>
- </div>
- {:else}
- {#if sessionModal.busy}
- <p class="modal-hint">Loading…</p>
- {:else}
- {#if sessionModal.list.length > 6}
- <div class="picker-search">
- <SearchInput bind:value={sessionQuery} placeholder="Search sessions…" width="100%" />
- <button class="btn btn-ghost btn-sm browse-btn" title="Browse folders" onclick={toggleSessionBrowser}>…</button>
- </div>
- {/if}
- {#if sessionModal.list.length === 0}
- <p class="modal-hint">No saved sessions yet.</p>
- {:else if visibleSessions.length === 0}
- <p class="modal-hint">No sessions match this search.</p>
- {:else}
- <div class="session-list">
- {#each visibleSessions as s (s.name)}
- <div class="session-row">
- <button class="session-open" disabled={sessionLoading} onclick={() => openSession(s.name)}>
- <span class="session-title">{s.title}</span>
- <span class="session-meta">{s.frames} frame{s.frames === 1 ? '' : 's'} · {s.collage} collage piece{s.collage === 1 ? '' : 's'}</span>
- </button>
- <button class="btn btn-ghost btn-xs" disabled={sessionLoading} onclick={() => deleteSession(s.name)} aria-label="Delete session" title="Delete session">
- <Icon name="trash" size={14} />
- </button>
- </div>
- {/each}
- </div>
- {/if}
- {/if}
- {/if}
- </div>
- </div>
- {/if}
</div>
<style>
@@ -1683,15 +867,34 @@
}
.tool-header {
display: flex;
- align-items: baseline;
+ align-items: center;
gap: 10px;
padding: 14px 16px 12px;
border-bottom: 1px solid var(--border);
flex-shrink: 0;
}
- h2 {
- font-size: var(--fs-lg);
- font-weight: 700;
+ .file {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ flex: 0 1 420px;
+ min-width: 0;
+ color: var(--text-2);
+ }
+ .file-name {
+ flex: 1;
+ min-width: 0;
+ font-weight: 600;
+ }
+ .status {
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ color: var(--text-3);
+ font-size: var(--fs-xs);
+ }
+ .status.error {
+ color: var(--danger);
}
.spacer {
flex: 1;
@@ -1711,6 +914,31 @@
max-width: 260px;
font-size: var(--fs-sm);
}
+ /* The whole panel scrolls and the column sits centred in it, so the wheel works
+ over the margins and the scrollbar stays on the edge. */
+ .start {
+ flex: 1;
+ min-height: 0;
+ overflow: auto;
+ }
+ .start-col {
+ display: flex;
+ flex-direction: column;
+ gap: 14px;
+ max-width: 1240px;
+ margin: 0 auto;
+ padding: 24px 20px;
+ }
+ .start-head h3 {
+ font-size: var(--fs-md);
+ font-weight: 700;
+ margin: 0 0 4px;
+ }
+ .start-head p {
+ margin: 0;
+ color: var(--text-3);
+ font-size: var(--fs-sm);
+ }
.spinner {
width: 24px;
height: 24px;
@@ -1724,55 +952,20 @@
transform: rotate(360deg);
}
}
- .gone-banner {
- display: flex;
- align-items: flex-start;
- gap: 8px;
- padding: 8px 12px;
- font-size: var(--fs-xs);
- line-height: 1.45;
- color: color-mix(in srgb, var(--danger, #e5484d) 80%, var(--text-2));
- background: color-mix(in srgb, var(--danger, #e5484d) 10%, transparent);
- border-bottom: 1px solid color-mix(in srgb, var(--danger, #e5484d) 22%, transparent);
- }
- .gone-banner :global(svg) { flex-shrink: 0; margin-top: 2px; }
- .tabbar {
- display: flex;
- align-items: center;
- gap: 4px;
- padding: 8px 12px;
- border-bottom: 1px solid var(--border);
- flex-shrink: 0;
- }
- .tab-spacer {
+ .workspace {
flex: 1;
- }
- .tab {
display: flex;
- align-items: center;
- gap: 6px;
- padding: 7px 12px;
- border-radius: var(--r-md);
- font-size: var(--fs-sm);
- font-weight: 600;
- color: var(--text-3);
- }
- .tab:hover {
- color: var(--text-1);
- background: var(--bg-2);
- }
- .tab.active {
- color: var(--text-1);
- background: var(--bg-3);
+ min-height: 0;
}
- .workspace {
+ .stage {
flex: 1;
+ min-width: 0;
display: flex;
- min-height: 0;
+ flex-direction: column;
}
.viewer {
flex: 1;
- min-width: 0;
+ min-height: 0;
display: flex;
align-items: center;
justify-content: center;
@@ -1782,99 +975,6 @@
.viewer.pad {
padding: 18px;
}
- /* Frame tab: a zoom/pan/rotate surface with the crop overlay on top. */
- .frame-viewport {
- position: relative;
- width: 100%;
- height: 100%;
- display: flex;
- align-items: center;
- justify-content: center;
- overflow: hidden;
- touch-action: none;
- }
- .frame-viewport.pannable {
- cursor: grab;
- }
- .frame-viewport.cropping {
- cursor: crosshair;
- }
- .frame-viewport.rotating {
- cursor: grabbing;
- }
- /* Sober pivot mark (Google-Earth style): a faint translucent ring + dot. */
- .rotate-pivot {
- position: absolute;
- transform: translate(-50%, -50%);
- pointer-events: none;
- z-index: 5;
- color: #fff;
- }
- .rotate-pivot svg {
- display: block;
- overflow: visible;
- filter: drop-shadow(0 0 1.5px rgba(0, 0, 0, 0.55));
- }
- .rotate-pivot .ring {
- fill: none;
- stroke: currentColor;
- stroke-width: 1;
- opacity: 0.5;
- }
- .rotate-pivot .dot {
- fill: currentColor;
- opacity: 0.8;
- }
- .zoom-layer {
- position: relative;
- transform-origin: center center;
- display: inline-block;
- line-height: 0;
- }
- .img-stage {
- position: relative;
- display: inline-block;
- line-height: 0;
- }
- .img-stage > img {
- max-width: 100%;
- max-height: calc(100vh - var(--topbar-h) - 200px);
- display: block;
- }
- .crop-view {
- position: relative;
- overflow: hidden;
- aspect-ratio: var(--ar);
- height: calc(100vh - var(--topbar-h) - 220px);
- max-width: 100%;
- line-height: 0;
- }
- .crop-view img {
- display: block;
- }
- .view-ctl {
- position: absolute;
- right: 10px;
- bottom: 10px;
- display: flex;
- align-items: center;
- gap: 8px;
- padding: 3px 6px;
- border-radius: var(--r-md);
- background: rgba(22, 22, 22, 0.85);
- border: 1px solid var(--border);
- }
- .zoom-val {
- font-size: var(--fs-xs);
- font-weight: 700;
- color: var(--text-2);
- font-variant-numeric: tabular-nums;
- }
- .zoom-hint {
- font-size: 11px;
- color: var(--text-3);
- user-select: none;
- }
.panel {
width: 320px;
flex-shrink: 0;
@@ -1886,168 +986,9 @@
overflow: auto;
padding: 14px;
}
- .modal-back {
- position: fixed;
- inset: 0;
- background: rgba(10, 10, 10, 0.6);
- display: flex;
- align-items: center;
- justify-content: center;
- z-index: 50;
- }
- .modal {
- width: 420px;
- max-width: calc(100vw - 40px);
- max-height: calc(100vh - 80px);
- overflow: auto;
- background: var(--bg-1);
- border: 1px solid var(--border-strong);
- border-radius: var(--r-lg, 12px);
- box-shadow: var(--shadow-2);
- padding: 16px;
- display: flex;
- flex-direction: column;
- gap: 12px;
- }
- .source-modal {
- width: 560px;
- }
- .modal-head {
- display: flex;
- align-items: center;
- justify-content: space-between;
- }
- .modal-head h3 {
- font-size: var(--fs-md);
- font-weight: 700;
- }
- .modal-hint {
+ .hint {
color: var(--text-3);
font-size: var(--fs-sm);
margin: 0;
}
- .modal-actions {
- display: flex;
- justify-content: flex-end;
- gap: 8px;
- }
- .source-list {
- display: flex;
- flex-direction: column;
- gap: 6px;
- max-height: min(52vh, 480px);
- overflow: auto;
- }
- .source-filters {
- display: flex;
- gap: 4px;
- overflow-x: auto;
- padding-bottom: 2px;
- }
- .picker-search {
- display: flex;
- align-items: center;
- gap: 6px;
- }
- .picker-search :global(.search-box) {
- flex: 1;
- }
- .browse-btn {
- min-width: 30px;
- font-size: var(--fs-lg);
- line-height: 1;
- }
- .source-filters .active {
- color: var(--text-1);
- background: var(--bg-3);
- }
- .source-open {
- display: flex;
- align-items: center;
- gap: 10px;
- width: 100%;
- padding: 7px;
- text-align: left;
- border: 1px solid var(--border);
- border-radius: var(--r-md);
- background: var(--bg-2);
- }
- .source-open:hover {
- border-color: var(--accent);
- background: var(--bg-3);
- }
- .source-thumb {
- display: grid;
- place-items: center;
- width: 48px;
- height: 40px;
- flex-shrink: 0;
- overflow: hidden;
- border-radius: var(--r-sm);
- background: var(--bg-0);
- color: var(--text-3);
- }
- .source-thumb img {
- width: 100%;
- height: 100%;
- object-fit: cover;
- }
- .source-copy {
- display: flex;
- flex-direction: column;
- min-width: 0;
- gap: 2px;
- }
- .source-title,
- .source-meta {
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
- }
- .source-title {
- color: var(--text-1);
- font-size: var(--fs-sm);
- font-weight: 600;
- }
- .source-meta {
- color: var(--text-3);
- font-size: var(--fs-xs);
- }
- .session-list {
- display: flex;
- flex-direction: column;
- gap: 6px;
- }
- .session-row {
- display: flex;
- align-items: center;
- gap: 6px;
- }
- .session-open {
- flex: 1;
- display: flex;
- flex-direction: column;
- gap: 2px;
- text-align: left;
- padding: 8px 10px;
- border: 1px solid var(--border);
- border-radius: var(--r-md);
- background: var(--bg-2);
- }
- .session-open:hover {
- border-color: var(--accent);
- }
- .session-open:disabled {
- opacity: 0.55;
- cursor: default;
- }
- .session-title {
- font-size: var(--fs-sm);
- font-weight: 600;
- color: var(--text-1);
- }
- .session-meta {
- font-size: var(--fs-xs);
- color: var(--text-3);
- }
</style>
diff --git a/frontend/src/tools/Inspector.test.js b/frontend/src/tools/Inspector.test.js
index d5658fc..c90f84c 100644
--- a/frontend/src/tools/Inspector.test.js
+++ b/frontend/src/tools/Inspector.test.js
@@ -1,216 +1,55 @@
import { describe, expect, it } from 'vitest';
import { readFileSync } from 'node:fs';
+/**
+ * The guards in Inspect that a render test cannot easily reach: work that returns
+ * after the file it was started for has closed, a save sent while the page goes,
+ * and the one route every preview is rendered through. Behaviour is driven in
+ * `Inspector.render.test.js`.
+ */
const source = readFileSync(new URL('./Inspector.svelte', import.meta.url), 'utf8');
-describe('Inspect sessions', () => {
- it('opens saved workspaces under an explicit label', () => {
- expect(source).toContain('<Icon name="folderOpen" size={14} /> Open session');
- expect(source).toContain('title="Reopen a saved session"');
+describe('Inspect — work that outlives the file it was started for', () => {
+ it('drops a frame whose file was closed while it rendered', () => {
+ // A capture is two round trips. The frame is evidence, so one that returns
+ // after the analyst switched file must not land in the file now open.
+ expect(source).toMatch(/async function capture\(time\) \{[\s\S]*?const run = openRun;/);
+ expect(source).toMatch(/const dim = await imageSize\(url\);\s*\n\s*if \(run !== openRun\) return;/);
+ expect(source).toMatch(/function closeFile\(\) \{\s*\n\s*openRun \+= 1;/);
});
- it('uses the same non-gold colored save action as Proof', () => {
- expect(source).toContain('class="btn btn-ok btn-sm"');
- expect(source).toContain('onclick={saveSession}');
- expect(source).not.toContain('class="btn btn-primary btn-sm"\n disabled={!session.source}');
+ it('saves to the case the work was opened in, even after the case changed', () => {
+ expect(source).toContain('await api.put(`/api/cases/${work.caseId}/inspect/work`');
+ expect(source).toContain('if (work.caseId && work.caseId !== caseState.current?.id) closeFile();');
});
- it('names the session in the header, and saves under that name', () => {
- // Same affordance as the Proof Composer: the name is edited at the top of
- // the tool, and Save writes under it — there is no "name this" dialog.
- expect(source).toContain('<input class="input title-input" bind:value={sessionName}');
- expect(source).toContain('aria-label="Session name"');
- expect(source).toContain('rename_from: openedSession?.name ?? null, title, spec: sessionSpec()');
- expect(source).toContain('sessionName = res.title;');
- expect(source).toContain('openedSession = { name: res.name, title: res.title };');
- expect(source).not.toContain("sessionModal.mode = 'save'");
- expect(source).not.toContain('placeholder="Session name"');
+ it('writes before letting go of a file', () => {
+ expect(source).toMatch(/async function open\(item\) \{[\s\S]*?await autosave\.flush\(\);/);
+ expect(source).toContain("if (uiState.tool !== 'inspect') {\n autosave.flush();");
+ expect(source).toContain('$effect(() => () => autosave.flush());');
});
- it('numbers a fresh session past the ones already in the case', () => {
- expect(source).toContain("nextName('session', savedTitles(sessionEntities, 'session'))");
+ it('sends a pending save with the page as it closes', () => {
+ expect(source).toContain('<svelte:window onkeydown={onWindowKeydown} {onpagehide} />');
+ expect(source).toContain('if (autosave.pending) writeWork({ keepalive: true }).catch(() => {});');
});
- it('flags unsaved work against the last save rather than a hand-set flag', () => {
- expect(source).toContain('{#if sessionDirty}<span class="badge">unsaved</span>{/if}');
- expect(source).toContain("const signature = () => JSON.stringify([sessionName.trim(), sessionSpec()]);");
- });
-
- it('checks the current hidden spec path before claiming a saved session was deleted', () => {
- // Sessions moved from `inspect/` to `.inspect/` when the case folder hid its
- // machinery. The old literal matched no entity, so every save dropped the
- // binding and warned the session had been deleted. Ask the helper instead.
- expect(source).toContain("lookupEntity(id, specAttr('session'), specPath('session', sessionName))");
- expect(source).not.toContain('`inspect/${sessionName}.json`');
- });
-
- it('asks before an unbound workspace takes a name another session holds', () => {
- expect(source).toContain('if (!openedSession && takenSlugs().has(slug))');
- expect(source).toContain('title="Overwrite this session?"');
- });
-
- it('starts new workspaces from a searchable image/video picker', () => {
- expect(source).toContain("import SearchInput from '../components/SearchInput.svelte'");
- expect(source).toContain("m.kind === 'image' || m.kind === 'video'");
- expect(source).toContain('<Icon name="plus" size={14} /> New session');
- expect(source).toContain('<h3 id="new-session-title">New session</h3>');
- expect(source).toContain('bind:value={sourceQuery}');
- expect(source).toContain('filteredSourceMedia.filter((m) => matchesSourceName(m, sourceQuery))');
- expect(source).toContain('{#each pickableMedia as m (m.path)}');
- expect(source).toContain('placeholder="Search names…"');
- expect(source).toContain('function matchesSourceName(item, query)');
- expect(source).toContain("matchesTerms(item.title || item.filename || '', query)");
- expect(source).toContain('label={(m) => m.title || m.filename}');
- expect(source).not.toContain('class="input source-select"');
- expect(source).not.toContain('Choose a media…');
- });
-
- it('offers New session from the centered empty state', () => {
- expect(source).toContain('<h3>Start a session</h3>');
- expect(source).toContain(` <p>Start a session to choose media.</p>
- <button class="btn" onclick={startNewSession}>
- <Icon name="plus" size={15} /> New session
- </button>`);
- });
-
- it('separates images, videos, captures, frames, and collages in the new-session picker', () => {
- expect(source).toContain("{ id: 'all', label: 'All' }");
- expect(source).toContain("{ id: 'capture', label: 'Captures' }");
- expect(source).toContain("{ id: 'frame', label: 'Frames' }");
- expect(source).toContain("{ id: 'collage', label: 'Collages' }");
- expect(source).toContain("source.type === 'satellite' || source.type === 'screenshot'");
- expect(source).toContain("source.op === 'frame' || source.op === 'adjust'");
- expect(source).toContain("source.op === 'collage'");
- });
-
- it('adds session search only once the saved-session list has more than six entries', () => {
- expect(source).toContain('{#if sessionModal.list.length > 6}');
- expect(source).toContain('bind:value={sessionQuery}');
- expect(source).toContain('{#each visibleSessions as s (s.name)}');
- });
-
- it('offers a read-only folder browser with single selection and double-click confirmation', () => {
- expect(source).toContain('title="Browse folders"');
- expect(source).toContain('onconfirm={(m) => selectSourceBrowser(m, true)}');
- expect(source).toContain('onconfirm={(s) => selectSessionBrowser(s, true)}');
- expect(source).toContain('disabled={!sourceBrowseSelection} onclick={confirmSourceBrowser}');
- expect(source).toContain('disabled={!sessionBrowseSelection} onclick={confirmSessionBrowser}');
- expect(source).toContain("fetchAllEntities(caseState.current.id, { types: ['inspect-session'] })");
- expect(source).toContain('function toggleSourceBrowser()');
- expect(source).toContain('function toggleSessionBrowser()');
- expect(source).not.toContain('>Back</button>');
- });
-
- it('shares one folder-browser helper with the other pickers', () => {
- expect(source).toContain("import FolderBrowser from '../components/FolderBrowser.svelte'");
- expect(source).not.toContain('function browserView(');
- expect(source).not.toContain('class="browser-row"');
- expect(source).toContain('white-space: nowrap;');
- });
-
- it('requires an active workspace to be discarded before starting another', () => {
- expect(source).toContain('openSourceAfterDiscard = true;');
- expect(source).toContain('if (openSourceAfterDiscard) {');
- expect(source).toContain('openSourceDialog();');
- });
-
- it('keeps the Collage tab for video sessions but hides it for a still image', () => {
- expect(source).toContain(
- "session.source?.kind === 'video' ? ['selection', 'frame', 'collage', 'save'] : ['frame', 'save']"
- );
- expect(source).not.toContain(
- "session.source?.kind === 'video' ? ['selection', 'frame', 'collage', 'save'] : ['frame', 'collage', 'save']"
- );
- });
-
- it('names each savable after its source instead of Image 1', () => {
- expect(source).toContain('defaultName: `${stem} (enhanced)`');
- expect(source).toContain('defaultName: frameNames[i]');
- expect(source).toContain('const frameNames = frameSaveNames(');
- expect(source).not.toContain('label: `Image ${imgN}`');
- expect(source).not.toContain("label: 'Video 1'");
- });
-
- it('names a frame after its media title, which only its path can reach', () => {
- expect(source).toContain('const titleByPath = $derived(new Map(mediaList.map((m) => [m.path, m.title])))');
- expect(source).toContain('stem: stemFor(fr.path)');
- // the old shape read the file on disk and could never see a title
- expect(source).not.toContain('sourceStem({ path: fr.path })');
- });
-
- it('keeps typed names outside the derived list so a slider move cannot wipe them', () => {
- expect(source).toContain(
- "const saveUi = $state({ selected: {}, folder: '', names: {}, touched: {}, baseName: '', note: '' });"
- );
- });
-
- it('seeds every field with real text and lets the base name refill the untouched ones', () => {
- expect(source).toContain(` const auto = autoSaveNames(savables, saveUi.baseName);
- savables.forEach((it, i) => {
- if (saveUi.touched[it.key]) return;
- if (it.kind === 'collage') it.collage.name = auto[i];
- else saveUi.names[it.key] = auto[i];
- });`);
- });
-
- it('gives a collage one name, shared by the Collage tab and the Save tab', () => {
- expect(source).toContain(
- "const saveName = (it) => (it.kind === 'collage' ? (it.collage.name ?? '') : (saveUi.names[it.key] ?? ''));"
- );
- expect(source).toContain(` if (it.kind === 'collage') it.collage.name = value;
- else saveUi.names[it.key] = value;`);
- expect(source).toContain('<SaveGallery {savables} {saveUi} {saveName} {setSaveName} />');
- });
-
- it('protects a hand-renamed collage from being refilled by a base name', () => {
- expect(source).toContain('onRename={(cl) => (saveUi.touched[`collage:${cl.id}`] = true)}');
- });
-
- it('files every kind under its resolved name, with the batch note', () => {
- expect(source).toContain('const nameOf = (item) => saveNameOf(item, saveName(item));');
- expect(source).toContain('items: frameItems, folder, notes: note,');
- expect(source).toContain('label: nameOf(videoItem), notes: note,');
- expect(source).toContain('label: nameOf(it), notes: note,');
- expect(source).toContain('ops: buildFrameOps(filters, it.frame),\n label: nameOf(it),');
- });
-
- it('says when a save landed on media the case already held', () => {
- expect(source).toContain("dupes += (res?.saved ?? []).filter((r) => r.duplicate).length;");
- expect(source).toContain("matched existing media and ${dupes === 1 ? 'was' : 'were'} renamed");
- });
-
- it('clears the naming fields when the workspace resets', () => {
- expect(source).toContain(` saveUi.names = {};
- saveUi.touched = {};
- saveUi.baseName = '';
- saveUi.note = '';`);
+ it('files nothing for a file that was only looked at', () => {
+ expect(source).toContain('if (!work.name && isPristine(work, filters, videoFilters)) return;');
});
});
-describe('Inspect — work that outlived what it was started against', () => {
- it('drops a frame whose session was cleared while it rendered', () => {
- // `session` is one object mutated in place, so a capture awaiting two round
- // trips cannot notice a discard or a source switch on its own — the frame
- // landed in the new session and became the active one.
- expect(source).toContain('let sessionRun = 0;');
- expect(source).toContain('sessionRun += 1;');
- expect(source).toMatch(/async function capture\(time\) \{[\s\S]*?const run = sessionRun;/);
- expect(source).toMatch(/const dim = await imageSize\(url\);\s*\n\s*if \(run !== sessionRun\)/);
- });
-
+describe('Inspect — crop keys', () => {
it('lets Escape leave the crop it found rather than applying the new one', () => {
expect(source).toContain("if (e.key === 'Enter') { e.preventDefault(); commitCrop(); }");
expect(source).toContain("else if (e.key === 'Escape') { e.preventDefault(); cancelCrop(); }");
- expect(source).toContain('function cancelCrop()');
- expect(source).toContain('activeFrame.crop = cropBefore');
+ expect(source).toContain('if (activeFrame) activeFrame.crop = cropBefore;');
expect(source).toContain('cropBefore = activeFrame.crop ? { ...activeFrame.crop } : null;');
});
});
describe('Inspect → Reverse Search', () => {
it('hands the frame over as it reads here, rendered without filing it', () => {
- // The same recipe Save and the collage use, so what is searched is what is
- // on screen: turned, adjusted and cropped.
expect(source).toContain(
'const blob = await renderBlob(frame.path, frame.time, buildFrameOps(filters, frame));'
);
@@ -218,8 +57,15 @@ describe('Inspect → Reverse Search', () => {
expect(source).toContain('reverse={reverseFrame}');
});
- it('keeps one render route for the tray, the collage and the handoff', () => {
- expect(source).toContain('return URL.createObjectURL(await renderBlob(path, time, ops));');
+ it('keeps one render route for frames, previews and the handoff', () => {
expect(source.match(/inspect\/render-preview/g)).toHaveLength(1);
});
});
+
+describe('Inspect — words', () => {
+ it('no longer speaks of sessions to open, name or discard', () => {
+ const markup = source.slice(source.indexOf('</script>'));
+ expect(markup).not.toMatch(/session/i);
+ expect(markup).not.toContain('Discard');
+ });
+});
diff --git a/frontend/src/tools/ProofComposer.svelte b/frontend/src/tools/ProofComposer.svelte
index f8351dc..36b341a 100644
--- a/frontend/src/tools/ProofComposer.svelte
+++ b/frontend/src/tools/ProofComposer.svelte
@@ -4000,7 +4000,7 @@
picker || newProofOpen || importOpen || openList !== null || discardConfirm
|| replaceWithNewConfirm || exportPicker || overwritePrompt !== null
|| placeOffer !== null || orphanOffer !== null || deleteEntry !== null
- || sourcePick !== null
+ || sourcePick !== null || pointMap !== null
);
const editableShape = $derived(editableShapes.length === 1 ? editableShapes[0] : null);
const fillableSelection = $derived(editableShapes.some((s) => canFill(s.kind)));
diff --git a/frontend/src/tools/ReverseSearch.render.test.js b/frontend/src/tools/ReverseSearch.render.test.js
index 82b3ba4..765205f 100644
--- a/frontend/src/tools/ReverseSearch.render.test.js
+++ b/frontend/src/tools/ReverseSearch.render.test.js
@@ -3,15 +3,24 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { flushSync, mount, unmount } from 'svelte';
/**
- * Arriving in Reverse Search with a picture another tool handed over. The tab has
- * to open on that picture rather than on the empty picker, spend the handoff once,
- * and say when what it shows is not a file of the case.
+ * Reverse Search lands on Inspect's file list and leaves it for the picture that
+ * was picked. Arriving with a picture another tool handed over, the tab has to
+ * open on that picture rather than on the list, spend the handoff once, and say
+ * when what it shows is not a file of the case.
*/
-vi.mock('../lib/api.js', () => ({ api: { get: vi.fn(async () => []) } }));
+const MEDIA = [
+ { path: 'media/quai.jpg', kind: 'image', title: 'Quai', source: { type: 'upload' } },
+ { path: 'media/clip.mp4', kind: 'video', title: 'Convoy clip', source: { type: 'download' } },
+ { path: 'media/notes.pdf', kind: 'document', title: 'Notes', source: { type: 'upload' } },
+];
+
+const get = vi.fn(async () => []);
+vi.mock('../lib/api.js', () => ({ api: { get } }));
const uiState = { tool: 'reverse', reverseTarget: null };
+const caseState = { current: { id: 'case-a' }, rev: 0 };
vi.mock('../lib/state.svelte.js', () => ({
- caseState: { current: { id: 'case-a' } },
+ caseState,
prefs: { reversePrefill: false },
uiState,
toast: vi.fn(),
@@ -29,8 +38,25 @@ function open() {
flushSync();
}
+/** Mount, and let the case's media list come back. */
+async function land(media = MEDIA) {
+ get.mockResolvedValue(media);
+ open();
+ await vi.waitFor(() => expect(get).toHaveBeenCalledWith('/api/cases/case-a/media'));
+ await Promise.resolve();
+ flushSync();
+}
+
+const cardTitles = () => [...target.querySelectorAll('.card .title')].map((el) => el.textContent);
+const buttonNamed = (text) =>
+ [...document.querySelectorAll('button')].find((b) => b.textContent.trim() === text || b.getAttribute('aria-label') === text);
+
beforeEach(() => {
uiState.tool = 'reverse';
+ uiState.reverseTarget = null;
+ caseState.current = { id: 'case-a' };
+ get.mockReset();
+ get.mockResolvedValue([]);
vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:frame');
vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => {});
});
@@ -48,7 +74,7 @@ describe('a picture handed over by another tool', () => {
open();
expect(target.querySelector('.preview img').getAttribute('src')).toBe('/files/case-a/media/quai.jpg');
- expect(target.querySelector('.preview-bar .name').textContent).toBe('Quai');
+ expect(target.querySelector('.tool-header .name').textContent).toBe('Quai');
expect(uiState.reverseTarget).toBeNull();
expect(target.textContent).not.toContain('not saved in the case');
});
@@ -75,7 +101,7 @@ describe('a picture handed over by another tool', () => {
};
open();
- [...target.querySelectorAll('button')].find((b) => b.textContent.includes('Discard')).click();
+ buttonNamed('Close file').click();
flushSync();
expect(URL.revokeObjectURL).toHaveBeenCalledWith('blob:frame');
@@ -92,3 +118,71 @@ describe('a picture handed over by another tool', () => {
uiState.reverseTarget = null;
});
});
+
+describe('the landing', () => {
+ it('is the case file list, images and videos only', async () => {
+ await land();
+
+ expect(cardTitles()).toEqual(['Quai', 'Convoy clip']);
+ // Reverse Search keeps no work, so nothing leads the list.
+ expect(target.querySelector('h4')).toBeNull();
+ expect(target.querySelector('.tool-header')).toBeNull();
+ });
+
+ it('keeps the engines one click away for a file outside the case', async () => {
+ await land();
+
+ const links = [...target.querySelectorAll('.engine-link')];
+ expect(links.map((a) => a.textContent.trim())).toEqual(['Google Lens', 'Yandex', 'Bing', 'TinEye']);
+ expect(links.every((a) => a.target === '_blank')).toBe(true);
+ });
+
+ it('puts a picked picture in front of the engines, and the cross goes back', async () => {
+ await land();
+
+ target.querySelector('.card').click();
+ flushSync();
+ expect(target.querySelector('.preview img').getAttribute('src')).toBe('/files/case-a/media/quai.jpg');
+ expect(target.querySelector('.tool-header .name').textContent).toBe('Quai');
+ expect(target.querySelector('.start')).toBeNull();
+
+ buttonNamed('Close file').click();
+ flushSync();
+ expect(cardTitles()).toEqual(['Quai', 'Convoy clip']);
+ });
+
+ it('changes the picture from the same list, marking the one shown', async () => {
+ await land();
+ target.querySelector('.card').click();
+ flushSync();
+
+ buttonNamed('Change file').click();
+ flushSync();
+ const dialog = document.querySelector('[role="dialog"]');
+ expect(dialog.querySelector('.card.current .title').textContent).toBe('Quai');
+
+ [...dialog.querySelectorAll('.card')].find((c) => c.textContent.includes('Convoy clip')).click();
+ flushSync();
+ expect(document.querySelector('[role="dialog"]')).toBeNull();
+ expect(target.querySelector('.preview video').getAttribute('src')).toBe('/files/case-a/media/clip.mp4');
+ });
+
+ it('sends a case with nothing to search to the Media Library', async () => {
+ await land([MEDIA[2]]);
+
+ expect(target.textContent).toContain('Add an image or a video to the case to search it.');
+ buttonNamed('Go to Media Library').click();
+ expect(uiState.tool).toBe('media');
+ expect(target.querySelectorAll('.engine-link')).toHaveLength(4);
+ });
+
+ it('still offers the engines with no case open, and asks for nothing', () => {
+ caseState.current = null;
+ open();
+
+ expect(get).not.toHaveBeenCalled();
+ expect(target.querySelector('.start')).toBeNull();
+ expect(target.textContent).toContain('Open a case to pick one of its pictures.');
+ expect(target.querySelectorAll('.engine-link')).toHaveLength(4);
+ });
+});
diff --git a/frontend/src/tools/ReverseSearch.svelte b/frontend/src/tools/ReverseSearch.svelte
index f06b8f6..aaba8cf 100644
--- a/frontend/src/tools/ReverseSearch.svelte
+++ b/frontend/src/tools/ReverseSearch.svelte
@@ -10,21 +10,20 @@
// is still what every refusal falls back to.
//
// Pick a case photo, or scrub a case video to a frame — or arrive from the Media
- // Library or Inspect already holding one (`uiState.reverseTarget`). Adjustments
+ // Library or Inspect already holding one (`uiState.reverseTarget`). The picking
+ // is Inspect's own file list, kept on screen until a picture is chosen. Adjustments
// (brightness, contrast, …) preview live and are baked into the exported
// image via a same-origin canvas — nothing leaves the machine until an
// engine tab is opened by the analyst.
import { untrack } from 'svelte';
import { api } from '../lib/api.js';
import { fileUrl } from '../lib/fileUrl.js';
- import { matchesTerms } from '../lib/folderBrowse.js';
import { caseState, prefs, uiState, toast } from '../lib/state.svelte.js';
import { extensionVersion, handOffReverse } from '../lib/extBridge.js';
import { MAX_HANDOFF_BYTES, UPLOAD_PAGES } from '../lib/reverseSearch.js';
import Modal from '../components/Modal.svelte';
import Icon from '../components/Icon.svelte';
- import SearchInput from '../components/SearchInput.svelte';
- import FolderBrowser from '../components/FolderBrowser.svelte';
+ import SourcePicker from '../components/SourcePicker.svelte';
const PASTE = UPLOAD_PAGES.filter((e) => e.paste);
const DRAG = UPLOAD_PAGES.filter((e) => !e.paste);
@@ -32,37 +31,16 @@
// installing it with the app already open needs a tab reload either way, and
// Settings is where that is said.
const extInstalled = extensionVersion();
- const MEDIA_FILTERS = [
- { id: 'all', label: 'All' },
- { id: 'image', label: 'Images' },
- { id: 'video', label: 'Video' },
- { id: 'capture', label: 'Captures' },
- { id: 'frame', label: 'Frames' },
- { id: 'collage', label: 'Collages' },
- ];
let pickerOpen = $state(false);
- let mediaLibrary = $state([]);
- let mediaQuery = $state('');
- let mediaFilter = $state('all');
- let pickerBrowserOpen = $state(false);
- let pickerBrowsePath = $state('');
- let pickerBrowseSelection = $state(null);
+ let mediaList = $state([]);
+ let mediaFor = $state(null); // the case `mediaList` was read from, once it has been
+ let loadedFor; // the case this tab last followed
let selected = $state(null); // the chosen media item, or null
let videoEl = $state(null); // the <video> element, when a video is selected
- const searchableMedia = $derived(mediaLibrary.filter((m) => m.kind === 'image' || m.kind === 'video'));
- const filteredPickerMedia = $derived(
- mediaFilter === 'all' ? searchableMedia : searchableMedia.filter((m) => mediaCategory(m) === mediaFilter)
- );
- const pickableMedia = $derived(
- mediaQuery.trim()
- ? filteredPickerMedia.filter((m) => matchesMediaName(m, mediaQuery))
- : filteredPickerMedia
- );
- const pickerBrowserEntries = $derived(
- filteredPickerMedia.map((m) => ({ ...m, id: m.path, attrs: { folder: m.folder ?? '' } }))
- );
+ const searchableMedia = $derived(mediaList.filter((m) => m.kind === 'image' || m.kind === 'video'));
+ const listed = $derived(caseState.current != null && mediaFor === caseState.current.id);
// -- adjustments (client-side CSS filters, baked into the export) -----------
const NEUTRAL = { brightness: 100, contrast: 100, saturate: 100, grayscale: 0 };
@@ -83,7 +61,8 @@
// A picture that exists nowhere on disk is shown from an address made for it here,
// and revoked once it is replaced or discarded.
const srcOf = (item) => item.src ?? fileUrl(caseState.current.id, item.path);
- const nameOf = (item) => (item.label || item.path).replace(/^media\//, '');
+ // The name the list and the Media Library show it by, as a handoff already carries.
+ const nameOf = (item) => (item.label || item.title || item.path).replace(/^media\//, '');
const frameLabel = $derived(selected?.kind === 'video' ? 'frame' : 'image');
const downloadName = () =>
`reverse-${nameOf(selected).replace(/^.*\//, '').replace(/\.[^.]+$/, '')}.png`;
@@ -96,24 +75,34 @@
const dragLeft = $derived(DRAG.filter((e) => !filled.includes(e)));
// -- picker -----------------------------------------------------------------
- async function openPicker() {
- if (!caseState.current) {
- toast('Open a case to search its media', 'warn');
- return;
- }
- mediaQuery = '';
- mediaFilter = 'all';
- pickerBrowserOpen = false;
- pickerBrowsePath = '';
- pickerBrowseSelection = null;
+ async function refresh(id) {
try {
- mediaLibrary = await api.get(`/api/cases/${caseState.current.id}/media`);
- pickerOpen = true;
+ const list = await api.get(`/api/cases/${id}/media`);
+ if (id !== caseState.current?.id) return;
+ mediaList = list;
+ mediaFor = id;
} catch (e) {
toast(e.message, 'danger');
}
}
+ // The list follows the case like Inspect's: an import, a delete or a restore
+ // elsewhere bumps its revision. A picture of the case before goes with it, as
+ // its handoff does, and before the page redraws, since its address names that
+ // case. The handoff below runs after, so it may then show the one it was given.
+ $effect.pre(() => {
+ const id = caseState.current?.id;
+ caseState.rev;
+ if (id !== loadedFor) {
+ if (loadedFor) untrack(discard);
+ loadedFor = id;
+ mediaList = [];
+ mediaFor = null;
+ pickerOpen = false;
+ }
+ if (id) refresh(id);
+ });
+
/** Put a picture in front of the engines, dropping the address of the one before. */
function show(item) {
if (selected?.src) URL.revokeObjectURL(selected.src);
@@ -145,54 +134,6 @@
videoEl.currentTime = Math.min(selected.time, videoEl.duration || selected.time);
}
- function matchesMediaName(item, query) {
- return matchesTerms(item.title || item.filename || '', query);
- }
-
- function mediaCategory(item) {
- const source = item.source ?? {};
- if (source.type === 'satellite' || source.type === 'screenshot') return 'capture';
- if (source.op === 'collage') return 'collage';
- if (source.op === 'frame' || source.op === 'adjust') return 'frame';
- return item.kind;
- }
-
- function openPickerBrowser() {
- mediaQuery = '';
- pickerBrowsePath = '';
- pickerBrowseSelection = null;
- pickerBrowserOpen = true;
- }
-
- function togglePickerBrowser() {
- if (pickerBrowserOpen) {
- pickerBrowserOpen = false;
- return;
- }
- openPickerBrowser();
- }
-
- function setMediaFilter(filter) {
- mediaFilter = filter;
- pickerBrowsePath = '';
- pickerBrowseSelection = null;
- }
-
- function openPickerFolder(path) {
- pickerBrowsePath = path;
- pickerBrowseSelection = null;
- }
-
- function confirmPickerBrowser() {
- const item = pickerBrowserEntries.find((m) => m.path === pickerBrowseSelection);
- if (item) pickMedia(item);
- }
-
- function selectPickerBrowser(item, confirm = false) {
- pickerBrowseSelection = item.path;
- if (confirm) pickMedia(item);
- }
-
function discard() {
if (selected?.src) URL.revokeObjectURL(selected.src);
selected = null;
@@ -354,69 +295,84 @@
];
</script>
-<div class="tool">
- <div class="tool-header">
- <h2>Reverse Search</h2>
- {#if selected}
- <span class="sub">
- {filled.length
- ? `Send the ${frameLabel} to an engine`
- : `Copy or save the ${frameLabel}, then hand it to an engine`}
- </span>
- {/if}
+{#snippet engineLinks()}
+ <div class="direct">
+ <span class="eg-head">Or open an engine and drag any file in</span>
+ <div class="engine-links">
+ {#each UPLOAD_PAGES as e (e.id)}
+ <a href={e.url} target="_blank" rel="noreferrer" class="engine-link">
+ {e.label} <Icon name="external" size={12} />
+ </a>
+ {/each}
+ </div>
</div>
+{/snippet}
- <div class="tool-body">
- {#if !selected}
- <div class="empty" style="height: 100%">
- <div class="empty-icon"><Icon name="search" size={42} /></div>
- <h3>Reverse image search</h3>
- <p>Pick a case photo, or a video to grab a frame from, then send it to the engines.</p>
- <button class="btn btn-sm" onclick={openPicker}>
- <Icon name="image" size={15} /> Pick from case
- </button>
- <div class="fallback">
- <span class="eg-head">Or open an engine and drag any file in</span>
- <div class="engine-links">
- {#each UPLOAD_PAGES as e (e.id)}
- <a href={e.url} target="_blank" rel="noreferrer" class="engine-link">
- {e.label} <Icon name="external" size={12} />
- </a>
- {/each}
+<div class="tool">
+ {#if selected}
+ <div class="tool-header">
+ <span class="file">
+ <Icon name={selected.kind === 'video' ? 'video' : 'image'} size={14} />
+ <span class="name" title={selected.path}>{nameOf(selected)}</span>
+ </span>
+ <div class="spacer"></div>
+ <button class="btn btn-sm" onclick={() => (pickerOpen = true)} title="Pick another image or video">
+ <Icon name="folderOpen" size={14} /> Change file
+ </button>
+ <button class="btn btn-ghost btn-sm" onclick={discard} title="Back to the file list" aria-label="Close file">
+ <Icon name="x" size={15} />
+ </button>
+ </div>
+ {/if}
+
+ {#if !selected}
+ {#if !caseState.current}
+ <div class="empty">
+ <Icon name="search" size={40} />
+ <p>Open a case to pick one of its pictures.</p>
+ {@render engineLinks()}
+ </div>
+ {:else if listed && searchableMedia.length === 0}
+ <div class="empty">
+ <Icon name="search" size={40} />
+ <p>Add an image or a video to the case to search it.</p>
+ <button class="btn" onclick={() => (uiState.tool = 'media')}>Go to Media Library</button>
+ {@render engineLinks()}
+ </div>
+ {:else}
+ <div class="start">
+ <div class="start-col">
+ <div class="start-head">
+ <div>
+ <h3>Pick a picture</h3>
+ <p>A photo, or a video to take a frame from. Nothing is sent until you press an engine.</p>
+ </div>
+ {@render engineLinks()}
</div>
+ {#if listed}
+ <SourcePicker media={searchableMedia} caseId={caseState.current.id} onpick={pickMedia} />
+ {/if}
</div>
</div>
- {:else}
+ {/if}
+ {:else}
+ <div class="tool-body">
<div class="work">
<div class="preview-col">
- <div class="preview-panel card">
- <div class="preview-bar">
- <span class="file">
- <Icon name={selected.kind === 'video' ? 'video' : 'image'} size={13} />
- <span class="name" title={selected.path}>{nameOf(selected)}</span>
- </span>
- <span class="bar-actions">
- <button class="btn btn-ghost btn-sm" onclick={openPicker}>Change</button>
- <button class="btn btn-ghost btn-sm" onclick={discard}>
- <Icon name="x" size={13} /> Discard
- </button>
- </span>
- </div>
- <div class="preview">
- {#if selected.kind === 'video'}
- <!-- svelte-ignore a11y_media_has_caption -->
- <video
- bind:this={videoEl}
- src={srcOf(selected)}
- controls
- preload="metadata"
- style="filter: {filterCss}"
- onloadedmetadata={seekToTarget}
- ></video>
- {:else}
- <img src={srcOf(selected)} alt={nameOf(selected)} style="filter: {filterCss}" />
- {/if}
- </div>
+ <div class="preview card">
+ {#if selected.kind === 'video'}
+ <!-- svelte-ignore a11y_media_has_caption -->
+ <video
+ bind:this={videoEl}
+ src={srcOf(selected)}
+ controls
+ preload="metadata"
+ style="filter: {filterCss}"
+ onloadedmetadata={seekToTarget}
+ ></video>
+ {:else}
+ <img src={srcOf(selected)} alt={nameOf(selected)} style="filter: {filterCss}" />
+ {/if}
</div>
{#if selected.kind === 'video'}
<p class="hint">Scrub to the moment, then copy or save the frame.</p>
@@ -515,76 +471,13 @@
{/if}
</div>
</div>
- {/if}
- </div>
+ </div>
+ {/if}
</div>
-{#if pickerOpen}
- <Modal title="Pick a case image or video" width="640px" onclose={() => (pickerOpen = false)}>
- <div class="picker-content">
- <div class="picker-search">
- <SearchInput bind:value={mediaQuery} placeholder="Search names…" width="100%" />
- <button class="btn btn-ghost btn-sm browse-btn" title="Browse folders" onclick={togglePickerBrowser}>…</button>
- </div>
-
- {#if searchableMedia.length === 0}
- <p class="picker-empty">No images or videos in this case yet. Import or download some in the Media tab.</p>
- {:else}
- <div class="picker-filters" aria-label="Media type">
- {#each MEDIA_FILTERS as filter (filter.id)}
- <button
- class="btn btn-ghost btn-sm"
- class:active={mediaFilter === filter.id}
- aria-pressed={mediaFilter === filter.id}
- onclick={() => setMediaFilter(filter.id)}
- >
- {filter.label}
- </button>
- {/each}
- </div>
-
- {#if pickerBrowserOpen}
- <FolderBrowser
- entries={pickerBrowserEntries}
- path={pickerBrowsePath}
- rootLabel="Case media"
- selectedId={pickerBrowseSelection}
- matches={(m) => matchesMediaName(m, mediaQuery)}
- emptyText="This folder has no matching media."
- icon={(m) => (m.kind === 'video' ? 'video' : 'image')}
- label={(m) => m.title || m.filename}
- onnavigate={openPickerFolder}
- onselect={(m) => selectPickerBrowser(m)}
- onconfirm={(m) => selectPickerBrowser(m, true)}
- />
- <div class="modal-actions">
- <button class="btn btn-primary btn-sm" disabled={!pickerBrowseSelection} onclick={confirmPickerBrowser}>Use selected</button>
- </div>
- {:else if pickableMedia.length === 0}
- <p class="modal-hint">No media matches this filter.</p>
- {:else}
- <div class="picker-list">
- {#each pickableMedia as item (item.path)}
- <button class="picker-open" onclick={() => pickMedia(item)} title={item.path}>
- <div class="picker-thumb">
- {#if item.thumbnail}
- <img src={fileUrl(caseState.current.id, item.thumbnail)} alt="" loading="lazy" />
- {:else}
- <Icon name={item.kind === 'video' ? 'video' : 'image'} size={22} />
- {/if}
- </div>
- <span class="picker-copy">
- <span class="picker-title">{item.title || item.filename}</span>
- <span class="picker-meta">
- {mediaCategory(item)}{item.folder ? ` · ${item.folder}` : ''}
- </span>
- </span>
- </button>
- {/each}
- </div>
- {/if}
- {/if}
- </div>
+{#if pickerOpen && listed}
+ <Modal title="Pick a case image or video" width="720px" onclose={() => (pickerOpen = false)}>
+ <SourcePicker media={searchableMedia} caseId={caseState.current.id} current={selected?.path} onpick={pickMedia} />
</Modal>
{/if}
@@ -597,24 +490,88 @@
color: var(--text-3);
}
- /* empty state — shared .empty primitive, with the engine fallback below */
- .fallback {
- margin-top: 22px;
- padding-top: 20px;
- border-top: 1px solid var(--border);
+ /* the picture's header, laid out as Inspect's */
+ .file {
+ display: flex;
+ align-items: center;
+ gap: 7px;
+ min-width: 0;
+ color: var(--text-2);
+ }
+ .file :global(svg) {
+ color: var(--text-3);
+ flex-shrink: 0;
+ }
+ .name {
+ font-weight: 600;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ .spacer {
+ flex: 1;
+ }
+
+ /* landing: Inspect's file list, with the engines' own pages beside it. The
+ whole panel scrolls and the column sits centred in it, so the wheel works
+ over the margins and the scrollbar stays on the edge. */
+ .empty {
+ flex: 1;
+ }
+ .start {
+ flex: 1;
+ min-height: 0;
+ overflow: auto;
+ }
+ .start-col {
display: flex;
flex-direction: column;
+ gap: 14px;
+ max-width: 1240px;
+ margin: 0 auto;
+ padding: 24px 20px;
+ }
+ .start-head {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: flex-end;
+ justify-content: space-between;
+ gap: 12px 24px;
+ }
+ .start-head h3 {
+ font-size: var(--fs-md);
+ font-weight: 700;
+ margin: 0 0 4px;
+ }
+ .start-head p {
+ margin: 0;
+ color: var(--text-3);
+ font-size: var(--fs-sm);
+ }
+ .direct {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ }
+ .direct .eg-head {
+ margin-bottom: 0;
+ }
+ .empty .direct {
align-items: center;
- gap: 10px;
width: 100%;
max-width: 360px;
+ margin-top: 22px;
+ padding-top: 20px;
+ border-top: 1px solid var(--border);
}
.engine-links {
display: flex;
flex-wrap: wrap;
- justify-content: center;
gap: 6px 18px;
}
+ .empty .engine-links {
+ justify-content: center;
+ }
.engine-link {
display: inline-flex;
align-items: center;
@@ -645,41 +602,8 @@
flex-direction: column;
gap: 10px;
}
- .preview-panel {
- overflow: hidden;
- }
- .preview-bar {
- display: flex;
- align-items: center;
- justify-content: space-between;
- gap: 12px;
- padding: 6px 8px 6px 12px;
- border-bottom: 1px solid var(--border);
- background: var(--bg-2);
- }
- .file {
- display: inline-flex;
- align-items: center;
- gap: 7px;
- min-width: 0;
- color: var(--text-2);
- }
- .file :global(svg) {
- color: var(--text-3);
- flex-shrink: 0;
- }
- .name {
- font-size: var(--fs-sm);
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
- }
- .bar-actions {
- display: inline-flex;
- gap: 2px;
- flex-shrink: 0;
- }
.preview {
+ overflow: hidden;
background: var(--bg-0);
display: flex;
justify-content: center;
@@ -722,9 +646,6 @@
justify-content: center;
min-width: 120px;
}
- .reset {
- align-self: flex-end;
- }
.inspect-link {
align-self: flex-start;
}
@@ -786,108 +707,4 @@
align-self: flex-end;
margin-top: 2px;
}
-
- /* picker modal */
- .picker-content {
- display: flex;
- flex-direction: column;
- gap: 12px;
- }
- .picker-empty {
- color: var(--text-3);
- font-size: var(--fs-sm);
- padding: 8px;
- }
- .modal-hint {
- color: var(--text-3);
- font-size: var(--fs-sm);
- margin: 0;
- }
- .modal-actions {
- display: flex;
- justify-content: flex-end;
- gap: 8px;
- }
- .picker-search {
- display: flex;
- align-items: center;
- gap: 6px;
- }
- .picker-search :global(.search-box) {
- flex: 1;
- }
- .browse-btn {
- min-width: 30px;
- font-size: var(--fs-lg);
- line-height: 1;
- }
- .picker-filters {
- display: flex;
- gap: 4px;
- overflow-x: auto;
- padding-bottom: 2px;
- }
- .picker-filters .active {
- color: var(--text-1);
- background: var(--bg-3);
- }
- .picker-list {
- display: flex;
- flex-direction: column;
- gap: 6px;
- max-height: min(52vh, 480px);
- overflow: auto;
- }
- .picker-open {
- display: flex;
- align-items: center;
- gap: 10px;
- width: 100%;
- padding: 7px;
- text-align: left;
- border: 1px solid var(--border);
- border-radius: var(--r-md);
- background: var(--bg-2);
- }
- .picker-open:hover {
- border-color: var(--accent);
- background: var(--bg-3);
- }
- .picker-thumb {
- display: grid;
- place-items: center;
- width: 48px;
- height: 40px;
- flex-shrink: 0;
- overflow: hidden;
- border-radius: var(--r-sm);
- background: var(--bg-0);
- color: var(--text-3);
- }
- .picker-thumb img {
- width: 100%;
- height: 100%;
- object-fit: cover;
- }
- .picker-copy {
- display: flex;
- flex-direction: column;
- min-width: 0;
- gap: 2px;
- }
- .picker-title,
- .picker-meta {
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
- }
- .picker-title {
- color: var(--text-1);
- font-size: var(--fs-sm);
- font-weight: 600;
- }
- .picker-meta {
- color: var(--text-3);
- font-size: var(--fs-xs);
- }
</style>
diff --git a/frontend/src/tools/ReverseSearch.test.js b/frontend/src/tools/ReverseSearch.test.js
index ca9cd01..e7f98fb 100644
--- a/frontend/src/tools/ReverseSearch.test.js
+++ b/frontend/src/tools/ReverseSearch.test.js
@@ -4,26 +4,11 @@ import { readFileSync } from 'node:fs';
const source = readFileSync(new URL('./ReverseSearch.svelte', import.meta.url), 'utf8');
describe('Reverse Search case picker', () => {
- it('starts from a searchable image/video media list', () => {
- expect(source).toContain("import SearchInput from '../components/SearchInput.svelte'");
+ it('picks from the same file list as Inspect, not a copy of it', () => {
+ expect(source).toContain("import SourcePicker from '../components/SourcePicker.svelte'");
expect(source).toContain("m.kind === 'image' || m.kind === 'video'");
- expect(source).toContain('bind:value={mediaQuery}');
- expect(source).toContain('filteredPickerMedia.filter((m) => matchesMediaName(m, mediaQuery))');
- expect(source).toContain('{#each pickableMedia as item (item.path)}');
- expect(source).toContain('placeholder="Search names…"');
- expect(source).toContain('function matchesMediaName(item, query)');
- expect(source).toContain("matchesTerms(item.title || item.filename || '', query)");
- expect(source).not.toContain("item.filename !== item.title");
- });
-
- it('separates reverse-search sources by media type and provenance', () => {
- expect(source).toContain("{ id: 'all', label: 'All' }");
- expect(source).toContain("{ id: 'capture', label: 'Captures' }");
- expect(source).toContain("{ id: 'frame', label: 'Frames' }");
- expect(source).toContain("{ id: 'collage', label: 'Collages' }");
- expect(source).toContain("source.type === 'satellite' || source.type === 'screenshot'");
- expect(source).toContain("source.op === 'frame' || source.op === 'adjust'");
- expect(source).toContain("source.op === 'collage'");
+ expect(source).not.toContain('FolderBrowser');
+ expect(source).not.toContain('SearchInput');
});
it('decides the road before it awaits, since the button is a real link', () => {
@@ -61,14 +46,4 @@ describe('Reverse Search case picker', () => {
expect(source).toContain('const pending = pngBlob();\n copyPng(pending);');
expect(source).toContain('blob = await pending;');
});
-
- it('offers the same read-only folder browser as Inspect', () => {
- expect(source).toContain("import FolderBrowser from '../components/FolderBrowser.svelte'");
- expect(source).toContain('title="Browse folders"');
- expect(source).toContain('onconfirm={(m) => selectPickerBrowser(m, true)}');
- expect(source).toContain('disabled={!pickerBrowseSelection} onclick={confirmPickerBrowser}');
- expect(source).toContain('function togglePickerBrowser()');
- expect(source).toContain('Use selected');
- });
-
});
diff --git a/frontend/src/tools/Satellite.svelte b/frontend/src/tools/Satellite.svelte
index 63b56f7..0a84a81 100644
--- a/frontend/src/tools/Satellite.svelte
+++ b/frontend/src/tools/Satellite.svelte
@@ -32,20 +32,22 @@
caseState, uiState, ensureCase, reloadCase, toast, dismissToast, prefs, fmtCoords, prefsReady,
} from '../lib/state.svelte.js';
import { markerGeometry, markerSvg } from '../lib/mapMarkers.js';
- import { startRectDrag, startRotateDrag } from '../lib/map/gestures.js';
+ import { startRectDrag, turnFromKey, turnFromPress } from '../lib/map/gestures.js';
import { panelWidth } from '../lib/panelWidth.js';
import PlaceSearch from './satellite/PlaceSearch.svelte';
import { assignFolder } from '../lib/filing.js';
import { saveRelation } from '../lib/relations.svelte.js';
- import { openEntity } from '../lib/navigate.js';
+ import { openComparison, openEntity, openMapAt } from '../lib/navigate.js';
import { deletedToast, RESTORABLE } from '../lib/trash.js';
import { extensionVersion, mapLinkRelay, onActivated } from '../lib/extBridge.js';
import { SENTINEL_ID } from '../lib/sentinel.js';
import { WAYBACK_ID } from '../lib/wayback.js';
import { COMPARE_SOURCES, comparePair } from '../lib/map/comparePair.js';
+ import { actionsFor, otherMapTools } from '../lib/map/contextMenu.js';
import { buildHash, readSolo, splitHash } from '../lib/hash.js';
import { readView, readWindowLabel, viewParams } from '../lib/map/view.js';
import { createViewLink } from '../lib/map/link.js';
+ import { shareView } from '../lib/map/sharedView.js';
import {
askable,
DATED as FIRMS_DATED,
@@ -78,6 +80,7 @@
railSections,
} from '../lib/map/tools.js';
import Icon from '../components/Icon.svelte';
+ import TurnGuide from '../components/TurnGuide.svelte';
import ConfirmDialog from '../components/ConfirmDialog.svelte';
import Modal from '../components/Modal.svelte';
import EntityDetails from '../components/EntityDetails.svelte';
@@ -138,6 +141,9 @@
// The map opens on the saved home view, so it is not built until preferences
// have landed — a deep link can mount this tool first.
let homeReady = $state(false);
+ // …and the view it actually opens on, settled in `build`: the address, else
+ // where the other map tabs left the window, else home.
+ let opensOn = $state(null);
let center = $state({ ...prefs.homeView });
let markerStyle = $state('none'); // 'crosshair' | 'pin' | 'none'
let moveMode = $state(false); // pin decoupled from center, draggable
@@ -509,8 +515,12 @@
// The address wins over the saved home view: it is what a detached window,
// a reload and a kept link all carry. A basemap named there has to exist —
// the catalogue depends on which keys are configured, and an address can be
- // typed by hand.
- center = { ...openingHome };
+ // typed by hand. An address with no view leaves the map where the other map
+ // tabs left the window, when they share one.
+ const shared = openingView?.lat == null ? share.opening() : null;
+ center = shared ? { lat: shared.lat, lon: shared.lon, zoom: shared.zoom } : { ...openingHome };
+ if (shared) bearing = shared.bearing ?? 0;
+ opensOn = { ...center };
if (openingView?.provider && imagery.find(openingView.provider)) {
providerId = openingView.provider;
}
@@ -519,9 +529,15 @@
loadFireSensors();
// A peer moved. Applied whatever this tab was doing, because the analyst
// asked for that by pressing the link — but only while it is pressed.
+ // With the map tabs sharing a camera it is the window's camera that moves,
+ // so the tab on screen follows, whichever it is.
viewLink = createViewLink(
(view) => {
if (!linked || !engine) return;
+ if (prefs.mapSync) {
+ uiState.mapView = { ...view, by: 'link' };
+ return;
+ }
engine.setView(view, view.zoom);
setBearing(view.bearing);
},
@@ -582,6 +598,8 @@
if (notesItem || placeModal || detailsEntityId || refs.picking || deleteTarget) return;
const tag = e.target?.tagName;
const typing = tag === 'INPUT' || tag === 'TEXTAREA' || e.target?.isContentEditable;
+ // Shift and an arrow turn the map, as on every map in the app
+ if (!typing && turnFromKey(engine, e)) return;
// Enter confirms a polygon area, same as the Confirm button
if (grid.on && grid.drawMode === 'polygon' && !typing && e.key === 'Enter') {
e.preventDefault();
@@ -653,20 +671,16 @@
if (mapReady && shown.provider?.id === WAYBACK_ID) wb.loadReleases();
});
- // --- middle-drag rotate (item 3), Google-Earth style ---
- // Grab a point → the map turns around *that* point (not the centre) as the
- // cursor sweeps, with a sober target marking the pivot. A map only rotates
- // about the centre, so after each bearing change we pan the grabbed geographic
- // point back under the cursor — keeping it pinned exactly where you grabbed.
+ // --- middle-drag rotate, Google-Earth style ---
+ // Grab a point and drag sideways: the map turns around *that* point (not the
+ // centre), with a sober target marking the pivot. A middle click alone puts
+ // north back up (lib/map/gestures.js).
function onMiddleRotateStart(e) {
if (!engine) return;
- // Middle button, or shift and the left one — the second was the old map's
- // own gesture, kept rather than quietly dropped. Never shift over a mode
- // already waiting for a left drag, though: those own the button.
- const shiftDrag =
- e.button === 0 && e.shiftKey && !capture.armed && grid.drawMode !== 'rect';
- if (e.button !== 1 && !shiftDrag) return;
- startRotateDrag(engine, e, {
+ // Shift and the left button turns too, as it did on the old map. Never over
+ // a mode already waiting for a left drag, though: those own the button.
+ turnFromPress(engine, e, {
+ shift: !capture.armed && grid.drawMode !== 'rect',
onPivot: (pivot) => {
rotatePivot = pivot;
rotating = true;
@@ -793,15 +807,39 @@
*/
let peerMaps = $state(0);
+ /** What the link sends: the window's camera while the map tabs share one, so
+ * a pan in Compare or Detect reaches the other maps too; else this map's. */
+ function linkedView() {
+ if (prefs.mapSync && uiState.mapView) return uiState.mapView;
+ return { lat: center.lat, lon: center.lon, zoom: center.zoom, bearing };
+ }
+
function toggleLink() {
if (!peerMaps) return;
linked = !linked;
- if (linked) viewLink?.send({ lat: center.lat, lon: center.lon, zoom: center.zoom, bearing });
+ if (linked) viewLink?.send(linkedView());
}
$effect(() => {
if (!linked || !mapReady) return;
- viewLink?.send({ lat: center.lat, lon: center.lon, zoom: center.zoom, bearing });
+ viewLink?.send(linkedView());
+ });
+
+ /**
+ * The camera this window's map tabs share (`lib/map/sharedView.js`).
+ *
+ * Written when this map comes to rest on screen, and taken when this tab
+ * shows, or when the link moves it while it does.
+ */
+ const share = shareView('satellite', { state: uiState, enabled: () => prefs.mapSync });
+
+ $effect(() => {
+ uiState.mapView;
+ if (uiState.tool !== 'satellite' || !mapReady) return;
+ untrack(() => {
+ const next = share.pending(engine.camera());
+ if (next) engine.setCamera(next);
+ });
});
const WINDOWS_KEY = 'azimut:mapWindows';
@@ -852,6 +890,8 @@
// part of a capture.
let pointMenu = $state(null); // { lat, lon, x, y, frame, lookup }
let pointLookupSeq = 0;
+ const pointActions = actionsFor(['lookup', 'place', 'measure', 'sky', 'history', 'centre']);
+ const pointTools = otherMapTools('satellite');
function onMapContextMenu(at) {
pointLookupSeq += 1;
@@ -899,6 +939,8 @@
wb.historyAt({ lat: point.lat, lon: point.lon, zoom });
} else if (id === 'compare') {
await comparePoint(point, value);
+ } else if (id === 'goto') {
+ openMapAt(value, { ...point, zoom: center.zoom });
}
}
@@ -1789,6 +1831,13 @@
// Deletions drop a file / an entity — always behind a confirm. The target is
// a saved-index row; its kind says which of the two it is.
let deleteTarget = $state(null);
+ const DELETE_WORDS = {
+ place: { title: 'Delete this place?', detail: 'Moves the saved point to the case trash.' },
+ comparison: {
+ title: 'Delete this comparison?',
+ detail: 'Moves the saved comparison to the case trash. Its images stay in Media.',
+ },
+ };
let deleteBusy = $state(false);
async function confirmDelete() {
@@ -1808,9 +1857,11 @@
}
}
- /** The edit action, for whichever kind of row it was pressed on. */
+ /** The edit action, for whichever kind of row it was pressed on. A comparison
+ * is edited where it was made. */
function editSaved(row) {
if (row.kind === 'place') openEditPlace(row);
+ else if (row.kind === 'comparison') openComparison(row);
else notesItem = row;
}
@@ -2124,7 +2175,7 @@
{s2}
wayback={wb}
{s1}
- home={openingHome}
+ home={opensOn}
{overlays}
imperial={prefs.units === 'imperial'}
controlsTop={railBottom}
@@ -2136,6 +2187,7 @@
onwidgetload={(meter) => imagery.countLoad(meter)}
onwidgetauthfailure={onWidgetAuthFailure}
onwidgetfailed={onWidgetFailed}
+ onviewsettled={(camera) => share.settled(camera, engine?.maxZoom())}
>
<!-- saved work on the map: navigation only, off by default, session-only.
It draws the panel's current selection, not the whole index. -->
@@ -2325,15 +2377,10 @@
</div>
{/if}
- <!-- middle-drag rotation pivot: sober target at the grabbed point, pinned
- on screen while the map turns around it -->
+ <!-- middle-drag rotation: the wheel about the grabbed point, pinned on
+ screen while the map turns around it -->
{#if rotating}
- <div class="rotate-pivot" style:left={`${rotatePivot.x}px`} style:top={`${rotatePivot.y}px`} aria-hidden="true">
- <svg width="40" height="40" viewBox="0 0 40 40">
- <circle class="ring" cx="20" cy="20" r="15" />
- <circle class="dot" cx="20" cy="20" r="1.5" />
- </svg>
- </div>
+ <TurnGuide x={rotatePivot.x} y={rotatePivot.y} />
{/if}
<!-- Where you are and what the armed tool is reading, then the two acts
@@ -2404,6 +2451,8 @@
zoom={center.zoom}
format={prefs.coordFormat}
{fullscreen}
+ actions={pointActions}
+ tools={pointTools}
lookup={pointMenu.lookup}
{compareSources}
onpick={onPointMenu}
@@ -2597,14 +2646,12 @@
/>
{/if}
-<!-- delete confirm: a capture drops its image file, a place its entity -->
+<!-- delete confirm: a capture drops its image file, a place or a comparison its entity -->
{#if deleteTarget}
<ConfirmDialog
- title={deleteTarget.kind === 'place' ? 'Delete this place?' : 'Delete this capture?'}
+ title={DELETE_WORDS[deleteTarget.kind]?.title ?? 'Delete this capture?'}
message={`“${deleteTarget.title || coordsLabel(deleteTarget)}” will be removed from the case.`}
- detail={deleteTarget.kind === 'place'
- ? 'Moves the saved point to the case trash.'
- : 'Moves the capture and its image to the case trash.'}
+ detail={DELETE_WORDS[deleteTarget.kind]?.detail ?? 'Moves the capture and its image to the case trash.'}
restorable={RESTORABLE}
confirmLabel="Delete"
tone="default"
@@ -2762,30 +2809,6 @@
:global(.sat-marker) {
filter: drop-shadow(0 1px 2px rgba(0, 0, 0, 0.5));
}
- /* Sober rotation pivot (Google-Earth style): faint translucent ring + dot. */
- .rotate-pivot {
- position: absolute;
- transform: translate(-50%, -50%);
- pointer-events: none;
- z-index: 650;
- color: #fff;
- }
- .rotate-pivot svg {
- display: block;
- overflow: visible;
- filter: drop-shadow(0 0 1.5px rgba(0, 0, 0, 0.55));
- }
- .rotate-pivot .ring {
- fill: none;
- stroke: currentColor;
- stroke-width: 1;
- opacity: 0.5;
- }
- .rotate-pivot .dot {
- fill: currentColor;
- opacity: 0.8;
- }
-
/* fullscreen: the whole tool covers the viewport, above the app chrome */
.tool.fullscreen {
position: fixed;
diff --git a/frontend/src/tools/Satellite.test.js b/frontend/src/tools/Satellite.test.js
index 64802df..caf3eb0 100644
--- a/frontend/src/tools/Satellite.test.js
+++ b/frontend/src/tools/Satellite.test.js
@@ -46,7 +46,7 @@ describe('Satellite saved work', () => {
expect(body).toContain('notesItem = row');
for (const [, name] of body.matchAll(/\b(open\w+)\(/g)) {
expect(source, `${name} is called but never defined`).toMatch(
- new RegExp(`function ${name}\\b|const ${name}\\b`)
+ new RegExp(`function ${name}\\b|const ${name}\\b|import \\{[^}]*\\b${name}\\b[^}]*\\}`)
);
}
});
@@ -225,9 +225,7 @@ describe('the saved panel is resizable', () => {
it('leaves the left button to whichever mode is armed for it', () => {
// shift and the left button turn the map, but the capture marquee and the
// grid box are both waiting on that same drag
- expect(source).toContain(
- "e.button === 0 && e.shiftKey && !capture.armed && grid.drawMode !== 'rect'"
- );
+ expect(source).toContain("shift: !capture.armed && grid.drawMode !== 'rect'");
});
it('redraws the map for the new size', () => {
@@ -630,8 +628,17 @@ describe('a map in more than one window', () => {
expect(source).toContain('zoom: openingView.zoom ?? prefs.homeView.zoom,');
// the surface reads where it opens once, at build, so it has to be handed
// the same answer the tool gave `center`
- expect(source).toContain('home={openingHome}');
- expect(source).toContain('center = { ...openingHome };');
+ expect(source).toContain('home={opensOn}');
+ expect(source).toContain('opensOn = { ...center };');
+ });
+
+ it('opens where the other map tabs left the window when the address names no view', () => {
+ // the address still wins: a detached window and a reload keep their own view
+ expect(source).toContain("const shared = openingView?.lat == null ? share.opening() : null;");
+ expect(source).toContain(
+ 'center = shared ? { lat: shared.lat, lon: shared.lon, zoom: shared.zoom } : { ...openingHome };'
+ );
+ expect(source).toContain('if (shared) bearing = shared.bearing ?? 0;');
});
it('refuses a basemap the catalogue does not hold, since an address is typed', () => {
@@ -689,7 +696,15 @@ describe('a map in more than one window', () => {
it('follows the other tabs only while the link is pressed', () => {
expect(source).toContain('let linked = $state(false);');
expect(source).toContain('if (!linked || !engine) return;');
- expect(source).toContain('viewLink?.send({ lat: center.lat, lon: center.lon, zoom: center.zoom, bearing })');
+ expect(source).toContain('return { lat: center.lat, lon: center.lon, zoom: center.zoom, bearing };');
+ expect(source).toContain('viewLink?.send(linkedView());');
+ });
+
+ it('carries the window camera over the link while the map tabs share one', () => {
+ // a pan in Compare or Detect reaches the other windows and the extension…
+ expect(source).toContain('if (prefs.mapSync && uiState.mapView) return uiState.mapView;');
+ // …and what arrives moves the window, so the tab on screen follows it
+ expect(source).toContain("uiState.mapView = { ...view, by: 'link' };");
});
it('links to the extension panels on other sites as well as to its own tabs', () => {
@@ -707,6 +722,19 @@ describe('a map in more than one window', () => {
});
});
+describe('one camera for the map tabs', () => {
+ it('writes the window camera when this map comes to rest, at its own ceiling', () => {
+ expect(source).toContain("const share = shareView('satellite', { state: uiState, enabled: () => prefs.mapSync });");
+ expect(source).toContain('onviewsettled={(camera) => share.settled(camera, engine?.maxZoom())}');
+ });
+
+ it('takes the window camera in one jump when it shows', () => {
+ const taking = source.slice(source.indexOf("if (uiState.tool !== 'satellite' || !mapReady) return;\n untrack"));
+ expect(taking.slice(0, 200)).toContain('const next = share.pending(engine.camera());');
+ expect(taking.slice(0, 200)).toContain('if (next) engine.setCamera(next);');
+ });
+});
+
describe('the key-less reference layers', () => {
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.
@@ -791,6 +819,15 @@ describe('the right-click menu', () => {
expect(body).not.toContain('displayCoords');
});
+ it('offers its own subset of acts, and opens the point in Compare or Detect', () => {
+ expect(source).toContain("actionsFor(['lookup', 'place', 'measure', 'sky', 'history', 'centre'])");
+ expect(source).toContain("otherMapTools('satellite')");
+ expect(source).toContain('tools={pointTools}');
+ const acts = source.slice(source.indexOf('async function onPointMenu(id, value)'));
+ const body = acts.slice(0, acts.indexOf('async function comparePoint'));
+ expect(body).toContain("openMapAt(value, { ...point, zoom: center.zoom })");
+ });
+
it('drops a lookup answer that arrives after the menu moved on', () => {
const lookup = source.slice(source.indexOf('async function lookUpPoint(point)'));
expect(lookup.slice(0, 600)).toContain('if (mine !== pointLookupSeq || !pointMenu) return;');
diff --git a/frontend/src/tools/Settings.svelte b/frontend/src/tools/Settings.svelte
index 1f26dad..47d0d18 100644
--- a/frontend/src/tools/Settings.svelte
+++ b/frontend/src/tools/Settings.svelte
@@ -336,6 +336,7 @@
let updateOnStart = $state(true); // pop a notice on load when a release is out
// whether saving a proof files its point as a place, or asks first
let proofPlaceAuto = $state(true);
+ let mapSync = $state(true); // Satellite, Compare and Detect share one camera
let radarLayer = $state('');
// a card of the Imagery tab asked for from elsewhere, opened and scrolled to
let focusCard = $state('');
@@ -552,6 +553,7 @@
reversePrefill = s.reverse_prefill ?? true;
updateOnStart = s.update_check_on_start ?? true;
proofPlaceAuto = s.proof_place_auto ?? true;
+ mapSync = s.map_sync ?? true;
radarLayer = s.sentinel1_layer ?? '';
applyPrefs(s); // the rest of the app reads these live
await loadScrapers().catch(() => {}); // local disk read; never blocks Settings
@@ -851,6 +853,7 @@
{saveHome}
bind:proofPlaceAuto
bind:reversePrefill
+ bind:mapSync
/>
{/if}
diff --git a/frontend/src/tools/Settings.test.js b/frontend/src/tools/Settings.test.js
index 45dcdfe..17723fe 100644
--- a/frontend/src/tools/Settings.test.js
+++ b/frontend/src/tools/Settings.test.js
@@ -123,6 +123,13 @@ describe('Settings sections', () => {
expect(general).toContain('so it\n searches straight away');
});
+ it('switches the shared map view from General, checked by default', () => {
+ expect(general).toContain('map_sync: mapSync');
+ expect(shell).toContain('mapSync = s.map_sync ?? true');
+ expect(shell).toContain('bind:mapSync');
+ expect(general).toContain('Share one view');
+ });
+
it('manages all three export folders from Storage', () => {
expect(shell).toContain("{ id: 'notes', label: 'Note PDFs' }");
expect(shell).toContain("{ id: 'media', label: 'Media copies' }");
diff --git a/frontend/src/tools/Timeline.svelte b/frontend/src/tools/Timeline.svelte
index 84d70e2..36aabbc 100644
--- a/frontend/src/tools/Timeline.svelte
+++ b/frontend/src/tools/Timeline.svelte
@@ -42,6 +42,7 @@
resizeWindow,
ribbonBands,
shiftWindow,
+ temporalKindLabel,
timeAtRatio,
windowInputValue,
windowMillis,
@@ -1844,7 +1845,7 @@
{#if selected}
<header><span class={`category-dot ${selected.category}`}></span><span>{categoryName(selected)}</span><button title="Close inspector" onclick={() => (selected = null)}><Icon name="x" size={13} /></button></header>
<div class="inspector-body">
- <div class="item-kind">{selected.kind}{#if selected.time_role} · {selected.time_role}{/if}</div>
+ <div class="item-kind">{temporalKindLabel(selected.kind)}{#if selected.time_role} · {selected.time_role}{/if}</div>
<h2>{selected.label}</h2>
{#if inspectorLoading}<div class="inspector-loading">Loading details…</div>{/if}
<div class="date-reading">
diff --git a/frontend/src/tools/compare/DifferenceBar.svelte b/frontend/src/tools/compare/DifferenceBar.svelte
index 48d9083..b1524c6 100644
--- a/frontend/src/tools/compare/DifferenceBar.svelte
+++ b/frontend/src/tools/compare/DifferenceBar.svelte
@@ -26,6 +26,8 @@
stale = false,
onrun = () => {},
onzone = () => {},
+ /** Keep this index reading as a Detect analyzer, to sweep areas with it. */
+ onanalyzer = () => {},
} = $props();
let open = $state(false);
@@ -165,6 +167,8 @@
</label>
{#if settings.method === 'index'}
<p class="hint">Highlights {index?.label} moved by {indexThreshold(settings.sensitivity).toFixed(2)} or more.</p>
+ <button class="btn btn-sm" title="Sweep areas or run a routine with this reading in Detect"
+ onclick={() => onanalyzer()}>Save as a Detect analyzer</button>
{/if}
<button class="btn btn-sm" onclick={() => (settings = { ...settings, normalize: 'none', smoothing: 0, cleanup: 0, alignment: 0, threshold: 'manual', sensitivity: 90 })}>
Preserve fine changes
diff --git a/frontend/src/tools/compare/DifferenceBar.test.js b/frontend/src/tools/compare/DifferenceBar.test.js
index ee36934..37c380e 100644
--- a/frontend/src/tools/compare/DifferenceBar.test.js
+++ b/frontend/src/tools/compare/DifferenceBar.test.js
@@ -31,6 +31,18 @@ const base = (target, label) =>
.find((entry) => entry.textContent.trim() === label);
describe('Difference strip', () => {
+ it('keeps an index reading as a Detect analyzer, and offers nothing for the picture methods', () => {
+ const onanalyzer = vi.fn();
+ const index = render({ settings: changeSettings({ method: 'index', index: 'nbr' }),
+ status: { ...ready, methods: ['colour', 'index'] }, onanalyzer }, { open: true });
+ button(index.target, 'Save as a Detect analyzer').click();
+ expect(onanalyzer).toHaveBeenCalledOnce();
+ index.done();
+ const colour = render({}, { open: true });
+ expect(button(colour.target, 'Save as a Detect analyzer')).toBeUndefined();
+ colour.done();
+ });
+
it('lays the highlights over both images by default, and over one on request', () => {
const { target, done } = render();
expect(base(target, 'Both').getAttribute('aria-pressed')).toBe('true');
diff --git a/frontend/src/tools/detect/AnalyzerBuilder.svelte b/frontend/src/tools/detect/AnalyzerBuilder.svelte
new file mode 100644
index 0000000..6680596
--- /dev/null
+++ b/frontend/src/tools/detect/AnalyzerBuilder.svelte
@@ -0,0 +1,656 @@
+<script>
+ /**
+ * An analyzer of your own, built rule by rule over the map.
+ *
+ * A rule is a line a pixel has to cross: a quantity, on pass A, on pass B or
+ * across the two. The map beside the dock is the bench. Once two passes are
+ * picked, every change to a rule redraws what each one keeps there in its
+ * own colour, with the candidates a run would return outlined, because the
+ * preview runs the engine's own evaluation on the frames a run would read.
+ * The preview follows the map: wherever frames are held, the detections are
+ * live, and the rest of the view is one Read away.
+ *
+ * Checks are the analyst's own proof, and optional: a place, its passes, and
+ * points where a candidate should come out or none should. They are reread
+ * from the cache whenever the rules change, so a tuned line that loses the
+ * burn or catches the reef says so at once. Nothing is fetched without a
+ * press, and a press that costs requests says how many.
+ */
+ import { onDestroy, onMount, untrack } from 'svelte';
+ import { api } from '../../lib/api.js';
+ import { acquisitionQuery } from '../../lib/map/acquisitions.js';
+ import { clone, viewZone } from '../../lib/map/analyzers.js';
+ import {
+ RULE_COLOURS, checksSummary, describeRecipe, formatShare, markOutcomes, newCheck, newRule, readsOneDate,
+ readsRadar, recipeCapability, recipeProblem, signalOf, signature, suggestedLayer, withMark, withoutMark,
+ } from '../../lib/map/analyzerRules.js';
+ import AcquisitionPicker from './AcquisitionPicker.svelte';
+ import AnalyzerChecks from './AnalyzerChecks.svelte';
+ import AnalyzerLabel from './AnalyzerLabel.svelte';
+ import AnalyzerSettings from './AnalyzerSettings.svelte';
+ import RuleRow from './RuleRow.svelte';
+ import DateField from '../../components/DateField.svelte';
+ import Icon from '../../components/Icon.svelte';
+
+ /** What a configuration that has not answered yet still offers. */
+ const STANDARD_LAYERS = [
+ { id: 'TRUE_COLOR', label: 'True colour' }, { id: 'FALSE_COLOR', label: 'False colour (infrared)' },
+ { id: 'SWIR', label: 'SWIR (short-wave infrared)' }, { id: 'NDVI', label: 'NDVI (vegetation index)' },
+ ];
+
+ let {
+ catalogue,
+ recipe = $bindable(),
+ isNew = false,
+ /** Where to open: `{ tab, check }`, a tab and a check to put on the bench. */
+ start = null,
+ /** What the map draws while the builder is open: the preview, the shown
+ * rules, the hovered one, the last point read and the marks on the bench. */
+ builder = $bindable(null),
+ /** The map's view as `{ west, south, east, north }`, or null. */
+ viewBounds = () => null,
+ /** The settled camera; each new one moves the preview with the map. */
+ mapView = null,
+ /** The Copernicus layers this configuration offers, `[{ id, label, hint }]`. */
+ layers = [],
+ onshow = () => {},
+ onleavepass = () => {},
+ /** Blink A and B on the map: `onblink({ a, b })`, or `onblink(null)` to stop. */
+ onblink = () => {},
+ /** Frame a place: `{ lon, lat, zoom }` or `{ bounds }`. */
+ onfly = () => {},
+ onsave = async () => {},
+ oncancel = () => {},
+ } = $props();
+
+ const limits = $derived(catalogue?.rules ?? {});
+ const capability = $derived(recipeCapability(recipe, catalogue?.methods ?? []));
+ const single = $derived(readsOneDate(recipe));
+ const radar = $derived(readsRadar(recipe));
+ const problem = $derived(recipeProblem(recipe, limits));
+ const signal = $derived(signalOf(recipe));
+ const phrase = $derived(describeRecipe(recipe));
+ const most = $derived(limits.max_rules ?? 6);
+ const offered = $derived(layers.length ? layers : STANDARD_LAYERS);
+ const suggested = $derived(suggestedLayer(recipe.rules[Math.max(0, signal)], offered));
+ const labelOf = (id) => offered.find((entry) => entry.id === id)?.label ?? id.replace(/_/g, ' ').toLowerCase();
+
+ let tab = $state(untrack(() => start?.tab ?? 'rules'));
+ let a = $state({ date: '', time: '' });
+ let b = $state({ date: '', time: '' });
+ let region = $state(null);
+ let preview = $state(null);
+ let missing = $state(0);
+ let working = $state(false);
+ let reading = $state(false);
+ let error = $state('');
+ let saving = $state(false);
+ let shown = $state([]);
+ let hover = $state(null);
+ let probe = $state(null);
+ let showing = $state('basemap');
+ let layer = $state('TRUE_COLOR');
+ let passes = $state({ list: [], days: 90, busy: false, error: '', searched: false, truncated: false, open: false });
+ /** The check on the bench, and what each check's last read left. */
+ let active = $state(null);
+ let readings = $state({});
+ let running = $state('');
+ let generation = 0;
+ let checkGeneration = 0;
+
+ const current = $derived(signature(recipe));
+ const summary = $derived(checksSummary(recipe));
+ const bench = $derived(recipe.checks.find((check) => check.id === active) ?? null);
+
+ /** The view, held inside the ranges the engine accepts. */
+ function bounded(bounds) {
+ if (!bounds) return null;
+ const lon = (value) => Math.max(-180, Math.min(180, value));
+ const lat = (value) => Math.max(-85, Math.min(85, value));
+ return { west: lon(bounds.west), south: lat(bounds.south), east: lon(bounds.east), north: lat(bounds.north) };
+ }
+
+ /** The ground the passes on the bench were picked for. */
+ let passesFor = null;
+ const overlaps = (one, other) => one.west < other.east && other.west < one.east
+ && one.south < other.north && other.south < one.north;
+
+ // The preview is wherever the map is: each settled view moves it there. A
+ // view off the ground the passes were picked for drops them, since a pass
+ // there says nothing of here: somewhere else starts from its own passes.
+ $effect(() => {
+ mapView;
+ untrack(() => {
+ const next = bounded(viewBounds());
+ if (!next) return;
+ region = next;
+ if (passesFor && !overlaps(passesFor, next)) forgetPasses();
+ // A check with no pin yet is wherever the map is.
+ if (bench && !bench.marks.length) patchCheck(bench.id, (check) => ({ ...check, bounds: { ...next } }));
+ });
+ });
+
+ function forgetPasses() {
+ passesFor = null;
+ a = { date: '', time: '' };
+ b = { date: '', time: '' };
+ // A check still being placed moves with the map and starts over on its
+ // passes; one with pins stays where it was and leaves the bench.
+ if (bench && !bench.marks.length) {
+ patchCheck(bench.id, (check) => ({ ...check, a: {}, b: { date: '' }, result: null }));
+ } else {
+ active = null;
+ }
+ passes = { ...passes, list: [], searched: false, truncated: false, open: false, error: '' };
+ if (showing !== 'basemap') show('basemap');
+ }
+
+ /** A rule's eye; one added since the last toggle starts open. */
+ const isShown = (i) => shown[i] ?? true;
+ function toggle(i) {
+ shown = recipe.rules.map((_, k) => (k === i ? !isShown(k) : isShown(k)));
+ }
+
+ /** What a reading depends on; the name, label, colour and checks do not. */
+ const readingRecipe = $derived({ name: 'Preview', method: 'rules', rules: recipe.rules, match: recipe.match,
+ parameters: recipe.parameters });
+ const request = $derived(
+ problem || !region || !b.date || (!single && !a.date) ? '' : JSON.stringify({
+ recipe: readingRecipe,
+ a: single ? { date: '' } : { date: a.date, time: a.time },
+ b: { date: b.date, time: b.time },
+ bounds: region,
+ })
+ );
+ const needs = $derived(
+ !region ? 'Open the map on the ground to try the rules on.'
+ : !b.date ? (single ? 'Pick the pass to try the rules on.' : 'Pick pass A and pass B to try the rules on.')
+ : !single && !a.date ? 'These rules read A as well; pick it too.'
+ : problem
+ );
+
+ $effect(() => {
+ const body = request;
+ if (!body) { untrack(() => { preview = null; missing = 0; }); return; }
+ const mine = ++generation;
+ const timer = setTimeout(() => void run(body, false, mine), 250);
+ return () => clearTimeout(timer);
+ });
+
+ async function run(body, read, mine) {
+ working = true;
+ error = '';
+ try {
+ const answer = await api.post('/api/compare/analyzers/preview', { ...JSON.parse(body), read });
+ if (mine !== generation) return;
+ missing = answer.missing;
+ preview = answer.ready ? answer : null;
+ if (probe && answer.ready) void probeAt(probe.point);
+ } catch (e) {
+ if (mine === generation) error = e.message;
+ } finally {
+ if (mine === generation) working = false;
+ }
+ }
+
+ async function readFrames() {
+ if (!request || reading) return;
+ reading = true;
+ try { await run(request, true, ++generation); } finally { reading = false; }
+ }
+
+ /**
+ * Read every rule at a point of the map: the builder's way of asking why.
+ * Where nothing is read yet the card still opens, to say what is missing
+ * and to let the point become a mark all the same.
+ */
+ export async function probeAt(point) {
+ if (!request || !preview) {
+ probe = { point, result: null, error: '', unread: request ? 'frames' : 'passes' };
+ return;
+ }
+ const body = request;
+ probe = { point, result: null, error: '' };
+ try {
+ const result = await api.post('/api/compare/analyzers/probe', { ...JSON.parse(body), point: [point.lon, point.lat] });
+ if (body === request) probe = { point, result, error: '' };
+ } catch (e) {
+ probe = { point, result: null, error: e.message };
+ }
+ }
+
+ export function closeProbe() { probe = null; }
+
+ // -- checks ------------------------------------------------------------------
+
+ function sourceFor(letter) {
+ const side = letter === 'a' ? a : b;
+ return radar
+ ? { provider: 'sentinel1', date: side.date, time: side.time }
+ : { provider: 'sentinel2', date: side.date, layer, maxcc: 100 };
+ }
+ /** A check is complete once it has the passes the rules read. */
+ const complete = (check) => !!check.b?.date && (single || !!check.a?.date);
+ const incomplete = $derived(recipe.checks.find((check) => !complete(check)) ?? null);
+ const saveProblem = $derived(problem || (incomplete ? `“${incomplete.name}” needs its passes.` : ''));
+
+ /** Whether a point is on a check's ground, or within one of its widths of it. */
+ function near(bounds, { lon, lat }) {
+ const across = bounds.east - bounds.west;
+ const up = bounds.north - bounds.south;
+ return lon >= bounds.west - across && lon <= bounds.east + across && lat >= bounds.south - up && lat <= bounds.north + up;
+ }
+ /** The check a point read now would be marked in: the one on the bench, when
+ * the point is on its ground. Anywhere else a mark starts a check of its own. */
+ const markingInto = $derived(bench && probe && near(bench.bounds, probe.point) ? bench : null);
+
+ let benchSection = $state(null);
+ /** The pass list lives on the bench, above the tabs: open it and go there. */
+ function findPasses() {
+ benchSection?.scrollIntoView?.({ behavior: 'smooth', block: 'start' });
+ if (passes.searched && !passes.open) passes = { ...passes, open: true };
+ else if (!passes.open) void lookUp();
+ }
+
+ /**
+ * A new check where the map is, open on the bench: it takes the passes
+ * picked from now on, and pins wherever the map is clicked while one is armed.
+ */
+ function addCheck() {
+ if (!region || recipe.checks.length >= (limits.max_checks ?? 12)) return null;
+ const check = newCheck({ name: `Check ${recipe.checks.length + 1}`,
+ a: single || !a.date ? {} : sourceFor('a'), b: b.date ? sourceFor('b') : { date: '' }, bounds: region });
+ recipe.checks = [...recipe.checks, check];
+ active = check.id;
+ pinning = null;
+ tab = 'checks';
+ return check;
+ }
+
+ /** Which pin a click on the map drops in the open check, or null. */
+ let pinning = $state(null);
+ $effect(() => {
+ if (!bench) untrack(() => { pinning = null; });
+ });
+ export function pinMode(mode) { pinning = mode && bench ? mode : null; }
+ export function pinAt(point) {
+ if (!pinning || !bench) return;
+ patchCheck(bench.id, (check) => withMark(check, [point.lon, point.lat], pinning));
+ }
+ function closeCheck() {
+ pinning = null;
+ active = null;
+ }
+
+ /** Mark the point read on the map in the check on the bench, or in a new one. */
+ export function markProbe(expect) {
+ if (!probe) return;
+ const target = markingInto ?? addCheck();
+ if (!target) return;
+ recipe.checks = recipe.checks.map((check) => (check.id === target.id
+ ? withMark(check, [probe.point.lon, probe.point.lat], expect) : check));
+ probe = null;
+ tab = 'checks';
+ }
+
+ /** Put a check on the bench: its view, its passes and the layer it shows. */
+ function openCheck(check) {
+ active = check.id;
+ passesFor = { ...check.bounds };
+ a = { date: check.a?.date ?? '', time: check.a?.time ?? '' };
+ b = { date: check.b.date, time: check.b.time ?? '' };
+ if (check.b.layer && offered.some((entry) => entry.id === check.b.layer)) layer = check.b.layer;
+ probe = null;
+ onfly({ bounds: check.bounds });
+ show('b');
+ }
+
+ function patchCheck(id, change) {
+ recipe.checks = recipe.checks.map((check) => (check.id === id ? change(check) : check));
+ }
+
+ const body = (check) => ({ ...clone(check), result: null });
+ /** What changes a check's answer: the rules, and its own passes and marks.
+ * Its result is not in it, so writing one never asks for another read. */
+ const checksKey = $derived(JSON.stringify([current, recipe.checks.map((check) => [check.id, check.a, check.b, check.bounds, check.marks])]));
+ const hasChecks = $derived(recipe.checks.length > 0);
+
+ /** Reread every check; `read` fetches what the cache lacks. */
+ async function readChecks(read) {
+ const mine = ++checkGeneration;
+ const rules = clone(readingRecipe);
+ const signed = current;
+ const list = clone(recipe.checks);
+ for (const [i, check] of list.entries()) {
+ if (mine !== checkGeneration) return;
+ if (!complete(check)) {
+ readings = { ...readings, [check.id]: { busy: false, missing: 0, error: '' } };
+ continue;
+ }
+ // A read from the cache is over in a moment; only a fetch says it is reading.
+ if (read) {
+ running = `Reading ${i + 1} of ${list.length}…`;
+ readings = { ...readings, [check.id]: { ...readings[check.id], busy: true, error: '' } };
+ }
+ try {
+ const answer = await api.post('/api/compare/analyzers/check', { recipe: rules, check: body(check), read });
+ if (mine !== checkGeneration) return;
+ readings = { ...readings, [check.id]: { busy: false, missing: answer.missing ?? 0, error: '' } };
+ if (answer.ready) {
+ patchCheck(check.id, (entry) => ({ ...entry, result: { signature: signed, count: answer.count, covered: answer.covered } }));
+ }
+ } catch (e) {
+ if (mine !== checkGeneration) return;
+ readings = { ...readings, [check.id]: { busy: false, missing: 0, error: e.message } };
+ }
+ }
+ if (mine === checkGeneration) running = '';
+ }
+
+ // The checks follow the rules from the cache: never a request, only a read.
+ $effect(() => {
+ checksKey;
+ if (problem || !hasChecks) return;
+ const timer = setTimeout(() => untrack(() => void readChecks(false)), 700);
+ return () => clearTimeout(timer);
+ });
+
+ async function runAll() {
+ if (running || problem) return;
+ try { await readChecks(true); } finally { running = ''; }
+ }
+
+ function removeCheck(id) {
+ recipe.checks = recipe.checks.filter((check) => check.id !== id);
+ if (active === id) active = null;
+ }
+
+ // -- the map -----------------------------------------------------------------
+
+ $effect(() => {
+ const outcomes = bench && bench.result?.signature === current ? markOutcomes(bench) : [];
+ builder = {
+ preview, probe,
+ // A hidden rule stays hidden while the pointer is on its row.
+ hover: hover !== null && isShown(hover) ? hover : null,
+ shown: recipe.rules.map((_, i) => isShown(i)),
+ rules: clone(recipe.rules),
+ colour: recipe.colour, style: recipe.style, phenomenon: recipe.phenomenon,
+ colours: RULE_COLOURS,
+ marks: (bench?.marks ?? []).map((mark, i) => ({ ...mark, ok: outcomes[i] ?? null })),
+ ground: bench ? { bounds: bench.bounds, name: bench.name } : null,
+ checking: markingInto?.name ?? '',
+ canMark: !!region,
+ pinning,
+ pass: { showing, a: single ? '' : a.date, b: b.date, blink: blinkable },
+ };
+ });
+ onMount(() => {
+ const first = start?.check && recipe.checks.find((check) => check.id === start.check);
+ if (first) openCheck(first);
+ });
+ onDestroy(() => {
+ builder = null;
+ checkGeneration++;
+ if (showing === 'blink') onblink(null);
+ if (showing !== 'basemap') onleavepass();
+ });
+
+ function add() {
+ if (recipe.rules.length >= most) return;
+ recipe.rules = [...recipe.rules, newRule(radar ? 'radar' : 'index', 'b')];
+ }
+ function remove(i) {
+ shown = recipe.rules.map((_, k) => isShown(k)).filter((_, k) => k !== i);
+ recipe.rules = recipe.rules.filter((_, k) => k !== i);
+ hover = null;
+ }
+ /** The ranking rule goes first, which is where the engine looks for it. */
+ function rank(i) {
+ const order = [i, ...recipe.rules.map((_, k) => k).filter((k) => k !== i)];
+ shown = order.map((k) => isShown(k));
+ recipe.rules = order.map((k) => recipe.rules[k]);
+ }
+
+ const blinkable = $derived(!single && !!a.date && !!b.date);
+
+ /** Lay the basemap, A, B, or A and B blinking, under the preview. */
+ function show(which) {
+ if (showing === 'blink' && which !== 'blink') onblink(null);
+ showing = which;
+ if (which === 'basemap') { onleavepass(); return; }
+ if (which === 'blink') {
+ if (blinkable) onblink({ a: sourceFor('a'), b: sourceFor('b') });
+ else show('b');
+ return;
+ }
+ if ((which === 'a' ? a : b).date) onshow(sourceFor(which));
+ }
+ /** The map's own A / B / Blink bar asks through here. */
+ export function showPass(which) { show(which); }
+ function setLayer(id) {
+ layer = id;
+ if (bench) {
+ patchCheck(bench.id, (check) => ({ ...check, a: check.a?.date ? { ...check.a, layer: id } : check.a,
+ b: check.b?.date ? { ...check.b, layer: id } : check.b }));
+ }
+ // Seeing a layer means seeing a pass in it: B, unless A is already up.
+ show(showing === 'basemap' ? (b.date ? 'b' : a.date ? 'a' : 'basemap') : showing);
+ }
+ function setDate(letter, date, time = '') {
+ const source = { date: date ?? '', time: radar ? time : '' };
+ if (letter === 'a') a = source;
+ else b = source;
+ if (region) passesFor = { ...region };
+ // The check open on the bench takes the passes picked for it.
+ if (bench) {
+ patchCheck(bench.id, (check) => ({ ...check, a: single || !a.date ? {} : sourceFor('a'),
+ b: b.date ? sourceFor('b') : { date: '' }, result: null }));
+ }
+ if (source.date) show(letter);
+ }
+
+ async function lookUp() {
+ if (!region) return;
+ passes = { ...passes, busy: true, error: '', open: true };
+ try {
+ const found = await api.post('/api/satellite/sentinel/acquisitions',
+ acquisitionQuery([viewZone(region, 'Preview')], passes.days, new Date(), radar ? 'sentinel1' : 'sentinel2'));
+ passes = { ...passes, list: found.dates ?? [], searched: true, truncated: !!found.truncated };
+ } catch (e) {
+ passes = { ...passes, error: e.message };
+ } finally {
+ passes = { ...passes, busy: false };
+ }
+ }
+
+ async function save() {
+ if (saving || saveProblem || !recipe.name.trim()) return;
+ saving = true;
+ error = '';
+ try {
+ await onsave({ ...clone(recipe), name: recipe.name.trim(), description: recipe.description.trim() || phrase });
+ } catch (e) {
+ error = e.message;
+ } finally {
+ saving = false;
+ }
+ }
+
+ const checksBadge = $derived(!summary.total ? '' : summary.pass + summary.fail ? `${summary.pass}/${summary.total}` : `${summary.total}`);
+</script>
+
+<div class="cmp-dock-body builder">
+ {#if error}<p class="warn" role="alert">{error}</p>{/if}
+ <h3>{isNew ? 'Build an analyzer' : `Edit ${recipe.name}`}</h3>
+ <label class="name" title="The name shown in the analyzer library across all cases.">Name
+ <input aria-label="Analyzer name" bind:value={recipe.name} maxlength="120" placeholder="What it finds" />
+ </label>
+ <p class="phrase">{phrase || 'Add a rule.'}</p>
+
+ <section class="try" aria-label="On the map" bind:this={benchSection}>
+ <strong>On the map</strong>
+ <div class="dates">
+ {#if !single}
+ <div class="date">
+ <span class="cmp-letter a">A</span>
+ <DateField day reading={false} label="Preview pass A" value={a.date} onchange={(value) => setDate('a', value)} />
+ {#if radar && a.time}<small class="mono">{a.time.slice(0, 5)} UTC</small>{/if}
+ </div>
+ {/if}
+ <div class="date">
+ <span class="cmp-letter b">B</span>
+ <DateField day reading={false} label="Preview pass B" value={b.date} onchange={(value) => setDate('b', value)} />
+ {#if radar && b.time}<small class="mono">{b.time.slice(0, 5)} UTC</small>{/if}
+ </div>
+ <button class="btn btn-sm" aria-expanded={passes.open} disabled={!region}
+ onclick={() => (passes.open ? (passes = { ...passes, open: false }) : passes.searched ? (passes = { ...passes, open: true }) : lookUp())}>
+ {passes.open ? 'Hide passes' : 'Find passes'}
+ </button>
+ </div>
+ {#if passes.open}
+ <AcquisitionPicker list={passes.list} days={passes.days} busy={passes.busy} error={passes.error}
+ searched={passes.searched} truncated={passes.truncated} areas={region ? 1 : 0} {single} {radar}
+ wantsReference={!single} wantsCompare={true} {a} {b}
+ ondays={(days) => (passes = { ...passes, days })} onlook={lookUp}
+ onpick={(letter, entry) => setDate(letter, entry.date, entry.time ?? '')} />
+ {/if}
+ <div class="row under">
+ <span class="hint">Imagery</span>
+ <div class="cmp-seg" role="group" aria-label="Imagery under the preview">
+ {#each [['basemap', 'Basemap'], ...(single ? [] : [['a', 'A']]), ['b', 'B'], ...(single ? [] : [['blink', 'Blink']])] as [id, label] (id)}
+ <button type="button" class:on={showing === id} aria-pressed={showing === id}
+ disabled={id === 'blink' ? !blinkable : id !== 'basemap' && !(id === 'a' ? a : b).date} onclick={() => show(id)}>{label}</button>
+ {/each}
+ </div>
+ {#if !radar}
+ <select class="grow" aria-label="Copernicus layer" title={offered.find((entry) => entry.id === layer)?.hint ?? ''}
+ value={layer} onchange={(event) => setLayer(event.currentTarget.value)}>
+ {#each offered as entry (entry.id)}<option value={entry.id}>{entry.label}</option>{/each}
+ </select>
+ {/if}
+ </div>
+ {#if !radar && suggested !== layer}
+ <button class="link suggest" onclick={() => setLayer(suggested)}>Show it in {labelOf(suggested)}, which reads rule ★ best</button>
+ {/if}
+
+ <div class="status" aria-live="polite">
+ {#if needs}
+ <p class="hint">{needs}</p>
+ {:else}
+ {#if preview}
+ <p class="result"><strong>{preview.count} candidate{preview.count === 1 ? '' : 's'}</strong> on the map
+ · {formatShare(preview.kept)} of the measured ground kept{#if working} · updating…{/if}</p>
+ {#if preview.candidates.length && preview.count > preview.candidates.length}<p class="hint">The {preview.candidates.length} strongest are drawn.</p>{/if}
+ {#if preview.note}<p class="warn">{preview.note}</p>{/if}
+ {:else if working && !missing}
+ <p class="hint">Reading the rules…</p>
+ {/if}
+ {#if missing}
+ <button class="btn btn-primary btn-sm read" disabled={reading} onclick={readFrames}>
+ {reading ? 'Reading from Copernicus…' : preview ? 'Read the rest of the view' : 'Show the detections here'}
+ </button>
+ <p class="hint">{missing} frame{missing === 1 ? '' : 's'} from Copernicus, one request each. Frames already read stay live as you move.</p>
+ {/if}
+ {#if preview}
+ {#if preview.clipped}<p class="hint">The preview covers the middle of the view, {limits.preview_span ?? 3} tiles a side. Zoom in to see all of it.</p>{/if}
+ <p class="hint">Click the map to read every rule at a point and mark it in a check.</p>
+ {/if}
+ {/if}
+ </div>
+ </section>
+
+ <div class="tabs" role="tablist" aria-label="Analyzer parts">
+ <button role="tab" aria-selected={tab === 'rules'} class:on={tab === 'rules'} onclick={() => (tab = 'rules')}>
+ Rules <span class="count">{recipe.rules.length}</span>
+ </button>
+ <button role="tab" aria-selected={tab === 'checks'} class:on={tab === 'checks'} onclick={() => (tab = 'checks')}>
+ Checks{#if checksBadge} <span class="count" class:fail={summary.fail} class:pass={!summary.fail && summary.pass === summary.total}>{checksBadge}</span>{/if}
+ </button>
+ <button role="tab" aria-selected={tab === 'settings'} class:on={tab === 'settings'} onclick={() => (tab = 'settings')}>Settings</button>
+ </div>
+
+ {#if tab === 'rules'}
+ <section class="rules" aria-label="Rules">
+ <div class="row match">
+ <span class="hint grow">Keep what passes</span>
+ <div class="cmp-seg" role="group" aria-label="How the rules combine">
+ <button type="button" class:on={recipe.match === 'all'} aria-pressed={recipe.match === 'all'}
+ title="A pixel is kept when it passes every rule" onclick={() => (recipe.match = 'all')}>all</button>
+ <button type="button" class:on={recipe.match === 'any'} aria-pressed={recipe.match === 'any'}
+ title="A pixel is kept when it passes one rule or more" onclick={() => (recipe.match = 'any')}>any</button>
+ </div>
+ </div>
+ {#each recipe.rules as _, i (i)}
+ <RuleRow bind:rule={recipe.rules[i]} index={i} colour={RULE_COLOURS[i % RULE_COLOURS.length]}
+ signal={i === signal} reading={preview?.rules?.[i] ?? null} match={recipe.match} shown={isShown(i)} ontoggle={() => toggle(i)}
+ bands={limits.bands} classes={limits.classes} maxAround={limits.max_around}
+ canRemove={recipe.rules.length > 1} onremove={() => remove(i)} onsignal={() => rank(i)}
+ onhover={(index) => (hover = index)} />
+ {/each}
+ <button class="btn btn-sm" disabled={recipe.rules.length >= most} onclick={add}>
+ <Icon name="plus" size={13} /> Add a rule
+ </button>
+ </section>
+ {:else if tab === 'checks'}
+ <AnalyzerChecks checks={recipe.checks} {current} {readings} {active} {running} canAdd={!!region} {pinning}
+ onadd={addCheck} onpin={pinMode} ondone={closeCheck} onfindpasses={findPasses}
+ most={limits.max_checks ?? 12} onrun={runAll} onopen={openCheck}
+ onremove={removeCheck} onrename={(id, name) => patchCheck(id, (check) => ({ ...check, name }))}
+ onremovemark={(id, i) => patchCheck(id, (check) => withoutMark(check, i))} />
+ {:else}
+ <section class="settings" aria-label="Size and grouping">
+ <strong>Size and grouping</strong>
+ <AnalyzerSettings bind:recipe {capability} expanded />
+ </section>
+ <section aria-label="Description">
+ <label title="What this analyzer looks for, and what it cannot tell you. Left empty, it takes the sentence at the top.">Description
+ <textarea bind:value={recipe.description} maxlength="500" placeholder={phrase}></textarea>
+ </label>
+ </section>
+ <AnalyzerLabel bind:recipe />
+ {/if}
+</div>
+<div class="cmp-dock-foot">
+ <div class="row">
+ <button class="btn btn-sm" onclick={oncancel}>Cancel</button>
+ <button class="btn btn-primary grow" disabled={saving || !!saveProblem || !recipe.name.trim()} onclick={save}>
+ {isNew ? 'Add to my analyzers' : 'Save changes'}
+ </button>
+ </div>
+ <span class="reason" class:warn={!recipe.name.trim() || !!incomplete}>{!recipe.name.trim() ? 'Name it to save it.'
+ : incomplete ? saveProblem : 'Shared by every case, and carried by Settings backup.'}</span>
+</div>
+
+<style>
+ .builder { grid-template-columns: minmax(0, 1fr); }
+ h3 { margin: 0; font-size: var(--fs-sm); font-weight: 700; }
+ section { display: grid; grid-template-columns: minmax(0, 1fr); gap: 7px; }
+ section > strong {
+ color: var(--text-2);
+ font-size: var(--fs-xs);
+ font-weight: 700;
+ letter-spacing: 0.06em;
+ text-transform: uppercase;
+ }
+ .name { display: grid; gap: 3px; }
+ .dates { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; }
+ .date { display: flex; align-items: center; gap: 5px; }
+ .date :global(.date-field) { width: 118px; }
+ .under { flex-wrap: wrap; }
+ .mono { color: var(--text-3); font-family: var(--font-mono); font-size: 10.5px; }
+ .status { display: grid; gap: 5px; }
+ .read { justify-self: start; }
+ .result { margin: 0; font-size: var(--fs-xs); color: var(--text-1); }
+ .phrase { margin: 0; color: var(--text-1); font-size: var(--fs-xs); line-height: 1.5; }
+ .link { color: var(--accent); font-size: var(--fs-xs); text-align: left; }
+ .suggest { justify-self: start; }
+ .tabs { display: flex; gap: 3px; border-bottom: 1px solid var(--border); }
+ .tabs button { flex: 1; padding: 7px 4px; color: var(--text-2); font-size: var(--fs-xs); font-weight: 600; }
+ .tabs button.on { color: var(--accent); border-bottom: 2px solid var(--accent); }
+ .count { margin-left: 3px; padding: 0 5px; border-radius: 999px; background: var(--bg-3); color: var(--text-3); font-size: 10px; }
+ .count.pass { background: color-mix(in srgb, var(--ok, #46a758) 18%, transparent); color: var(--ok, #46a758); }
+ .count.fail { background: color-mix(in srgb, var(--danger, #ef4444) 18%, transparent); color: var(--danger, #ef4444); }
+ .match { gap: 6px; }
+ textarea { min-height: 48px; resize: vertical; }
+</style>
diff --git a/frontend/src/tools/detect/AnalyzerChecks.svelte b/frontend/src/tools/detect/AnalyzerChecks.svelte
new file mode 100644
index 0000000..00c00ff
--- /dev/null
+++ b/frontend/src/tools/detect/AnalyzerChecks.svelte
@@ -0,0 +1,193 @@
+<script>
+ /**
+ * The checks of the analyzer being built: places the analyst trusts, each
+ * with its passes and pins where a candidate should come out or none should.
+ * They are optional. Add a check and it is open where the map is: the passes
+ * picked are its passes, and while a pin is armed every click on the map
+ * drops one. Whatever the tile cache holds is reread as the rules change;
+ * Run all fetches the rest, and says first how many requests that is.
+ */
+ import { checkState, describeOutcome, markOutcomes } from '../../lib/map/analyzerRules.js';
+ import Icon from '../../components/Icon.svelte';
+
+ let {
+ checks = [],
+ /** The signature of the rules as they stand. */
+ current = '',
+ /** Per check id: `{ busy, missing, error }` from the last read. */
+ readings = {},
+ active = null,
+ running = '',
+ /** A view is on the map, so a check can be added there. */
+ canAdd = false,
+ /** The pin a click on the map drops: 'found', 'empty' or null. */
+ pinning = null,
+ most = 12,
+ onadd = () => {},
+ onpin = () => {},
+ ondone = () => {},
+ onfindpasses = () => {},
+ onrun = () => {},
+ onopen = () => {},
+ onremove = () => {},
+ onrename = () => {},
+ onremovemark = () => {},
+ } = $props();
+
+ const ICONS = { pass: '✓', fail: '✗', counted: '#', stale: '–', unrun: '–' };
+ /** Each check's own count; checks that share a tile read it once. */
+ const missing = $derived(checks.reduce((sum, check) => sum + (readings[check.id]?.missing ?? 0), 0));
+ const dated = (check) => !!check.b?.date;
+ const passes = (check) => (!dated(check) ? 'no passes yet'
+ : check.a?.date ? `A ${check.a.date} → B ${check.b.date}` : `B ${check.b.date}`);
+ const PINS = [['found', 'Should be found'], ['empty', 'Should stay empty']];
+
+ function status(check) {
+ const reading = readings[check.id] ?? {};
+ if (!dated(check)) return 'pick its passes';
+ if (reading.busy) return 'Reading…';
+ if (reading.error) return reading.error;
+ const state = checkState(check, current);
+ if (reading.missing && (state === 'unrun' || state === 'stale')) {
+ const frames = `${reading.missing} frame${reading.missing === 1 ? '' : 's'} to read`;
+ return check.marks.length ? frames : `${frames} for its whole view; pins read only their own tiles`;
+ }
+ return describeOutcome(check, current);
+ }
+</script>
+
+<section class="checks" aria-label="Checks">
+ <div class="row actions">
+ <button class="btn btn-sm" disabled={!canAdd || checks.length >= most} onclick={onadd}>
+ <Icon name="plus" size={12} /> Add a check
+ </button>
+ {#if checks.some(dated)}
+ <button class="btn btn-sm btn-primary" disabled={!!running} onclick={onrun}>
+ {running || (missing ? `Run all · up to ${missing} request${missing === 1 ? '' : 's'}` : 'Run all')}
+ </button>
+ {/if}
+ </div>
+ {#if !checks.length}
+ <p class="hint">A check is a place you trust, two passes, and pins where a candidate should come out or none
+ should. Rerun it after each change and it says which rule broke what. Checks are optional.</p>
+ {/if}
+
+ {#each checks as check (check.id)}
+ {@const state = checkState(check, current)}
+ {@const outcomes = markOutcomes(check)}
+ <div class="check" class:on={active === check.id}>
+ <div class="row head">
+ <span class="state {state}" class:busy={readings[check.id]?.busy} aria-hidden="true">{ICONS[state]}</span>
+ <button class="open grow" aria-label={`Open the check ${check.name} on the map`} onclick={() => onopen(check)}>
+ <strong>{check.name}</strong>
+ <small>{passes(check)} · {status(check)}</small>
+ </button>
+ <button class="cmp-icon" aria-label={`Remove the check ${check.name}`} title="Remove this check"
+ onclick={() => onremove(check.id)}><Icon name="trash" size={12} /></button>
+ </div>
+ {#if active === check.id}
+ <div class="editor">
+ <label class="field">Name
+ <input aria-label="Check name" value={check.name} maxlength="120"
+ onchange={(event) => event.currentTarget.value.trim() && onrename(check.id, event.currentTarget.value.trim())} />
+ </label>
+ <div class="field">
+ <span>Passes</span>
+ <div class="row">
+ <span class="grow" class:missing={!dated(check)}>{dated(check) ? passes(check) : 'None yet: until it has pins, this check is where the map is.'}</span>
+ <button class="link" onclick={onfindpasses}>{dated(check) ? 'Change' : 'Find passes'}</button>
+ </div>
+ </div>
+ <div class="field">
+ <span>Pins</span>
+ <div class="pins" role="group" aria-label="Pin to drop on the map">
+ {#each PINS as [mode, label] (mode)}
+ <button type="button" class="pin pin-{mode}" class:on={pinning === mode} aria-pressed={pinning === mode}
+ onclick={() => onpin(pinning === mode ? null : mode)}>
+ <span class="dot pin-{mode}" aria-hidden="true"></span>{label}
+ </button>
+ {/each}
+ </div>
+ <span class="hint">{pinning ? 'Click the map to drop pins; press the button again to stop.' : 'Pick a pin, then click the map where it goes.'}</span>
+ </div>
+ {#if check.marks.length}
+ <ul class="marks">
+ {#each check.marks as mark, i (i)}
+ <li>
+ <span class="dot pin-{mark.expect}" aria-hidden="true"></span>
+ <span class="grow">{mark.expect === 'found' ? 'Should be found' : 'Should stay empty'}</span>
+ {#if state === 'pass' || state === 'fail'}
+ <span class="verdict" class:ok={outcomes[i]}>{outcomes[i] ? '✓' : '✗'}</span>
+ {/if}
+ <button class="cmp-icon" aria-label={`Remove pin ${i + 1}`} title="Remove this pin"
+ onclick={() => onremovemark(check.id, i)}><Icon name="x" size={11} /></button>
+ </li>
+ {/each}
+ </ul>
+ {/if}
+ <button class="btn btn-sm done" onclick={ondone}>Done</button>
+ </div>
+ {/if}
+ </div>
+ {/each}
+</section>
+
+<style>
+ .checks { display: grid; grid-template-columns: minmax(0, 1fr); gap: 7px; }
+ .actions { flex-wrap: wrap; gap: 6px; }
+ .check {
+ display: grid;
+ gap: 6px;
+ padding: 6px 8px;
+ border: 1px solid var(--border);
+ border-radius: var(--r-sm);
+ background: var(--bg-2);
+ }
+ .check.on { border-color: var(--accent); }
+ .head { gap: 6px; align-items: flex-start; }
+ .open { display: grid; gap: 2px; min-width: 0; text-align: left; }
+ .open strong { overflow: hidden; color: var(--text-1); font-size: var(--fs-xs); text-overflow: ellipsis; white-space: nowrap; }
+ .open small { color: var(--text-3); font-size: 10.5px; line-height: 1.4; }
+ .state { width: 16px; margin-top: 1px; color: var(--text-3); font-weight: 700; text-align: center; }
+ .state.pass { color: var(--ok, #46a758); }
+ .state.fail { color: var(--danger, #ef4444); }
+ .state.busy { color: var(--accent); }
+ .editor { display: grid; gap: 8px; }
+ .field { display: grid; gap: 4px; color: var(--text-3); font-size: 10.5px; }
+ .field > .row { color: var(--text-1); font-size: var(--fs-xs); }
+ .missing { color: var(--warn, #e2a03f); }
+ .pins { display: flex; flex-wrap: wrap; gap: 5px; }
+ .pin {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ padding: 4px 9px;
+ border: 1px solid var(--border);
+ border-radius: 999px;
+ color: var(--text-2);
+ font-size: var(--fs-xs);
+ }
+ .pin:hover { border-color: var(--border-strong); }
+ .pin.on { border-color: var(--accent); color: var(--text-1); background: var(--accent-soft); }
+ .marks { display: grid; gap: 3px; margin: 0; padding: 0; list-style: none; font-size: var(--fs-xs); }
+ .marks li { display: flex; align-items: center; gap: 6px; color: var(--text-2); }
+ /* The shapes the map draws: filled where a candidate should come out, struck
+ where none should. Green and red are kept for how a pin came out. */
+ .dot { position: relative; flex: 0 0 auto; width: 10px; height: 10px; border: 2px solid var(--text-1); border-radius: 50%; }
+ .dot.pin-found::after { position: absolute; inset: 1px; border-radius: 50%; background: var(--text-1); content: ''; }
+ .dot.pin-empty { border-style: dashed; }
+ .dot.pin-empty::after {
+ position: absolute;
+ top: 50%;
+ left: -2px;
+ width: 10px;
+ height: 2px;
+ background: var(--text-1);
+ transform: translateY(-50%) rotate(-45deg);
+ content: '';
+ }
+ .verdict { color: var(--danger, #ef4444); font-weight: 700; }
+ .verdict.ok { color: var(--ok, #46a758); }
+ .link { color: var(--accent); font-size: var(--fs-xs); }
+ .done { justify-self: start; }
+</style>
diff --git a/frontend/src/tools/detect/AnalyzerLabel.svelte b/frontend/src/tools/detect/AnalyzerLabel.svelte
new file mode 100644
index 0000000..0e3ff0e
--- /dev/null
+++ b/frontend/src/tools/detect/AnalyzerLabel.svelte
@@ -0,0 +1,28 @@
+<script>
+ /** How an analyzer's candidates are named and drawn. It never changes what is found. */
+ let { recipe = $bindable(), readonly = false } = $props();
+</script>
+
+<details class="look">
+ <summary>Label and colour</summary>
+ <fieldset class="fields" disabled={readonly}>
+ <label title="The label each candidate carries. It does not change what is detected.">Candidate label
+ <input bind:value={recipe.phenomenon} maxlength="120" />
+ </label>
+ <div class="row">
+ <label class="grow">Colour<input type="color" bind:value={recipe.colour} /></label>
+ <label class="grow">Layer style
+ <select bind:value={recipe.style}>
+ <option value="both">Pins and outlines</option><option value="pins">Pins</option><option value="outlines">Outlines with pins</option>
+ </select>
+ </label>
+ </div>
+ </fieldset>
+</details>
+
+<style>
+ .fields { display: grid; gap: 8px; min-width: 0; margin: 0; padding: 0; border: 0; }
+ .look { display: grid; gap: 8px; }
+ .look[open] { padding-top: 4px; }
+ summary { color: var(--text-2); font-size: var(--fs-xs); cursor: pointer; }
+</style>
diff --git a/frontend/src/tools/detect/AnalyzerLibrary.svelte b/frontend/src/tools/detect/AnalyzerLibrary.svelte
index f1af258..ff4e337 100644
--- a/frontend/src/tools/detect/AnalyzerLibrary.svelte
+++ b/frontend/src/tools/detect/AnalyzerLibrary.svelte
@@ -2,30 +2,53 @@
/**
* What a detection can look for, shared by every case.
*
- * A built-in is a method calibrated on real scenes. One of your own starts as
- * a copy of the closest built-in, which is the only way to make one: the
- * method comes with it, and what is yours is how picky it is, what it is
- * called and how it looks on the map. Saying that up front is the point of
- * this page; a method picked from a list of six told nobody what they were
- * choosing between.
+ * A built-in is a method calibrated on real scenes; a copy of one keeps the
+ * method and tunes how picky it is. One of your own is built from rules
+ * instead, each a line a pixel has to cross, tried on the map as it is
+ * written (AnalyzerBuilder). The two are offered side by side because they
+ * are different promises: calibrated, or exactly what you set. An example
+ * is one of your own already made, with the checks that show it working.
*/
import { api } from '../../lib/api.js';
import { toast } from '../../lib/state.svelte.js';
import { analyzerGroups, analyzerLock, clone } from '../../lib/map/analyzers.js';
+ import { describeChecks, newRecipe } from '../../lib/map/analyzerRules.js';
+ import AnalyzerBuilder from './AnalyzerBuilder.svelte';
+ import AnalyzerLabel from './AnalyzerLabel.svelte';
import AnalyzerSettings from './AnalyzerSettings.svelte';
import Icon from '../../components/Icon.svelte';
- let { catalogue, onchanged = async () => {}, onsaved = () => {} } = $props();
+ let {
+ catalogue,
+ onchanged = async () => {},
+ onsaved = () => {},
+ /** What the map draws while an analyzer of your own is being built. */
+ builder = $bindable(null),
+ viewBounds = () => null,
+ /** The settled camera, the Copernicus layers on offer and a way to frame a
+ * place: what the builder needs of the map. */
+ mapView = null,
+ layers = [],
+ onfly = () => {},
+ onshow = () => {},
+ onleavepass = () => {},
+ onblink = () => {},
+ } = $props();
- /** 'list', 'base' (what a new one starts from) or 'edit'. */
+ /** 'list', 'base' (what a new one starts from), 'edit' (a copy of a
+ * built-in) or 'build' (rules of your own). */
let mode = $state('list');
+ let bench = $state(null);
let recipe = $state(null);
+ /** Where the builder opens: `{ tab, check }`. */
+ let start = $state(null);
let readonly = $state(false);
let busy = $state(false);
let error = $state('');
const builtins = $derived(catalogue?.builtins ?? []);
const custom = $derived(catalogue?.custom ?? []);
+ const examples = $derived(catalogue?.examples ?? []);
const methodOf = (method) => catalogue?.methods?.find((m) => m.id === method) ?? {};
const capability = $derived(methodOf(recipe?.method));
const isNew = $derived(recipe?.id === 'custom');
@@ -37,12 +60,55 @@
finally { busy = false; }
}
- function view(entry) {
- recipe = clone(entry);
+ function view(entry, opening = null) {
+ recipe = entry.method === 'rules' ? { checks: [], ...clone(entry) } : clone(entry);
readonly = builtins.some((r) => r.id === entry.id);
- mode = 'edit';
+ start = opening;
+ mode = entry.method === 'rules' ? 'build' : 'edit';
+ }
+
+ function build(from = newRecipe(catalogue?.methods ?? [])) {
+ recipe = { checks: [], ...clone(from), id: 'custom' };
+ readonly = false;
+ start = null;
+ mode = 'build';
+ }
+
+ /** A name no analyzer of the library has yet: "Fresh burn", then "Fresh burn 2". */
+ function freeName(name) {
+ const taken = new Set(custom.map((entry) => entry.name));
+ let next = name;
+ for (let n = 2; taken.has(next); n++) next = `${name} ${n}`;
+ return next;
+ }
+
+ /**
+ * An example is copied into the library at once, checks and all, and opens
+ * on its checks with the first one on the map: running them is the lesson.
+ */
+ async function startExample(example) {
+ const saved = await api.post('/api/compare/analyzers', { ...clone(example.recipe), id: 'custom',
+ name: freeName(example.recipe.name) });
+ await onchanged();
+ toast(`${saved.name} is in your analyzers, with its checks`, 'ok');
+ view(saved, { tab: 'checks', check: saved.checks?.[0]?.id ?? null });
+ }
+
+ /** Open one of the analyst's own analyzers, as if picked from the list. */
+ export function openEntry(id) {
+ const entry = custom.find((row) => row.id === id);
+ if (entry) view(entry);
}
+ /** Read every rule at a point of the map, while one is being built, and
+ * mark that point in a check. */
+ export function probeAt(point) { return bench?.probeAt(point); }
+ export function closeProbe() { bench?.closeProbe(); }
+ export function markProbe(expect) { bench?.markProbe(expect); }
+ export function pinAt(point) { bench?.pinAt(point); }
+ export function pinMode(mode) { bench?.pinMode(mode); }
+ export function showPass(which) { bench?.showPass(which); }
+
/** Built-ins can't be written over, so a copy is how an analyst keeps a tuned version. */
function copy(entry) {
recipe = { ...clone(entry), id: 'custom', name: `${entry.name} copy` };
@@ -55,8 +121,8 @@
recipe = null;
}
- async function save() {
- const saved = await api.post('/api/compare/analyzers', clone(recipe));
+ async function save(next = recipe) {
+ const saved = await api.post('/api/compare/analyzers', clone(next));
await onchanged();
onsaved(saved);
toast('Analyzer saved for all cases', 'ok');
@@ -73,7 +139,7 @@
{#if mode === 'list'}
<div class="cmp-dock-body">
{#if error}<p class="warn" role="alert">{error}</p>{/if}
- <p class="hint">An analyzer is what a detection looks for: one calibrated method and how picky it is. Yours start as a copy of the closest built-in.</p>
+ <p class="hint">An analyzer is what a detection looks for. Start from an example, build your own from rules you try on the map, or copy a calibrated built-in to tune it.</p>
<button class="btn btn-primary" onclick={() => (mode = 'base')}><Icon name="plus" size={14} /> New analyzer</button>
<section aria-label="My analyzers">
@@ -83,7 +149,7 @@
<div class="row entry">
<button class="pick grow" style={`--tint: ${entry.colour}`} disabled={busy} onclick={() => view(entry)}>
<span class="swatch" aria-hidden="true"></span>
- <span class="name">{entry.name}<small>{methodOf(entry.method).label ?? entry.method}</small></span>
+ <span class="name">{entry.name}<small>{entry.method === 'rules' ? entry.description || methodOf(entry.method).label : methodOf(entry.method).label ?? entry.method}</small>{#if describeChecks(entry)}<small class="checked">{describeChecks(entry)}</small>{/if}</span>
</button>
<button class="cmp-icon" title="Edit" aria-label={`Edit ${entry.name}`} disabled={busy} onclick={() => view(entry)}>
<Icon name="edit" size={13} />
@@ -116,18 +182,46 @@
</div>
{:else if mode === 'base'}
<div class="cmp-dock-body">
- <h3>Start from</h3>
- <p class="hint">Pick the analyzer closest to what you want to find. Its method comes with it; you tune the rest.</p>
+ {#if error}<p class="warn" role="alert">{error}</p>{/if}
+ {#if examples.length}
+ <h3>Start from an example</h3>
+ <p class="hint">A ready analyzer with its checks. Run them, change a rule and see which check turns red.</p>
+ <div class="examples">
+ {#each examples as example (example.id)}
+ <button class="pick base grow" style={`--tint: ${example.recipe.colour}`} disabled={busy}
+ aria-label={`Start from the example ${example.recipe.name}`} onclick={() => act(() => startExample(example))}>
+ <span class="swatch" aria-hidden="true"></span>
+ <span class="name">{example.recipe.name}<small>{example.place} · {example.when} · {example.recipe.checks.length} checks</small></span>
+ </button>
+ {/each}
+ </div>
+ {/if}
+ <button class="pick base own" onclick={() => build()}>
+ <span class="swatch" aria-hidden="true"></span>
+ <span class="name">Build your own rules<small>Say what a pixel has to show, on A, on B or between them, and watch each rule on the map as you set it.</small></span>
+ </button>
+ <h3>Or start from a built-in</h3>
+ <p class="hint">Its calibrated method comes with it; you tune how picky it is. The ones marked rules open as the rules they apply.</p>
<div class="bases">
{#each [...builtins, ...custom] as entry (entry.id)}
- <button class="pick base" style={`--tint: ${entry.colour}`} onclick={() => copy(entry)}>
- <span class="swatch" aria-hidden="true"></span>
- <span class="name">{entry.name}<small>{entry.description || methodOf(entry.method).label}</small></span>
- </button>
+ {@const rules = catalogue?.as_rules?.[entry.id]}
+ <div class="row entry">
+ <button class="pick base grow" style={`--tint: ${entry.colour}`} onclick={() => (entry.method === 'rules' ? build({ ...entry, name: `${entry.name} copy` }) : copy(entry))}>
+ <span class="swatch" aria-hidden="true"></span>
+ <span class="name">{entry.name}<small>{entry.description || methodOf(entry.method).label}</small></span>
+ </button>
+ {#if rules}
+ <button class="btn btn-sm" title="Open it as the rules it applies" aria-label={`Open ${entry.name} as rules`}
+ onclick={() => build(rules)}>rules</button>
+ {/if}
+ </div>
{/each}
</div>
</div>
<div class="cmp-dock-foot"><button class="btn btn-sm" onclick={back}>Cancel</button></div>
+{:else if mode === 'build' && recipe}
+ <AnalyzerBuilder bind:this={bench} {catalogue} bind:recipe isNew={isNew} {start} bind:builder {viewBounds} {mapView} {layers} {onfly} {onshow} {onleavepass} {onblink}
+ onsave={(next) => save(next)} oncancel={back} />
{:else if recipe}
<div class="cmp-dock-body">
{#if error}<p class="warn" role="alert">{error}</p>{/if}
@@ -143,27 +237,15 @@
</label>
</fieldset>
<AnalyzerSettings bind:recipe {capability} expanded {readonly} />
- <details>
- <summary>Label and colour</summary>
- <fieldset class="fields" disabled={readonly}>
- <label title="The label each candidate carries. It does not change what is detected.">Candidate label
- <input bind:value={recipe.phenomenon} maxlength="120" />
- </label>
- <div class="row">
- <label class="grow">Colour<input type="color" bind:value={recipe.colour} /></label>
- <label class="grow">Layer style
- <select bind:value={recipe.style}>
- <option value="both">Pins and outlines</option><option value="pins">Pins</option><option value="outlines">Outlines with pins</option>
- </select>
- </label>
- </div>
- </fieldset>
- </details>
+ <AnalyzerLabel bind:recipe {readonly} />
</div>
<div class="cmp-dock-foot">
<div class="row">
<button class="btn btn-sm" onclick={back}>{readonly ? 'Back' : 'Cancel'}</button>
{#if readonly}
+ {#if catalogue?.as_rules?.[recipe.id]}
+ <button class="btn btn-sm" onclick={() => build(catalogue.as_rules[recipe.id])}>Open as rules</button>
+ {/if}
<button class="btn btn-primary grow" onclick={() => copy(recipe)}>Copy to tune</button>
{:else}
<button class="btn btn-primary grow" disabled={busy || !recipe.name.trim()} onclick={() => act(save)}>
@@ -199,16 +281,16 @@
.pick:hover:not(:disabled) { background: var(--bg-2); }
.base { border: 1px solid var(--border); background: var(--bg-2); }
.base:hover { border-color: var(--accent); }
- .bases { display: grid; gap: 6px; }
+ .bases, .examples { display: grid; gap: 6px; }
+ .examples { margin-bottom: 4px; }
+ .name small.checked { color: var(--text-2); }
.swatch { flex: 0 0 auto; width: 9px; height: 9px; margin-top: 4px; border-radius: 50%; background: var(--tint); }
.name { display: grid; gap: 2px; min-width: 0; color: var(--text-1); font-size: var(--fs-xs); font-weight: 600; }
.name small { color: var(--text-3); font-size: 10.5px; font-weight: 400; line-height: 1.4; }
.measures { margin: 0; color: var(--text-1); font-size: var(--fs-xs); }
.measures span { margin-right: 4px; color: var(--text-3); font-weight: 700; }
.fields { display: grid; gap: 8px; min-width: 0; margin: 0; padding: 0; border: 0; }
- details { display: grid; gap: 8px; }
- details[open] { padding-top: 4px; }
- summary { color: var(--text-2); font-size: var(--fs-xs); cursor: pointer; }
+ .own { border-color: var(--accent); --tint: var(--accent); }
.group {
margin: 8px 0 2px;
color: var(--text-3);
diff --git a/frontend/src/tools/detect/AnalyzerSettings.render.test.js b/frontend/src/tools/detect/AnalyzerSettings.render.test.js
new file mode 100644
index 0000000..3695874
--- /dev/null
+++ b/frontend/src/tools/detect/AnalyzerSettings.render.test.js
@@ -0,0 +1,37 @@
+// @vitest-environment happy-dom
+import { afterEach, expect, it } from 'vitest';
+import { flushSync, mount, unmount } from 'svelte';
+import AnalyzerSettings from './AnalyzerSettings.svelte';
+
+/** A threshold is shown only where the method reads it, in the unit it reads it in. */
+const parameters = { sensitivity: 60, min_area: 2000, max_area: 0, cleanup: 1, smoothing: 2, merge_metres: 30,
+ index: 'ndvi', direction: 'both', sar_ground: 'any', ignore_clouds: true, ignore_shadows: true, cloud_margin: 5 };
+let live, target;
+afterEach(() => { if (live) unmount(live); live = null; target?.remove(); });
+
+function open(capability) {
+ target = document.createElement('div'); document.body.append(target);
+ live = mount(AnalyzerSettings, { target, props: { recipe: { method: capability.id, parameters: { ...parameters } },
+ capability: { sizes: {}, ...capability }, expanded: true } });
+ flushSync();
+ return target.textContent;
+}
+
+it('counts radar averaging on the ground', () => {
+ const text = open({ id: 'sar-change', single: false, sensor: 'sentinel1', smoothing_m: 45 });
+ expect(text).toContain('Averaging · 90 m');
+ expect(text).not.toContain('Smoothing');
+});
+
+it('keeps pixels for optical change', () => {
+ const text = open({ id: 'surface', single: false, smoothing_m: null });
+ expect(text).toContain('Smoothing · 2px');
+ expect(text).toContain('Noise cleanup');
+});
+
+it('offers no cleanup or smoothing to a method that reads one image', () => {
+ const text = open({ id: 'sar-vessels', single: true, sensor: 'sentinel1', smoothing_m: null });
+ expect(text).not.toContain('Noise cleanup');
+ expect(text).not.toContain('Smoothing');
+ expect(text).toContain('Group within');
+});
diff --git a/frontend/src/tools/detect/AnalyzerSettings.svelte b/frontend/src/tools/detect/AnalyzerSettings.svelte
index ad2d134..381fea0 100644
--- a/frontend/src/tools/detect/AnalyzerSettings.svelte
+++ b/frontend/src/tools/detect/AnalyzerSettings.svelte
@@ -26,6 +26,10 @@
let showThresholds = $state(false);
const open = $derived(expanded || showThresholds);
const single = $derived(!!capability.single);
+ /** An analyzer of your own sets its lines rule by rule, so it has no
+ * sensitivity or direction here, and it cleans and smooths on one date too. */
+ const rules = $derived(recipe.method === 'rules');
+ const SHAPES = [['any', 'Any shape'], ['compact', 'Compact: roofs, craters, vehicles'], ['elongated', 'Long and thin: roads, tracks, trenches']];
const size = $derived(sizeOf(recipe.parameters, capability.sizes));
function setSize(name) {
@@ -61,9 +65,11 @@
</button>
{/if}
{#if open}
- <label title="Higher finds fainter signals, and more noise with them.">Sensitivity · {recipe.parameters.sensitivity}
- <input aria-label="Analyzer sensitivity" type="range" min="0" max="100" bind:value={recipe.parameters.sensitivity} />
- </label>
+ {#if !rules}
+ <label title="Higher finds fainter signals, and more noise with them.">Sensitivity · {recipe.parameters.sensitivity}
+ <input aria-label="Analyzer sensitivity" type="range" min="0" max="100" bind:value={recipe.parameters.sensitivity} />
+ </label>
+ {/if}
<div class="row">
<label class="grow" title="Drop candidates smaller than this.">Min area (m²)
<input aria-label="Minimum area" type="number" min="0" max="100000000" bind:value={recipe.parameters.min_area} />
@@ -79,7 +85,13 @@
</select>
</label>
{/if}
- {#if !single}
+ <label title="Keep only candidates of this shape, measured along their own length.">Shape
+ <select aria-label="Candidate shape" value={recipe.parameters.shape ?? 'any'}
+ onchange={(event) => (recipe.parameters = { ...recipe.parameters, shape: event.currentTarget.value })}>
+ {#each SHAPES as [id, label] (id)}<option value={id}>{label}</option>{/each}
+ </select>
+ </label>
+ {#if !single && !rules}
<label title="Keep what brightened, what darkened, or both.">Direction
<select bind:value={recipe.parameters.direction}><option value="both">Both</option><option value="gain">Gain</option><option value="loss">Loss</option></select>
</label>
@@ -91,10 +103,19 @@
<input aria-label="Cloud mask margin" type="range" min="0" max="10" bind:value={recipe.parameters.cloud_margin} />
</label>
{/if}
+ <!-- Cleanup and smoothing work on a difference, so a built-in that reads
+ one image has neither; rules of your own clean and smooth whatever they
+ read. Radar counts its smoothing on the ground. -->
<details>
- <summary>Noise and grouping</summary>
- <label title="Remove specks narrower than this; it also removes small real objects.">Noise cleanup · {recipe.parameters.cleanup}px<input type="range" min="0" max="3" bind:value={recipe.parameters.cleanup} /></label>
- <label title="Blur the reading first; zero keeps the finest detail.">Smoothing · {recipe.parameters.smoothing}px<input type="range" min="0" max="3" bind:value={recipe.parameters.smoothing} /></label>
+ <summary>{single && !rules ? 'Grouping' : 'Noise and grouping'}</summary>
+ {#if !single || rules}
+ <label title="Remove specks narrower than this; it also removes small real objects.">Noise cleanup · {recipe.parameters.cleanup}px<input type="range" min="0" max="3" bind:value={recipe.parameters.cleanup} /></label>
+ {#if capability.smoothing_m}
+ <label title="Average the radar over this much ground first; wider is quieter and coarser.">Averaging · {capability.smoothing_m * Math.max(1, recipe.parameters.smoothing)} m<input aria-label="Radar averaging" type="range" min="1" max="3" bind:value={recipe.parameters.smoothing} /></label>
+ {:else}
+ <label title="Blur the reading first; zero keeps the finest detail.">Smoothing · {recipe.parameters.smoothing}px<input type="range" min="0" max="3" bind:value={recipe.parameters.smoothing} /></label>
+ {/if}
+ {/if}
<label title="Join candidates this close; zero joins only touching ones.">Group within (m)<input type="number" min="0" max="500" bind:value={recipe.parameters.merge_metres} /></label>
</details>
{/if}
diff --git a/frontend/src/tools/detect/CheckMarks.render.test.js b/frontend/src/tools/detect/CheckMarks.render.test.js
new file mode 100644
index 0000000..6bd6d58
--- /dev/null
+++ b/frontend/src/tools/detect/CheckMarks.render.test.js
@@ -0,0 +1,37 @@
+// @vitest-environment happy-dom
+import { expect, it } from 'vitest';
+import { flushSync, mount, unmount } from 'svelte';
+import CheckMarks from './CheckMarks.svelte';
+
+it('pins each mark to its ground point, saying what it expects and how it came out', () => {
+ const engine = { on: () => () => {}, latLngToContainerPoint: ({ lon }) => ({ x: lon * 100, y: 50 }) };
+ const target = document.createElement('div');
+ document.body.append(target);
+ const live = mount(CheckMarks, { target, props: { engine, marks: [
+ { point: [1, 48], expect: 'found', ok: true },
+ { point: [2, 48], expect: 'empty', ok: false },
+ { point: [3, 48], expect: 'found', ok: null },
+ ] } });
+ flushSync();
+ const marks = [...target.querySelectorAll('.mark')];
+ expect(marks.map((mark) => mark.style.left)).toEqual(['100px', '200px', '300px']);
+ expect(marks.map((mark) => mark.getAttribute('aria-label'))).toEqual([
+ 'Should be found, and it is', 'Should stay empty, and it is not', 'Should be found']);
+ expect(marks[0].classList.contains('pass')).toBe(true);
+ expect(marks[1].classList.contains('fail')).toBe(true);
+ unmount(live);
+ target.remove();
+});
+
+it('draws the open check’s view as a frame with its name', () => {
+ const engine = { on: () => () => {}, latLngToContainerPoint: ({ lon, lat }) => ({ x: lon * 100, y: (50 - lat) * 100 }) };
+ const target = document.createElement('div');
+ document.body.append(target);
+ const live = mount(CheckMarks, { target, props: { engine, marks: [],
+ ground: { name: 'Check 4', bounds: { west: 1, south: 48, east: 2, north: 49 } } } });
+ flushSync();
+ expect(target.querySelector('polygon').getAttribute('points')).toBe('100,100 200,100 200,200 100,200');
+ expect(target.querySelector('.ground-name').textContent).toBe('Check 4');
+ unmount(live);
+ target.remove();
+});
diff --git a/frontend/src/tools/detect/CheckMarks.svelte b/frontend/src/tools/detect/CheckMarks.svelte
new file mode 100644
index 0000000..896c65a
--- /dev/null
+++ b/frontend/src/tools/detect/CheckMarks.svelte
@@ -0,0 +1,100 @@
+<script>
+ /**
+ * The check on the bench, on the ground: its view as a dashed frame with its
+ * name, and its pins, a filled ring where a candidate should come out and a
+ * struck ring where none should, green or red once the check has been read
+ * with the rules as they stand. The map keeps its clicks: this only shows.
+ */
+ let { engine, marks = [], ground = null } = $props();
+
+ let revision = $state(0);
+ $effect(() => {
+ if (!engine) return;
+ return engine.on('view-move', () => revision++);
+ });
+ const placed = $derived.by(() => {
+ revision;
+ return marks.map((mark) => ({
+ ...mark,
+ at: engine?.latLngToContainerPoint({ lon: mark.point[0], lat: mark.point[1] }) ?? { x: 0, y: 0 },
+ }));
+ });
+ /** The frame's four corners on screen, turned with the map if it is. */
+ const frame = $derived.by(() => {
+ revision;
+ if (!engine || !ground) return null;
+ const { west, south, east, north } = ground.bounds;
+ const corners = [[west, north], [east, north], [east, south], [west, south]]
+ .map(([lon, lat]) => engine.latLngToContainerPoint({ lon, lat }));
+ const top = corners.reduce((best, point) => (point.y < best.y ? point : best), corners[0]);
+ return { points: corners.map((point) => `${point.x},${point.y}`).join(' '), label: top };
+ });
+ const words = (mark) => `${mark.expect === 'found' ? 'Should be found' : 'Should stay empty'}${
+ mark.ok === true ? ', and it is' : mark.ok === false ? ', and it is not' : ''}`;
+</script>
+
+{#if frame}
+ <svg class="ground" aria-hidden="true"><polygon points={frame.points} /></svg>
+ <span class="ground-name" style:left={`${frame.label.x}px`} style:top={`${frame.label.y}px`}>{ground.name}</span>
+{/if}
+{#each placed as mark, i (i)}
+ <span class="mark pin-{mark.expect}" class:pass={mark.ok === true} class:fail={mark.ok === false}
+ style:left={`${mark.at.x}px`} style:top={`${mark.at.y}px`} title={words(mark)} aria-label={words(mark)}></span>
+{/each}
+
+<style>
+ .ground {
+ position: absolute;
+ inset: 0;
+ z-index: 550;
+ width: 100%;
+ height: 100%;
+ overflow: visible;
+ pointer-events: none;
+ }
+ .ground polygon { fill: rgb(255 255 255 / 0.04); stroke: #f8fafc; stroke-width: 1.5; stroke-dasharray: 6 4; }
+ .ground-name {
+ position: absolute;
+ z-index: 551;
+ padding: 1px 6px;
+ transform: translate(0, calc(-100% - 3px));
+ border-radius: 3px;
+ background: rgb(0 0 0 / 0.6);
+ color: #f8fafc;
+ font-size: 11px;
+ white-space: nowrap;
+ pointer-events: none;
+ }
+ .mark {
+ --ring: #f8fafc;
+ position: absolute;
+ z-index: 555;
+ width: 16px;
+ height: 16px;
+ transform: translate(-50%, -50%);
+ border: 2px solid var(--ring);
+ border-radius: 50%;
+ box-shadow: 0 0 0 1px rgb(0 0 0 / 0.65);
+ pointer-events: none;
+ }
+ .mark.pass { --ring: #4ade80; }
+ .mark.fail { --ring: #f87171; }
+ .mark.pin-found::after {
+ position: absolute;
+ inset: 4px;
+ border-radius: 50%;
+ background: var(--ring);
+ content: '';
+ }
+ .mark.pin-empty { border-style: dashed; }
+ .mark.pin-empty::after {
+ position: absolute;
+ top: 50%;
+ left: -2px;
+ width: 16px;
+ height: 2px;
+ background: var(--ring);
+ transform: rotate(-45deg);
+ content: '';
+ }
+</style>
diff --git a/frontend/src/tools/detect/DetectDetection.svelte b/frontend/src/tools/detect/DetectDetection.svelte
index 6ed7cfd..c58a430 100644
--- a/frontend/src/tools/detect/DetectDetection.svelte
+++ b/frontend/src/tools/detect/DetectDetection.svelte
@@ -10,7 +10,7 @@
* choice costs a Copernicus request and an analyst usually knows which day
* they are chasing.
*/
- import { STRENGTHS, describeMeasure } from '../../lib/map/analyzers.js';
+ import { STRENGTHS, readingOf } from '../../lib/map/analyzers.js';
import { isActive, plural, ruleLabel, runState } from '../../lib/map/detections.js';
import Icon from '../../components/Icon.svelte';
@@ -32,11 +32,11 @@
let tab = $state('findings');
const methodOf = (method) => methods.find((m) => m.id === method) ?? {};
- const single = $derived(!!methodOf(detection.method).single);
+ const single = $derived(detection.single ?? !!methodOf(detection.method).single);
const state = $derived(runState(detection.active ?? detection.latest));
const reading = (row) => [
STRENGTHS[row.strength],
- describeMeasure(methodOf(detection.method).measure, row.measure, detail?.recipe?.parameters?.index),
+ readingOf(detail?.recipe ?? { method: detection.method }, methods, row.measure),
].filter(Boolean).join(' · ');
</script>
diff --git a/frontend/src/tools/detect/DetectHome.svelte b/frontend/src/tools/detect/DetectHome.svelte
index bb54527..ce7d145 100644
--- a/frontend/src/tools/detect/DetectHome.svelte
+++ b/frontend/src/tools/detect/DetectHome.svelte
@@ -91,7 +91,7 @@
</div>
{#if item.note}<p class="note">{item.note}</p>{/if}
<p class="meta">{[item.analyzer, plural(item.areas ?? 0, 'area'),
- ruleLabel(item.date_rule, single(item.method))].filter(Boolean).join(' · ')}</p>
+ ruleLabel(item.date_rule, item.single ?? single(item.method))].filter(Boolean).join(' · ')}</p>
<p class={`state ${state.tone}`}>{state.text}</p>
{#if item.active?.status === 'running'}
<progress max={item.active.total || 1} value={item.active.progress ?? 0}></progress>
diff --git a/frontend/src/tools/detect/DetectPanel.svelte b/frontend/src/tools/detect/DetectPanel.svelte
index dc97d7b..39fa115 100644
--- a/frontend/src/tools/detect/DetectPanel.svelte
+++ b/frontend/src/tools/detect/DetectPanel.svelte
@@ -10,11 +10,13 @@
* Opening the panel reads local state only. Starting a run is what fetches
* imagery.
*/
- import { onMount, untrack } from 'svelte';
+ import { onMount, tick, untrack } from 'svelte';
import { api } from '../../lib/api.js';
import { ensureCase, reloadCase, toast } from '../../lib/state.svelte.js';
import { detectRuns, refreshRuns } from '../../lib/detectRuns.svelte.js';
- import { clone } from '../../lib/map/analyzers.js';
+ import { clone, zoneRing } from '../../lib/map/analyzers.js';
+ import { recipeCapability } from '../../lib/map/analyzerRules.js';
+ import { containsPoint } from '../../lib/measure.js';
import { detectionsWithRuns, isActive, plural } from '../../lib/map/detections.js';
import AnalyzerLibrary from './AnalyzerLibrary.svelte';
import DetectDetection from './DetectDetection.svelte';
@@ -37,6 +39,11 @@
showZones = $bindable(true),
/** The candidate the review is on, so the map can ring the same one. */
selectedResult = $bindable(null),
+ /** The review's eye and blink (DetectReview), which only a review holds. */
+ bare = $bindable(false),
+ blinking = $bindable(false),
+ /** Whether a run's results are open, which holds the map on them. */
+ reviewing = $bindable(false),
/** Every watched area of the case, for the map to draw while the list is up. */
areaGroups = $bindable([]),
/** The areas the pointer is on, drawn heavier on the map. */
@@ -45,12 +52,26 @@
opening = null,
onopened = () => {},
onfocus = () => {},
- /** Frame a set of areas on the map, so opening a routine shows all of it. */
+ /** Frame a set of areas on the map, so opening a routine shows all of it.
+ * `{ landing: true }` marks the once-per-case framing on arrival. */
onframe = () => {},
onusecurrentview = () => {},
/** Put a Copernicus pass on the map, so the picture matches the work. */
onshow = () => {},
onleavepass = () => {},
+ /** The passes the candidate under review was read between, or null. */
+ onpair = () => {},
+ /** What the map draws while an analyzer of your own is built (AnalyzerBuilder). */
+ builder = $bindable(null),
+ /** Blink A and B on the map for the builder: `onblink({ a, b })`, or null to stop. */
+ onblink = () => {},
+ /** The map's view, for the builder to preview on. */
+ viewBounds = () => null,
+ /** The settled camera, the Copernicus layers on offer and a way to frame a
+ * place, which the builder's preview and checks use. */
+ mapView = null,
+ passLayers = [],
+ onfly = () => {},
} = $props();
const TITLES = { new: 'New detection', review: 'Results', library: 'Analyzers' };
@@ -66,6 +87,16 @@
let view = $state('home');
let tab = $state('routines');
let picking = $state(false);
+ let newActionEl = $state(null);
+ // Pointerdown in the capture phase, so a press on the map still closes it.
+ $effect(() => {
+ if (!picking) return;
+ const outside = (event) => {
+ if (newActionEl && !newActionEl.contains(event.target)) picking = false;
+ };
+ document.addEventListener('pointerdown', outside, true);
+ return () => document.removeEventListener('pointerdown', outside, true);
+ });
/** The wizard's starting point while one is open; a new object mounts a fresh one. */
let draft = $state(null);
/** Where the library goes back to, and where the review returns to. */
@@ -89,11 +120,19 @@
const runs = $derived(detectRuns.caseId === caseId ? detectRuns.rows : []);
const routines = $derived(detectionsWithRuns(lists.followups, runs));
const detection = $derived(routines.find((row) => row.id === detectionId) ?? null);
- const methodOf = (method) => catalogue?.methods?.find((m) => m.id === method) ?? {};
+ /** What a recipe's method can do; an analyzer of your own answers from its rules. */
+ const capabilityOf = (recipe) => recipeCapability(recipe, catalogue?.methods ?? []);
const pending = $derived(isActive(current));
+ let library = $state(null);
const kindTitle = $derived(draft?.kind === 'routine' ? (draft.followupId ? 'Edit routine' : 'New routine') : 'New pass');
$effect(() => { selectedResult = view === 'review' ? candidateId : null; });
+ $effect(() => { reviewing = view === 'review'; });
+ $effect(() => {
+ if (view === 'review') return;
+ bare = false;
+ blinking = false;
+ });
// The map draws every watched area while the list is up, and only the open
// detection's or run's ground once one is open: what is on screen is what is
// in hand. One drawing either way, in the area's own colour, so the same
@@ -140,7 +179,7 @@
// that the camera is the analyst's.
if (!framed && areas.length) {
framed = true;
- onframe(areas.map(areaZone));
+ onframe(areas.map(areaZone), { landing: true });
}
}
@@ -213,11 +252,15 @@
});
$effect(() => {
- if (!opening || !caseId) return;
+ // Analyzers belong to every case, so one opens with no case at all.
+ if (!opening || (!caseId && !opening.startsWith('analyzer:'))) return;
const match = /^(areas|zones|followups|runs)-([a-f0-9]{12})$/.exec(opening);
+ // An analyzer kept from elsewhere (Compare's Difference) opens in the library.
+ const analyzer = /^analyzer:(custom-[a-f0-9]{12})$/.exec(opening);
untrack(() => {
onopened();
if (match) void act(() => openItem(match[1], match[2]));
+ else if (analyzer) void act(() => openAnalyzer(analyzer[1]));
});
});
@@ -315,6 +358,15 @@
startWizard({ kind: 'once', body: { ...clone(current.input), followup_id: null }, fromRun: true });
}
+ async function openAnalyzer(id) {
+ collapsed = false;
+ await loadCatalogue();
+ libraryFrom = 'home';
+ view = 'library';
+ await tick();
+ library?.openEntry(id);
+ }
+
function openLibrary() {
libraryFrom = view === 'new' ? 'new' : view === 'detection' ? 'detection' : 'home';
view = 'library';
@@ -444,7 +496,13 @@
export async function addManual(geometry) {
if (!manual || !current) return;
- const areaId = manual.areaId;
+ await addCandidate(manual.areaId, geometry);
+ }
+
+ /** Record a candidate the detector missed, on one of the open run's areas. */
+ export async function addCandidate(areaId, geometry) {
+ if (!current) return;
+ collapsed = false;
await act(async () => {
const row = await api.post(`${base()}/runs/${current.id}/results`, { area_id: areaId, geometry });
acceptRun({ ...current, results: [...current.results, row], count: current.count + 1 });
@@ -453,6 +511,28 @@
});
}
+ /**
+ * The area of the open run a point falls in, if the run read it: where a
+ * right-click can add a candidate. Null when no finished run is under review.
+ */
+ export function candidateAreaAt({ lat, lon }) {
+ if (view !== 'review' || current?.status !== 'ready') return null;
+ const read = (zone) => !current.area_runs
+ || current.area_runs.some((pair) => pair.area_id === zone.id && pair.status === 'ready');
+ const inside = (zone) => containsPoint(zoneRing(zone).map(([x, y]) => ({ lat: y, lon: x })), { lat, lon });
+ return current.input.zones.find((zone) => read(zone) && inside(zone))?.id ?? null;
+ }
+
+ /** Read every rule of the analyzer being built at a point of the map, and
+ * mark that point in one of its checks. */
+ export function probeAt(point) { return library?.probeAt(point); }
+ export function closeProbe() { library?.closeProbe(); }
+ export function markProbe(expect) { library?.markProbe(expect); }
+ /** The builder's pins, and its passes under the preview, from the map. */
+ export function pinAt(point) { library?.pinAt(point); }
+ export function pinMode(mode) { library?.pinMode(mode); }
+ export function showPass(which) { library?.showPass(which); }
+
/** A candidate picked on the map opens its review. */
export function pick(runId, resultId) {
collapsed = false;
@@ -484,7 +564,7 @@
onclick={openLibrary}><Icon name="sliders" size={15} /></button>
</nav>
<div class="dock-content" hidden={collapsed}>
- <div class="new-action">
+ <div class="new-action" bind:this={newActionEl}>
<button class="btn btn-primary" aria-expanded={picking} onclick={() => (picking = !picking)}><Icon name="plus" size={14} /> New detection</button>
{#if picking}
<!-- The kind is the first question because it changes every one after
@@ -573,6 +653,7 @@
{#if error}<p class="warn" role="alert">{error}</p>{/if}
{#if current}
<DetectReview {caseId} run={current} methods={catalogue.methods} active={!collapsed} bind:candidateId
+ bind:bare bind:blinking {onpair}
onaccept={afterVerdict} {onfocus} {onshow} onedit={editRun}
onadd={(areaId, kind) => {
manual = { areaId, kind };
@@ -586,7 +667,8 @@
{/if}
</div>
{:else if view === 'library'}
- <AnalyzerLibrary {catalogue} onchanged={loadCatalogue}
+ <AnalyzerLibrary bind:this={library} {catalogue} onchanged={loadCatalogue} bind:builder {viewBounds} {onshow} {onleavepass}
+ {mapView} layers={passLayers} {onfly} {onblink}
onsaved={(recipe) => { if (draft) offer = recipe.id; }} />
{/if}
{/if}
@@ -595,8 +677,8 @@
{#if launch}
<Modal title={`Run ${launch.title}`} width="760px" onclose={() => { launch = null; onleavepass(); }}>
- <AreaDates zones={launch.zones} bind:pairs={launch.area_dates} single={!!methodOf(launch.recipe.method).single}
- sensor={methodOf(launch.recipe.method).sensor} {onshow} />
+ <AreaDates zones={launch.zones} bind:pairs={launch.area_dates} single={!!capabilityOf(launch.recipe).single}
+ sensor={capabilityOf(launch.recipe).sensor} {onshow} />
{#if error}<p class="warn" role="alert">{error}</p>{/if}
<button class="btn btn-primary" disabled={busy} onclick={() => act(() => runDetection(launch, { area_dates: clone(launch.area_dates) }))}>
{launch.zones.length > 1 ? `Run ${plural(launch.zones.length, 'area')}` : 'Run this area'}
diff --git a/frontend/src/tools/detect/DetectPanel.test.js b/frontend/src/tools/detect/DetectPanel.test.js
index a3c24c0..45b108c 100644
--- a/frontend/src/tools/detect/DetectPanel.test.js
+++ b/frontend/src/tools/detect/DetectPanel.test.js
@@ -32,6 +32,7 @@ vi.mock('../../lib/api.js', () => ({ api: { get, post, patch, put, del } }));
vi.mock('../../lib/state.svelte.js', () => ({ ensureCase: async () => ({ id: 'case-a' }),
reloadCase: async () => {}, toast, uiState: {}, prefs: { units: 'metric' } }));
const { default: Panel } = await import('./DetectPanel.svelte');
+const { liveProps } = await import('./props.fixture.svelte.js');
const { refreshRuns } = await import('../../lib/detectRuns.svelte.js');
let live, target;
@@ -55,7 +56,7 @@ const runRow = (extra = {}) => ({ id: RUN, title: 'Harbour weekly', followup_id:
created_at: '2026-09-06T10:00:00Z', ...extra });
const finding = (extra = {}) => ({ id: '0-1', run_id: RUN, run_title: 'Harbour weekly', date: '2026-09-06',
coordinates: [42.95, 14.81], phenomenon: 'Vessel candidate', strength: 'strong', measure: { value: 6.2 },
- review: 'noted', area: 90, width: 15, height: 6, ...extra });
+ review: 'noted', area: 90, ...extra });
/** A GET answered from a table of paths, with the libraries empty by default. */
function answer(table = {}) {
@@ -106,6 +107,15 @@ it('asks which kind before asking anything else', async () => {
expect(target.textContent).toContain('New pass');
});
+it('closes the kind menu on a press anywhere else', async () => {
+ await open();
+ button('New detection').click(); await settle();
+ labelled('New one pass').dispatchEvent(new PointerEvent('pointerdown', { bubbles: true })); await settle();
+ expect(labelled('New one pass')).not.toBe(null);
+ document.body.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true })); await settle();
+ expect(labelled('New one pass')).toBe(null);
+});
+
it('shows a routine with what it is for and where its last run stands', async () => {
answer({ '/api/cases/case-a/analysis/followups': [watchRow()], '/api/cases/case-a/analysis/runs': [runRow()],
[`/api/cases/case-a/analysis/followups/${WATCH}`]: watchBody() });
@@ -532,7 +542,7 @@ it('makes an analyzer of its own from the closest built-in, and never writes ove
post.mockImplementation(async (_, body) => ({ ...body, id: 'custom-copy' }));
await open();
labelled('Analyzers').click(); await settle();
- expect(target.textContent).toContain('Yours start as a copy of the closest built-in.');
+ expect(target.textContent).toContain('build your own from rules you try on the map, or copy a calibrated built-in');
starts('Vessels').click(); await settle();
expect(target.textContent).toContain('Measures Vessels: infrared contrast over water');
expect(button('Save changes')).toBeUndefined();
@@ -540,7 +550,7 @@ it('makes an analyzer of its own from the closest built-in, and never writes ove
button('Back').click(); await settle();
button('New analyzer').click(); await settle();
- expect(heading()).toBe('Start from');
+ expect(heading()).toBe('Or start from a built-in');
[...target.querySelectorAll('button.base')].find((b) => b.textContent.includes(recipe.name)).click(); await settle();
const name = target.querySelector('[aria-label="Analyzer name"]');
expect(name.value).toBe(`${recipe.name} copy`);
@@ -562,11 +572,346 @@ it('edits and removes an analyzer of its own', async () => {
expect(del).toHaveBeenCalledWith('/api/compare/analyzers/custom-1');
});
+// -- analyzers of your own rules ------------------------------------------------------
+
+const rulesMethods = [...methods, { id: 'rules', label: 'Your own rules', single: false, clouds: true,
+ sensor: 'sentinel2', frames: 4, sizes, measure: '', rules: true },
+{ id: 'sar-change', label: 'Radar change', single: false, clouds: false, sensor: 'sentinel1', frames: 4,
+ sizes, measure: '', smoothing_m: 45 }];
+const rulesCatalogue = (extra = {}) => catalogue({ methods: rulesMethods, rules: {
+ bands: ['B02', 'B03', 'B04', 'B08', 'B11', 'B12'], classes: ['vegetation', 'bare', 'water'],
+ max_rules: 6, max_bands: 6, max_around: 300, max_checks: 12, max_marks: 20, preview_span: 3 }, ...extra });
+const VIEW = { west: 2, south: 48, east: 2.05, north: 48.03 };
+const PREVIEWED = { ready: true, missing: 0, tiles: [[4230, 2930]], clipped: false,
+ box: { west: 0, south: 0, east: 1, north: 1 }, size: [512, 512], mask: '', measured: 0.9,
+ rules: [{ share: 0.012, kept: 0.012 }], kept: 0.01, count: 1, note: '',
+ candidates: [{ id: '0-1', coordinates: [2.01, 48.01], bbox: [2.01, 48.01, 2.011, 48.011], area: 900,
+ margin: 4, strength: 'strong', measure: {}, geometry: null }] };
+const debounce = (ms = 320) => new Promise((resolve) => setTimeout(resolve, ms));
+const phrase = () => [...target.querySelectorAll('.phrase')].map((p) => p.textContent.trim())[0];
+const tab = (name) => [...target.querySelectorAll('[role="tab"]')].find((b) => b.textContent.trim().startsWith(name));
+const rule = (extra = {}) => ({ measure: 'index', index: 'nbr', bands: ['B08', 'B04'], band: 'B08', polarisation: 'vv',
+ classes: [], on: 'change', op: 'le', value: -0.2, upper: 0, around: 0, ...extra });
+
+function copernicus(previewed = PREVIEWED, checked = () => ({ ready: true, missing: 0, count: 1, covered: [true] })) {
+ post.mockImplementation(async (path, body) => {
+ if (path === '/api/satellite/sentinel/acquisitions') {
+ return { dates: [{ date: '2026-05-11', cloud: 5, coverage: 1 }, { date: '2026-05-04', cloud: 3, coverage: 1 }], truncated: false };
+ }
+ if (path === '/api/compare/analyzers/preview') {
+ return body.read ? previewed : { ready: false, missing: 2, tiles: [[4230, 2930]], clipped: false, box: {}, size: [512, 512] };
+ }
+ if (path === '/api/compare/analyzers/probe') {
+ return { ready: true, imaged: true, measured: true, kept: true, rules: [{ passes: true, value: -0.6, before: 0.8, after: 0.2 }] };
+ }
+ if (path === '/api/compare/analyzers/check') return checked(body);
+ return { ...body, id: 'custom-aaaaaaaaaaaa' };
+ });
+}
+
+async function openBuilder(props = {}) {
+ await open({ viewBounds: () => VIEW, ...props });
+ labelled('Analyzers').click(); await settle();
+ button('New analyzer').click(); await settle();
+ starts('Build your own rules').click(); await settle();
+}
+
+/** Pick the two passes of the view and read its frames. */
+async function readTheView() {
+ button('Find passes').click(); await settle();
+ target.querySelector('[aria-label="Use 2026-05-04"] button').click(); await settle();
+ target.querySelectorAll('[aria-label="Use 2026-05-11"] button')[1].click(); await settle();
+ await debounce(); await settle();
+ button('Show the detections here').click(); await settle();
+}
+
+it('builds an analyzer from rules, tries it on the view, reads a point and keeps it for every case', async () => {
+ answer({ '/api/compare/analyzers': rulesCatalogue() });
+ copernicus();
+ await openBuilder();
+ expect(heading()).toBe('Build an analyzer');
+ expect(target.textContent).toContain('Pick pass A and pass B to try the rules on.');
+ expect(phrase()).toBe('Keeps ground where NDVI dropped by 0.25 or more, outside cloud.');
+ expect(tab('Rules').getAttribute('aria-selected')).toBe('true');
+ // building reads nothing: the pass lookup and the frames each wait to be asked for
+ await debounce(); await settle();
+ expect(post).not.toHaveBeenCalled();
+
+ button('Find passes').click(); await settle();
+ expect(post).toHaveBeenCalledWith('/api/satellite/sentinel/acquisitions', expect.objectContaining({ collection: 'sentinel2' }));
+ target.querySelector('[aria-label="Use 2026-05-04"] button').click(); await settle();
+ target.querySelectorAll('[aria-label="Use 2026-05-11"] button')[1].click(); await settle();
+ await debounce(); await settle();
+ const asked = post.mock.calls.filter(([path]) => path === '/api/compare/analyzers/preview');
+ expect(asked).toHaveLength(1);
+ expect(asked[0][1]).toMatchObject({ read: false, a: { date: '2026-05-04' }, b: { date: '2026-05-11' }, bounds: VIEW,
+ recipe: { method: 'rules', match: 'all' } });
+ expect(target.textContent).toContain('2 frames from Copernicus, one request each.');
+
+ button('Show the detections here').click(); await settle();
+ expect(post).toHaveBeenLastCalledWith('/api/compare/analyzers/preview', expect.objectContaining({ read: true }));
+ expect(target.textContent).toContain('1 candidate on the map');
+ expect(target.textContent).toContain('1.2 % of the ground');
+
+ await live.probeAt({ lon: 2.01, lat: 48.01 }); await settle();
+ expect(post).toHaveBeenLastCalledWith('/api/compare/analyzers/probe', expect.objectContaining({ point: [2.01, 48.01] }));
+
+ expect(button('Add to my analyzers').disabled).toBe(true);
+ const name = target.querySelector('[aria-label="Analyzer name"]');
+ name.value = 'Cleared ground'; name.dispatchEvent(new Event('input', { bubbles: true })); await settle();
+ button('Add to my analyzers').click(); await settle();
+ expect(post).toHaveBeenCalledWith('/api/compare/analyzers', expect.objectContaining({
+ id: 'custom', method: 'rules', name: 'Cleared ground', match: 'all', checks: [],
+ description: 'Keeps ground where NDVI dropped by 0.25 or more, outside cloud.',
+ rules: [expect.objectContaining({ measure: 'index', index: 'ndvi', on: 'change', op: 'le', value: -0.25 })] }));
+ // no check was asked for, so none was read
+ expect(post.mock.calls.some(([path]) => path === '/api/compare/analyzers/check')).toBe(false);
+});
+
+const EXAMPLE = { id: 'burn', place: 'Lahaina, Maui', when: 'August 2023', recipe: {
+ id: 'custom', name: 'Fresh burn', description: 'The burn ratio dropped.', phenomenon: 'Fresh burn', method: 'rules',
+ colour: '#ef4444', style: 'both', match: 'all', parameters: { ...recipe.parameters, shape: 'any', merge_metres: 30 },
+ rules: [rule(), rule({ on: 'b', value: 0.1 })],
+ checks: [
+ { id: 'town', name: 'The town that burned', a: { provider: 'sentinel2', date: '2023-08-08', layer: 'SWIR', maxcc: 100 },
+ b: { provider: 'sentinel2', date: '2023-08-13', layer: 'SWIR', maxcc: 100 },
+ bounds: { west: -156.69, south: 20.86, east: -156.66, north: 20.90 },
+ marks: [{ point: [-156.675, 20.872], expect: 'found' }, { point: [-156.675, 20.894], expect: 'found' }], result: null },
+ { id: 'reef', name: 'The reef off the town', a: { provider: 'sentinel2', date: '2023-08-08', layer: 'SWIR', maxcc: 100 },
+ b: { provider: 'sentinel2', date: '2023-08-13', layer: 'SWIR', maxcc: 100 },
+ bounds: { west: -156.69, south: 20.85, east: -156.66, north: 20.87 },
+ marks: [{ point: [-156.6753, 20.865], expect: 'empty' }], result: null },
+ ] } };
+
+it('starts from an example: copies it with its checks, opens on them and reads them when asked', async () => {
+ answer({ '/api/compare/analyzers': rulesCatalogue({ examples: [EXAMPLE] }) });
+ let reads = 0;
+ copernicus(PREVIEWED, (body) => {
+ if (!body.read) return { ready: false, missing: 2 };
+ reads++;
+ // the reef gets a candidate on it: the check that should stay empty does not
+ return { ready: true, missing: 0, count: 3, covered: body.check.id === 'town' ? [true, true] : [true] };
+ });
+ const onfly = vi.fn();
+ const onshow = vi.fn();
+ await open({ viewBounds: () => VIEW, onfly, onshow });
+ labelled('Analyzers').click(); await settle();
+ button('New analyzer').click(); await settle();
+ expect(target.textContent).toContain('Start from an example');
+ expect(target.textContent).toContain('Lahaina, Maui · August 2023 · 2 checks');
+ labelled('Start from the example Fresh burn').click(); await settle();
+
+ // it is in the library at once, under a name of its own, checks and all
+ expect(post).toHaveBeenCalledWith('/api/compare/analyzers', expect.objectContaining({
+ id: 'custom', name: 'Fresh burn', checks: EXAMPLE.recipe.checks }));
+ expect(toast).toHaveBeenCalledWith('Fresh burn is in your analyzers, with its checks', 'ok');
+ expect(heading()).toBe('Edit Fresh burn');
+ expect(tab('Checks').getAttribute('aria-selected')).toBe('true');
+ // the first check is on the bench: its ground, its passes, B in its layer
+ expect(onfly).toHaveBeenCalledWith({ bounds: EXAMPLE.recipe.checks[0].bounds });
+ expect(onshow).toHaveBeenLastCalledWith({ provider: 'sentinel2', date: '2023-08-13', layer: 'SWIR', maxcc: 100 });
+ expect(target.textContent).toContain('A 2023-08-08 → B 2023-08-13');
+
+ // the cache is read on its own; what it lacks waits for Run all, which says the cost
+ await debounce(900); await settle();
+ const dry = post.mock.calls.filter(([path, body]) => path === '/api/compare/analyzers/check' && !body.read);
+ expect(dry).toHaveLength(2);
+ expect(dry[0][1]).toMatchObject({ recipe: { method: 'rules' }, check: { id: 'town', result: null } });
+ expect(reads).toBe(0);
+ expect(starts('Run all').textContent.trim()).toBe('Run all · up to 4 requests');
+ expect(target.textContent).toContain('2 frames to read');
+
+ starts('Run all').click(); await settle();
+ expect(reads).toBe(2);
+ expect(target.textContent).toContain('2 of 2 found');
+ expect(target.textContent).toContain('1 of 1 flagged');
+ expect(tab('Checks').textContent.replace(/\s+/g, '')).toBe('Checks1/2');
+});
+
+it('marks a point read on the map in a check, which turns red when a rule loses it', async () => {
+ answer({ '/api/compare/analyzers': rulesCatalogue() });
+ let found = true;
+ copernicus(PREVIEWED, () => ({ ready: true, missing: 0, count: 1, covered: [found] }));
+ await openBuilder();
+ await readTheView();
+ await live.probeAt({ lon: 2.01, lat: 48.01 }); await settle();
+ live.markProbe('found'); await settle();
+
+ // no check was on the bench, so the view became one, with the passes shown
+ expect(tab('Checks').getAttribute('aria-selected')).toBe('true');
+ expect(target.textContent).toContain('Check 1');
+ await debounce(900); await settle();
+ const first = post.mock.calls.filter(([path]) => path === '/api/compare/analyzers/check').at(-1)[1];
+ expect(first).toMatchObject({ read: false, check: { name: 'Check 1', bounds: VIEW,
+ a: { date: '2026-05-04' }, b: { date: '2026-05-11' }, marks: [{ point: [2.01, 48.01], expect: 'found' }] } });
+ expect(target.textContent).toContain('1 of 1 found');
+ // the result written back asks for no other read, and a read from the cache never says Reading…
+ const reads = () => post.mock.calls.filter(([path]) => path === '/api/compare/analyzers/check').length;
+ const settled = reads();
+ await debounce(1600); await settle();
+ expect(reads()).toBe(settled);
+ expect(target.textContent).not.toContain('Reading…');
+
+ // a stricter line loses it: the check is reread from the cache and says so
+ found = false;
+ tab('Rules').click(); await settle();
+ const value = target.querySelector('[aria-label="Rule 1 value"]');
+ value.value = '-0.6'; value.dispatchEvent(new Event('change', { bubbles: true })); await settle();
+ await debounce(900); await settle();
+ tab('Checks').click(); await settle();
+ expect(target.textContent).toContain('0 of 1 found');
+ expect(tab('Checks').textContent.replace(/\s+/g, '')).toBe('Checks0/1');
+
+ const name = target.querySelector('[aria-label="Analyzer name"]');
+ name.value = 'Cleared ground'; name.dispatchEvent(new Event('input', { bubbles: true })); await settle();
+ button('Add to my analyzers').click(); await settle();
+ const saved = post.mock.calls.find(([path]) => path === '/api/compare/analyzers')[1];
+ expect(saved.checks).toEqual([expect.objectContaining({ name: 'Check 1',
+ result: expect.objectContaining({ count: 1, covered: [false] }) })]);
+ expect(saved.checks[0].result.signature).toMatch(/^[0-9a-z]+$/);
+});
+
+it('adds a check where the map is: pick its passes, drop pins with the map, done', async () => {
+ answer({ '/api/compare/analyzers': rulesCatalogue() });
+ copernicus();
+ let view = VIEW;
+ const props = liveProps({ caseId: 'case-a', viewBounds: () => view, mapView: { lat: 48, lon: 2, zoom: 13 } });
+ live = mount(Panel, { target, props });
+ await settle();
+ labelled('Analyzers').click(); await settle();
+ button('New analyzer').click(); await settle();
+ starts('Build your own rules').click(); await settle();
+ const name = target.querySelector('[aria-label="Analyzer name"]');
+ name.value = 'Cleared ground'; name.dispatchEvent(new Event('input', { bubbles: true })); await settle();
+ tab('Checks').click(); await settle();
+
+ starts('Add a check').click(); await settle();
+ expect(target.textContent).toContain('Check 1');
+ expect(target.textContent).toContain('None yet: until it has pins, this check is where the map is.');
+ // a check still being placed follows the map, and keeps the analyzer from being saved half made
+ expect(button('Add to my analyzers').disabled).toBe(true);
+ expect(target.textContent).toContain('“Check 1” needs its passes.');
+ view = { west: 139.6, south: 35.6, east: 139.7, north: 35.7 };
+ props.mapView = { lat: 35.65, lon: 139.65, zoom: 13 }; await settle();
+
+ // its dates are the passes picked now
+ button('Find passes').click(); await settle();
+ expect(post).toHaveBeenCalledWith('/api/satellite/sentinel/acquisitions', expect.objectContaining({
+ zones: [expect.objectContaining({ points: expect.arrayContaining([[139.6, 35.7]]) })] }));
+ target.querySelector('[aria-label="Use 2026-05-04"] button').click(); await settle();
+ target.querySelectorAll('[aria-label="Use 2026-05-11"] button')[1].click(); await settle();
+ expect(target.textContent).toContain('A 2026-05-04 → B 2026-05-11');
+
+ // arm a pin, and each click on the map drops one
+ button('Should be found').click(); await settle();
+ expect(button('Should be found').getAttribute('aria-pressed')).toBe('true');
+ live.pinAt({ lon: 139.65, lat: 35.65 }); await settle();
+ button('Should stay empty').click(); await settle();
+ live.pinAt({ lon: 139.62, lat: 35.66 }); await settle();
+ live.pinAt({ lon: 139.68, lat: 35.62 }); await settle();
+ expect([...target.querySelectorAll('.marks li')].map((li) => li.textContent.trim())).toEqual(
+ ['Should be found', 'Should stay empty', 'Should stay empty']);
+ labelled('Remove pin 3').click(); await settle();
+ button('Done').click(); await settle();
+ expect(target.querySelector('.editor')).toBe(null);
+ live.pinAt({ lon: 139.66, lat: 35.66 }); await settle(); // no check open: the click drops nothing
+
+ button('Add to my analyzers').click(); await settle();
+ const saved = post.mock.calls.find(([path]) => path === '/api/compare/analyzers')[1];
+ expect(saved.checks).toEqual([expect.objectContaining({ name: 'Check 1',
+ a: expect.objectContaining({ date: '2026-05-04' }), b: expect.objectContaining({ date: '2026-05-11' }),
+ bounds: expect.objectContaining({ west: 139.6, east: 139.7 }),
+ marks: [{ point: [139.65, 35.65], expect: 'found' }, { point: [139.62, 35.66], expect: 'empty' }] })]);
+});
+
+it('opens the reading card anywhere, and a point far off the open check starts a check of its own', async () => {
+ answer({ '/api/compare/analyzers': rulesCatalogue() });
+ copernicus();
+ await openBuilder();
+ // nothing picked yet: the card still opens and says why nothing is read
+ await live.probeAt({ lon: 2.01, lat: 48.01 }); await settle();
+ await readTheView();
+ await live.probeAt({ lon: 2.01, lat: 48.01 }); await settle();
+ live.markProbe('found'); await settle();
+ expect(target.textContent).toContain('Check 1');
+ await live.probeAt({ lon: 2.4, lat: 48.4 }); await settle();
+ live.markProbe('empty'); await settle();
+ expect(target.textContent).toContain('Check 2');
+});
+
+it('shows the passes in any Copernicus layer, and suggests the one that reads rule ★', async () => {
+ answer({ '/api/compare/analyzers': rulesCatalogue() });
+ copernicus();
+ const onshow = vi.fn();
+ await openBuilder({ onshow, passLayers: [{ id: 'TRUE_COLOR', label: 'True colour' }, { id: 'SWIR', label: 'SWIR' }, { id: 'NDVI', label: 'NDVI' }] });
+ button('Find passes').click(); await settle();
+ target.querySelector('[aria-label="Use 2026-05-11"] button:nth-child(2)').click(); await settle();
+ expect(onshow).toHaveBeenLastCalledWith(expect.objectContaining({ date: '2026-05-11', layer: 'TRUE_COLOR' }));
+ const layer = target.querySelector('[aria-label="Copernicus layer"]');
+ layer.value = 'SWIR'; layer.dispatchEvent(new Event('change', { bubbles: true })); await settle();
+ expect(onshow).toHaveBeenLastCalledWith(expect.objectContaining({ date: '2026-05-11', layer: 'SWIR' }));
+ starts('Show it in NDVI').click(); await settle();
+ expect(onshow).toHaveBeenLastCalledWith(expect.objectContaining({ layer: 'NDVI' }));
+ expect(starts('Show it in')).toBeUndefined();
+});
+
+it('adds, ranks, rewrites and removes rules, and the sentence follows', async () => {
+ answer({ '/api/compare/analyzers': rulesCatalogue() });
+ await openBuilder();
+ button('Add a rule').click(); await settle();
+ expect(phrase()).toBe('Keeps ground where NDVI dropped by 0.25 or more and NDVI on B at least 0.40, outside cloud.');
+ button('any').click(); await settle();
+ expect(phrase()).toContain('or NDVI on B at least 0.40');
+ labelled('Rank candidates by rule 2').click(); await settle();
+ expect(phrase()).toMatch(/^Keeps ground where NDVI on B at least 0.40 or NDVI dropped/);
+ const measure = target.querySelector('[aria-label="Rule 2 measures"]');
+ measure.value = 'band'; measure.dispatchEvent(new Event('change', { bubbles: true })); await settle();
+ expect(phrase()).toContain('B08 (near infrared) moved by 5.0% or more either way');
+ labelled('Remove rule 1').click(); await settle();
+ expect(phrase()).toBe('Keeps ground where B08 (near infrared) moved by 5.0% or more either way, outside cloud.');
+ expect(labelled('Remove rule 1')).toBe(null); // the last rule stays
+ // size, description and label live under Settings
+ tab('Settings').click(); await settle();
+ expect(target.textContent).toContain('Size and grouping');
+ expect(target.querySelector('textarea').placeholder).toBe(phrase());
+});
+
+it('opens a calibrated index built-in as the rules it applies', async () => {
+ const asRules = { id: 'custom', name: 'Any surface change (rules)', description: '', phenomenon: 'Surface change',
+ method: 'rules', colour: '#f6a81a', style: 'both', parameters: { ...recipe.parameters, shape: 'any' }, match: 'all',
+ rules: [rule({ value: -0.27 })], checks: [] };
+ answer({ '/api/compare/analyzers': rulesCatalogue({ as_rules: { 'large-change': asRules } }) });
+ await open({ viewBounds: () => VIEW });
+ labelled('Analyzers').click(); await settle();
+ button('New analyzer').click(); await settle();
+ labelled('Open Any surface change as rules').click(); await settle();
+ expect(heading()).toBe('Build an analyzer');
+ expect(target.querySelector('[aria-label="Analyzer name"]').value).toBe('Any surface change (rules)');
+ expect(phrase()).toBe('Keeps ground where NBR dropped by 0.27 or more, outside cloud.');
+});
+
+it('opens an analyzer kept from Compare straight in the builder, with no case open', async () => {
+ const own = { ...structuredClone(recipe), id: 'custom-aaaaaaaaaaaa', name: 'NBR: Burnt', method: 'rules', match: 'all',
+ rules: [rule({ value: -0.3 })] };
+ answer({ '/api/compare/analyzers': rulesCatalogue({ custom: [own] }) });
+ await open({ caseId: null, opening: 'analyzer:custom-aaaaaaaaaaaa', viewBounds: () => VIEW });
+ expect(heading()).toBe('Edit NBR: Burnt');
+ expect(button('Save changes')).toBeDefined();
+});
+
+it('says in the library how an analyzer’s checks last came out', async () => {
+ const own = { ...EXAMPLE.recipe, id: 'custom-bbbbbbbbbbbb' };
+ answer({ '/api/compare/analyzers': rulesCatalogue({ custom: [own] }) });
+ await open();
+ labelled('Analyzers').click(); await settle();
+ expect(target.textContent).toContain('2 checks · not run');
+});
+
// -- review --------------------------------------------------------------------------
it('offers three verdicts, and only the pin reaches the case', async () => {
const row = (id, lon, strength, value) => ({ id, coordinates: [lon, 48], bbox: [lon, 48, lon + 0.001, 48.001],
- area: 90, width: 15, height: 6, margin: 2, strength, measure: { value }, review: 'new',
+ area: 90, margin: 2, strength, measure: { value }, review: 'new',
phenomenon: 'Surface change', parts: [{ frames: ['a', 'b'], box: [0, 0, 4, 4] }] });
const saved = { id: RUN, title: 'Harbour sweep', status: 'ready', progress: 1, total: 1,
count: 2, engine_version: 2, results: [row('0-1', 2, 'strong', 12.34), row('0-2', 2.002, 'weak', 8)],
@@ -601,7 +946,7 @@ it('offers three verdicts, and only the pin reaches the case', async () => {
it('walks the queue from the keys, and narrows it to what is still to review', async () => {
const row = (id, lon, review) => ({ id, coordinates: [lon, 48], bbox: [lon, 48, lon + 0.001, 48.001],
- area: 90, width: 15, height: 6, margin: 2, strength: 'strong', measure: { value: 3 }, review,
+ area: 90, margin: 2, strength: 'strong', measure: { value: 3 }, review,
phenomenon: 'Surface change', parts: [{ frames: ['a', 'b'], box: [0, 0, 4, 4] }] });
const saved = { id: RUN, title: 'Harbour sweep', status: 'ready', progress: 1, total: 1,
count: 3, engine_version: 2,
@@ -639,6 +984,59 @@ it('walks the queue from the keys, and narrows it to what is still to review', a
expect(target.textContent).toContain('1 of 1');
});
+it('says how long a hull is, and walks the largest first when asked', async () => {
+ // Cells of 0.0001°, 7.4 m east to west and 11 m north to south at 48° N: a skiff of one,
+ // and a ship of twenty lying east to west.
+ const step = 0.0001;
+ const hull = (count) => ({ type: 'Polygon', coordinates: [[[2, 48], [2 + count * step, 48],
+ [2 + count * step, 48 + step], [2, 48 + step], [2, 48]]] });
+ const row = (id, count, strength) => ({ id, coordinates: [2, 48], bbox: [2, 48, 2 + count * step, 48 + step],
+ geometry: hull(count), area: count * 55, margin: 2, strength, measure: { value: 3 }, review: 'new',
+ phenomenon: 'Vessel candidate', parts: [{ frames: ['b'], box: [0, 0, 4, 4] }] });
+ const saved = { id: RUN, title: 'Harbour sweep', status: 'ready', progress: 1, total: 1, count: 2,
+ engine_version: 2, results: [row('0-1', 1, 'strong'), row('0-2', 20, 'weak')],
+ input: { title: 'Harbour sweep', zones: area, recipe: structuredClone(vessels), note: '',
+ a: { provider: 'sentinel2', date: '2026-05-11' }, b: { provider: 'sentinel2', date: '2026-05-11' },
+ offline: false, date_rule: 'manual', followup_id: null } };
+ answer({ [`/api/cases/case-a/analysis/runs/${RUN}`]: saved });
+ await open({ opening: `runs-${RUN}` });
+ // strongest first, as the run lists it: the skiff, long side first
+ expect(target.textContent).toContain('1 of 2');
+ expect(target.textContent).toContain('55 m² · ≈ 11 m long, 7.4 m wide');
+ button('Largest first').click(); await settle();
+ expect(button('Largest first').getAttribute('aria-pressed')).toBe('true');
+ // the ship comes up first, measured along its hull
+ expect(target.textContent).toContain('1 of 2');
+ expect(target.textContent).toContain('≈ 149 m long, 11 m wide');
+ // and back to the run's own order, from its top
+ button('Largest first').click(); await settle();
+ expect(target.textContent).toContain('≈ 11 m long, 7.4 m wide');
+});
+
+it('adds a candidate where the map was right-clicked, inside an area the run read', async () => {
+ const saved = { id: RUN, title: 'Harbour sweep', status: 'ready', progress: 1, total: 1, count: 0,
+ engine_version: 2, results: [],
+ area_runs: [{ area_id: 'area', status: 'ready', b: { provider: 'sentinel2', date: '2026-05-11' } }],
+ input: { title: 'Harbour sweep', zones: area, recipe: structuredClone(vessels), note: '',
+ a: { provider: 'sentinel2', date: '2026-05-11' }, b: { provider: 'sentinel2', date: '2026-05-11' },
+ offline: false, date_rule: 'manual', followup_id: null } };
+ // not while the list is up: there is no run to add it to
+ answer({ [`/api/cases/case-a/analysis/runs/${RUN}`]: saved });
+ await open();
+ expect(live.candidateAreaAt({ lat: 48.0005, lon: 2.0005 })).toBe(null);
+ unmount(live);
+ await open({ opening: `runs-${RUN}` });
+ expect(live.candidateAreaAt({ lat: 48.0005, lon: 2.0005 })).toBe('area');
+ expect(live.candidateAreaAt({ lat: 48.01, lon: 2.0005 })).toBe(null);
+ post.mockImplementation(async (_, body) => ({ id: 'manual-1', origin: 'manual', area_id: body.area_id,
+ geometry: body.geometry, coordinates: body.geometry.coordinates, bbox: [2, 48, 2.0001, 48.0001],
+ area: 55, margin: 0, measure: {}, review: 'new', phenomenon: 'Manual candidate', parts: [] }));
+ await live.addCandidate('area', { type: 'Point', coordinates: [2.0005, 48.0005] }); await settle();
+ expect(post).toHaveBeenCalledWith(`/api/cases/case-a/analysis/runs/${RUN}/results`,
+ { area_id: 'area', geometry: { type: 'Point', coordinates: [2.0005, 48.0005] } });
+ expect(target.textContent).toContain('Manual candidate · Manual');
+});
+
it('reopens a run saved against Wayback without pretending it had a Sentinel-2 date', async () => {
const old = { id: 'aaaaaaaaaaaa', title: 'Old harbour', status: 'ready', progress: 1, total: 1, count: 0,
engine_version: 1, results: [],
@@ -660,7 +1058,7 @@ it('reopens a run saved against Wayback without pretending it had a Sentinel-2 d
it('opens a candidate in Compare on the passes that found it', async () => {
const { uiState } = await import('../../lib/state.svelte.js');
- const row = { id: '0-1', coordinates: [2, 48], bbox: [2, 48, 2.001, 48.001], area: 90, width: 15, height: 6,
+ const row = { id: '0-1', coordinates: [2, 48], bbox: [2, 48, 2.001, 48.001], area: 90,
margin: 2, strength: 'strong', measure: { value: 3 }, review: 'new', phenomenon: 'Surface change',
parts: [{ frames: ['a', 'b'], box: [0, 0, 4, 4] }],
sources: { a: { provider: 'sentinel2', date: '2026-05-04' }, b: { provider: 'sentinel2', date: '2026-05-11' } } };
diff --git a/frontend/src/tools/detect/DetectReview.show.svelte.test.js b/frontend/src/tools/detect/DetectReview.show.svelte.test.js
index 02f6a85..f3676f4 100644
--- a/frontend/src/tools/detect/DetectReview.show.svelte.test.js
+++ b/frontend/src/tools/detect/DetectReview.show.svelte.test.js
@@ -12,8 +12,8 @@ const RUN = '123456789abc';
const area = [{ id: 'area', name: 'Area', kind: 'rect', points: [[2, 48], [2.001, 48.001]] }];
const pass = { provider: 'sentinel1', date: '2026-09-22', layer: 'RADAR', maxcc: 100, time: '02:06:41' };
const other = { ...pass, date: '2026-09-10', time: '02:06:40' };
-const row = (id, source) => ({ id, coordinates: [2, 48], bbox: [2, 48, 2.001, 48.001], area: 90, width: 15,
- height: 6, margin: 2, strength: 'strong', measure: { value: 3 }, review: 'new', phenomenon: 'Vessel candidate (radar)',
+const row = (id, source) => ({ id, coordinates: [2, 48], bbox: [2, 48, 2.001, 48.001], area: 90,
+ margin: 2, strength: 'strong', measure: { value: 3 }, review: 'new', phenomenon: 'Vessel candidate (radar)',
parts: [{ frames: ['a'], box: [0, 0, 4, 4] }], sources: { a: source, b: source } });
const recipe = { id: 'radar-vessels', name: 'Vessels by radar', method: 'sar-vessels', colour: '#38bdf8', style: 'both',
phenomenon: 'Vessel candidate (radar)', parameters: {} };
diff --git a/frontend/src/tools/detect/DetectReview.svelte b/frontend/src/tools/detect/DetectReview.svelte
index 2c32786..da683fa 100644
--- a/frontend/src/tools/detect/DetectReview.svelte
+++ b/frontend/src/tools/detect/DetectReview.svelte
@@ -4,16 +4,20 @@
* act that creates case evidence; dismissing deletes the candidate. A
* run still working shows how far it got and can be stopped from here.
*/
- import { untrack } from 'svelte';
+ import { onDestroy, untrack } from 'svelte';
import { api } from '../../lib/api.js';
- import { reloadCase, toast, uiState } from '../../lib/state.svelte.js';
+ import { prefs, reloadCase, toast, uiState } from '../../lib/state.svelte.js';
import { refreshRuns } from '../../lib/detectRuns.svelte.js';
- import { STRENGTHS, describeMeasure, sourceLabel } from '../../lib/map/analyzers.js';
+ import { STRENGTHS, readingOf, sourceLabel } from '../../lib/map/analyzers.js';
+ import { recipeCapability } from '../../lib/map/analyzerRules.js';
import { sweptNote } from '../../lib/map/acquisitions.js';
import { isActive, plural } from '../../lib/map/detections.js';
import Icon from '../../components/Icon.svelte';
import Modal from '../../components/Modal.svelte';
- import { comparePairFor, pinDefaults } from '../../lib/map/detectReview.js';
+ import {
+ blinkable, candidatePair, candidateSize, comparePairFor, orderCandidates, pinDefaults,
+ } from '../../lib/map/detectReview.js';
+ import { formatArea, formatDistance } from '../../lib/measure.js';
let {
caseId,
@@ -23,31 +27,43 @@
active = true,
methods = [],
candidateId = $bindable(null),
+ /** The detection's drawing taken off the map, so the imagery shows bare. */
+ bare = $bindable(false),
+ /** Pass A flipped against pass B on the map, while the pair has two dates. */
+ blinking = $bindable(false),
onaccept = () => {},
onfocus = () => {},
onedit = () => {},
onshow = () => {},
onexport = () => {},
onadd = () => {},
+ /** The two passes the candidate was read between, `{ a, b }`, or null once gone. */
+ onpair = () => {},
} = $props();
let busy = $state(false);
let error = $state('');
let filter = $state('all');
+ let order = $state('strength');
let enlarged = $state(false);
let pin = $state(null);
let adding = $state(false);
let manualArea = $state('');
const base = $derived(`/api/cases/${caseId}/analysis/runs/${run.id}`);
- const methodOf = (method) => methods.find((m) => m.id === method) ?? {};
const pending = $derived(isActive(run));
const all = $derived(run.results ?? []);
+ /** The queue in the order asked: strongest first, or the largest hulls first. */
+ const ordered = $derived(orderCandidates(all, order));
/** Which candidates the arrows walk. A sweep of a hundred is worked in
* passes — the ones nobody has judged, then what was kept — so the queue
* narrows rather than being scrolled. */
- const candidates = $derived(filter === 'all' ? all : all.filter((row) => matches(row, filter)));
+ const candidates = $derived(filter === 'all' ? ordered : ordered.filter((row) => matches(row, filter)));
const candidate = $derived(all.find((r) => r.id === candidateId));
+ const size = $derived(candidateSize(candidate));
+ const pair = $derived(candidatePair(candidate, run));
+ const canBlink = $derived(run.status === 'ready' && blinkable(pair));
+ $effect(() => { if (!canBlink && blinking) blinking = false; });
const matches = (row, name) => (name === 'new' ? row.review === 'new'
: name === 'kept' ? row.review === 'noted' : row.review === 'kept');
const position = $derived(candidates.findIndex((r) => r.id === candidateId));
@@ -65,16 +81,16 @@
counts.new === 0 ? `All ${candidates.length} reviewed · ${verdicts}`
: `${counts.new} still to review · ${verdicts}`
);
- const previewAlt = $derived(methodOf(run.input.recipe.method).single
+ const previewAlt = $derived(recipeCapability(run.input.recipe, methods).single
? 'Candidate evidence' : 'Candidate evidence: A on the left, B on the right');
const statusLabel = (status) => ({ queued: 'Queued', running: 'Running', ready: 'Completed',
failed: 'Failed', cancelled: 'Cancelled', no_new_imagery: 'No new imagery' }[status] ?? status);
- const dates = (input) => methodOf(input.recipe.method).single || !(input.a?.date || input.a?.release)
+ const dates = (input) => recipeCapability(input.recipe, methods).single || !(input.a?.date || input.a?.release)
? sourceLabel(input.b) : `${sourceLabel(input.a)} → ${sourceLabel(input.b)}`;
/** A candidate's reading, in the words its method's catalogue entry gives. */
const reading = (row, input) => [
STRENGTHS[row.strength],
- describeMeasure(methodOf(input.recipe.method).measure, row.measure, input.recipe.parameters.index),
+ readingOf(input.recipe, methods, row.measure),
].filter(Boolean).join(' · ');
/** Sentinel-2 reads 10 m to the pixel, so a candidate metres across is only
* worth judging from close in: the review asks for that zoom, not the
@@ -84,14 +100,25 @@
// changes it. Showing it writes the map's own state, which this must not
// read back: a radar pass is an object, so every write looked new, and the
// effect fed itself until Svelte stopped the whole page.
+ const passKey = (source) => (source?.date ? [source.provider, source.date, source.time ?? '', source.layer ?? ''].join('|') : '');
let shownPass = '';
$effect(() => {
- const source = candidate?.sources?.b ?? run.area_runs?.find((p) => p.status === 'ready')?.b ?? run.input?.b;
- const key = source?.date ? [source.provider, source.date, source.time ?? '', source.layer ?? ''].join('|') : '';
+ const source = pair.b;
+ const key = passKey(source);
if (!key || key === shownPass) return;
shownPass = key;
untrack(() => onshow(source));
});
+ // The map blinks the pair it is told about, for the same reason by key.
+ let toldPair = '';
+ $effect(() => {
+ const told = pair;
+ const key = `${passKey(told.a)}/${passKey(told.b)}`;
+ if (key === toldPair) return;
+ toldPair = key;
+ untrack(() => onpair(told));
+ });
+ onDestroy(() => onpair(null));
// The map goes where the panel is: judging a candidate you cannot see is
// guesswork, and that held whenever a run was opened rather than stepped
// through. Only a change of candidate moves the camera, so panning is free.
@@ -111,8 +138,12 @@
if (!active || !run || run.status !== 'ready' || busy || pin || enlarged || event.ctrlKey || event.metaKey || event.altKey
|| event.target?.closest?.('input, textarea, select, [contenteditable="true"]')) return;
const key = event.key.toLowerCase();
+ // Shift and an arrow turn the map, so the queue takes the bare arrows only
+ if (event.shiftKey && event.key.startsWith('Arrow')) return;
if (event.key === 'ArrowLeft') step(-1);
else if (event.key === 'ArrowRight') step(1);
+ else if (key === 'h') bare = !bare;
+ else if (key === 'b' && canBlink) blinking = !blinking;
else if (!candidate) return;
else if (key === 'k' && !['kept', 'noted'].includes(candidate.review)) void act(() => review('noted'));
else if (key === 'd' && candidate.review !== 'kept') void act(() => review('dismissed'));
@@ -138,9 +169,9 @@
/** Reviewing is a queue: a verdict moves on to the next one still waiting. */
function advance() {
- const index = all.findIndex((r) => r.id === candidateId);
- for (let i = 1; i <= all.length; i++) {
- const row = all[(index + i) % all.length];
+ const index = ordered.findIndex((r) => r.id === candidateId);
+ for (let i = 1; i <= ordered.length; i++) {
+ const row = ordered[(index + i) % ordered.length];
if (row?.review === 'new') { candidateId = row.id; focus(row.coordinates); return; }
}
}
@@ -156,7 +187,7 @@
*/
function openInCompare() {
const pair = comparePairFor(candidate, {
- single: !!methodOf(run.input.recipe.method).single, method: run.input.recipe.method,
+ single: !!recipeCapability(run.input.recipe, methods).single, method: run.input.recipe.method,
});
if (!pair) return;
uiState.compareAt = pair;
@@ -164,7 +195,7 @@
}
/** The pin's name has to mean something in the case, long after this run. */
- function openPin() { pin = pinDefaults(candidate, !!methodOf(run.input.recipe.method).single); }
+ function openPin() { pin = pinDefaults(candidate, !!recipeCapability(run.input.recipe, methods).single); }
async function keep() {
const answer = await api.post(`${base}/results/${candidateId}/promote`, pin);
@@ -225,7 +256,15 @@
adding = !adding;
manualArea = candidate?.area_id ?? run.area_runs?.find((p) => p.status === 'ready')?.area_id ?? run.input.zones[0]?.id ?? '';
}}>Add candidate</button>
- <button class="btn btn-sm" onclick={onexport}>Export as layer</button></div>
+ <button class="btn btn-sm" onclick={onexport}>Export as layer</button>
+ <span class="map-acts">
+ <button class="cmp-icon" class:on={bare} aria-pressed={bare} aria-label="Hide the candidates and areas"
+ title="Hide the candidates and areas (H)" onclick={() => (bare = !bare)}><Icon name={bare ? 'eyeOff' : 'eye'} size={14} /></button>
+ {#if canBlink}
+ <button class="cmp-icon" class:on={blinking} aria-pressed={blinking} aria-label="Blink A and B"
+ title="Blink A and B on the map (B)" onclick={() => (blinking = !blinking)}><Icon name="blink" size={14} /></button>
+ {/if}
+ </span></div>
{#if adding}
<label>Area<select aria-label="Manual candidate area" bind:value={manualArea}>
<option value="">Choose an area</option>
@@ -250,6 +289,13 @@
onclick={() => (filter = id)}>{label} <span class="n">{n}</span></button>
{/if}
{/each}
+ <!-- A new order starts from its own top: the largest is what was asked for. -->
+ <button class="chip order" class:on={order === 'size'} aria-pressed={order === 'size'}
+ title="Walk the longest first, rather than the strongest"
+ onclick={() => {
+ order = order === 'size' ? 'strength' : 'size';
+ if (candidates[0]) candidateId = candidates[0].id;
+ }}>Largest first</button>
</div>
<div class="row nav">
<button class="cmp-icon" aria-label="Previous candidate" title="Previous candidate (←)" onclick={() => step(-1)}><Icon name="chevronLeft" size={14} /></button>
@@ -268,13 +314,14 @@
<p class={`strength ${candidate.strength ?? ''}`}>{reading(candidate, run.input)}</p>
{/if}
<p class="facts">
- {Math.round(candidate.area)} m² · {Math.round(candidate.width)} × {Math.round(candidate.height)} m ·
+ {formatArea(candidate.area, prefs.units)} ·
+ {#if size}<span title="Measured on the footprint’s 10 m pixels">≈ {formatDistance(size.length, prefs.units)} long, {formatDistance(size.width, prefs.units)} wide</span> ·{/if}
<button class="link inline" onclick={() => focus(candidate.coordinates)}>
{candidate.coordinates[1].toFixed(5)}, {candidate.coordinates[0].toFixed(5)}
</button>
</p>
<button class="btn btn-sm compare" onclick={openInCompare}
- title={methodOf(run.input.recipe.method).single
+ title={recipeCapability(run.input.recipe, methods).single
? 'Hold it against today’s high-resolution picture in Compare'
: 'Read the two passes that found it in Compare'}>
<Icon name="compare" size={13} /> Compare
@@ -351,6 +398,8 @@
.chip.on { color: var(--accent); border-color: var(--accent); background: var(--accent-soft); }
.chip .n { color: var(--text-3); }
.chip.on .n { color: inherit; }
+ .order { margin-left: auto; }
+ .map-acts { display: flex; gap: 2px; margin-left: auto; }
.compare { justify-self: start; }
.facts { margin: 0; color: var(--text-2); font-size: var(--fs-xs); line-height: 1.5; }
.strength { margin: 0; font-size: var(--fs-xs); font-weight: 600; color: var(--text-1); }
diff --git a/frontend/src/tools/detect/DetectWizard.svelte b/frontend/src/tools/detect/DetectWizard.svelte
index f372d3e..f6e59fa 100644
--- a/frontend/src/tools/detect/DetectWizard.svelte
+++ b/frontend/src/tools/detect/DetectWizard.svelte
@@ -26,6 +26,7 @@
zoneRing,
} from '../../lib/map/analyzers.js';
import { plural } from '../../lib/map/detections.js';
+ import { recipeCapability } from '../../lib/map/analyzerRules.js';
import { openCopernicusSettings } from '../../lib/navigate.js';
import { uniform, whenNeed, whenSummary } from '../../lib/map/detectWhen.js';
import AnalyzerSettings from './AnalyzerSettings.svelte';
@@ -84,8 +85,7 @@
const builtins = $derived(catalogue?.builtins ?? []);
const custom = $derived(catalogue?.custom ?? []);
- const methodOf = (method) => catalogue?.methods?.find((m) => m.id === method) ?? {};
- const capability = $derived(methodOf(recipe?.method));
+ const capability = $derived(recipeCapability(recipe, catalogue?.methods ?? []));
/** A vessel or a fire is present on a date, not a difference between two. */
const isSingle = $derived(!!capability.single);
/** Radar reads Sentinel-1 through the layer Settings found, and has no clouds. */
diff --git a/frontend/src/tools/detect/RuleLayers.svelte b/frontend/src/tools/detect/RuleLayers.svelte
new file mode 100644
index 0000000..46c5d2c
--- /dev/null
+++ b/frontend/src/tools/detect/RuleLayers.svelte
@@ -0,0 +1,83 @@
+<script>
+ /**
+ * What each rule of the analyzer being built keeps, painted on the map in
+ * the rule's colour. The engine sends one byte a pixel over the preview's
+ * tiles (a bit per rule, detect_rules.py); this lays it on the ground
+ * through the map's own frame, so it stays put however the map is panned,
+ * zoomed or turned, and repaints only when a rule is shown, hidden or hovered.
+ */
+ import { compose, cssMatrix, imageToMercator, invert, screenToMercator } from '../../lib/map/groundFrame.js';
+ import { RULE_COLOURS, paintMask } from '../../lib/map/analyzerRules.js';
+
+ let { engine, element, preview = null, shown = [], hover = null, colours = RULE_COLOURS } = $props();
+
+ let canvas = $state(null);
+ let bits = $state(null);
+ let revision = $state(0);
+
+ $effect(() => {
+ if (!engine) return;
+ return engine.on('view-move', () => revision++);
+ });
+
+ /** One byte a pixel out of the PNG the engine sent: its first channel. */
+ async function decode(base64, width, height) {
+ const image = new Image();
+ image.src = `data:image/png;base64,${base64}`;
+ await image.decode();
+ const scratch = document.createElement('canvas');
+ scratch.width = width;
+ scratch.height = height;
+ const context = scratch.getContext('2d', { willReadFrequently: true });
+ context.drawImage(image, 0, 0);
+ const rgba = context.getImageData(0, 0, width, height).data;
+ const out = new Uint8Array(width * height);
+ for (let i = 0; i < out.length; i++) out[i] = rgba[i * 4];
+ return out;
+ }
+
+ $effect(() => {
+ const mask = preview?.mask;
+ const [width, height] = preview?.size ?? [0, 0];
+ if (!mask) { bits = null; return; }
+ let cancelled = false;
+ decode(mask, width, height)
+ .then((decoded) => { if (!cancelled) bits = decoded; })
+ .catch(() => { if (!cancelled) bits = null; });
+ return () => { cancelled = true; };
+ });
+
+ $effect(() => {
+ if (!canvas || !bits || !preview) return;
+ const [width, height] = preview.size;
+ if (bits.length !== width * height) return;
+ canvas.width = width;
+ canvas.height = height;
+ canvas.getContext('2d').putImageData(new ImageData(paintMask(bits, { shown, hover, colours }), width, height), 0, 0);
+ });
+
+ const transform = $derived.by(() => {
+ revision;
+ if (!engine?.frame || !element || !preview?.box) return '';
+ const box = element.getBoundingClientRect();
+ const frame = { ...engine.frame(), width: box.width || 1, height: box.height || 1 };
+ const [width, height] = preview.size;
+ return cssMatrix(compose(invert(screenToMercator(frame)), imageToMercator(preview.box, width, height)));
+ });
+</script>
+
+{#if preview?.mask}
+ <canvas bind:this={canvas} class="rule-layers" style:transform={transform} aria-label="What each rule keeps"></canvas>
+{/if}
+
+<style>
+ .rule-layers {
+ position: absolute;
+ top: 0;
+ left: 0;
+ z-index: 540;
+ transform-origin: 0 0;
+ image-rendering: pixelated;
+ pointer-events: none;
+ }
+</style>
diff --git a/frontend/src/tools/detect/RuleProbe.render.test.js b/frontend/src/tools/detect/RuleProbe.render.test.js
new file mode 100644
index 0000000..be16860
--- /dev/null
+++ b/frontend/src/tools/detect/RuleProbe.render.test.js
@@ -0,0 +1,84 @@
+// @vitest-environment happy-dom
+import { describe, expect, it, vi } from 'vitest';
+import { flushSync, mount, unmount } from 'svelte';
+import RuleProbe from './RuleProbe.svelte';
+import { newRule } from '../../lib/map/analyzerRules.js';
+
+const engine = { on: () => () => {}, latLngToContainerPoint: () => ({ x: 900, y: 40 }) };
+const rules = [newRule('index', 'change'), newRule('band', 'b', { band: 'B12' })];
+
+function render(result, extra = {}) {
+ const target = document.createElement('div');
+ document.body.append(target);
+ const live = mount(RuleProbe, { target, props: { engine, rules, colours: ['#f00', '#0f0'], width: 1000, height: 600,
+ probe: { point: { lon: 2, lat: 48 }, result, error: '' }, ...extra } });
+ flushSync();
+ return { target, done: () => { unmount(live); target.remove(); } };
+}
+
+describe('reading the rules at a point', () => {
+ it('says what every rule read there and which one let it go', () => {
+ const { target, done } = render({ ready: true, imaged: true, measured: true, kept: false, rules: [
+ { passes: true, value: -0.41, before: 0.72, after: 0.31 },
+ { passes: false, value: 0.18, before: null, after: null },
+ ] });
+ expect(target.textContent).toContain('Not kept');
+ const rows = [...target.querySelectorAll('li')].map((li) => li.textContent.replace(/\s+/g, ' ').trim());
+ expect(rows[0]).toContain('0.72 → 0.31 (−0.41)');
+ expect(rows[0]).toContain('✓');
+ expect(rows[1]).toContain('18.0%');
+ expect(rows[1]).toContain('✗');
+ // near the right edge the card opens to the left of the point
+ expect(target.querySelector('.probe').style.left).toBe('566px');
+ done();
+ });
+
+ it('says why nothing was read under cloud, off the imagery or outside the preview', () => {
+ for (const [result, words] of [
+ [{ ready: true, imaged: true, measured: false, kept: false, rules: [] }, 'Under cloud or shadow'],
+ [{ ready: true, imaged: false, measured: false, kept: false, rules: [] }, 'No imagery here'],
+ [{ ready: false }, 'Outside the preview'],
+ ]) {
+ const { target, done } = render(result);
+ expect(target.textContent).toContain(words);
+ expect(target.querySelector('li')).toBe(null);
+ done();
+ }
+ });
+
+ it('marks the point in the check on the bench, or in a new check of this view', () => {
+ const read = { ready: true, imaged: true, measured: true, kept: true, rules: [] };
+ const onmark = vi.fn();
+ const { target, done } = render(read, { onmark, markTarget: 'The town that burned' });
+ expect(target.textContent).toContain('Mark it in “The town that burned”');
+ [...target.querySelectorAll('button')].find((b) => b.textContent === 'Should stay empty').click();
+ expect(onmark).toHaveBeenCalledWith('empty');
+ done();
+ const fresh = render(read, { onmark });
+ expect(fresh.target.textContent).toContain('Mark it in a new check of this view');
+ fresh.done();
+ // nothing to mark off the imagery, and nothing without a way to keep it
+ for (const extra of [{ onmark }, {}]) {
+ const off = render(extra.onmark ? { ...read, imaged: false } : read, extra);
+ expect(off.target.textContent).not.toContain('Should be found');
+ off.done();
+ }
+ });
+
+ it('opens where nothing is read yet, says what is missing, and still takes a mark', () => {
+ const onmark = vi.fn();
+ const unread = (kind) => render(null, { onmark, probe: { point: { lon: 2, lat: 48 }, result: null, error: '', unread: kind } });
+ const frames = unread('frames');
+ expect(frames.target.textContent).toContain('Not read here yet');
+ [...frames.target.querySelectorAll('button')].find((b) => b.textContent === 'Should be found').click();
+ expect(onmark).toHaveBeenCalledWith('found');
+ frames.done();
+ const passes = unread('passes');
+ expect(passes.target.textContent).toContain('Pick the passes to read the rules here.');
+ passes.done();
+ const nowhere = render(null, { onmark, canMark: false, probe: { point: { lon: 2, lat: 48 }, result: null, error: '', unread: 'passes' } });
+ expect(nowhere.target.textContent).toContain('this point can become a mark of a check');
+ expect(nowhere.target.textContent).not.toContain('Should be found');
+ nowhere.done();
+ });
+});
diff --git a/frontend/src/tools/detect/RuleProbe.svelte b/frontend/src/tools/detect/RuleProbe.svelte
new file mode 100644
index 0000000..ab93480
--- /dev/null
+++ b/frontend/src/tools/detect/RuleProbe.svelte
@@ -0,0 +1,129 @@
+<script>
+ /**
+ * Every rule read at the point the analyst clicked: the value, the line and
+ * whether it passed. It is how a builder answers "why was this not kept?".
+ * Pinned to the ground point, so it follows the map. From here the point can
+ * become a mark of a check: somewhere a candidate should come out, or none.
+ */
+ import { describeRule, formatValue } from '../../lib/map/analyzerRules.js';
+ import Icon from '../../components/Icon.svelte';
+
+ let {
+ engine, probe, rules = [], colours = [], width = 0, height = 0, onclose = () => {},
+ /** Mark the point in a check: `onmark('found' | 'empty')`. */
+ onmark = null,
+ /** The check a mark goes to, or '' for a new one of this view. */
+ markTarget = '',
+ /** False while no check can take a mark here. */
+ canMark = true,
+ } = $props();
+
+ let revision = $state(0);
+ $effect(() => {
+ if (!engine) return;
+ return engine.on('view-move', () => revision++);
+ });
+ const at = $derived.by(() => {
+ revision;
+ return engine?.latLngToContainerPoint(probe.point) ?? { x: 0, y: 0 };
+ });
+ /** Beside the point, on whichever side the map has room for it. */
+ const place = $derived({
+ left: width && at.x + 334 > width ? Math.max(4, at.x - 334) : at.x + 14,
+ top: height && at.y + 180 > height ? Math.max(4, at.y - 180) : at.y + 14,
+ });
+ const result = $derived(probe.result);
+ const status = $derived(
+ probe.unread === 'passes' ? 'Pick the passes to read the rules here.'
+ : probe.unread === 'frames' ? 'Not read here yet: Show the detections here reads it.'
+ : probe.error ? probe.error
+ : !result ? 'Reading…'
+ : !result.ready ? 'Outside the preview. Read this view first.'
+ : !result.imaged ? 'No imagery here on the passes read.'
+ : !result.measured ? 'Under cloud or shadow, so no rule is read.'
+ : result.kept ? 'Kept' : 'Not kept'
+ );
+ /** A mark needs no reading, only somewhere to go; off the imagery it says nothing. */
+ const markable = $derived(!!onmark && !(result?.ready && !result.imaged));
+
+ function reading(rule, row) {
+ if (rule.measure === 'class') return row.passes ? 'yes' : 'no';
+ if (rule.on === 'change' && rule.measure !== 'colour' && row.before !== null) {
+ return `${formatValue(rule, row.before)} → ${formatValue(rule, row.after)} (${formatValue(rule, row.value, { signed: true })})`;
+ }
+ return formatValue(rule, row.value, { signed: !!rule.around });
+ }
+</script>
+
+<div class="marker" style:left={`${at.x}px`} style:top={`${at.y}px`} aria-hidden="true"></div>
+<div class="probe cmp-glass" role="dialog" aria-label="Rules at this point"
+ style:left={`${place.left}px`} style:top={`${place.top}px`}>
+ <header>
+ <strong class:kept={result?.kept}>{status}</strong>
+ <button class="cmp-icon" aria-label="Close the reading" title="Close" onclick={onclose}><Icon name="x" size={12} /></button>
+ </header>
+ {#if result?.ready && result.measured}
+ <ul>
+ {#each result.rules as row, i (i)}
+ {#if rules[i]}
+ <li style={`--tint: ${colours[i % colours.length]}`}>
+ <span class="dot"></span>
+ <span class="what" title={describeRule(rules[i])}>{describeRule(rules[i])}</span>
+ <span class="value">{reading(rules[i], row)}</span>
+ <span class="verdict" class:pass={row.passes}>{row.passes ? '✓' : '✗'}</span>
+ </li>
+ {/if}
+ {/each}
+ </ul>
+ {/if}
+ {#if markable}
+ <footer>
+ {#if canMark}
+ <span class="target">{markTarget ? `Mark it in “${markTarget}”` : 'Mark it in a new check of this view'}</span>
+ <div class="marks">
+ <button class="btn btn-sm" onclick={() => onmark('found')}>Should be found</button>
+ <button class="btn btn-sm" onclick={() => onmark('empty')}>Should stay empty</button>
+ </div>
+ {:else}
+ <span class="target">Pick pass A and pass B, and this point can become a mark of a check.</span>
+ {/if}
+ </footer>
+ {/if}
+</div>
+
+<style>
+ .marker {
+ position: absolute;
+ z-index: 560;
+ width: 14px;
+ height: 14px;
+ transform: translate(-50%, -50%);
+ border: 2px solid #fff;
+ border-radius: 50%;
+ box-shadow: 0 0 0 1px rgb(0 0 0 / 0.6);
+ pointer-events: none;
+ }
+ .probe {
+ position: absolute;
+ z-index: 660;
+ display: grid;
+ gap: 6px;
+ width: min(320px, 70vw);
+ padding: 8px 10px;
+ font-size: var(--fs-xs);
+ }
+ header { display: flex; align-items: center; gap: 8px; }
+ header strong { flex: 1; color: var(--glass-muted); }
+ header strong.kept { color: var(--ok, #46a758); }
+ ul { display: grid; gap: 4px; margin: 0; padding: 0; list-style: none; }
+ li { display: grid; grid-template-columns: 10px 1fr auto 14px; align-items: center; gap: 6px; }
+ .dot { width: 8px; height: 8px; border-radius: 50%; background: var(--tint); }
+ .what { overflow: hidden; color: var(--glass-muted); text-overflow: ellipsis; white-space: nowrap; }
+ .value { color: var(--glass-ink); font-variant-numeric: tabular-nums; white-space: nowrap; }
+ .verdict { color: var(--danger, #ef4444); font-weight: 700; text-align: center; }
+ .verdict.pass { color: var(--ok, #46a758); }
+ footer { display: grid; gap: 5px; padding-top: 6px; border-top: 1px solid var(--glass-line); }
+ .target { color: var(--glass-muted); font-size: 10.5px; }
+ .marks { display: flex; gap: 6px; }
+ .marks .btn { flex: 1; }
+</style>
diff --git a/frontend/src/tools/detect/RuleRow.svelte b/frontend/src/tools/detect/RuleRow.svelte
new file mode 100644
index 0000000..1e9a702
--- /dev/null
+++ b/frontend/src/tools/detect/RuleRow.svelte
@@ -0,0 +1,222 @@
+<script>
+ /**
+ * One rule of an analyzer of your own: what it measures, on which date or
+ * across the two, and the line it has to cross. Its colour is the colour its
+ * pixels take on the map, and the share under it is how much of the measured
+ * ground it keeps, alone and together with the rules above it.
+ */
+ import {
+ BAND_NAMES, CLASS_NAMES, INDICES, L2A_BANDS, MEASURES, PAIRS, POLARISATIONS, formatShare, opsFor,
+ retarget, scaleOf, ruleProblem, toEngine,
+ } from '../../lib/map/analyzerRules.js';
+ import Icon from '../../components/Icon.svelte';
+
+ let {
+ rule = $bindable(),
+ index = 0,
+ colour = '#facc15',
+ /** The first measured rule: candidates are ranked by it. */
+ signal = false,
+ /** `{ share, kept }` from the last preview, or null. */
+ reading = null,
+ match = 'all',
+ shown = true,
+ ontoggle = () => {},
+ bands = L2A_BANDS,
+ classes = Object.keys(CLASS_NAMES),
+ maxAround = 300,
+ canRemove = true,
+ onremove = () => {},
+ onsignal = () => {},
+ onhover = () => {},
+ } = $props();
+
+ const n = $derived(index + 1);
+ const scale = $derived(scaleOf(rule));
+ const shownValue = $derived(Number((rule.value * scale.factor).toFixed(4)));
+ const shownUpper = $derived(Number((rule.upper * scale.factor).toFixed(4)));
+ const problem = $derived(ruleProblem(rule));
+ const pair = $derived(PAIRS.find((entry) => entry.bands[0] === rule.bands[0] && entry.bands[1] === rule.bands[1])?.id ?? '');
+ const DATES = [['a', 'A'], ['b', 'B'], ['change', 'A → B']];
+ /** Its own share of the measured ground, then what is left once the rules above it have had theirs. */
+ const shareText = $derived(!reading ? '' : [
+ `${formatShare(reading.share)} of the ground`,
+ index > 0 ? `${formatShare(reading.kept)} ${match === 'any' ? 'with any above' : 'left with the ones above'}` : '',
+ ].filter(Boolean).join(' · '));
+
+ function set(patch) {
+ rule = retarget(rule, patch);
+ }
+ function setValue(key, shown) {
+ const number = Number(shown);
+ if (!Number.isFinite(number)) return;
+ set({ [key]: toEngine(rule, number) });
+ }
+ function toggleClass(id) {
+ const next = rule.classes.includes(id) ? rule.classes.filter((entry) => entry !== id) : [...rule.classes, id];
+ set({ classes: next });
+ }
+</script>
+
+<!-- svelte-ignore a11y_no_static_element_interactions -->
+<div class="rule" style={`--tint: ${colour}`} onpointerenter={() => onhover(index)} onpointerleave={() => onhover(null)}>
+ <div class="row head">
+ <button class="eye" class:off={!shown} aria-pressed={shown} aria-label={`${shown ? 'Hide' : 'Show'} rule ${n} on the map`}
+ title={shown ? 'Hide its pixels on the map' : 'Show its pixels on the map'} onclick={ontoggle}>
+ <span class="swatch"></span>
+ </button>
+ {#if signal}
+ <span class="rank on" title="Candidates are ranked by this rule">★ {n}</span>
+ {:else}
+ <button class="rank" title="Rank candidates by this rule" aria-label={`Rank candidates by rule ${n}`}
+ disabled={rule.measure === 'class'} onclick={onsignal}>{n}</button>
+ {/if}
+ <select class="grow" aria-label={`Rule ${n} measures`} value={rule.measure}
+ onchange={(event) => set({ measure: event.currentTarget.value })}>
+ {#each MEASURES as measure (measure.id)}<option value={measure.id}>{measure.label}</option>{/each}
+ </select>
+ {#if canRemove}
+ <button class="cmp-icon" aria-label={`Remove rule ${n}`} title="Remove this rule" onclick={onremove}>
+ <Icon name="x" size={13} />
+ </button>
+ {/if}
+ </div>
+
+ {#if rule.measure === 'index'}
+ <select aria-label={`Rule ${n} index`} value={rule.index}
+ onchange={(event) => set({ index: event.currentTarget.value })}>
+ {#each INDICES as entry (entry.id)}<option value={entry.id}>{entry.label} · {entry.hint}</option>{/each}
+ </select>
+ {:else if rule.measure === 'nd'}
+ <div class="row">
+ <select class="grow" aria-label={`Rule ${n} first band`} value={rule.bands[0]}
+ onchange={(event) => set({ bands: [event.currentTarget.value, rule.bands[1]] })}>
+ {#each bands as band (band)}<option value={band}>{band} · {BAND_NAMES[band] ?? ''}</option>{/each}
+ </select>
+ <span class="minus">vs</span>
+ <select class="grow" aria-label={`Rule ${n} second band`} value={rule.bands[1]}
+ onchange={(event) => set({ bands: [rule.bands[0], event.currentTarget.value] })}>
+ {#each bands as band (band)}<option value={band}>{band} · {BAND_NAMES[band] ?? ''}</option>{/each}
+ </select>
+ </div>
+ <select aria-label={`Rule ${n} known pair`} value={pair}
+ onchange={(event) => {
+ const found = PAIRS.find((entry) => entry.id === event.currentTarget.value);
+ if (found) set({ bands: [...found.bands] });
+ }}>
+ <option value="">(first − second) / (first + second)</option>
+ {#each PAIRS as entry (entry.id)}<option value={entry.id}>{entry.label} · {entry.hint}</option>{/each}
+ </select>
+ {:else if rule.measure === 'band'}
+ <select aria-label={`Rule ${n} band`} value={rule.band}
+ onchange={(event) => set({ band: event.currentTarget.value })}>
+ {#each bands as band (band)}<option value={band}>{band} · {BAND_NAMES[band] ?? ''}</option>{/each}
+ </select>
+ {:else if rule.measure === 'radar'}
+ <div class="cmp-seg fill" role="group" aria-label={`Rule ${n} polarisation`}>
+ {#each POLARISATIONS as entry (entry.id)}
+ <button type="button" class:on={rule.polarisation === entry.id} aria-pressed={rule.polarisation === entry.id}
+ onclick={() => set({ polarisation: entry.id })}>{entry.label}</button>
+ {/each}
+ </div>
+ {:else if rule.measure === 'class'}
+ <div class="classes" role="group" aria-label={`Rule ${n} ground classes`}>
+ {#each classes as id (id)}
+ <button type="button" class="chip" class:on={rule.classes.includes(id)} aria-pressed={rule.classes.includes(id)}
+ onclick={() => toggleClass(id)}>{CLASS_NAMES[id] ?? id}</button>
+ {/each}
+ </div>
+ {/if}
+
+ <div class="row">
+ <div class="cmp-seg" role="group" aria-label={`Rule ${n} reads`}>
+ {#each DATES as [id, label] (id)}
+ {@const allowed = rule.measure === 'colour' ? id === 'change' : rule.measure === 'class' ? id !== 'change' : true}
+ <button type="button" class:on={rule.on === id} aria-pressed={rule.on === id}
+ title={id === 'change' ? 'The change from A to B' : `Pass ${label} alone`}
+ disabled={!allowed} onclick={() => set({ on: id })}>{label}</button>
+ {/each}
+ </div>
+ <select class="grow" aria-label={`Rule ${n} comparison`} value={rule.op}
+ onchange={(event) => set({ op: event.currentTarget.value })}>
+ {#each opsFor(rule) as [id, label] (id)}<option value={id}>{label}</option>{/each}
+ </select>
+ </div>
+
+ {#if rule.measure !== 'class'}
+ <div class="row value">
+ <input type="number" aria-label={`Rule ${n} value`} step={scale.step}
+ value={shownValue} onchange={(event) => setValue('value', event.currentTarget.value)} />
+ {#if rule.op === 'between'}
+ <span class="minus">to</span>
+ <input type="number" aria-label={`Rule ${n} upper value`} step={scale.step}
+ value={shownUpper} onchange={(event) => setValue('upper', event.currentTarget.value)} />
+ {/if}
+ <span class="unit">{scale.suffix.trim()}</span>
+ </div>
+ <input type="range" aria-label={`Rule ${n} line`} min={scale.min} max={scale.max} step={scale.step}
+ value={Math.min(scale.max, Math.max(scale.min, shownValue))}
+ oninput={(event) => setValue('value', event.currentTarget.value)} />
+ <label class="check" title="Compare with the ground around it rather than with a fixed value">
+ <input type="checkbox" checked={rule.around > 0}
+ onchange={(event) => set({ around: event.currentTarget.checked ? 150 : 0 })} />
+ Against its surroundings
+ {#if rule.around > 0}
+ <input class="metres" type="number" min="20" max={maxAround} step="10" aria-label={`Rule ${n} surroundings in metres`}
+ value={rule.around}
+ onchange={(event) => set({ around: Math.min(maxAround, Math.max(20, Math.round(Number(event.currentTarget.value) || 150))) })} />
+ m
+ {/if}
+ </label>
+ {/if}
+
+ {#if problem}
+ <p class="warn">{problem}</p>
+ {:else if reading}
+ <p class="share" aria-label={`Rule ${n} share`}>{shareText}</p>
+ {/if}
+</div>
+
+<style>
+ .rule {
+ display: grid;
+ grid-template-columns: minmax(0, 1fr);
+ gap: 6px;
+ padding: 8px;
+ border: 1px solid var(--border);
+ border-left: 3px solid var(--tint);
+ border-radius: var(--r-sm);
+ background: var(--bg-2);
+ }
+ .head { gap: 5px; }
+ /* A band's name is long; the column is not, and must not widen for it. */
+ .rule > select, .rule select.grow { width: 100%; min-width: 0; }
+ .eye { display: grid; place-items: center; width: 22px; height: 22px; border-radius: 50%; }
+ .eye:hover { background: var(--bg-3); }
+ .swatch { width: 12px; height: 12px; border-radius: 50%; background: var(--tint); box-shadow: 0 0 0 1px rgb(0 0 0 / 0.3); }
+ .eye.off .swatch { background: transparent; box-shadow: inset 0 0 0 2px var(--tint); }
+ .rank {
+ min-width: 26px;
+ padding: 2px 5px;
+ border-radius: var(--r-sm);
+ color: var(--text-3);
+ font-size: 10.5px;
+ font-weight: 700;
+ text-align: center;
+ }
+ button.rank:hover:not(:disabled) { color: var(--text-1); background: var(--bg-3); }
+ .rank.on { color: var(--accent); background: var(--accent-soft); }
+ .minus, .unit { color: var(--text-3); font-size: var(--fs-xs); }
+ .value input[type='number'] { width: 84px; }
+ .metres { width: 62px; }
+ .classes { display: flex; flex-wrap: wrap; gap: 4px; }
+ .chip {
+ padding: 3px 8px;
+ border: 1px solid var(--border);
+ border-radius: 999px;
+ color: var(--text-2);
+ font-size: 10.5px;
+ }
+ .chip.on { border-color: var(--accent); color: var(--accent); background: var(--accent-soft); }
+ .share { margin: 0; color: var(--text-3); font-size: 10.5px; }
+</style>
diff --git a/frontend/src/tools/detect/props.fixture.svelte.js b/frontend/src/tools/detect/props.fixture.svelte.js
new file mode 100644
index 0000000..d2c4477
--- /dev/null
+++ b/frontend/src/tools/detect/props.fixture.svelte.js
@@ -0,0 +1,8 @@
+/**
+ * Props a test can change after mounting: a plain object would hand the
+ * component its first values and never tell it of the next ones.
+ */
+export function liveProps(initial) {
+ const props = $state(initial);
+ return props;
+}
diff --git a/frontend/src/tools/detect/uistate.fixture.svelte.js b/frontend/src/tools/detect/uistate.fixture.svelte.js
index f05a3d9..d918d71 100644
--- a/frontend/src/tools/detect/uistate.fixture.svelte.js
+++ b/frontend/src/tools/detect/uistate.fixture.svelte.js
@@ -3,4 +3,6 @@
* tool writes and another reads (a saved item to open, a pair handed over).
* A plain object would take the write and never wake the effect behind it.
*/
-export const uiState = $state({ tool: 'detect', openAnalyzer: null });
+export const uiState = $state({
+ tool: 'detect', openAnalyzer: null, lookAt: null, gotoCoords: null, mapView: null, mapPoint: null,
+});
diff --git a/frontend/src/tools/inspect/AdjustSliders.svelte b/frontend/src/tools/inspect/AdjustSliders.svelte
index d2eedc5..b62fa88 100644
--- a/frontend/src/tools/inspect/AdjustSliders.svelte
+++ b/frontend/src/tools/inspect/AdjustSliders.svelte
@@ -1,6 +1,6 @@
<script>
// Slider bank generated from the backend filter registry (/api/inspect/ops).
- // Writes live into `values` (a reactive object owned by the session), so the
+ // Writes live into `values` (a reactive object owned by the work), so the
// caller can build both the CSS live-preview and the backend op pipeline.
let { filters, values } = $props();
</script>
diff --git a/frontend/src/tools/inspect/CollageCanvas.svelte b/frontend/src/tools/inspect/CollageCanvas.svelte
index 6913165..07fbde6 100644
--- a/frontend/src/tools/inspect/CollageCanvas.svelte
+++ b/frontend/src/tools/inspect/CollageCanvas.svelte
@@ -6,11 +6,11 @@
import { uiState } from '../../lib/state.svelte.js';
import Icon from '../../components/Icon.svelte';
- // Interactive collage surface. Each node is a tray frame placed as a 4-point
- // quad (canvas pixels). Drag the body to move all four corners together; drag a
- // corner handle to warp — a hand-made panorama. The same quads are sent to the
- // backend, which renders the full-res warp with PIL (see compose_perspective).
- // `collage` is the session's *active* collage (a session may hold several).
+ // Interactive collage surface. Each node is a piece (a frame or a case image)
+ // placed as a 4-point quad in canvas pixels. Drag the body to move all four
+ // corners together; drag a corner handle to warp, for a hand-made panorama. The
+ // same quads go to the backend, which renders the full-res warp with PIL (see
+ // compose_perspective).
//
// Selection is a *set*: shift-click adds/removes a piece. One piece gets the
// per-piece handles (warp corners, side resize, rotate, toolbar); several get
@@ -228,11 +228,11 @@
collage.nodes = [...nodes];
}
- // Delete / Backspace removes every selected piece. The Inspect tool stays
+ // Delete / Backspace removes every selected piece. The Collage tool stays
// mounted when another tab is shown, so bail unless it is the visible tool —
// and when typing in a field or when a modal (e.g. the crop editor) is open.
function onKey(e) {
- if (uiState.tool !== 'inspect') return;
+ if (uiState.tool !== 'collage') return;
if (!selectedIds.length) return;
if (e.key !== 'Delete' && e.key !== 'Backspace') return;
const t = e.target;
@@ -288,6 +288,29 @@
>
{#each collage.nodes as node (node.id)}
{@const box = boxOf(node)}
+ {#if !box.url}
+ <!-- A piece whose file is gone keeps its place, so the layout still reads
+ and the analyst can see what to replace. One still rendering holds
+ its place the same way, without the warning. -->
+ {@const mark = Math.max(16, Math.min(box.w, box.h) / 4)}
+ <!-- svelte-ignore a11y_no_static_element_interactions -->
+ <div
+ class="node placeholder"
+ class:missing={node.missing}
+ class:selected={isSel(node.id)}
+ style:width={`${box.w}px`}
+ style:height={`${box.h}px`}
+ style:transform={quadMatrix3d(box.w, box.h, node.quad)}
+ onpointerdown={(e) => (e.stopPropagation(), startMove(e, node))}
+ title={node.missing ? "This piece's file is no longer in the case" : 'Loading this piece'}
+ >
+ {#if node.missing}
+ <Icon name="alert" size={mark} />
+ {:else}
+ <span class="spinner" style:width={`${mark}px`} style:height={`${mark}px`} style:border-width={`${Math.max(2, mark / 10)}px`}></span>
+ {/if}
+ </div>
+ {:else}
<img
class="node"
class:selected={isSel(node.id)}
@@ -301,6 +324,7 @@
onpointerdown={(e) => (e.stopPropagation(), startMove(e, node))}
ondblclick={() => { selectedIds = [node.id]; requestCrop?.(node); }}
/>
+ {/if}
{#if node.id === soloId}
<!-- round corner handles: free perspective warp -->
{#each node.quad as pt, i (i)}
@@ -517,6 +541,28 @@
user-select: none;
outline: 1px solid transparent;
}
+ .node.placeholder {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ background: var(--bg-2);
+ }
+ .node.missing {
+ background: repeating-linear-gradient(45deg, var(--bg-2), var(--bg-2) 10px, var(--bg-3) 10px, var(--bg-3) 20px);
+ border: 1px dashed var(--warn);
+ color: var(--warn);
+ }
+ .spinner {
+ border: 2px solid var(--border);
+ border-top-color: var(--accent);
+ border-radius: 50%;
+ animation: spin 0.8s linear infinite;
+ }
+ @keyframes spin {
+ to {
+ transform: rotate(360deg);
+ }
+ }
.node.selected {
outline: 1px dashed var(--accent);
}
diff --git a/frontend/src/tools/inspect/CollageMenu.svelte b/frontend/src/tools/inspect/CollageMenu.svelte
index 81fd081..f54c52c 100644
--- a/frontend/src/tools/inspect/CollageMenu.svelte
+++ b/frontend/src/tools/inspect/CollageMenu.svelte
@@ -1,85 +1,22 @@
<script>
import {
- previewStyle, scaleQuad, rotateQuad, quadCentroid, cropImgStyle, styleText,
- rotateQuads, scaleQuads, pinholeOps, newCollage, clampCollageDim, stitchCanvas,
- COLLAGE_MIN_DIM, COLLAGE_MAX_DIM,
+ scaleQuad, rotateQuad, quadCentroid, rotateQuads, scaleQuads, pinholeOps, clampCollageDim,
+ stitchCanvas, COLLAGE_MIN_DIM, COLLAGE_MAX_DIM,
} from '../../lib/inspect.js';
import { api } from '../../lib/api.js';
import { caseState, toast } from '../../lib/state.svelte.js';
import Icon from '../../components/Icon.svelte';
- // Right-panel menu for the Collage tab: switch/create collages, add tray frames
- // to the active one, and act on the selected piece. A session holds several
- // collages (session.collages / session.activeCollageId); each is saved as its
- // own PNG. Each added piece is a frozen snapshot of the frame (addToCollage).
- let {
- session, filters, selectedIds = $bindable([]), addToCollage, requestCrop, renderPiece,
- onRename,
- } = $props();
+ // The panel beside the canvas: its size, the selected piece or block, and the
+ // auto panorama. Adding pieces and exporting live in the Collage tool around it.
+ let { collage: active, selectedIds = $bindable([]), requestCrop, renderPiece } = $props();
- const active = $derived(
- session.collages.find((c) => c.id === session.activeCollageId) ?? session.collages[0]
- );
-
- // How many pieces on this collage came from that tray frame — a tile can be
- // added several times, and with a long tray that count is the only way to see
- // what is already placed.
- const usedCount = (id) => active?.nodes.filter((n) => n.frameId === id).length ?? 0;
-
- // Same wording as the Frame tab tray, so a frame keeps one name across tabs.
- const frameLabel = (fr, i) =>
- fr.time != null ? `Image ${i + 1} · t=${fr.time.toFixed(2)}s` : `Image ${i + 1}`;
// These controls act on one piece; a multi-piece block is transformed as a
// whole on the canvas, so the section simply steps aside for it.
const selected = $derived(
selectedIds.length === 1 ? (active?.nodes.find((n) => n.id === selectedIds[0]) ?? null) : null
);
- function switchCollage(id) {
- session.activeCollageId = id;
- selectedIds = [];
- }
-
- // Renaming rides on the tab itself: a click switches, a click on the tab you
- // are already in opens it for editing. The name follows the collage into the
- // Save tab, so it is worth setting here while the layout is in front of you.
- let renamingId = $state(null);
- let draftName = $state('');
-
- function tabClick(cl) {
- if (cl.id === session.activeCollageId) {
- renamingId = cl.id;
- draftName = cl.name ?? '';
- } else {
- switchCollage(cl.id);
- }
- }
-
- function commitRename(cl) {
- const next = draftName.trim();
- if (next && next !== cl.name) {
- cl.name = next;
- // The Save tab shows this same name; tell it the name is now the user's,
- // so a base name typed there stops refilling it.
- onRename?.(cl);
- }
- renamingId = null;
- }
-
- function renameKey(event, cl) {
- if (event.key === 'Enter') commitRename(cl);
- else if (event.key === 'Escape') renamingId = null;
- }
-
- function addCollage() {
- const nums = session.collages.map((c) => parseInt((c.name?.match(/\d+/) ?? [])[0]) || 0);
- const next = Math.max(0, ...nums) + 1;
- const c = newCollage(`Collage ${next}`);
- session.collages.push(c);
- session.activeCollageId = c.id;
- selectedIds = [];
- }
-
// The canvas is the resolution everything on it is worked and exported at, so
// it is the analyst's to set. Held inside the bounds compose accepts, and the
// field is put back to what was taken so a refused number never sits there.
@@ -89,13 +26,6 @@
event.currentTarget.value = next;
}
- function removeCollage(id) {
- if (session.collages.length <= 1) return; // always keep at least one
- session.collages = session.collages.filter((c) => c.id !== id);
- if (session.activeCollageId === id) session.activeCollageId = session.collages[0].id;
- selectedIds = [];
- }
-
function removeNode(id) {
active.nodes = active.nodes.filter((n) => n.id !== id);
selectedIds = selectedIds.filter((x) => x !== id);
@@ -255,102 +185,36 @@
</script>
<div class="module">
- <div class="section">
- <div class="section-head"><span>Collages</span></div>
- <div class="collage-tabs">
- {#each session.collages as cl (cl.id)}
- <div class="ctab" class:active={cl.id === session.activeCollageId}>
- {#if renamingId === cl.id}
- <!-- svelte-ignore a11y_autofocus -->
- <input
- class="ctab-input"
- bind:value={draftName}
- onblur={() => commitRename(cl)}
- onkeydown={(e) => renameKey(e, cl)}
- aria-label="Collage name"
- maxlength="200"
- autofocus
- />
- {:else}
- <button
- class="ctab-name"
- onclick={() => tabClick(cl)}
- title={cl.id === session.activeCollageId ? 'Rename this collage' : 'Switch to this collage'}
- >
- {cl.name}{#if cl.nodes.length}<span class="count">{cl.nodes.length}</span>{/if}
- </button>
- {/if}
- {#if session.collages.length > 1}
- <button class="ctab-x" onclick={() => removeCollage(cl.id)} aria-label="Delete collage" title="Delete collage"><Icon name="x" size={11} /></button>
- {/if}
- </div>
- {/each}
- <button class="ctab add" onclick={addCollage} title="New collage"><Icon name="plus" size={13} /></button>
- </div>
- {#if active}
- <div class="scale-row">
- <span class="lbl">Canvas</span>
- <input
- class="input dim"
- type="number"
- min={COLLAGE_MIN_DIM}
- max={COLLAGE_MAX_DIM}
- value={active.width}
- onchange={(e) => setDim(e, 'width')}
- aria-label="Canvas width in pixels"
- />
- <span class="sub">×</span>
- <input
- class="input dim"
- type="number"
- min={COLLAGE_MIN_DIM}
- max={COLLAGE_MAX_DIM}
- value={active.height}
- onchange={(e) => setDim(e, 'height')}
- aria-label="Canvas height in pixels"
- />
- <span class="sub">px</span>
- </div>
- <p class="hint">Pieces are placed and exported at this scale, so raise it to keep a
- high-resolution frame sharp.</p>
- {/if}
- </div>
-
<p class="hint">Drag pieces to arrange them, pull corners to warp; shift-click selects several.</p>
<div class="section">
- <div class="section-head"><span>Frames</span></div>
- <div class="tray">
- {#each session.frames as fr, i (fr.id)}
- {@const look = previewStyle(filters, fr.adjust)}
- {@const used = usedCount(fr.id)}
- <button
- class="thumb"
- class:used={used > 0}
- onclick={() => addToCollage(fr)}
- title={used ? `${frameLabel(fr, i)} · added ${used}×` : frameLabel(fr, i)}
- >
- <img
- src={fr.url}
- alt={frameLabel(fr, i)}
- style={styleText(cropImgStyle(fr.crop))}
- style:filter={look.filter}
- style:transform={look.transform}
- />
- <span class="num">{i + 1}</span>
- {#if used}
- <span class="tag count">×{used}</span>
- {:else}
- <span class="tag"><Icon name="plus" size={11} /></span>
- {/if}
- </button>
- {/each}
+ <div class="scale-row">
+ <span class="lbl">Canvas</span>
+ <input
+ class="input dim"
+ type="number"
+ min={COLLAGE_MIN_DIM}
+ max={COLLAGE_MAX_DIM}
+ value={active.width}
+ onchange={(e) => setDim(e, 'width')}
+ aria-label="Canvas width in pixels"
+ />
+ <span class="sub">×</span>
+ <input
+ class="input dim"
+ type="number"
+ min={COLLAGE_MIN_DIM}
+ max={COLLAGE_MAX_DIM}
+ value={active.height}
+ onchange={(e) => setDim(e, 'height')}
+ aria-label="Canvas height in pixels"
+ />
+ <span class="sub">px</span>
</div>
- {#if session.frames.length === 0}<p class="empty">No frames captured yet.</p>{/if}
+ <p class="hint">Pieces are placed and exported at this scale, so raise it to keep a
+ high-resolution frame sharp.</p>
</div>
- <p class="hint">Exports only the pieces as a <strong>transparent PNG</strong>, trimmed to their bounds.</p>
-
{#if selected}
<div class="section">
<div class="section-head"><span>Selected piece</span></div>
@@ -443,8 +307,7 @@
flex-direction: column;
gap: 12px;
}
- .hint,
- .empty {
+ .hint {
color: var(--text-3);
font-size: var(--fs-xs);
margin: 0;
@@ -462,126 +325,6 @@
font-weight: 600;
font-size: var(--fs-sm);
}
- .collage-tabs {
- display: flex;
- flex-wrap: wrap;
- gap: 6px;
- }
- .ctab {
- display: flex;
- align-items: center;
- border: 1px solid var(--border);
- border-radius: var(--r-sm);
- overflow: hidden;
- background: var(--bg-1);
- }
- .ctab.active {
- border-color: var(--border-strong);
- background: var(--bg-3);
- }
- .ctab-name {
- display: flex;
- align-items: center;
- gap: 5px;
- padding: 4px 8px;
- font-size: var(--fs-xs);
- color: var(--text-2);
- background: transparent;
- border: none;
- }
- .ctab.active .ctab-name {
- color: var(--accent);
- }
- .ctab-input {
- width: 9em;
- font: inherit;
- font-size: var(--fs-xs);
- color: var(--text-1);
- background: var(--bg-0);
- border: none;
- padding: 4px 8px;
- }
- .ctab-input:focus {
- outline: none;
- }
- .ctab-name .count {
- font-size: 9px;
- padding: 0 4px;
- border-radius: 8px;
- background: var(--bg-2);
- color: var(--text-3);
- }
- .ctab-x {
- display: flex;
- align-items: center;
- padding: 4px 5px;
- color: var(--text-3);
- background: transparent;
- border: none;
- border-left: 1px solid var(--border);
- }
- .ctab-x:hover {
- color: var(--danger, #d86a6a);
- }
- .ctab.add {
- padding: 4px 8px;
- color: var(--text-2);
- cursor: pointer;
- }
- .tray {
- display: flex;
- flex-wrap: wrap;
- gap: 6px;
- }
- .thumb {
- position: relative;
- width: 60px;
- height: 60px;
- border-radius: var(--r-sm);
- overflow: hidden;
- border: 2px solid transparent;
- padding: 0;
- }
- .thumb.used {
- border-color: var(--border-strong);
- }
- .thumb img {
- width: 100%;
- height: 100%;
- object-fit: cover;
- display: block;
- }
- .num {
- position: absolute;
- top: 2px;
- left: 2px;
- min-width: 15px;
- height: 15px;
- padding: 0 3px;
- border-radius: 4px;
- background: rgba(10, 10, 10, 0.7);
- color: #fff;
- font-size: 10px;
- font-weight: 700;
- line-height: 15px;
- text-align: center;
- }
- .tag {
- position: absolute;
- bottom: 2px;
- right: 2px;
- background: var(--accent);
- color: var(--accent-text);
- border-radius: 4px;
- display: flex;
- padding: 1px;
- }
- .tag.count {
- padding: 0 4px;
- font-size: 10px;
- font-weight: 700;
- line-height: 15px;
- }
.modes {
display: flex;
gap: 0;
diff --git a/frontend/src/tools/inspect/CollageMenu.test.js b/frontend/src/tools/inspect/CollageMenu.test.js
index ae3fb51..afe200d 100644
--- a/frontend/src/tools/inspect/CollageMenu.test.js
+++ b/frontend/src/tools/inspect/CollageMenu.test.js
@@ -3,56 +3,11 @@ import { readFileSync } from 'node:fs';
const source = readFileSync(new URL('./CollageMenu.svelte', import.meta.url), 'utf8');
-describe('CollageMenu renaming', () => {
- it('opens the tab you are already in for editing, and switches to the others', () => {
- expect(source).toContain(` if (cl.id === session.activeCollageId) {
- renamingId = cl.id;
- draftName = cl.name ?? '';
- } else {
- switchCollage(cl.id);
- }`);
- expect(source).toContain(
- "title={cl.id === session.activeCollageId ? 'Rename this collage' : 'Switch to this collage'}"
- );
- });
-
- it('commits on Enter or blur and abandons on Escape', () => {
- expect(source).toContain("if (event.key === 'Enter') commitRename(cl);");
- expect(source).toContain("else if (event.key === 'Escape') renamingId = null;");
- expect(source).toContain('onblur={() => commitRename(cl)}');
- });
-
- it('refuses to blank a collage name', () => {
- expect(source).toContain(` const next = draftName.trim();
- if (next && next !== cl.name) {`);
- });
-
- it('tells the Save tab the name is now the user\'s', () => {
- expect(source).toContain('onRename?.(cl);');
- });
-
- it('caps the name at the length the Save gate accepts', () => {
- expect(source).toContain('maxlength="200"');
- });
-});
-
-describe('CollageMenu frame tray', () => {
- it('numbers the tiles and names them like the Frame tab', () => {
- expect(source).toContain(
- "fr.time != null ? `Image ${i + 1} · t=${fr.time.toFixed(2)}s` : `Image ${i + 1}`"
- );
- expect(source).toContain('<span class="num">{i + 1}</span>');
- });
-
- it('counts how many pieces a frame already has on the collage', () => {
- expect(source).toContain(
- 'const usedCount = (id) => active?.nodes.filter((n) => n.frameId === id).length ?? 0;'
- );
- expect(source).toContain('<span class="tag count">×{used}</span>');
- });
-
- it('lets the panel scroll instead of boxing the tray in its own window', () => {
- expect(source).not.toContain('max-height: 200px');
+describe('CollageMenu scope', () => {
+ it('acts on the collage it is handed, and no longer switches between several', () => {
+ expect(source).toContain('let { collage: active, selectedIds = $bindable([]), requestCrop, renderPiece } = $props();');
+ expect(source).not.toContain('session.');
+ expect(source).not.toContain('addCollage');
});
});
diff --git a/frontend/src/tools/inspect/CollagePreview.svelte b/frontend/src/tools/inspect/CollagePreview.svelte
deleted file mode 100644
index 6b6a3e1..0000000
--- a/frontend/src/tools/inspect/CollagePreview.svelte
+++ /dev/null
@@ -1,79 +0,0 @@
-<script>
- import { quadMatrix3d, collageBounds } from '../../lib/inspect.js';
-
- // Read-only miniature of a collage layout — the same node quads/urls the Save
- // tab will composite. Framed to the pieces' trimmed bounds (not the full
- // canvas), so the thumbnail matches the exported PNG instead of showing the
- // empty working area around the pieces.
- let { collage } = $props();
-
- let availW = $state(150);
- let availH = $state(112);
-
- const bounds = $derived(collageBounds(collage.nodes));
- const scale = $derived(Math.min(availW / bounds.width, availH / bounds.height) || 0);
- const boxOf = (n) => ({ w: n.w || 320, h: n.h || 240, url: n.url });
-</script>
-
-<div class="prev" bind:clientWidth={availW} bind:clientHeight={availH}>
- <div
- class="surface"
- class:checker={collage.transparent}
- style:width={`${bounds.width}px`}
- style:height={`${bounds.height}px`}
- style:transform={`scale(${scale})`}
- style:background={collage.transparent ? null : collage.background}
- >
- <div class="layer" style:transform={`translate(${-bounds.minX}px, ${-bounds.minY}px)`}>
- {#each collage.nodes as node (node.id)}
- {@const box = boxOf(node)}
- <img
- class="node"
- src={box.url}
- alt="collage piece"
- style:width={`${box.w}px`}
- style:height={`${box.h}px`}
- style:transform={quadMatrix3d(box.w, box.h, node.quad)}
- draggable="false"
- />
- {/each}
- </div>
- </div>
-</div>
-
-<style>
- .prev {
- position: absolute;
- inset: 0;
- display: flex;
- align-items: center;
- justify-content: center;
- overflow: hidden;
- }
- .surface {
- position: relative;
- transform-origin: center;
- flex-shrink: 0;
- }
- .surface.checker {
- background-color: #2a2f3a;
- background-image:
- linear-gradient(45deg, rgba(255, 255, 255, 0.07) 25%, transparent 25%, transparent 75%, rgba(255, 255, 255, 0.07) 75%),
- linear-gradient(45deg, rgba(255, 255, 255, 0.07) 25%, transparent 25%, transparent 75%, rgba(255, 255, 255, 0.07) 75%);
- background-size: 16px 16px;
- background-position: 0 0, 8px 8px;
- }
- .layer {
- position: absolute;
- top: 0;
- left: 0;
- transform-origin: 0 0;
- }
- .node {
- position: absolute;
- top: 0;
- left: 0;
- transform-origin: 0 0;
- user-select: none;
- }
-</style>
diff --git a/frontend/src/tools/inspect/FrameMenu.render.test.js b/frontend/src/tools/inspect/FrameMenu.render.test.js
index d132588..e0d5157 100644
--- a/frontend/src/tools/inspect/FrameMenu.render.test.js
+++ b/frontend/src/tools/inspect/FrameMenu.render.test.js
@@ -3,13 +3,17 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
import { flushSync, mount, unmount } from 'svelte';
/**
- * The Frame tab's reverse-search press, driven the way an analyst drives it: the
+ * The frame panel's reverse-search press, driven the way an analyst drives it: the
* frame pressed on is the one handed over, and a second press while the first is
* still rendering does not send it twice.
*/
vi.mock('../../lib/api.js', () => ({ api: { post: vi.fn(), get: vi.fn() } }));
-vi.mock('../../lib/state.svelte.js', () => ({ caseState: { current: { id: 'case-a' } }, toast: vi.fn() }));
+vi.mock('../../lib/state.svelte.js', () => ({
+ caseState: { current: { id: 'case-a', folders: [] } },
+ uiState: { tool: 'inspect' },
+ toast: vi.fn(),
+}));
const { default: FrameMenu } = await import('./FrameMenu.svelte');
@@ -27,15 +31,14 @@ function open(reverse) {
live = mount(FrameMenu, {
target,
props: {
- session: { frames: [FRAME], activeFrameId: FRAME.id, saved: {} },
+ frame: FRAME,
filters: [],
analyses: [],
- activeFrame: FRAME,
shared: {},
- removeFrame: vi.fn(),
- setActive: vi.fn(),
setRotation: vi.fn(),
reverse,
+ onduplicate: vi.fn(),
+ frameSave: { defaultName: '00-00-12 clip', filedPath: null, busy: false, blocked: '', onsave: vi.fn() },
},
});
flushSync();
@@ -49,7 +52,7 @@ afterEach(() => {
target?.remove();
});
-describe('reverse search from the Frame tab', () => {
+describe('reverse search from a frame', () => {
it('hands over the active frame', async () => {
const reverse = vi.fn(async () => {});
open(reverse);
diff --git a/frontend/src/tools/inspect/FrameMenu.svelte b/frontend/src/tools/inspect/FrameMenu.svelte
index cd3e75d..c08f7b0 100644
--- a/frontend/src/tools/inspect/FrameMenu.svelte
+++ b/frontend/src/tools/inspect/FrameMenu.svelte
@@ -1,41 +1,47 @@
<script>
import { api } from '../../lib/api.js';
import { caseState, toast } from '../../lib/state.svelte.js';
- import { adjustDefaults, buildFrameOps, previewStyle, cropImgStyle, styleText } from '../../lib/inspect.js';
+ import { adjustDefaults, buildFrameOps } from '../../lib/inspect.js';
import Icon from '../../components/Icon.svelte';
import AdjustSliders from './AdjustSliders.svelte';
import CropControls from './CropControls.svelte';
import OrientationControls from './OrientationControls.svelte';
+ import SaveToCase from './SaveToCase.svelte';
- // Right-panel menu for the Frame tab. Works on the *active* tray frame:
- // pick it, adjust it (live-previewed), crop it, or analyse it — all without
- // filing anything. The recipe is committed later from the Save tab.
+ // The panel beside one frame: turn it, adjust it, crop it, then save it as
+ // media or read it closer. Edits are kept with the file's work as they are
+ // made; only Save to case puts a file in the Media Library.
let {
- session, filters, analyses, activeFrame, shared, removeFrame, setActive,
+ frame, filters, analyses, shared,
cropAspect = $bindable(null), cropEditing = $bindable(false), beginCrop, commitCrop,
- setRotation, rotationBusy = false, reverse,
+ setRotation, rotationBusy = false, reverse, onduplicate,
+ frameSave, folder = $bindable(''),
} = $props();
- let showAnalyze = $state(false);
let analyzing = $state(null);
let analysis = $state(null);
let canvasEl = $state();
let reversing = $state(false);
+ // A reading belongs to the frame it was run on.
+ $effect(() => {
+ frame.id;
+ analysis = null;
+ });
+
async function reverseActive() {
- if (!activeFrame || reversing) return;
+ if (reversing) return;
reversing = true;
try {
- await reverse(activeFrame);
+ await reverse(frame);
} finally {
reversing = false;
}
}
async function reset() {
- if (!activeFrame) return;
- activeFrame.adjust = adjustDefaults(filters);
- activeFrame.crop = null;
+ frame.adjust = adjustDefaults(filters);
+ frame.crop = null;
shared.cropMode = false;
cropAspect = null;
cropEditing = false;
@@ -43,22 +49,21 @@
}
function clearCrop() {
- if (activeFrame) activeFrame.crop = null;
+ frame.crop = null;
shared.cropMode = false;
cropAspect = null;
cropEditing = false;
}
async function runAnalysis(name) {
- if (!activeFrame) return;
analyzing = name;
analysis = null;
try {
analysis = await api.post(`/api/cases/${caseState.current.id}/inspect/analyze`, {
- path: activeFrame.path,
+ path: frame.path,
name,
- time: activeFrame.time ?? null,
- ops: buildFrameOps(filters, activeFrame),
+ time: frame.time ?? null,
+ ops: buildFrameOps(filters, frame),
});
if (analysis.kind === 'histogram') requestAnimationFrame(drawHistogram);
} catch (e) {
@@ -94,100 +99,88 @@
</script>
<div class="module">
- <div class="tray">
- {#each session.frames as fr, i (fr.id)}
- <div class="thumb" class:active={fr.id === session.activeFrameId}>
- <button class="pick" onclick={() => setActive(fr.id)} title={fr.time != null ? `Image ${i + 1} · t=${fr.time.toFixed(2)}s` : `Image ${i + 1}`}>
- <img
- src={fr.url}
- alt={`Image ${i + 1}`}
- style={styleText(cropImgStyle(fr.crop))}
- style:filter={previewStyle(filters, fr.adjust).filter}
- />
- <span class="num">{i + 1}</span>
- {#if session.saved[`frame:${fr.id}`]}<span class="saved" title="Saved"><Icon name="check" size={11} /></span>{/if}
- </button>
- <button class="del" onclick={() => removeFrame(fr.id)} aria-label="Remove frame" title="Remove frame"><Icon name="x" size={12} /></button>
- </div>
- {/each}
- {#if session.frames.length === 0}
- <p class="empty">No frames yet. Capture some in the Selection tab.</p>
- {/if}
- </div>
-
- {#if activeFrame}
- <div class="section">
- <div class="section-head"><span>Orientation</span></div>
- <OrientationControls
- value={activeFrame.rotation ?? 0}
- disabled={rotationBusy}
- onchange={setRotation}
- hint="The saved image uses this orientation."
- />
- <AdjustSliders {filters} values={activeFrame.adjust} />
- <div class="crop-block">
- <div class="crop-row">
- {#if cropEditing}
- <button class="btn btn-sm active" onclick={() => commitCrop?.()} title="Apply the crop (Enter)">
- <Icon name="check" size={14} /> Apply crop
- </button>
- <button class="btn btn-ghost btn-xs" onclick={() => (shared.cropMode = true)} title="Draw a fresh region">
- <Icon name="crop" size={13} /> Redraw
- </button>
- {:else}
- <button class="btn btn-sm" onclick={() => beginCrop?.()}>
- <Icon name="crop" size={14} /> {activeFrame.crop ? 'Edit crop' : 'Crop region'}
- </button>
- {#if activeFrame.crop}
- <span class="crop-info">or double-click the image</span>
- {/if}
- {/if}
- </div>
+ <div class="section first">
+ <div class="section-head"><span>Orientation</span></div>
+ <OrientationControls
+ value={frame.rotation ?? 0}
+ disabled={rotationBusy}
+ onchange={setRotation}
+ hint="The saved image uses this orientation."
+ />
+ <AdjustSliders {filters} values={frame.adjust} />
+ <div class="crop-block">
+ <div class="crop-row">
{#if cropEditing}
- <CropControls bind:crop={activeFrame.crop} bind:aspect={cropAspect} natW={activeFrame.w} natH={activeFrame.h} onclear={clearCrop} />
+ <button class="btn btn-sm active" onclick={() => commitCrop?.()} title="Apply the crop (Enter)">
+ <Icon name="check" size={14} /> Apply crop
+ </button>
+ <button class="btn btn-ghost btn-xs" onclick={() => (shared.cropMode = true)} title="Draw a fresh region">
+ <Icon name="crop" size={13} /> Redraw
+ </button>
+ {:else}
+ <button class="btn btn-sm" onclick={() => beginCrop?.()}>
+ <Icon name="crop" size={14} /> {frame.crop ? 'Edit crop' : 'Crop region'}
+ </button>
+ {#if frame.crop}
+ <span class="crop-info">or double-click the image</span>
+ {/if}
{/if}
</div>
- <button class="btn btn-ghost btn-sm reset" onclick={reset}><Icon name="reset" size={14} /> Reset frame</button>
- <button
- class="btn btn-sm reverse"
- disabled={reversing}
- onclick={reverseActive}
- title="Search the web for this image as it is adjusted and cropped here"
- >
- <Icon name="search" size={14} /> {reversing ? 'Preparing…' : 'Reverse image search'}
+ {#if cropEditing}
+ <CropControls bind:crop={frame.crop} bind:aspect={cropAspect} natW={frame.w} natH={frame.h} onclear={clearCrop} />
+ {/if}
+ </div>
+ <div class="row">
+ <button class="btn btn-ghost btn-sm" onclick={reset}><Icon name="reset" size={14} /> Reset frame</button>
+ <button class="btn btn-ghost btn-sm" onclick={() => onduplicate?.(frame)} title="A second copy to crop or adjust differently">
+ <Icon name="copy" size={14} /> Duplicate
</button>
</div>
+ </div>
- <div class="section">
- <button class="section-head as-btn" onclick={() => (showAnalyze = !showAnalyze)}>
- <span><Icon name="eye" size={14} /> Analyze</span>
- <Icon name={showAnalyze ? 'chevronDown' : 'chevronRight'} size={14} />
- </button>
- {#if showAnalyze}
- <div class="atabs">
- {#each analyses as a (a.id)}
- <button class="btn btn-sm" class:active={analyzing === a.id} onclick={() => runAnalysis(a.id)}>{a.label}</button>
- {/each}
- </div>
- {#if analyzing}
- <p class="hint"><Icon name="clock" size={13} /> Analysing…</p>
- {:else if analysis}
- {#if analysis.kind === 'keyvalue'}
- <table class="kv"><tbody>
- {#each Object.entries(analysis.rows) as [k, v] (k)}<tr><th>{k}</th><td class="mono">{v}</td></tr>{/each}
- </tbody></table>
- {:else if analysis.kind === 'histogram'}
- <canvas bind:this={canvasEl} class="hist"></canvas>
- {:else if analysis.kind === 'image'}
- <img class="ana-img" src={analysis.data_url} alt="analysis" />
- {#if analysis.note}<p class="note"><Icon name="alert" size={13} /> {analysis.note}</p>{/if}
- {:else if analysis.kind === 'text'}
- <pre class="text">{analysis.text}</pre>
- {/if}
- {/if}
- {/if}
+ <div class="section">
+ <SaveToCase
+ defaultName={frameSave.defaultName}
+ filedPath={frameSave.filedPath}
+ busy={frameSave.busy}
+ blocked={frameSave.blocked}
+ bind:folder
+ onsave={frameSave.onsave}
+ />
+ </div>
+
+ <div class="section">
+ <div class="section-head"><span><Icon name="eye" size={14} /> Analyze</span></div>
+ <div class="atabs">
+ {#each analyses as a (a.id)}
+ <button class="btn btn-sm" class:active={analyzing === a.id} disabled={!!analyzing} onclick={() => runAnalysis(a.id)}>{a.label}</button>
+ {/each}
</div>
- {/if}
+ {#if analyzing}
+ <p class="hint"><Icon name="clock" size={13} /> Analysing…</p>
+ {:else if analysis}
+ {#if analysis.kind === 'keyvalue'}
+ <table class="kv"><tbody>
+ {#each Object.entries(analysis.rows) as [k, v] (k)}<tr><th>{k}</th><td class="mono">{v}</td></tr>{/each}
+ </tbody></table>
+ {:else if analysis.kind === 'histogram'}
+ <canvas bind:this={canvasEl} class="hist"></canvas>
+ {:else if analysis.kind === 'image'}
+ <img class="ana-img" src={analysis.data_url} alt="analysis" />
+ {#if analysis.note}<p class="note"><Icon name="alert" size={13} /> {analysis.note}</p>{/if}
+ {:else if analysis.kind === 'text'}
+ <pre class="text">{analysis.text}</pre>
+ {/if}
+ {/if}
+ <button
+ class="btn btn-sm reverse"
+ disabled={reversing}
+ onclick={reverseActive}
+ title="Search the web for this image as it is adjusted and cropped here"
+ >
+ <Icon name="search" size={14} /> {reversing ? 'Preparing…' : 'Reverse image search'}
+ </button>
+ </div>
</div>
<style>
@@ -196,78 +189,6 @@
flex-direction: column;
gap: 12px;
}
- .tray {
- display: flex;
- gap: 6px;
- flex-wrap: wrap;
- }
- .thumb {
- position: relative;
- width: 60px;
- height: 60px;
- }
- .thumb .pick {
- position: relative;
- width: 100%;
- height: 100%;
- border-radius: var(--r-sm);
- overflow: hidden;
- border: 2px solid transparent;
- padding: 0;
- }
- .thumb.active .pick {
- border-color: var(--accent);
- }
- .thumb img {
- width: 100%;
- height: 100%;
- object-fit: cover;
- display: block;
- }
- .thumb .del {
- position: absolute;
- top: -6px;
- right: -6px;
- width: 18px;
- height: 18px;
- border-radius: 50%;
- background: var(--bg-2);
- border: 1px solid var(--border-strong);
- display: flex;
- align-items: center;
- justify-content: center;
- color: var(--text-2);
- }
- .num {
- position: absolute;
- top: 2px;
- left: 2px;
- min-width: 15px;
- height: 15px;
- padding: 0 3px;
- border-radius: 4px;
- background: rgba(10, 10, 10, 0.7);
- color: #fff;
- font-size: 10px;
- font-weight: 700;
- line-height: 15px;
- text-align: center;
- }
- .saved {
- position: absolute;
- bottom: 2px;
- left: 2px;
- background: var(--accent);
- color: var(--accent-text);
- border-radius: 4px;
- display: flex;
- padding: 1px;
- }
- .empty {
- color: var(--text-3);
- font-size: var(--fs-xs);
- margin: 4px 0;
- }
.section {
border-top: 1px solid var(--border);
padding-top: 12px;
@@ -293,10 +214,17 @@
color: var(--accent);
border-color: var(--accent);
}
- .reset,
.reverse {
align-self: flex-start;
}
+ .row {
+ display: flex;
+ gap: 6px;
+ }
+ .section.first {
+ border-top: 0;
+ padding-top: 0;
+ }
.section-head {
display: flex;
align-items: center;
@@ -309,12 +237,6 @@
align-items: center;
gap: 6px;
}
- .as-btn {
- width: 100%;
- background: none;
- color: var(--text-1);
- text-align: left;
- }
.atabs {
display: flex;
flex-wrap: wrap;
diff --git a/frontend/src/tools/inspect/FrameStrip.render.test.js b/frontend/src/tools/inspect/FrameStrip.render.test.js
new file mode 100644
index 0000000..a443c2e
--- /dev/null
+++ b/frontend/src/tools/inspect/FrameStrip.render.test.js
@@ -0,0 +1,95 @@
+// @vitest-environment happy-dom
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { flushSync, mount, unmount } from 'svelte';
+
+const { default: FrameStrip } = await import('./FrameStrip.svelte');
+
+const frame = (id, time, extra = {}) => ({
+ id, path: 'media/clip.mp4', time, url: `blob:${id}`, adjust: {}, crop: null, ...extra,
+});
+
+let live = null;
+let target = null;
+
+function show(props) {
+ target = document.createElement('div');
+ document.body.append(target);
+ const all = {
+ source: { kind: 'video', path: 'media/clip.mp4' },
+ frames: [],
+ selected: 'video',
+ filters: [],
+ filedIds: new Set(),
+ onselect: vi.fn(),
+ onremove: vi.fn(),
+ onsaveall: vi.fn(),
+ ...props,
+ };
+ live = mount(FrameStrip, { target, props: all });
+ flushSync();
+ return all;
+}
+
+const buttons = () => [...target.querySelectorAll('button')];
+
+afterEach(() => {
+ if (live) unmount(live);
+ live = null;
+ target?.remove();
+});
+
+describe('the frame strip', () => {
+ it('leads with the video, where frames come from', () => {
+ const props = show({ frames: [frame('a', 12.4)] });
+
+ const first = target.querySelector('.tile');
+ expect(first.textContent).toContain('Video');
+ first.click();
+ expect(props.onselect).toHaveBeenCalledWith('video');
+ });
+
+ it('names each frame by where it sits in the clip', () => {
+ const props = show({ frames: [frame('a', 12.4), frame('b', 75)] });
+
+ const pick = target.querySelector('button[aria-label="Frame 2 at 1:15.0"]');
+ expect(pick).not.toBeNull();
+ pick.click();
+ expect(props.onselect).toHaveBeenCalledWith('b');
+ });
+
+ it('says where captures go before there are any', () => {
+ show({ frames: [] });
+ expect(target.textContent).toContain('Frames you capture are kept with this video.');
+ });
+
+ it('offers to save every frame not in the case yet, once there are two', () => {
+ const props = show({ frames: [frame('a', 1), frame('b', 2), frame('c', 3)], filedIds: new Set(['a']) });
+
+ const saveAll = buttons().find((b) => b.textContent.includes('Save 2 frames'));
+ saveAll.click();
+ expect(props.onsaveall).toHaveBeenCalled();
+ expect(target.querySelectorAll('.filed')).toHaveLength(1);
+ });
+
+ it('keeps the save-all press out of the way for a single frame', () => {
+ show({ frames: [frame('a', 1)] });
+ expect(buttons().some((b) => b.textContent.includes('Save'))).toBe(false);
+ });
+
+ it('keeps the last frame of an image, which is the image itself', () => {
+ show({
+ source: { kind: 'image', path: 'media/roof.png' },
+ frames: [frame('a', null, { path: 'media/roof.png' })],
+ selected: 'a',
+ removable: false,
+ });
+ expect(target.querySelector('button[aria-label="Remove frame"]')).toBeNull();
+ expect(target.textContent).not.toContain('Video');
+ });
+
+ it('removes a frame on its own button', () => {
+ const props = show({ frames: [frame('a', 1)] });
+ target.querySelector('button[aria-label="Remove frame"]').click();
+ expect(props.onremove).toHaveBeenCalledWith('a');
+ });
+});
diff --git a/frontend/src/tools/inspect/FrameStrip.svelte b/frontend/src/tools/inspect/FrameStrip.svelte
new file mode 100644
index 0000000..92b93da
--- /dev/null
+++ b/frontend/src/tools/inspect/FrameStrip.svelte
@@ -0,0 +1,207 @@
+<script>
+ import { previewStyle, cropImgStyle, styleText } from '../../lib/inspect.js';
+ import Icon from '../../components/Icon.svelte';
+
+ // What has been cut from the open file, left to right in the order it was cut.
+ // A video leads with the clip itself, which is where frames come from; clicking
+ // a tile is what puts it in the viewer. The strip replaces the old tabs: there is
+ // no stage to move through, only the file and what was taken from it.
+ let {
+ source,
+ sourceThumb = null,
+ frames,
+ selected,
+ filters,
+ filedIds,
+ removable = true,
+ savingAll = false,
+ onselect,
+ onremove,
+ onsaveall,
+ } = $props();
+
+ const unfiled = $derived(frames.filter((f) => !filedIds.has(f.id) && f.url).length);
+
+ function stamp(t) {
+ const m = Math.floor(t / 60);
+ const s = (t % 60).toFixed(1).padStart(4, '0');
+ return `${m}:${s}`;
+ }
+
+ const label = (fr, i) => (fr.time != null ? `Frame ${i + 1} at ${stamp(fr.time)}` : `Frame ${i + 1}`);
+</script>
+
+<div class="strip" aria-label="Frames">
+ {#if source.kind === 'video'}
+ <button
+ class="tile source"
+ class:active={selected === 'video'}
+ onclick={() => onselect('video')}
+ title="The video, where frames are captured"
+ >
+ {#if sourceThumb}<img src={sourceThumb} alt="" />{:else}<Icon name="video" size={20} />{/if}
+ <span class="tag"><Icon name="play" size={10} /> Video</span>
+ </button>
+ {/if}
+
+ {#each frames as fr, i (fr.id)}
+ {@const look = previewStyle(filters, fr.adjust)}
+ <div class="tile" class:active={selected === fr.id}>
+ <button class="pick" onclick={() => onselect(fr.id)} title={label(fr, i)} aria-label={label(fr, i)}>
+ {#if fr.url}
+ <span class="crop">
+ <img src={fr.url} alt="" style={styleText(cropImgStyle(fr.crop))} style:filter={look.filter} />
+ </span>
+ {:else if fr.missing}
+ <Icon name="alert" size={16} />
+ {:else}
+ <span class="spinner" aria-hidden="true"></span>
+ {/if}
+ <span class="num">{fr.time != null ? stamp(fr.time) : i + 1}</span>
+ {#if filedIds.has(fr.id)}
+ <span class="filed" title="In the case"><Icon name="check" size={10} /></span>
+ {/if}
+ </button>
+ {#if removable}
+ <button class="del" onclick={() => onremove(fr.id)} aria-label="Remove frame" title="Remove frame">
+ <Icon name="x" size={11} />
+ </button>
+ {/if}
+ </div>
+ {/each}
+
+ {#if source.kind === 'video' && frames.length === 0}
+ <p class="empty">Frames you capture are kept with this video.</p>
+ {/if}
+
+ {#if unfiled > 1}
+ <button class="btn btn-sm save-all" disabled={savingAll} onclick={onsaveall} title="Save every frame not in the case yet">
+ <Icon name="save" size={13} /> {savingAll ? 'Saving…' : `Save ${unfiled} frames`}
+ </button>
+ {/if}
+</div>
+
+<style>
+ .strip {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 8px 12px;
+ border-top: 1px solid var(--border);
+ background: var(--bg-1);
+ overflow-x: auto;
+ flex-shrink: 0;
+ min-height: 76px;
+ }
+ .tile {
+ position: relative;
+ flex-shrink: 0;
+ width: 88px;
+ height: 58px;
+ border-radius: var(--r-sm);
+ border: 2px solid transparent;
+ background: var(--bg-0);
+ overflow: hidden;
+ }
+ .tile.active {
+ border-color: var(--accent);
+ }
+ button.tile,
+ .pick {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ width: 100%;
+ height: 100%;
+ padding: 0;
+ border: 0;
+ background: none;
+ color: var(--text-3);
+ cursor: pointer;
+ }
+ button.tile {
+ width: 88px;
+ border: 2px solid transparent;
+ background: var(--bg-0);
+ }
+ button.tile.active {
+ border-color: var(--accent);
+ }
+ .tile img {
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ }
+ .crop {
+ position: absolute;
+ inset: 0;
+ overflow: hidden;
+ }
+ .crop img {
+ position: absolute;
+ inset: 0;
+ }
+ .tag,
+ .num {
+ position: absolute;
+ left: 4px;
+ bottom: 3px;
+ display: flex;
+ align-items: center;
+ gap: 3px;
+ padding: 0 4px;
+ border-radius: 3px;
+ background: rgba(10, 10, 10, 0.65);
+ color: #fff;
+ font-size: 10px;
+ font-family: var(--font-mono);
+ }
+ .filed {
+ position: absolute;
+ top: 3px;
+ left: 3px;
+ display: flex;
+ padding: 2px;
+ border-radius: 50%;
+ background: var(--ok);
+ color: #fff;
+ }
+ .del {
+ position: absolute;
+ top: 2px;
+ right: 2px;
+ display: none;
+ padding: 2px;
+ border: 0;
+ border-radius: 3px;
+ background: rgba(10, 10, 10, 0.7);
+ color: #fff;
+ cursor: pointer;
+ }
+ .tile:hover .del,
+ .tile:focus-within .del {
+ display: flex;
+ }
+ .spinner {
+ width: 16px;
+ height: 16px;
+ border: 2px solid var(--border);
+ border-top-color: var(--accent);
+ border-radius: 50%;
+ animation: spin 0.8s linear infinite;
+ }
+ @keyframes spin {
+ to {
+ transform: rotate(360deg);
+ }
+ }
+ .empty {
+ margin: 0;
+ color: var(--text-3);
+ font-size: var(--fs-xs);
+ }
+ .save-all {
+ margin-left: auto;
+ flex-shrink: 0;
+ }
+</style>
diff --git a/frontend/src/tools/inspect/FrameViewer.render.test.js b/frontend/src/tools/inspect/FrameViewer.render.test.js
new file mode 100644
index 0000000..83f3365
--- /dev/null
+++ b/frontend/src/tools/inspect/FrameViewer.render.test.js
@@ -0,0 +1,93 @@
+// @vitest-environment happy-dom
+import { afterEach, describe, expect, it } from 'vitest';
+import { flushSync, mount, unmount } from 'svelte';
+
+const { default: FrameViewer } = await import('./FrameViewer.svelte');
+
+let live = null;
+let target = null;
+
+function show() {
+ target = document.createElement('div');
+ document.body.append(target);
+ live = mount(FrameViewer, {
+ target,
+ props: {
+ frame: { id: 'f1', url: 'blob:f1', w: 800, h: 600, crop: null, adjust: {} },
+ preview: { filter: '', transform: '' },
+ },
+ });
+ flushSync();
+}
+
+const viewport = () => target.querySelector('.viewport');
+const angle = () => [...target.querySelectorAll('.val')].map((el) => el.textContent).find((t) => t.endsWith('°'));
+
+function press(x, y, init = {}) {
+ viewport().dispatchEvent(new window.PointerEvent('pointerdown', { button: 1, clientX: x, clientY: y, bubbles: true, cancelable: true, ...init }));
+}
+function move(x, y, init = {}) {
+ window.dispatchEvent(new window.PointerEvent('pointermove', { clientX: x, clientY: y, ...init }));
+}
+function release() {
+ window.dispatchEvent(new window.PointerEvent('pointerup'));
+ flushSync();
+}
+
+afterEach(() => {
+ if (live) unmount(live);
+ live = null;
+ target?.remove();
+});
+
+// Points on a wheel of radius 100 about (100, 100), clockwise degrees from east.
+const on = (deg) => [100 + 100 * Math.cos((deg * Math.PI) / 180), 100 + 100 * Math.sin((deg * Math.PI) / 180)];
+
+describe('turning a frame', () => {
+ it('turns by the angle a middle drag sweeps about the grabbed point', () => {
+ show();
+ press(100, 100);
+ move(...on(0)); // out of the circle: the wheel is taken here
+ move(...on(20));
+ move(...on(40));
+ release();
+ expect(angle()).toBe('40°');
+ });
+
+ it('holds inside the guide circle', () => {
+ show();
+ press(100, 100);
+ move(110, 100);
+ move(100, 115); // a quarter turn about the pivot, all inside the circle
+ release();
+ expect(angle()).toBeUndefined();
+ });
+
+ it('settles upright near zero, and on whole steps with Ctrl', () => {
+ show();
+ press(100, 100);
+ move(...on(0));
+ move(...on(2)); // 2°: pulled upright
+ release();
+ expect(angle()).toBeUndefined();
+
+ press(100, 100);
+ move(...on(0));
+ move(...on(24), { ctrlKey: true }); // 24° laid on 30
+ release();
+ expect(angle()).toBe('30°');
+ });
+
+ it('stands the frame upright again on a middle click', () => {
+ show();
+ press(100, 100);
+ move(...on(0));
+ move(...on(40));
+ release();
+ expect(angle()).toBe('40°');
+ press(300, 300);
+ release();
+ expect(angle()).toBeUndefined();
+ expect(target.querySelector('.hint')?.textContent).toContain('middle-drag turns');
+ });
+});
diff --git a/frontend/src/tools/inspect/FrameViewer.svelte b/frontend/src/tools/inspect/FrameViewer.svelte
new file mode 100644
index 0000000..e2e60c7
--- /dev/null
+++ b/frontend/src/tools/inspect/FrameViewer.svelte
@@ -0,0 +1,273 @@
+<script>
+ import { cropAspect, cropImgStyle, styleText } from '../../lib/inspect.js';
+ import { IDENTITY, matrixCss, rotateAbout, isIdentity, matrixAngleDeg } from '../../lib/frameRotate.js';
+ import { beyondGuide, sweepDelta, turnBearing } from '../../lib/turn.js';
+ import TurnGuide from '../../components/TurnGuide.svelte';
+ import Icon from '../../components/Icon.svelte';
+ import CropBox from './CropBox.svelte';
+
+ // One frame, to be read closely. Wheel zooms toward the pointer, left-drag pans,
+ // middle-drag turns the view around the grabbed point (Google-Earth style). All
+ // three are view only and never saved: turning just helps read a tilted sign.
+ //
+ // Crop has two modes. *Editing* shows the original with a draggable box; once
+ // applied, the viewer shows the cropped result. Double-click or the panel's
+ // button goes back to editing. The parent owns begin/apply/cancel, since Escape
+ // has to put back the crop that editing started from.
+ let {
+ frame,
+ preview,
+ aspect = null,
+ cropEditing = false,
+ cropMode = $bindable(false),
+ onbegincrop,
+ oncommitcrop,
+ } = $props();
+
+ let zoom = $state(1);
+ let pan = $state({ x: 0, y: 0 });
+ let rotMatrix = $state(IDENTITY); // accumulated view rotation, in the stage's own space
+ let rotating = $state(false);
+ let pivot = $state({ x: 0, y: 0 }); // the turn's marker, viewport-local px
+ let stageEl = $state(); // rotated stage (image + crop overlay)
+ let zoomEl = $state(); // zoom/pan layer, the reference box for screen → local
+ let viewportEl = $state(); // outer viewport, the reference box for the marker
+
+ // A new frame starts from a fitted, upright view.
+ $effect(() => {
+ frame.id;
+ zoom = 1;
+ pan = { x: 0, y: 0 };
+ rotMatrix = IDENTITY;
+ });
+
+ const dirty = $derived(zoom !== 1 || pan.x !== 0 || pan.y !== 0 || !isIdentity(rotMatrix));
+ const angle = $derived(Math.round(matrixAngleDeg(rotMatrix)));
+
+ function reset() {
+ zoom = 1;
+ pan = { x: 0, y: 0 };
+ rotMatrix = IDENTITY;
+ }
+
+ // Never below the fitted size; at 1× the pan snaps back to centre so the image
+ // cannot drift off.
+ function onwheel(e) {
+ e.preventDefault();
+ const r = e.currentTarget.getBoundingClientRect();
+ const px = e.clientX - r.left;
+ const py = e.clientY - r.top;
+ const cX = r.width / 2;
+ const cY = r.height / 2;
+ const old = zoom;
+ const next = Math.min(Math.max(old * (e.deltaY > 0 ? 0.9 : 1.1), 1), 8);
+ if (next === 1) {
+ zoom = 1;
+ pan = { x: 0, y: 0 };
+ return;
+ }
+ // keep the point under the pointer fixed (transform-origin is the centre)
+ const ratio = next / old;
+ pan = {
+ x: px - (px - (cX + pan.x)) * ratio - cX,
+ y: py - (py - (cY + pan.y)) * ratio - cY,
+ };
+ zoom = next;
+ }
+
+ // The turn is a wheel about the grabbed point, the same as the maps
+ // (`lib/turn.js`): read outside the guide circle, upright pulls it in, Ctrl
+ // lays it on whole steps. It is kept as a matrix in the stage's own space, so
+ // every new grab pivots from wherever you click with no jump, whatever the
+ // view already looks like. A middle click that never moved stands the frame
+ // back upright.
+ const CLICK_SLOP = 4; // px a middle press may wander and still be a click
+ function rotateStart(e) {
+ if (!stageEl || !zoomEl || !viewportEl) return;
+ // The zoom/pan layer carries only translate + scale, so its box is a clean
+ // screen → local map; offsetLeft/Top place the stage's origin within it.
+ const layer = zoomEl.getBoundingClientRect();
+ const vp = viewportEl.getBoundingClientRect();
+ const px = (e.clientX - layer.left) / zoom - stageEl.offsetLeft;
+ const py = (e.clientY - layer.top) / zoom - stageEl.offsetTop;
+ const base = rotMatrix;
+ const baseAngle = matrixAngleDeg(base);
+ const grab = { x: e.clientX, y: e.clientY };
+ pivot = { x: e.clientX - vp.left, y: e.clientY - vp.top };
+ rotating = true;
+ let moved = false;
+ let last = null; // the last point outside the circle, null while inside
+ let swept = 0;
+ const move = (ev) => {
+ const at = { x: ev.clientX, y: ev.clientY };
+ if (!moved && Math.hypot(at.x - grab.x, at.y - grab.y) >= CLICK_SLOP) moved = true;
+ const out = beyondGuide(grab, at);
+ const delta = out && last ? sweepDelta(grab, last, at) : 0;
+ last = out ? at : null;
+ if (!delta) return;
+ swept += delta;
+ const to = turnBearing(baseAngle, swept, { stepped: ev.ctrlKey || ev.metaKey });
+ rotMatrix = rotateAbout(base, px, py, to - baseAngle);
+ };
+ const up = () => {
+ rotating = false;
+ if (!moved) rotMatrix = IDENTITY;
+ window.removeEventListener('pointermove', move);
+ window.removeEventListener('pointerup', up);
+ };
+ window.addEventListener('pointermove', move);
+ window.addEventListener('pointerup', up);
+ }
+
+ function panStart(e) {
+ const sx = e.clientX;
+ const sy = e.clientY;
+ const ox = pan.x;
+ const oy = pan.y;
+ const move = (ev) => {
+ pan = { x: ox + ev.clientX - sx, y: oy + ev.clientY - sy };
+ };
+ const up = () => {
+ window.removeEventListener('pointermove', move);
+ window.removeEventListener('pointerup', up);
+ };
+ window.addEventListener('pointermove', move);
+ window.addEventListener('pointerup', up);
+ }
+
+ function onpointerdown(e) {
+ if (e.button === 1) {
+ e.preventDefault();
+ if (!cropEditing) rotateStart(e); // the crop box stays upright
+ return;
+ }
+ if (e.button !== 0 || cropMode || cropEditing) return; // the crop box owns drags
+ e.preventDefault(); // no native image-drag ghost
+ panStart(e);
+ }
+</script>
+
+<!-- svelte-ignore a11y_no_static_element_interactions -->
+<div
+ class="viewport"
+ class:cropping={cropMode}
+ class:pannable={!cropMode && !cropEditing}
+ class:rotating
+ bind:this={viewportEl}
+ {onwheel}
+ onmousedown={(e) => e.button === 1 && e.preventDefault()}
+ {onpointerdown}
+ onauxclick={(e) => e.preventDefault()}
+ ondblclick={() => onbegincrop?.()}
+>
+ <div class="zoom-layer" bind:this={zoomEl} style:transform={`translate(${pan.x}px, ${pan.y}px) scale(${zoom})`}>
+ <div class="stage" bind:this={stageEl} style:transform={matrixCss(rotMatrix)} style:transform-origin="0 0">
+ {#if frame.crop && !cropEditing}
+ <div class="crop-view" style:--ar={cropAspect(frame.crop, frame.w, frame.h) ?? 1}>
+ <img
+ src={frame.url}
+ alt="frame"
+ draggable="false"
+ style={styleText(cropImgStyle(frame.crop))}
+ style:filter={preview.filter}
+ style:transform={preview.transform}
+ />
+ </div>
+ {:else}
+ <img src={frame.url} alt="frame" draggable="false" style:filter={preview.filter} style:transform={preview.transform} />
+ <CropBox bind:crop={frame.crop} bind:draw={cropMode} {aspect} natW={frame.w} natH={frame.h} />
+ {/if}
+ </div>
+ </div>
+ {#if rotating}
+ <TurnGuide x={pivot.x} y={pivot.y} />
+ {/if}
+ <div class="view-ctl">
+ {#if cropEditing}
+ <span class="hint">drag to crop · Enter applies · Esc cancels</span>
+ <button class="btn btn-sm" onclick={() => oncommitcrop?.()} title="Apply the crop (Enter)">
+ <Icon name="check" size={14} /> Apply
+ </button>
+ {:else if dirty}
+ {#if zoom !== 1}<span class="val">{Math.round(zoom * 100)}%</span>{/if}
+ {#if angle !== 0}<span class="val">{angle}°</span>{/if}
+ <button class="btn btn-ghost btn-sm" onclick={reset} title="Reset zoom, pan and turn">
+ <Icon name="eye" size={14} /> Fit
+ </button>
+ {:else}
+ <span class="hint">scroll zoom · drag pan · middle-drag turns · double-click crop</span>
+ {/if}
+ </div>
+</div>
+
+<style>
+ .viewport {
+ position: relative;
+ width: 100%;
+ height: 100%;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ overflow: hidden;
+ touch-action: none;
+ }
+ .viewport.pannable {
+ cursor: grab;
+ }
+ .viewport.cropping {
+ cursor: crosshair;
+ }
+ .viewport.rotating {
+ cursor: grabbing;
+ }
+ .zoom-layer {
+ position: relative;
+ transform-origin: center center;
+ display: inline-block;
+ line-height: 0;
+ }
+ .stage {
+ position: relative;
+ display: inline-block;
+ line-height: 0;
+ }
+ .stage > img {
+ max-width: 100%;
+ max-height: calc(100vh - var(--topbar-h) - 260px);
+ display: block;
+ }
+ .crop-view {
+ position: relative;
+ overflow: hidden;
+ aspect-ratio: var(--ar);
+ height: calc(100vh - var(--topbar-h) - 280px);
+ max-width: 100%;
+ line-height: 0;
+ }
+ .crop-view img {
+ display: block;
+ }
+ .view-ctl {
+ position: absolute;
+ right: 10px;
+ bottom: 10px;
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 3px 6px;
+ border-radius: var(--r-md);
+ background: rgba(22, 22, 22, 0.85);
+ border: 1px solid var(--border);
+ }
+ .val {
+ font-size: var(--fs-xs);
+ font-weight: 700;
+ color: var(--text-2);
+ font-variant-numeric: tabular-nums;
+ }
+ .hint {
+ font-size: 11px;
+ color: var(--text-3);
+ user-select: none;
+ }
+</style>
diff --git a/frontend/src/tools/inspect/PiecePicker.svelte b/frontend/src/tools/inspect/PiecePicker.svelte
new file mode 100644
index 0000000..038d15b
--- /dev/null
+++ b/frontend/src/tools/inspect/PiecePicker.svelte
@@ -0,0 +1,259 @@
+<script>
+ import { untrack } from 'svelte';
+ import { api } from '../../lib/api.js';
+ import { fileUrl } from '../../lib/fileUrl.js';
+ import { buildFrameOps } from '../../lib/inspect.js';
+ import Icon from '../../components/Icon.svelte';
+
+ // Where a collage's pieces come from: the frames cut in Inspect, from any file,
+ // or any image already in the case. A piece is a recipe frozen when it is added,
+ // so what is picked here stays as it was even if the frame is edited later.
+ let { caseId, filters, works, images, used, rev = 0, onadd } = $props();
+
+ let tab = $state('frames');
+ let open = $state({}); // work name -> expanded
+ let frames = $state({}); // work name -> [{ frame, thumb }] once fetched
+ const blobs = new Set();
+
+ // A thumbnail per frame, rendered as the frame reads (turned, adjusted, cropped),
+ // only for the files the analyst actually unfolds.
+ async function load(name) {
+ const saved = await api.get(`/api/cases/${caseId}/inspect/works/${encodeURIComponent(name)}`);
+ const list = (saved.spec?.frames ?? []).map((frame) => ({ frame, thumb: null }));
+ frames[name] = list;
+ for (const entry of frames[name]) {
+ try {
+ const res = await fetch(`/api/cases/${caseId}/inspect/render-preview`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ path: entry.frame.path, time: entry.frame.time ?? null, ops: buildFrameOps(filters, entry.frame) }),
+ });
+ if (!res.ok) throw new Error('render failed');
+ const url = URL.createObjectURL(await res.blob());
+ blobs.add(url);
+ entry.thumb = url;
+ } catch {
+ entry.missing = true;
+ }
+ }
+ }
+
+ function toggle(name) {
+ open[name] = !open[name];
+ if (open[name] && !frames[name]) load(name).catch(() => (frames[name] = []));
+ }
+
+ // A capture in Inspect since the last look means the frames shown are stale.
+ $effect(() => {
+ rev;
+ caseId;
+ for (const url of blobs) URL.revokeObjectURL(url);
+ blobs.clear();
+ frames = {};
+ untrack(() => {
+ for (const [name, isOpen] of Object.entries(open)) if (isOpen) load(name).catch(() => (frames[name] = []));
+ });
+ });
+
+ $effect(() => () => {
+ for (const url of blobs) URL.revokeObjectURL(url);
+ });
+
+ const stamp = (t) => `${Math.floor(t / 60)}:${(t % 60).toFixed(1).padStart(4, '0')}`;
+
+ function addFrame(frame) {
+ onadd({ frameId: frame.id, save: { path: frame.path, time: frame.time ?? null, ops: buildFrameOps(filters, frame) } });
+ }
+
+ function addImage(item) {
+ onadd({ frameId: null, save: { path: item.path, time: null, ops: [] } });
+ }
+</script>
+
+<div class="picker">
+ <div class="tabs" role="tablist">
+ <button role="tab" class:on={tab === 'frames'} aria-selected={tab === 'frames'} onclick={() => (tab = 'frames')}>
+ Frames
+ </button>
+ <button role="tab" class:on={tab === 'images'} aria-selected={tab === 'images'} onclick={() => (tab = 'images')}>
+ Images
+ </button>
+ </div>
+
+ {#if tab === 'frames'}
+ {#if !works.some((w) => w.frames)}
+ <p class="hint">Frames captured or edited in Inspect show up here, grouped by file.</p>
+ {/if}
+ {#each works.filter((w) => w.frames) as w (w.name)}
+ <div class="group">
+ <button class="group-head" onclick={() => toggle(w.name)} aria-expanded={!!open[w.name]}>
+ <Icon name={open[w.name] ? 'chevronDown' : 'chevronRight'} size={13} />
+ <Icon name={w.kind === 'video' ? 'video' : 'image'} size={13} />
+ <span class="name">{w.title}</span>
+ <span class="count">{w.frames}</span>
+ </button>
+ {#if open[w.name]}
+ <div class="thumbs">
+ {#each frames[w.name] ?? [] as entry (entry.frame.id)}
+ {@const times = used.get(entry.frame.id) ?? 0}
+ <button
+ class="thumb"
+ class:used={times > 0}
+ disabled={entry.missing}
+ onclick={() => addFrame(entry.frame)}
+ title={times ? `On this collage ${times}×` : 'Add to the collage'}
+ >
+ {#if entry.thumb}<img src={entry.thumb} alt="" />{:else if entry.missing}<Icon name="alert" size={14} />{:else}<span class="spinner"></span>{/if}
+ {#if entry.frame.time != null}<span class="num">{stamp(entry.frame.time)}</span>{/if}
+ <span class="tag">{#if times}×{times}{:else}<Icon name="plus" size={10} />{/if}</span>
+ </button>
+ {:else}
+ {#if frames[w.name]}
+ <span class="hint">No frames left here.</span>
+ {:else}
+ <span class="spinner" aria-label="Loading"></span>
+ {/if}
+ {/each}
+ </div>
+ {/if}
+ </div>
+ {/each}
+ {:else}
+ {#if !images.length}
+ <p class="hint">No images in the case yet.</p>
+ {/if}
+ <div class="thumbs">
+ {#each images as item (item.path)}
+ <button class="thumb" onclick={() => addImage(item)} title={item.title || item.filename}>
+ {#if item.thumbnail}<img src={fileUrl(caseId, item.thumbnail)} alt="" loading="lazy" />{:else}<Icon name="image" size={14} />{/if}
+ <span class="tag"><Icon name="plus" size={10} /></span>
+ </button>
+ {/each}
+ </div>
+ {/if}
+</div>
+
+<style>
+ .picker {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ }
+ .tabs {
+ display: flex;
+ flex-shrink: 0;
+ border: 1px solid var(--border);
+ border-radius: var(--r-sm);
+ overflow: hidden;
+ }
+ .tabs button {
+ flex: 1;
+ padding: 5px 4px;
+ font-size: var(--fs-xs);
+ color: var(--text-2);
+ background: transparent;
+ border: none;
+ }
+ .tabs button + button {
+ border-left: 1px solid var(--border);
+ }
+ .tabs .on {
+ background: var(--bg-3);
+ color: var(--accent);
+ }
+ .group {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ }
+ .group-head {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ width: 100%;
+ padding: 4px 2px;
+ background: none;
+ border: 0;
+ color: var(--text-1);
+ font-size: var(--fs-sm);
+ text-align: left;
+ }
+ .name {
+ flex: 1;
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ .count {
+ color: var(--text-3);
+ font-size: var(--fs-xs);
+ }
+ .thumbs {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 6px;
+ }
+ .thumb {
+ position: relative;
+ width: 64px;
+ height: 48px;
+ padding: 0;
+ display: grid;
+ place-items: center;
+ border: 2px solid transparent;
+ border-radius: var(--r-sm);
+ background: var(--bg-0);
+ color: var(--text-3);
+ overflow: hidden;
+ }
+ .thumb:hover {
+ border-color: var(--accent);
+ }
+ .thumb.used {
+ border-color: var(--border-strong);
+ }
+ .thumb img {
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ }
+ .num,
+ .tag {
+ position: absolute;
+ display: flex;
+ align-items: center;
+ padding: 0 3px;
+ border-radius: 3px;
+ background: rgba(10, 10, 10, 0.65);
+ color: #fff;
+ font-size: 9px;
+ }
+ .num {
+ left: 2px;
+ bottom: 2px;
+ font-family: var(--font-mono);
+ }
+ .tag {
+ right: 2px;
+ top: 2px;
+ }
+ .spinner {
+ width: 14px;
+ height: 14px;
+ border: 2px solid var(--border);
+ border-top-color: var(--accent);
+ border-radius: 50%;
+ animation: spin 0.8s linear infinite;
+ }
+ @keyframes spin {
+ to {
+ transform: rotate(360deg);
+ }
+ }
+ .hint {
+ color: var(--text-3);
+ font-size: var(--fs-xs);
+ margin: 0;
+ }
+</style>
diff --git a/frontend/src/tools/inspect/SaveGallery.svelte b/frontend/src/tools/inspect/SaveGallery.svelte
deleted file mode 100644
index 60c1ba5..0000000
--- a/frontend/src/tools/inspect/SaveGallery.svelte
+++ /dev/null
@@ -1,199 +0,0 @@
-<script>
- import Icon from '../../components/Icon.svelte';
- import CollagePreview from './CollagePreview.svelte';
-
- // Viewer side of the Save tab: everything this session produced that can be
- // filed — the enhanced video, each adjusted frame, the collage. Tick the ones
- // to commit; the menu on the right does the actual save.
- // `saveName`/`setSaveName` read and write wherever an item's name actually
- // lives — the session for a collage, saveUi for everything else — so this
- // gallery never has to know the difference.
- let { savables, saveUi, saveName, setSaveName } = $props();
-
- function toggle(key) {
- saveUi.selected[key] = !saveUi.selected[key];
- }
-</script>
-
-<div class="gallery">
- {#if savables.length === 0}
- <div class="empty">
- <Icon name="save" size={34} />
- <p>Nothing to save yet. Capture frames, build a collage, or adjust the video first.</p>
- </div>
- {:else}
- {#each savables as it (it.key)}
- <div class="card" class:sel={saveUi.selected[it.key]} class:saved={it.saved}>
- <button class="pick" onclick={() => toggle(it.key)} aria-label={`Select ${it.defaultName}`}>
- <div class="thumb">
- {#if it.kind === 'collage' && it.collage?.nodes.length}
- {#if it.preview}
- <!-- the actual composited PNG (backend warp), on a checker so alpha reads -->
- <div class="collage-real checker"><img src={it.preview} alt={it.defaultName} /></div>
- {:else}
- <CollagePreview collage={it.collage} />
- {/if}
- {:else if it.thumb}
- <img src={it.thumb} alt={it.defaultName} style:filter={it.filter} style:transform={it.transform} />
- {:else}
- <Icon name={it.kind === 'collage' ? 'layers' : it.kind === 'video' ? 'video' : 'image'} size={30} />
- {/if}
- <span class="kind"><Icon name={it.kind === 'video' ? 'video' : it.kind === 'collage' ? 'layers' : 'image'} size={12} /></span>
- <span class="tick"><Icon name="check" size={14} /></span>
- {#if it.saved}<span class="badge">saved</span>{/if}
- </div>
- </button>
- <input
- class="name"
- bind:value={() => saveName(it), (v) => setSaveName(it, v)}
- placeholder={it.defaultName}
- aria-label={`Name for ${it.defaultName}`}
- maxlength="200"
- />
- </div>
- {/each}
- {/if}
-</div>
-
-<style>
- .gallery {
- display: grid;
- grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
- gap: 12px;
- align-content: start;
- width: 100%;
- height: 100%;
- overflow: auto;
- padding: 4px;
- }
- .empty {
- grid-column: 1 / -1;
- display: flex;
- flex-direction: column;
- align-items: center;
- justify-content: center;
- gap: 10px;
- color: var(--text-3);
- text-align: center;
- min-height: 240px;
- }
- .empty p {
- max-width: 280px;
- font-size: var(--fs-sm);
- }
- .card {
- display: flex;
- flex-direction: column;
- gap: 6px;
- padding: 8px;
- border: 2px solid var(--border);
- border-radius: var(--r-md);
- background: var(--bg-1);
- text-align: left;
- position: relative;
- }
- .pick {
- display: block;
- width: 100%;
- padding: 0;
- border: 0;
- background: none;
- }
- .card.sel {
- border-color: var(--accent);
- }
- .thumb {
- position: relative;
- aspect-ratio: 4 / 3;
- display: flex;
- align-items: center;
- justify-content: center;
- background: var(--bg-0);
- border-radius: var(--r-sm);
- overflow: hidden;
- color: var(--text-3);
- }
- .thumb img {
- width: 100%;
- height: 100%;
- object-fit: cover;
- }
- .collage-real {
- position: absolute;
- inset: 0;
- display: flex;
- align-items: center;
- justify-content: center;
- }
- .collage-real img {
- width: 100%;
- height: 100%;
- object-fit: contain;
- }
- .checker {
- background-color: #2a2f3a;
- background-image:
- linear-gradient(45deg, rgba(255, 255, 255, 0.07) 25%, transparent 25%, transparent 75%, rgba(255, 255, 255, 0.07) 75%),
- linear-gradient(45deg, rgba(255, 255, 255, 0.07) 25%, transparent 25%, transparent 75%, rgba(255, 255, 255, 0.07) 75%);
- background-size: 16px 16px;
- background-position: 0 0, 8px 8px;
- }
- .kind {
- position: absolute;
- top: 4px;
- left: 4px;
- background: rgba(10, 10, 10, 0.6);
- color: #fff;
- border-radius: 4px;
- display: flex;
- padding: 2px;
- }
- .tick {
- position: absolute;
- top: 4px;
- right: 4px;
- width: 22px;
- height: 22px;
- border-radius: 50%;
- background: var(--bg-2);
- border: 1px solid var(--border-strong);
- display: flex;
- align-items: center;
- justify-content: center;
- color: transparent;
- }
- .card.sel .tick {
- background: var(--accent);
- border-color: var(--accent);
- color: var(--accent-text);
- }
- .name {
- width: 100%;
- font: inherit;
- font-size: var(--fs-sm);
- color: var(--text-1);
- background: var(--bg-0);
- border: 1px solid var(--border);
- border-radius: var(--r-sm);
- padding: 3px 6px;
- }
- .name:focus {
- outline: none;
- border-color: var(--accent);
- }
- .name::placeholder {
- color: var(--text-3);
- }
- .badge {
- position: absolute;
- bottom: 4px;
- right: 4px;
- font-size: 9px;
- text-transform: uppercase;
- letter-spacing: 0.04em;
- padding: 1px 5px;
- border-radius: 4px;
- background: var(--bg-3);
- color: var(--text-2);
- }
-</style>
diff --git a/frontend/src/tools/inspect/SaveGallery.test.js b/frontend/src/tools/inspect/SaveGallery.test.js
deleted file mode 100644
index 7ffff00..0000000
--- a/frontend/src/tools/inspect/SaveGallery.test.js
+++ /dev/null
@@ -1,69 +0,0 @@
-import { describe, expect, it } from 'vitest';
-import { render } from 'svelte/server';
-import { readFileSync } from 'node:fs';
-import SaveGallery from './SaveGallery.svelte';
-
-const source = readFileSync(new URL('./SaveGallery.svelte', import.meta.url), 'utf8');
-
-const SAVABLES = [
- { key: 'frame:1', kind: 'frame', defaultName: 'roof 00-01-00', thumb: '/files/c/a.png' },
- { key: 'frame:2', kind: 'frame', defaultName: 'roof 00-02-00', thumb: '/files/c/b.png' },
-];
-
-function body(overrides = {}) {
- const saveUi = { selected: {}, folder: '', touched: {}, baseName: '', note: '' };
- const names = { 'frame:1': 'roof 00-01-00', 'frame:2': 'roof 00-02-00', ...overrides.names };
- return render(SaveGallery, {
- props: {
- savables: SAVABLES,
- saveUi,
- saveName: (it) => names[it.key] ?? '',
- setSaveName: (it, v) => (names[it.key] = v),
- ...overrides,
- },
- }).body;
-}
-
-describe('SaveGallery naming', () => {
- it('offers a name field per card instead of a fixed label', () => {
- const html = body();
- expect(html).toContain('aria-label="Name for roof 00-01-00"');
- expect(html).toContain('aria-label="Name for roof 00-02-00"');
- expect(html).not.toContain('class="label"');
- });
-
- it('holds the name as editable text, not a placeholder to guess at', () => {
- const html = body();
- expect(html).toContain('value="roof 00-01-00"');
- expect(html).toContain('value="roof 00-02-00"');
- });
-
- it('shows the base name the gallery was refilled with', () => {
- const html = body({ names: { 'frame:1': 'Roof 01', 'frame:2': 'Roof 02' } });
- expect(html).toContain('value="Roof 01"');
- });
-
- it('reads and writes through the owner of the name, not a local copy', () => {
- expect(source).toContain('bind:value={() => saveName(it), (v) => setSaveName(it, v)}');
- expect(source).not.toContain('saveUi.names[it.key]');
- });
-
- it('caps a name at the length the API accepts', () => {
- expect(body()).toContain('maxlength="200"');
- });
-
-
-
- it('keeps the thumbnail as the tick target, so typing does not toggle it', () => {
- expect(source).toContain('<button class="pick" onclick={() => toggle(it.key)}');
- expect(source).not.toContain('<button class="card"');
- });
-
- it('moves the saved badge onto the thumbnail, clear of the name field', () => {
- const saved = [{ ...SAVABLES[0], saved: true }];
- const html = body({ savables: saved });
- expect(html).toContain('saved');
- expect(source).toContain(`{#if it.saved}<span class="badge">saved</span>{/if}
- </div>`);
- });
-});
diff --git a/frontend/src/tools/inspect/SaveMenu.svelte b/frontend/src/tools/inspect/SaveMenu.svelte
deleted file mode 100644
index 4f9e327..0000000
--- a/frontend/src/tools/inspect/SaveMenu.svelte
+++ /dev/null
@@ -1,88 +0,0 @@
-<script>
- import { caseState, uiState } from '../../lib/state.svelte.js';
- import Icon from '../../components/Icon.svelte';
- import FolderSelect from '../../components/FolderSelect.svelte';
-
- // Right-panel menu for the Save tab: choose a destination folder and commit the
- // ticked items. This is the *only* place the Inspect session files case
- // entities — nothing before it touched the case.
- let { savables, saveUi, saving, save } = $props();
-
- const folders = $derived(caseState.current?.folders ?? []);
- const count = $derived(savables.filter((it) => saveUi.selected[it.key]).length);
-
- function selectAll() {
- for (const it of savables) saveUi.selected[it.key] = true;
- }
- function selectNone() {
- saveUi.selected = {};
- }
-</script>
-
-<div class="module">
- <p class="hint">Tick what to save. Names carry into the Media Library with the provenance.</p>
-
- <div class="pickers">
- <button class="btn btn-sm" onclick={selectAll} disabled={!savables.length}>Select all</button>
- <button class="btn btn-sm" onclick={selectNone} disabled={!count}>Clear</button>
- </div>
-
- <label class="field">
- <span><Icon name="edit" size={14} /> Base name (optional)</span>
- <input class="input" bind:value={saveUi.baseName} placeholder="Names the batch" maxlength="200" />
- </label>
-
- <div class="field">
- <span><Icon name="folder" size={14} /> Folder (optional)</span>
- <FolderSelect bind:value={saveUi.folder} {folders} emptyLabel="Unfiled" />
- </div>
-
- <label class="field">
- <span><Icon name="note" size={14} /> Note (optional)</span>
- <textarea class="input note" bind:value={saveUi.note} rows="2" placeholder="Why these matter" maxlength="2000"></textarea>
- </label>
-
- <button class="btn btn-primary w-full" disabled={saving || !count} onclick={save}>
- <Icon name="save" size={15} /> {saving ? 'Saving…' : `Save ${count || ''} to case`.trim()}
- </button>
-
- <button class="btn btn-ghost btn-sm w-full" onclick={() => (uiState.tool = 'media')}>
- <Icon name="media" size={14} /> Open Media Library
- </button>
-</div>
-
-<style>
- .module {
- display: flex;
- flex-direction: column;
- gap: 12px;
- }
- .hint {
- color: var(--text-3);
- font-size: var(--fs-xs);
- margin: 0;
- }
- .pickers {
- display: flex;
- gap: 6px;
- }
- .field {
- display: flex;
- flex-direction: column;
- gap: 5px;
- font-size: var(--fs-sm);
- color: var(--text-2);
- }
- .field span {
- display: flex;
- align-items: center;
- gap: 6px;
- }
- .note {
- resize: vertical;
- }
- .w-full {
- width: 100%;
- justify-content: center;
- }
-</style>
diff --git a/frontend/src/tools/inspect/SaveMenu.test.js b/frontend/src/tools/inspect/SaveMenu.test.js
deleted file mode 100644
index 69e1cc9..0000000
--- a/frontend/src/tools/inspect/SaveMenu.test.js
+++ /dev/null
@@ -1,37 +0,0 @@
-import { describe, expect, it, vi } from 'vitest';
-import { render } from 'svelte/server';
-import SaveMenu from './SaveMenu.svelte';
-
-const SAVABLES = [
- { key: 'frame:1', kind: 'frame', defaultName: 'roof 00-01-00' },
- { key: 'frame:2', kind: 'frame', defaultName: 'roof 00-02-00' },
-];
-
-function body(overrides = {}) {
- const saveUi = { selected: {}, folder: '', names: {}, baseName: '', note: '' };
- return render(SaveMenu, {
- props: { savables: SAVABLES, saveUi, saving: false, save: vi.fn(), ...overrides },
- }).body;
-}
-
-describe('SaveMenu naming', () => {
- it('offers a base name for the whole batch', () => {
- const html = body();
- expect(html).toContain('Base name (optional)');
- expect(html).toContain('placeholder="Names the batch"');
- });
-
- it('offers one note for the batch, capped at the length the API accepts', () => {
- const html = body();
- expect(html).toContain('Note (optional)');
- expect(html).toContain('maxlength="2000"');
- });
-
- it('still offers the folder, unchanged', () => {
- expect(body()).toContain('Folder (optional)');
- });
-
- it('says names carry into the library, in one clause', () => {
- expect(body()).toContain('Tick what to save. Names carry into the Media Library with the provenance.');
- });
-});
diff --git a/frontend/src/tools/inspect/SaveToCase.render.test.js b/frontend/src/tools/inspect/SaveToCase.render.test.js
new file mode 100644
index 0000000..75a3b87
--- /dev/null
+++ b/frontend/src/tools/inspect/SaveToCase.render.test.js
@@ -0,0 +1,94 @@
+// @vitest-environment happy-dom
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { flushSync, mount, unmount } from 'svelte';
+
+const uiState = { tool: 'inspect', focusMedia: null };
+vi.mock('../../lib/state.svelte.js', () => ({
+ caseState: { current: { id: 'case-a', folders: ['Roofs'] } },
+ uiState,
+}));
+
+const { default: SaveToCase } = await import('./SaveToCase.svelte');
+
+let live = null;
+let target = null;
+
+function show(props) {
+ target = document.createElement('div');
+ document.body.append(target);
+ live = mount(SaveToCase, { target, props: { defaultName: '00-00-12 roof', onsave: vi.fn(async () => {}), ...props } });
+ flushSync();
+ return props;
+}
+
+const nameField = () => target.querySelector('input[aria-label="Name"]');
+const saveButton = () => [...target.querySelectorAll('button')].find((b) => /Save to case|Saved|Saving/.test(b.textContent) && b.classList.contains('btn-primary'));
+
+afterEach(() => {
+ if (live) unmount(live);
+ live = null;
+ target?.remove();
+});
+
+describe('Save to case', () => {
+ it('holds real text from the start, never a placeholder to guess at', () => {
+ show({});
+ expect(nameField().value).toBe('00-00-12 roof');
+ });
+
+ it('files under the typed name, and falls back to the default when the field is cleared', async () => {
+ const onsave = vi.fn(async () => {});
+ show({ onsave });
+
+ nameField().value = ' Chimney ';
+ nameField().dispatchEvent(new Event('input', { bubbles: true }));
+ flushSync();
+ saveButton().click();
+ await Promise.resolve();
+ expect(onsave).toHaveBeenLastCalledWith({ name: 'Chimney', folder: null, note: null });
+ await Promise.resolve();
+ flushSync();
+ // the next output starts from its own default, not from the last typed name
+ expect(nameField().value).toBe('00-00-12 roof');
+
+ nameField().value = ' ';
+ nameField().dispatchEvent(new Event('input', { bubbles: true }));
+ flushSync();
+ saveButton().click();
+ await Promise.resolve();
+ expect(onsave).toHaveBeenLastCalledWith({ name: '00-00-12 roof', folder: null, note: null });
+ });
+
+ it('carries a note once one is asked for', async () => {
+ const onsave = vi.fn(async () => {});
+ show({ onsave });
+
+ [...target.querySelectorAll('button')].find((b) => b.textContent.includes('Add a note')).click();
+ flushSync();
+ const note = target.querySelector('textarea[aria-label="Note"]');
+ note.value = 'The sign names the street';
+ note.dispatchEvent(new Event('input'));
+ flushSync();
+ saveButton().click();
+ await Promise.resolve();
+
+ expect(onsave).toHaveBeenCalledWith({ name: '00-00-12 roof', folder: null, note: 'The sign names the street' });
+ });
+
+ it('says an output is already in the case, and leads to it', () => {
+ show({ filedPath: 'media/00-00-12 roof.png' });
+
+ expect(saveButton().disabled).toBe(true);
+ expect(saveButton().textContent).toContain('Saved');
+ [...target.querySelectorAll('button')].find((b) => b.textContent.includes('In the case')).click();
+ expect(uiState.focusMedia).toBe('media/00-00-12 roof.png');
+ expect(uiState.tool).toBe('media');
+ });
+
+ it('says why a save cannot happen yet, instead of failing on the press', () => {
+ show({ blocked: 'Add a piece first.' });
+
+ expect(saveButton().disabled).toBe(true);
+ expect(target.textContent).toContain('Add a piece first.');
+ });
+});
diff --git a/frontend/src/tools/inspect/SaveToCase.svelte b/frontend/src/tools/inspect/SaveToCase.svelte
new file mode 100644
index 0000000..614a9e1
--- /dev/null
+++ b/frontend/src/tools/inspect/SaveToCase.svelte
@@ -0,0 +1,118 @@
+<script>
+ import { caseState, uiState } from '../../lib/state.svelte.js';
+ import { saveNameOf } from '../../lib/inspect.js';
+ import Icon from '../../components/Icon.svelte';
+ import FolderSelect from '../../components/FolderSelect.svelte';
+
+ // Files one output as case media: a frame, the adjusted video, an exported
+ // collage. Everything else in Examine is kept with the work as it is made; this
+ // is the one step that puts a file in the Media Library.
+ //
+ // `filedPath` is the media the last save produced, while the output still reads
+ // as it did then. An edit since clears it, and the button offers the save again.
+ let {
+ defaultName,
+ filedPath = null,
+ busy = false,
+ blocked = '',
+ hint = '',
+ folder = $bindable(''),
+ onsave,
+ } = $props();
+
+ // The field holds real text from the start. It follows the default until the
+ // analyst types in it, and is theirs from then on.
+ let typed = $state(null);
+ let note = $state('');
+ let noting = $state(false);
+ const name = $derived(typed ?? defaultName);
+ const folders = $derived(caseState.current?.folders ?? []);
+
+ async function save() {
+ await onsave({ name: saveNameOf({ defaultName }, name), folder: folder || null, note: note.trim() || null });
+ typed = null;
+ note = '';
+ noting = false;
+ }
+
+ function showInLibrary() {
+ uiState.focusMedia = filedPath;
+ uiState.tool = 'media';
+ }
+</script>
+
+<div class="save">
+ <div class="head">
+ <span><Icon name="save" size={14} /> Save to case</span>
+ {#if filedPath}
+ <button class="btn btn-ghost btn-xs filed" onclick={showInLibrary} title="Show it in the Media Library">
+ <Icon name="check" size={12} /> In the case
+ </button>
+ {/if}
+ </div>
+ <input
+ class="input"
+ value={name}
+ oninput={(e) => (typed = e.currentTarget.value)}
+ aria-label="Name"
+ maxlength="200"
+ />
+ <FolderSelect bind:value={folder} {folders} emptyLabel="Unfiled" />
+ {#if noting}
+ <textarea class="input note" bind:value={note} rows="2" placeholder="Why it matters" maxlength="2000" aria-label="Note"></textarea>
+ {:else}
+ <button class="btn btn-ghost btn-xs add-note" onclick={() => (noting = true)}>
+ <Icon name="note" size={12} /> Add a note
+ </button>
+ {/if}
+ <button class="btn btn-primary btn-sm w-full" disabled={busy || !!blocked || !!filedPath} onclick={save}>
+ <Icon name="save" size={14} />
+ {busy ? 'Saving…' : filedPath ? 'Saved' : 'Save to case'}
+ </button>
+ {#if blocked}
+ <p class="hint warn">{blocked}</p>
+ {:else if hint}
+ <p class="hint">{hint}</p>
+ {/if}
+</div>
+
+<style>
+ .save {
+ display: flex;
+ flex-direction: column;
+ gap: 7px;
+ }
+ .head {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ font-weight: 600;
+ font-size: var(--fs-sm);
+ }
+ .head span {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ }
+ .filed {
+ color: var(--ok);
+ }
+ .add-note {
+ align-self: flex-start;
+ }
+ .note {
+ resize: vertical;
+ }
+ .w-full {
+ width: 100%;
+ justify-content: center;
+ }
+ .hint {
+ color: var(--text-3);
+ font-size: var(--fs-xs);
+ margin: 0;
+ }
+ .warn {
+ color: var(--warn);
+ }
+</style>
diff --git a/frontend/src/tools/inspect/SelectionMenu.svelte b/frontend/src/tools/inspect/VideoMenu.svelte
similarity index 82%
rename from frontend/src/tools/inspect/SelectionMenu.svelte
rename to frontend/src/tools/inspect/VideoMenu.svelte
index 0911cba..4acb2ad 100644
--- a/frontend/src/tools/inspect/SelectionMenu.svelte
+++ b/frontend/src/tools/inspect/VideoMenu.svelte
@@ -5,11 +5,15 @@
import Icon from '../../components/Icon.svelte';
import AdjustSliders from './AdjustSliders.svelte';
import OrientationControls from './OrientationControls.svelte';
+ import SaveToCase from './SaveToCase.svelte';
- // Right-panel menu for the Selection tab: scrub the video, capture frames into
- // the transient tray (nothing is filed here), and tune video-level adjustments
- // via the gear — those feed the optional "enhanced video" saved in the Save tab.
- let { probeInfo, shared, videoFilters, session, capture } = $props();
+ // The panel beside the video: scrub it, capture frames (kept with the video's
+ // work as they are taken), and tune the whole clip. A turned or adjusted clip
+ // can be saved as a new video; the original is never touched.
+ let {
+ probeInfo, shared, videoFilters, work, capture,
+ videoEdited = false, videoSave, folder = $bindable(''),
+ } = $props();
let suggestions = $state([]);
let scanning = $state(false);
@@ -46,7 +50,7 @@
suggestions = [];
try {
const { job_id } = await api.post(`/api/cases/${caseState.current.id}/inspect/suggest`, {
- path: session.source.path,
+ path: work.source.path,
count: 12,
});
suggestions = await poll(job_id);
@@ -67,10 +71,10 @@
}
const maxScore = $derived(Math.max(1, ...suggestions.map((s) => s.score)));
- const gearActive = $derived(!isNeutral(videoFilters, session.videoAdjust));
+ const gearActive = $derived(!isNeutral(videoFilters, work.videoAdjust));
function resetVideoAdjust() {
- session.videoAdjust = adjustDefaults(videoFilters);
+ work.videoAdjust = adjustDefaults(videoFilters);
}
</script>
@@ -90,19 +94,15 @@
</div>
<button class="btn btn-primary w-full" disabled={capturing} onclick={() => grab()}>
- <Icon name="image" size={15} /> Capture frame to tray
+ <Icon name="image" size={15} /> Capture frame
</button>
- <p class="hint tray-note">
- <Icon name="layers" size={12} /> {session.frames.length} frame{session.frames.length === 1 ? '' : 's'}
- in the tray. Nothing is saved until you use the Save tab.
- </p>
<div class="section">
<div class="section-head"><span>Orientation</span></div>
<OrientationControls
- value={session.videoRotation}
- onchange={(angle) => (session.videoRotation = angle)}
- hint="The saved video and any new frames use this orientation."
+ value={work.videoRotation}
+ onchange={(angle) => (work.videoRotation = angle)}
+ hint="New frames and a saved video use this orientation."
/>
</div>
@@ -112,14 +112,27 @@
<Icon name={showGear ? 'chevronDown' : 'chevronRight'} size={14} />
</button>
{#if showGear}
- <p class="hint">Preview the whole clip brighter/clearer; save an enhanced copy in Save.</p>
- <AdjustSliders filters={videoFilters} values={session.videoAdjust} />
+ <p class="hint">Applies to the whole clip and to the frames captured from now on.</p>
+ <AdjustSliders filters={videoFilters} values={work.videoAdjust} />
<button class="btn btn-ghost btn-sm reset" disabled={!gearActive} onclick={resetVideoAdjust}>
<Icon name="reset" size={14} /> Reset adjustments
</button>
{/if}
</div>
+ {#if videoEdited}
+ <div class="section">
+ <SaveToCase
+ defaultName={videoSave.defaultName}
+ filedPath={videoSave.filedPath}
+ busy={videoSave.busy}
+ bind:folder
+ hint="Re-encodes the whole clip turned and adjusted as shown."
+ onsave={videoSave.onsave}
+ />
+ </div>
+ {/if}
+
<div class="section">
<div class="section-head">
<span>Sharpest frames</span>
@@ -173,12 +186,6 @@
width: 100%;
justify-content: center;
}
- .tray-note {
- display: flex;
- align-items: center;
- gap: 5px;
- margin: -4px 0 0;
- }
.section {
border-top: 1px solid var(--border);
padding-top: 12px;
diff --git a/frontend/src/tools/proof/PointMapDialog.svelte b/frontend/src/tools/proof/PointMapDialog.svelte
index 20ec65e..3fc31f6 100644
--- a/frontend/src/tools/proof/PointMapDialog.svelte
+++ b/frontend/src/tools/proof/PointMapDialog.svelte
@@ -17,10 +17,12 @@
import { onMount, untrack } from 'svelte';
import Modal from '../../components/Modal.svelte';
import Icon from '../../components/Icon.svelte';
+ import TurnGuide from '../../components/TurnGuide.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 { turnFromKey, turnFromPress } from '../../lib/map/gestures.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.
@@ -45,7 +47,9 @@
const imagery = createImageryState({ api });
let providerId = $state(FALLBACK_PROVIDER);
let engine = $state(null);
+ let element = $state(null);
let ready = $state(false);
+ let rotating = $state(null); // the grabbed point while the map turns
// 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 })));
@@ -105,6 +109,20 @@
};
});
+ // The same turn as every other map: a middle-drag, or Shift and the left
+ // button, about the grabbed point; Shift and an arrow from the keyboard.
+ $effect(() => {
+ if (!element || !engine) return;
+ const surface = element;
+ const down = (event) =>
+ turnFromPress(engine, event, {
+ onPivot: (point) => (rotating = point),
+ onEnd: () => (rotating = null),
+ });
+ surface.addEventListener('mousedown', down, true);
+ return () => surface.removeEventListener('mousedown', down, true);
+ });
+
// 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.
@@ -114,10 +132,13 @@
});
</script>
+<svelte:window onkeydown={(event) => turnFromKey(engine, event)} />
+
<Modal title="Move the point" {onclose} width="900px">
<div class="stage">
<MapSurface
bind:engine
+ bind:element
bind:ready
bind:providerId
{imagery}
@@ -127,6 +148,9 @@
controlsTop={8}
onclick={(clicked) => (at = clicked)}
/>
+ {#if rotating}
+ <TurnGuide x={rotating.x} y={rotating.y} />
+ {/if}
<div class="layers" class:open={layersOpen}>
{#if layersOpen}
<MapLayers rows={layerRows} bind:open={layersOpen} />
diff --git a/frontend/src/tools/satellite/MapContextMenu.svelte b/frontend/src/tools/satellite/MapContextMenu.svelte
index 3e431aa..076aedc 100644
--- a/frontend/src/tools/satellite/MapContextMenu.svelte
+++ b/frontend/src/tools/satellite/MapContextMenu.svelte
@@ -34,8 +34,10 @@
actions = ACTIONS,
/** Archives this point can be compared across; none hides the row. */
compareSources = [],
- /** `(id, value)`: `copy` with the text, `compare` with a source id, or an
- * action id from `ACTIONS`. */
+ /** The other map tabs the point opens in (`otherMapTools`), first under Open in…. */
+ tools = [],
+ /** `(id, value)`: `copy` with the text, `compare` with a source id, `goto`
+ * with a tool id, or an action id from `ACTIONS`. */
onpick,
onclose,
} = $props();
@@ -262,6 +264,10 @@
</button>
{/each}
{:else}
+ {#each tools as tool (tool.id)}
+ <button class="item" role="menuitem" onclick={() => onpick('goto', tool.id)}>{tool.label}</button>
+ {/each}
+ {#if tools.length}<div class="rule" role="separator"></div>{/if}
{#each links as link (link.id)}
<a
class="item link"
diff --git a/frontend/src/tools/satellite/MapSurface.svelte b/frontend/src/tools/satellite/MapSurface.svelte
index ca9ebcc..70f24f4 100644
--- a/frontend/src/tools/satellite/MapSurface.svelte
+++ b/frontend/src/tools/satellite/MapSurface.svelte
@@ -28,6 +28,7 @@
import { createBasemaps, OVERLAY_IDS } from '../../lib/map/basemap.js';
import { DEFAULT_LAYER, DEFAULT_MAXCC, SENTINEL_ID } from '../../lib/sentinel.js';
import { RADAR_ID, orbitMark } from '../../lib/radar.js';
+ import { pictureDate } from '../../lib/map/pictureDate.js';
import Icon from '../../components/Icon.svelte';
import Compass from '../../components/Compass.svelte';
import ImageryChip from './ImageryChip.svelte';
@@ -77,6 +78,11 @@
/** 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,
+ /** A second picture of the same ground, `{ provider, id, cell }` as
+ * `imagery.displayed()` answers, laid over the first and kept loaded. */
+ alternate = null,
+ /** Whether that second picture is the one on screen. */
+ alternateOn = false,
/** 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,
@@ -140,9 +146,13 @@
engine?.resize();
}
- /** What a capture of this surface must record: the pixels' own provenance. */
+ /**
+ * What a capture of this surface must record: the pixels' own provenance.
+ * `imageryExact` is false for a date the provider only estimated, and
+ * `imageryWhen` is the same date with a radar pass's UTC time when it has one.
+ */
export function provenance() {
- return { provider: shown.id, imageryDate: radarPass?.date ?? pinnedDay ?? imageryDate?.date ?? null };
+ return { provider: shown.id, ...pictureDate({ radarPass, pinnedDay, estimated: imageryDate?.date }) };
}
// Svelte only honours a cleanup returned from a *synchronous* onMount, and the
@@ -223,6 +233,19 @@
if (ready) basemaps?.setZoomCeiling(value);
});
+ // Only a tool that lays a second picture pays for one: the rest never ask.
+ let laidAlternate = false;
+ $effect(() => {
+ const { provider = null, id = '', cell = 256 } = alternate ?? {};
+ if (!ready || !basemaps || (!provider && !laidAlternate)) return;
+ basemaps.setAlternate(provider, id, cell);
+ laidAlternate = Boolean(provider);
+ });
+ $effect(() => {
+ const on = alternateOn;
+ if (ready && alternate) basemaps?.showAlternate(on);
+ });
+
$effect(() => {
shown.id; // a new provider, a new eco/block fallback, a new Sentinel window
shown.cell; // …and the z17 detail-boost bracket
diff --git a/frontend/src/tools/satellite/SavedOverlay.svelte b/frontend/src/tools/satellite/SavedOverlay.svelte
index 5eea9fb..de4cf0d 100644
--- a/frontend/src/tools/satellite/SavedOverlay.svelte
+++ b/frontend/src/tools/satellite/SavedOverlay.svelte
@@ -6,7 +6,7 @@
import { mount, unmount } from 'svelte';
import { createSurface } from '../../lib/map/surface.js';
import { paths } from '../../components/Icon.svelte';
- import { groupSavedMarkers, markerPrecision } from '../../lib/savedMarkers.js';
+ import { groupSavedMarkers, markKind, markerPrecision } from '../../lib/savedMarkers.js';
import { TEARDROP, TEARDROP_CARD_OFFSET } from '../../lib/mapMarkers.js';
import { openEntity } from '../../lib/navigate.js';
import SavedPopup from './SavedPopup.svelte';
@@ -27,7 +27,7 @@
onmedia,
} = $props();
- const GLYPH = { place: 'pin', capture: 'satellite', screenshot: 'screen' };
+ const GLYPH = { place: 'pin', capture: 'satellite', screenshot: 'screen', comparison: 'compare' };
/** True when every item under a mark is a located file: it opens the viewer. */
const isMedia = (mark) => mark.kinds.every((kind) => kind === 'media');
@@ -46,8 +46,8 @@
}
function icon(mark) {
- // Mixed stacks use the shared place glyph.
- const kind = mark.kinds.length > 1 ? 'place' : mark.kinds[0];
+ // A stack of imagery draws as a capture; one holding a place, as the place.
+ const kind = markKind(mark.kinds);
// 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')
@@ -155,19 +155,25 @@
*
* A mark with neither returns nothing and draws exactly as it always has —
* absence is a state, never something to flag.
+ *
+ * A comparison's footprint is something else: the export frame, the ground its
+ * images show. It is outlined in dashes and left unfilled, so it never reads as
+ * a guess about where something is.
*/
function shapesFor(mark, id) {
const row = mark.items.find((r) => r.footprint || r.radius_m > 0);
if (!row) return [];
- const style = {
- stroke: '#f5a623',
- strokeWidth: 1.5,
- strokeOpacity: 0.9,
- fill: '#f5a623',
- fillOpacity: 0.12,
- // never steals the click from the pin it sits under
- interactive: false,
- };
+ const style = row.kind === 'comparison'
+ ? { stroke: '#f5a623', strokeWidth: 1.5, strokeOpacity: 0.9, dash: '5 4', interactive: false }
+ : {
+ stroke: '#f5a623',
+ strokeWidth: 1.5,
+ strokeOpacity: 0.9,
+ fill: '#f5a623',
+ fillOpacity: 0.12,
+ // never steals the click from the pin it sits under
+ interactive: false,
+ };
return row.footprint
? [{ id: `${id}:shape`, kind: 'geojson', geometry: row.footprint, style }]
: [{ id: `${id}:shape`, kind: 'circle', at: mark, radiusM: row.radius_m, style }];
diff --git a/frontend/src/tools/satellite/SavedPopup.svelte b/frontend/src/tools/satellite/SavedPopup.svelte
index 9285b36..7ed8818 100644
--- a/frontend/src/tools/satellite/SavedPopup.svelte
+++ b/frontend/src/tools/satellite/SavedPopup.svelte
@@ -14,7 +14,7 @@
import { api } from '../../lib/api.js';
import { toast } from '../../lib/state.svelte.js';
import { loadRelationTypes, relationAction } from '../../lib/relations.svelte.js';
- import { stackOrder } from '../../lib/savedMarkers.js';
+ import { keptLabel, pairLabel, stackOrder } from '../../lib/savedMarkers.js';
let {
items = [],
@@ -28,8 +28,8 @@
onrefresh, // a relation was settled: sync the other surfaces
} = $props();
- const GLYPH = { place: 'pin', capture: 'satellite', screenshot: 'screen' };
- const KIND = { place: 'Place', capture: 'Capture', screenshot: 'Screenshot' };
+ const GLYPH = { place: 'pin', capture: 'satellite', screenshot: 'screen', comparison: 'compare' };
+ const KIND = { place: 'Place', capture: 'Capture', screenshot: 'Screenshot', comparison: 'Comparison' };
const rowKey = (row) => row.key ?? row.id;
@@ -42,6 +42,7 @@
* map behind this card, and editing it belongs to the details drawer. Two forms
* for one field is how they drift apart. */
function spread(row) {
+ if (row.kind === 'comparison') return row.footprint ? 'framed' : null;
if (row.footprint) return 'traced area';
const m = Number(row.radius_m);
if (!(m > 0)) return null;
@@ -155,8 +156,25 @@
</p>
<p class="meta">
{#if row.imagery_date}<span>Imagery {row.imagery_date}</span>{/if}
+ {#if pairLabel(row)}<span title="The dates of pictures A and B">{pairLabel(row)}</span>{/if}
{#if day(row.fetched_at)}<span>Saved {day(row.fetched_at)}</span>{/if}
</p>
+ {#if row.kept?.length}
+ <section class="kept">
+ <p class="rel-heading"><Icon name="image" size={11} /> {keptLabel(row)}</p>
+ {#each row.kept as image (image.path)}
+ <a
+ class="link"
+ class:off={fullscreen}
+ href={fullscreen ? undefined : fileUrl(caseId, image.path)}
+ target="_blank"
+ rel="noreferrer"
+ aria-disabled={fullscreen}
+ title={fullscreen ? 'Exit fullscreen first. This leaves the map' : 'Open this image'}
+ >{image.title || image.path}</a>
+ {/each}
+ </section>
+ {/if}
{#if worked(row)}
<p class="worked">
<span class="worked-dot"></span>
@@ -189,7 +207,9 @@
</section>
{/if}
<p class="acts">
- <button type="button" class="link" onclick={() => onedit(row)}>Edit</button>
+ <button type="button" class="link" onclick={() => onedit(row)}>
+ {row.kind === 'comparison' ? 'Open in Compare' : 'Edit'}
+ </button>
{#if row.kind === 'place' && ontrace}
<button
type="button"
@@ -373,11 +393,18 @@
.meta > .proposed::before {
content: none;
}
- .relations {
+ .relations,
+ .kept {
margin-top: 4px;
padding-top: 5px;
border-top: 1px solid var(--border);
}
+ .kept {
+ display: flex;
+ flex-direction: column;
+ align-items: flex-start;
+ gap: 2px;
+ }
.rel-heading {
display: flex;
align-items: center;
diff --git a/frontend/src/tools/satellite/SavedPopup.test.js b/frontend/src/tools/satellite/SavedPopup.test.js
index b4472dd..fcaa7bf 100644
--- a/frontend/src/tools/satellite/SavedPopup.test.js
+++ b/frontend/src/tools/satellite/SavedPopup.test.js
@@ -106,6 +106,45 @@ describe('SavedPopup', () => {
});
});
+describe('SavedPopup, a saved comparison', () => {
+ const comparison = {
+ id: 's1',
+ kind: 'comparison',
+ title: 'Harbour reading',
+ lat: 48.0159,
+ lon: 37.8029,
+ session: 'Harbour reading',
+ path: 'media/Harbour reading.png',
+ thumbnail: 'media/.thumbs/h.jpg',
+ imagery_a: '2024-05-03~',
+ imagery_b: '2026-09-02',
+ footprint: { type: 'Polygon', coordinates: [[[37.8, 48], [37.81, 48], [37.81, 48.01], [37.8, 48]]] },
+ fetched_at: '2026-09-20T09:00:00Z',
+ kept: [{ path: 'media/Harbour reading 2024-05-03_2026-09-02.png', title: 'Harbour reading 2024-05-03_2026-09-02' }],
+ };
+
+ it('says it is a comparison, with both pictures and the images kept from it', () => {
+ const body = at([comparison]);
+
+ expect(body).toContain('Comparison');
+ expect(body).toContain('2024-05-03~ → 2026-09-02');
+ expect(body).toContain('framed');
+ expect(body).toContain('1 image kept');
+ expect(body).toContain('/files/case-1/media/Harbour%20reading%202024-05-03_2026-09-02.png');
+ expect(body).toContain('Open in Compare');
+ expect(body).not.toContain('traced area');
+ });
+
+ it('draws a stack of captures and comparisons with the capture glyph, not a pin', () => {
+ expect(overlay).toContain('const kind = markKind(mark.kinds);');
+ });
+
+ it('outlines its frame in dashes, never as a guess about a place', () => {
+ expect(overlay).toContain("row.kind === 'comparison'");
+ expect(overlay).toContain("dash: '5 4'");
+ });
+});
+
describe('SavedOverlay popup wiring', () => {
it('mounts the card as a component rather than building HTML by hand', () => {
expect(overlay).toContain("import { mount, unmount } from 'svelte'");
diff --git a/frontend/src/tools/satellite/SavedRow.svelte b/frontend/src/tools/satellite/SavedRow.svelte
index a1e530f..cd81413 100644
--- a/frontend/src/tools/satellite/SavedRow.svelte
+++ b/frontend/src/tools/satellite/SavedRow.svelte
@@ -10,6 +10,7 @@
import Icon from '../../components/Icon.svelte';
import { fileUrl } from '../../lib/fileUrl.js';
import { roadWords } from '../../lib/mediaViewer.js';
+ import { keptLabel, pairLabel } from '../../lib/savedMarkers.js';
let {
row,
@@ -32,9 +33,11 @@
onhover = () => {},
} = $props();
- const GLYPH = { place: 'pin', capture: 'satellite', screenshot: 'screen' };
+ const GLYPH = { place: 'pin', capture: 'satellite', screenshot: 'screen', comparison: 'compare' };
const isPlace = $derived(row.kind === 'place');
+ // a saved comparison: it reopens in Compare, where its title and notes live
+ const isComparison = $derived(row.kind === 'comparison');
// 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(
@@ -51,9 +54,11 @@
const meta = $derived(
isMedia
? roadWords(row)
- : [row.zoom != null ? `z${Math.round(row.zoom)}` : null, row.provider ?? row.site, row.imagery_date]
- .filter(Boolean)
- .join(' · ')
+ : isComparison
+ ? [pairLabel(row), keptLabel(row)].filter(Boolean).join(' · ')
+ : [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');
@@ -139,14 +144,14 @@
title={blocked ?? `Open the source page (${row.site ?? 'external map'})`}
><Icon name="external" size={13} /></a>
{/if}
- <button class="act" title="Edit title & note" onclick={() => onedit(row)}>
- <Icon name="note" size={13} />
+ <button class="act" title={isComparison ? 'Open in Compare' : 'Edit title & note'} onclick={() => onedit(row)}>
+ <Icon name={isComparison ? 'compare' : 'note'} size={13} />
</button>
{#if !isPlace}
<button
class="act"
- disabled={fullscreen}
- title={blocked ?? 'Send to Geo Proof'}
+ disabled={fullscreen || !row.path}
+ title={blocked ?? (row.path ? 'Send to Geo Proof' : 'Save the comparison again to draw its picture')}
onclick={() => onproof(row)}
><Icon name="proof" size={13} /></button>
{/if}
diff --git a/frontend/src/tools/satellite/SavedTree.test.js b/frontend/src/tools/satellite/SavedTree.test.js
index d146a22..d7fa807 100644
--- a/frontend/src/tools/satellite/SavedTree.test.js
+++ b/frontend/src/tools/satellite/SavedTree.test.js
@@ -313,3 +313,31 @@ describe('accepting a proposed point', () => {
expect(at({ rows: proposed, query: 'roof' })).not.toContain('Accept this point');
});
});
+
+describe('SavedTree, a saved comparison', () => {
+ const comparison = {
+ id: 'k1',
+ kind: 'comparison',
+ title: 'harbour reading',
+ lat: 50.45,
+ lon: 30.52,
+ zoom: 16,
+ geo: ua('Kyiv Oblast'),
+ continent: 'Europe',
+ fetched_at: '2026-09-20T09:12:04Z',
+ session: 'harbour reading',
+ path: 'media/harbour reading.png',
+ imagery_a: '2024-05-03~',
+ imagery_b: '2026-09-02',
+ kept: [{ path: 'media/k.png', title: 'k' }],
+ };
+
+ it('lists it with the captures, by its two pictures and what was kept from it', () => {
+ const body = at({ rows: [...rows, comparison], kind: 'captures', query: 'harbour' });
+
+ expect(body).toContain('harbour reading');
+ expect(body).toContain('2024-05-03~ → 2026-09-02 · 1 image kept');
+ // it is reopened where it was made, not given a note box
+ expect(body).toContain('title="Open in Compare"');
+ });
+});
diff --git a/frontend/src/tools/satellite/TemporalPopup.svelte b/frontend/src/tools/satellite/TemporalPopup.svelte
index 7241291..c17536b 100644
--- a/frontend/src/tools/satellite/TemporalPopup.svelte
+++ b/frontend/src/tools/satellite/TemporalPopup.svelte
@@ -23,7 +23,7 @@
);
const TOOL = {
media: 'Media', proof: 'Proof', place: 'Map', post: 'Post',
- 'inspect-session': 'Inspect', note: 'Notebook', bookmark: 'the source',
+ 'inspect-session': 'Inspect', collage: 'Collage', note: 'Notebook', bookmark: 'the source',
capture: 'Map',
};
diff --git a/frontend/src/tools/satellite/state/capture.svelte.js b/frontend/src/tools/satellite/state/capture.svelte.js
index 2e10f92..45d1ec5 100644
--- a/frontend/src/tools/satellite/state/capture.svelte.js
+++ b/frontend/src/tools/satellite/state/capture.svelte.js
@@ -43,7 +43,8 @@
* @param {() => {style: string, at: object|null}} deps.marker the pin, if one was moved
* @param {() => object|undefined} deps.basemap the provider the analyst chose
* @param {() => number} deps.maxZoom the deepest zoom the *shown* provider has
- * @param {() => {provider: string, imageryDate: string|null}} deps.provenance the pixels' own
+ * @param {() => {provider: string, imageryDate: string|null, imageryExact?: boolean}} deps.provenance
+ * the pixels' own; `imageryExact` is false for a provider's estimate
* @param {(rect: object|null) => void} deps.onRect the live marquee outline
* @param {() => void} deps.onArm the map modes arming the marquee turns off
*/
@@ -311,6 +312,7 @@ export function createCaptureState({
// pinned Sentinel-2 window is that date outright; every other provider's
// is Esri's best-effort estimate, or nothing.
imagery_date: pixels.imageryDate,
+ imagery_exact: pixels.imageryExact ?? true,
scale_north: prefs.captureScaleNorth,
});
await reloadCase();
diff --git a/frontend/src/tools/satellite/state/capture.svelte.test.js b/frontend/src/tools/satellite/state/capture.svelte.test.js
index 4fcd107..f9e061f 100644
--- a/frontend/src/tools/satellite/state/capture.svelte.test.js
+++ b/frontend/src/tools/satellite/state/capture.svelte.test.js
@@ -162,6 +162,15 @@ describe('what a capture records', () => {
capture.run();
await vi.waitFor(() => expect(api.post).toHaveBeenCalled());
expect(api.post.mock.calls[0][1].imagery_date).toBe('2024-05-01');
+ expect(api.post.mock.calls[0][1].imagery_exact).toBe(true);
+ });
+
+ it('says when that date is only the provider estimate', async () => {
+ pixels = { provider: 'esri-world-imagery', imageryDate: '2024-05-01', imageryExact: false };
+ const capture = store();
+ capture.run();
+ await vi.waitFor(() => expect(api.post).toHaveBeenCalled());
+ expect(api.post.mock.calls[0][1].imagery_exact).toBe(false);
});
it('records the frame centre when no pin was moved', async () => {
diff --git a/frontend/src/tools/satellite/state/saved.svelte.js b/frontend/src/tools/satellite/state/saved.svelte.js
index c1b2691..6f369b7 100644
--- a/frontend/src/tools/satellite/state/saved.svelte.js
+++ b/frontend/src/tools/satellite/state/saved.svelte.js
@@ -34,6 +34,9 @@ function loadGroup() {
/** Where the Media position's rows come from. */
const MEDIA_INDEX = (caseId) => `/api/cases/${caseId}/satellite/media`;
+/** The entity a row's kind files through, where it is not the capture type. */
+const ENTITY_TYPE = { place: 'place', media: 'media', comparison: 'compare-session' };
+
export function createSavedState({ api, notify, assignFolder, reloadCase }) {
let rows = $state([]);
// the located files, read the first time that position is opened
@@ -193,11 +196,12 @@ export function createSavedState({ api, notify, assignFolder, reloadCase }) {
*/
async function move(caseId, row, folder) {
// the row's kind *is* its entity type, bar the screenshot that rides the
- // capture type. Filing a place as a capture would route it to PATCH /media,
- // the sidecar of an image it is not.
+ // capture type and a comparison, which is its saved session. Filing a place
+ // as a capture would route it to PATCH /media, the sidecar of an image it is
+ // not, and a comparison's folder is the session's, not its preview's.
const entity = {
id: row.id,
- type: ['place', 'media'].includes(row.kind) ? row.kind : 'capture',
+ type: ENTITY_TYPE[row.kind] ?? 'capture',
attrs: { path: row.path },
};
try {
@@ -209,9 +213,10 @@ export function createSavedState({ api, notify, assignFolder, reloadCase }) {
}
}
- /** Drop a saved item: a capture loses its image file, a place its entity. */
+ /** Drop a saved item: a capture loses its image file, a place or a comparison
+ * its entity. A comparison's images stay in Media, as they do from Compare. */
async function remove(caseId, row) {
- return row.kind === 'place'
+ return row.kind === 'place' || row.kind === 'comparison'
? api.del(`/api/cases/${caseId}/entities/${row.id}`)
: api.del(`/api/cases/${caseId}/satellite?path=${encodeURIComponent(row.path)}`);
}
diff --git a/frontend/src/tools/satellite/state/saved.svelte.test.js b/frontend/src/tools/satellite/state/saved.svelte.test.js
index 0e50c06..c83319a 100644
--- a/frontend/src/tools/satellite/state/saved.svelte.test.js
+++ b/frontend/src/tools/satellite/state/saved.svelte.test.js
@@ -304,7 +304,14 @@ describe('acting on a row', () => {
{ id: 'm1', type: 'media', attrs: { path: 'media/clip.mp4' } },
'Quays'
);
- expect(reloadCase).toHaveBeenCalledTimes(3);
+ // a comparison is filed as its saved session, never as its preview image
+ await saved.move('case-1', { id: 's1', kind: 'comparison', path: 'media/Harbour.png' }, 'Quays');
+ expect(assignFolder).toHaveBeenLastCalledWith(
+ 'case-1',
+ { id: 's1', type: 'compare-session', attrs: { path: 'media/Harbour.png' } },
+ 'Quays'
+ );
+ expect(reloadCase).toHaveBeenCalledTimes(4);
expect(notify).toHaveBeenLastCalledWith('Filed in Quays', 'ok', 1600);
});
@@ -316,5 +323,8 @@ describe('acting on a row', () => {
expect(api.del).toHaveBeenLastCalledWith(
'/api/cases/case-1/satellite?path=media%2Fa%20b.png'
);
+ // a comparison goes as its session; its images stay in Media
+ await saved.remove('case-1', { id: 's1', kind: 'comparison', path: 'media/Harbour.png' });
+ expect(api.del).toHaveBeenLastCalledWith('/api/cases/case-1/entities/s1');
});
});
diff --git a/frontend/src/tools/settings/GeneralTab.svelte b/frontend/src/tools/settings/GeneralTab.svelte
index ef24120..cba417d 100644
--- a/frontend/src/tools/settings/GeneralTab.svelte
+++ b/frontend/src/tools/settings/GeneralTab.svelte
@@ -1,8 +1,8 @@
<script>
/**
- * How every tool prints a coordinate, a distance and an area, plus the map's
- * opening position, what saving a proof does with its point, and how Reverse
- * Search reaches an engine.
+ * How every tool prints a coordinate, a distance and an area, plus where the
+ * maps open, what saving a proof does with its point, and how Reverse Search
+ * reaches an engine.
*
* Preferences save on change and the server answers with the canonical value,
* so nothing here keeps a draft the rest of the app cannot see.
@@ -17,6 +17,7 @@
saveHome,
proofPlaceAuto = $bindable(),
reversePrefill = $bindable(),
+ mapSync = $bindable(),
} = $props();
const COORD_CHOICES = [
@@ -96,6 +97,25 @@
</div>
</section>
+<section class="group">
+ <h3>Map tabs</h3>
+ <div class="row">
+ <div class="row-label">
+ <span>Share one view</span>
+ <span class="row-hint">
+ Satellite, Compare and Detect show the same place. A Detect review and a
+ saved comparison stay where they are.
+ </span>
+ </div>
+ <input
+ type="checkbox"
+ bind:checked={mapSync}
+ onchange={() => savePrefs({ map_sync: mapSync })}
+ aria-label="Share one view across the map tabs"
+ />
+ </div>
+</section>
+
<section class="group">
<h3>Proofs</h3>
<p class="intro">
diff --git a/frontend/src/tools/settings/ImageryTab.svelte b/frontend/src/tools/settings/ImageryTab.svelte
index 98295b1..3cb1347 100644
--- a/frontend/src/tools/settings/ImageryTab.svelte
+++ b/frontend/src/tools/settings/ImageryTab.svelte
@@ -15,6 +15,7 @@
import { tick } from 'svelte';
import Icon from '../../components/Icon.svelte';
import RadarLayer from './RadarLayer.svelte';
+ import { SENTINEL_ECO_MAX_ZOOM } from '../../lib/usage.js';
import {
monthCount,
tilesOfFree,
@@ -255,7 +256,7 @@
type="number"
min="0"
max="21"
- placeholder={k.id === 'sentinelhub' ? '11' : String(ecoMaxZoom)}
+ placeholder={k.id === 'sentinelhub' ? String(SENTINEL_ECO_MAX_ZOOM) : String(ecoMaxZoom)}
bind:value={ecoZooms[k.id]}
onchange={saveEcoZoom}
disabled={!eco}
@@ -263,7 +264,7 @@
/>
<span class="ctrl-note">
{k.id === 'sentinelhub'
- ? 'blank = 11 (it caps at z14)'
+ ? `blank = ${SENTINEL_ECO_MAX_ZOOM} (it caps at z14)`
: 'blank = the global threshold'}
</span>
</label>
diff --git a/src/azimut/api/analyzers.py b/src/azimut/api/analyzers.py
index 05183f9..51eebfe 100644
--- a/src/azimut/api/analyzers.py
+++ b/src/azimut/api/analyzers.py
@@ -5,7 +5,9 @@ from __future__ import annotations
import io
import math
import secrets
-from typing import Any, Literal
+from typing import Any, Literal, get_args
+
+import httpx
from fastapi import APIRouter, HTTPException
from fastapi.responses import Response
@@ -14,12 +16,16 @@ from pydantic import Field, ValidationError
from .. import config
from ..engine import analyzers as engine
-from ..engine import analysis_export, analysis_geometry, media, workqueue
+from ..engine import (
+ analysis_dating, analysis_examples, analysis_export, analysis_geometry, detect_rules, links, media, sentinel,
+ workqueue,
+)
from ..engine.analysis_models import (
- BUILTINS, GROUPS, METHODS, RELIABILITY, SINGLE_METHODS, Area, AreaDates, AreaGeometry, Model, Recipe,
- RunInput, ShortId, Source, Zone, ZoneSet,
+ BUILTINS, GROUPS, MAX_AROUND, MAX_BANDS, MAX_CHECKS, MAX_MARKS, MAX_RULES, METHODS, RELIABILITY, Area, AreaDates,
+ AreaGeometry, Bounds, Check, Latitude, Longitude, Model, Recipe, RunInput, SceneClass, ShortId, Source, Zone,
+ ZoneSet, is_single,
)
-from .cases import delete_by_path, delete_entity_deep, get_case
+from .cases import delete_by_path, delete_entities_deep, get_case
router = APIRouter(prefix="/api", tags=["analyzers"])
@@ -42,7 +48,17 @@ def recipes() -> dict[str, Any]:
"radar_layer": str(settings.get("sentinel1_layer") or ""),
"groups": [{"id": ident, "label": label, "recipes": members}
for ident, label, members in GROUPS],
- "reliability": RELIABILITY}
+ "reliability": RELIABILITY,
+ # What an analyzer of your own may say, and how far it may reach.
+ "rules": {"bands": list(sentinel.L2A_BANDS), "classes": list(get_args(SceneClass)),
+ "max_rules": MAX_RULES, "max_bands": MAX_BANDS,
+ "max_around": MAX_AROUND, "max_checks": MAX_CHECKS, "max_marks": MAX_MARKS,
+ "preview_span": detect_rules.PREVIEW_SPAN},
+ # The built-ins a builder can open as the rules they apply.
+ "as_rules": {recipe.id: converted for recipe in BUILTINS
+ if (converted := detect_rules.index_as_rules(recipe))},
+ # Ready analyzers with their checks, which a new one can start from.
+ "examples": analysis_examples.catalogue()}
@router.post("/compare/analyzers")
@@ -68,6 +84,77 @@ def delete_recipe(ident: str) -> dict[str, bool]:
return {"deleted": True}
+class PreviewInput(Model):
+ """An analyzer of your own, the two passes to try it on, and the view."""
+ recipe: Recipe
+ a: Source = Field(default_factory=Source)
+ b: Source
+ bounds: Bounds
+ #: Fetch the frames the cache lacks. Only the analyst's Read sets it.
+ read: bool = False
+
+
+class ProbeInput(PreviewInput):
+ #: Longitude and latitude, inside the grid the preview reads.
+ point: tuple[Longitude, Latitude]
+
+
+class CheckInput(Model):
+ """An analyzer of your own as it stands, and one of its checks to rerun."""
+ recipe: Recipe
+ check: Check
+ #: Fetch the frames the cache lacks. Only the analyst's Run all sets it.
+ read: bool = False
+
+
+def _rules_only(body: PreviewInput | CheckInput) -> None:
+ if body.recipe.method != "rules":
+ raise HTTPException(422, "only an analyzer of your own rules has a live preview")
+
+
+def _previewing(work: Any) -> dict[str, Any]:
+ """Run a preview step, saying what went wrong in words an analyst can act on."""
+ try:
+ result: dict[str, Any] = work()
+ return result
+ except ValueError as exc:
+ raise HTTPException(422, str(exc)) from exc
+ except sentinel.CoverageError as exc:
+ raise HTTPException(502, f"Copernicus returned no usable frame: {exc}") from exc
+ except httpx.HTTPError as exc:
+ raise HTTPException(502, "Copernicus could not be reached; nothing was fetched") from exc
+
+
[email protected]("/compare/analyzers/preview")
+def preview_rules(body: PreviewInput) -> dict[str, Any]:
+ """What an analyzer of your own keeps over the view, rule by rule.
+
+ Reads the tile cache only unless `read` is set, which fetches the missing
+ frames: one metered Sentinel Hub request each, for each date read.
+ """
+ _rules_only(body)
+ bounds = (body.bounds.west, body.bounds.south, body.bounds.east, body.bounds.north)
+ return _previewing(lambda: detect_rules.preview(body.recipe, body.a, body.b, bounds, read=body.read))
+
+
[email protected]("/compare/analyzers/probe")
+def probe_rules(body: ProbeInput) -> dict[str, Any]:
+ """Every rule's reading at one point of the preview. Never fetches."""
+ _rules_only(body)
+ return _previewing(lambda: detect_rules.probe(body.recipe, body.a, body.b, body.point))
+
+
[email protected]("/compare/analyzers/check")
+def check_rules(body: CheckInput) -> dict[str, Any]:
+ """One check rerun with the rules as they stand: what came out on each mark.
+
+ Reads the tile cache only unless `read` is set, which fetches the missing
+ frames the way the preview's Read does.
+ """
+ _rules_only(body)
+ return _previewing(lambda: detect_rules.check(body.recipe, body.check, read=body.read))
+
+
Kind = Literal["areas", "zones", "followups", "runs"]
@@ -315,7 +402,7 @@ def add_manual(case_id: str, ident: str, body: ManualCandidate) -> dict[str, Any
right = max(left + 1, math.ceil(max(p[0] for p in grid) * (1 << z) * size))
bottom = max(top + 1, math.ceil(max(p[1] for p in grid) * (1 << z) * size))
source = outcome or saved["input"]
- sources = [source["b"]] if saved["input"]["recipe"]["method"] in SINGLE_METHODS else [source["a"], source["b"]]
+ sources = [source["b"]] if is_single(saved["input"]["recipe"]) else [source["a"], source["b"]]
parts = []
for ty in range(top // size, (bottom - 1) // size + 1):
for tx in range(left // size, (right - 1) // size + 1):
@@ -336,7 +423,6 @@ def add_manual(case_id: str, ident: str, body: ManualCandidate) -> dict[str, Any
"bbox": [west, south, east, north], "parts": parts, "review": "new",
"phenomenon": "Manual candidate", "margin": 0, "measure": {},
"area": (right - left) * (bottom - top) * mpp ** 2,
- "width": (right - left) * mpp, "height": (bottom - top) * mpp,
"sources": {"a": source["a"], "b": source["b"]}}
saved["results"].append(row)
saved["count"] = len(saved["results"])
@@ -516,14 +602,17 @@ def promote(case_id: str, ident: str, result_id: str, body: Promotion) -> dict[s
# deleting the working run cannot remove evidence used by the case.
source = {"type": "compare", "analysis_run": ident, "candidate_id": result_id,
"input": saved["input"], "candidate": result, "engine_version": saved["engine_version"]}
- single = saved["input"]["recipe"]["method"] in SINGLE_METHODS
+ single = is_single(saved["input"]["recipe"])
as_area = body.shape == "area" or (body.shape is None and not single)
geometry = result["geometry"] if as_area else {"type": "Point", "coordinates": result["coordinates"]}
if as_area and geometry["type"] == "Point":
raise HTTPException(422, "this candidate is a point; pin it as a point")
- filed = media.import_rendered_bytes(case, preview_bytes(case, saved, result,
- after_only=single if body.after_only is None else body.after_only),
- body.title, ".png", source, by="compare")
+ after_only = single if body.after_only is None else body.after_only
+ passes = analysis_dating.candidate_sources(saved, result)
+ filed = media.import_rendered_bytes(case, preview_bytes(case, saved, result, after_only=after_only),
+ body.title, ".png",
+ {**source, **analysis_dating.pictured(passes, one_pass=after_only)},
+ by="compare")
lon, lat = result["coordinates"]
if as_area:
lon, lat = analysis_geometry.interior(geometry, (lon, lat))
@@ -533,21 +622,34 @@ def promote(case_id: str, ident: str, result_id: str, body: Promotion) -> dict[s
**({"footprint": geometry} if as_area else {}),
"evidence": filed["item"]["path"],
"analysis_provenance": source}, by="compare")
+ # The picture shows the place it pins. Without the edge the two were tied
+ # only by `evidence`, which the picture's connections never read.
+ case.add_link(filed["entity"]["id"], entity["id"], links.DEPICTS, by="compare", unique=True)
+ # When it was seen goes on a statement at the pin, never on the place itself.
+ claim = analysis_dating.state(case, place=entity, evidence=filed["entity"], run_id=ident,
+ candidate_id=result_id, sources=passes, single=single,
+ title=body.title)
result.update(entity_id=entity["id"], review="kept", reviewed_at=engine.now(),
title=body.title, description=body.description, pinned_geometry=geometry)
engine.persist_run(case, saved)
- return {"entity": entity, "image": filed["item"]["path"], "result": result}
+ return {"entity": entity, "image": filed["item"]["path"], "claim": claim, "result": result}
@router.delete("/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."""
+ """Undo keeping: the pin and its evidence go to Trash, the candidate returns.
+
+ The statement the pin made goes with it, in the same Trash group, unless the
+ analyst has written to it since.
+ """
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
+ claim = analysis_dating.withdrawable(case, ident, result_id)
+ going = [each for each in (entity["id"] if entity else None, claim) if each]
+ removed = delete_entities_deep(case, going) if going 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/common.py b/src/azimut/api/cases/common.py
index 898949a..743dc64 100644
--- a/src/azimut/api/cases/common.py
+++ b/src/azimut/api/cases/common.py
@@ -28,7 +28,7 @@ from .. import events
#: Entity types that are drawn on a map, and so whose deletion is news to a
#: surface that is not the one that asked for it (``api/events.py``).
-MAPPED_TYPES = {"place", "capture"}
+MAPPED_TYPES = {"place", "capture", "compare-session"}
def get_case(case_id: str) -> Case:
@@ -43,8 +43,8 @@ def delete_entities_deep(case: Case, entity_ids: list[str]) -> dict[str, Any]:
The one door every delete goes through — sidebar, Media Library, a tool's
own list — so the rules hold wherever the click came from:
- - artifacts that ``depends-on`` the target die with it (an Inspect session
- is only adjustments over a video), transitively;
+ - artifacts that ``depends-on`` the target die with it (a file's Inspect
+ work is only frames and edits over it), transitively;
- artifacts ``derived-from`` it are never touched, and are scarred with a
tombstone first, while the target can still describe itself.
diff --git a/src/azimut/api/compare.py b/src/azimut/api/compare.py
index 65cb3a2..0e49426 100644
--- a/src/azimut/api/compare.py
+++ b/src/azimut/api/compare.py
@@ -12,7 +12,19 @@ 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.
+The image records the date of each picture it shows (`imagery_a`, `imagery_b`),
+the same fact a capture keeps as its imagery date: two instants, never a range,
+because a comparison does not say that anything happened between them. A date a
+provider only estimated is kept with `exact: false` beside it.
+
Finished copies go to the configured export destination and are not case state.
+They are named by those dates, so two comparisons of one pair would share a name,
+and none ever overwrites another. An export may also be kept in the case: it is then
+a media file of its own, stamped with the reading it shows and never replaced
+(`engine/comparisons.py`).
+
+A saved comparison stands on the map as saved work, at its frame's centre or its
+view's, and is listed with the captures in the Saved panel.
"""
from __future__ import annotations
@@ -30,12 +42,13 @@ from pydantic import BaseModel, Field, field_validator, model_validator
from .. import config, layout
from ..engine import artifacts as artifact_engine
-from ..engine import exportdir, sentinel, tiles
+from ..engine import comparisons, 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
+from .satellite import locate_on_save, saved_changed
router = APIRouter(prefix="/api", tags=["compare"])
@@ -50,8 +63,13 @@ MAX_GIF_EDGE = 1280
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"
+#: The reading a kept image carries, as JSON. A session holds at most 200
+#: annotations, each a handful of points and a short text.
+MAX_SPEC_CHARS = 400_000
_DAY = r"^(|\d{4}-\d{2}-\d{2})$"
+#: A picture's date as the browser states it: a day, or a radar pass's UTC instant.
+_PICTURE_DATE = r"^(|\d{4}-\d{2}-\d{2}(T([01]\d|2[0-3]):[0-5]\d:[0-5]\dZ)?)$"
class CompareCamera(BaseModel):
@@ -458,25 +476,33 @@ def save_session(case_id: str, body: SessionIn) -> dict[str, Any]:
raise HTTPException(status_code=409, detail="a comparison already uses that name")
previous = case.resolve_inside(layout.compare_session_rel(old or name))
+ reading = _validated_spec(body.spec)
saved = {
"azimut_compare": 1,
"title": name,
"created_at": read_created_at(previous) or _now(),
"updated_at": _now(),
- "spec": _validated_spec(body.spec),
+ "spec": reading,
}
media_engine.write_json_atomic(path, saved)
+ # The comparison stands where its reading is: saved work, beside the captures.
+ placed = comparisons.placement(reading)
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)
+ stale = comparisons.moved(existing.get("attrs") or {}, placed)
+ case.update_entity(existing["id"], {"label": name, "attrs": {"spec": rel, **placed}})
+ entity_id = existing["id"]
else:
- case.add_entity("compare-session", name, attrs={"spec": rel}, by="compare")
+ stale = True
+ entity_id = case.add_entity("compare-session", name, attrs={"spec": rel, **placed},
+ by="compare")["id"]
if old_rel:
+ comparisons.follow_rename(case, old_rel, rel)
case.resolve_inside(old_rel).unlink(missing_ok=True)
+ if stale:
+ locate_on_save(case, entity_id, placed["lat"], placed["lon"])
+ saved_changed(case)
return {"name": name, "title": name, "spec_path": rel}
@@ -518,6 +544,10 @@ async def save_session_preview(
image_b: UploadFile | None = File(default=None),
format_: Literal["png", "blink"] = Form(alias="format"),
interval: int = Form(default=800, ge=200, le=4000),
+ imagery_a: str = Form(default="", pattern=_PICTURE_DATE),
+ imagery_b: str = Form(default="", pattern=_PICTURE_DATE),
+ imagery_a_exact: bool = Form(default=True),
+ imagery_b_exact: bool = Form(default=True),
) -> dict[str, Any]:
"""File the rendered comparison as the session's media working file.
@@ -561,7 +591,13 @@ async def save_session_preview(
# The composer writes both provider credits into the image footer.
"attribution_burned": True,
}
- attrs = {"lat": camera["lat"], "lon": camera["lon"], "compare_session": spec_rel}
+ for key, value, exact in (("imagery_a", imagery_a, imagery_a_exact),
+ ("imagery_b", imagery_b, imagery_b_exact)):
+ if value:
+ source[key] = value
+ if not exact:
+ source[f"{key}_exact"] = False
+ attrs = {"lat": camera["lat"], "lon": camera["lon"], comparisons.SESSION_ATTR: spec_rel}
current = _preview_of(case, spec_rel)
current_entity = case.find_entity(attr="path", value=current) if current else None
@@ -590,9 +626,87 @@ async def save_session_preview(
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
+ # the preview is the comparison's picture in the Saved panel
+ saved_changed(case)
return {"path": rel, "format": format_, "replaced": replaced}
[email protected]("/cases/{case_id}/compare/sessions/{name}/images")
+async def keep_image(
+ case_id: str,
+ name: str,
+ image_a: UploadFile = File(),
+ image_b: UploadFile | None = File(default=None),
+ format_: Literal["png", "blink", "slide"] = Form(alias="format"),
+ interval: int = Form(default=800, ge=200, le=4000),
+ filename: str = Form(min_length=1, max_length=120),
+ spec: str = Form(min_length=2, max_length=MAX_SPEC_CHARS),
+ imagery_a: str = Form(default="", pattern=_PICTURE_DATE),
+ imagery_b: str = Form(default="", pattern=_PICTURE_DATE),
+ imagery_a_exact: bool = Form(default=True),
+ imagery_b_exact: bool = Form(default=True),
+) -> dict[str, Any]:
+ """Keep one export in the case, as an image nothing replaces.
+
+ The session's preview is redrawn by every save; this is the copy somebody chose
+ to keep, so it carries the reading it was made from rather than the session's,
+ which may have moved on since. It is named like the finished copy and never
+ written over another file.
+ """
+ case = get_case(case_id)
+ canonical = slugify(name, "Comparison")
+ spec_rel = layout.compare_session_rel(canonical)
+ if _read_session(case, canonical) is None or case.find_entity(attr="spec", value=spec_rel) is None:
+ raise HTTPException(status_code=404, detail="save the comparison before keeping its images")
+ try:
+ reading = _validated_spec(CompareSpec.model_validate_json(spec))
+ except ValueError as exc:
+ raise HTTPException(status_code=422, detail="that is not a comparison this image could show") from exc
+
+ a = await _read_png(image_a, "A")
+ if format_ == "png":
+ out = io.BytesIO()
+ a.save(out, "PNG", optimize=True)
+ data, suffix = out.getvalue(), ".png"
+ else:
+ if image_b is None:
+ raise HTTPException(status_code=422, detail="an animated image needs image B")
+ b = await _read_png(image_b, "B")
+ data, suffix = _gif_bytes(a, b, format_, interval), ".gif"
+
+ placed = comparisons.placement(reading)
+ source: dict[str, Any] = {
+ "type": SOURCE_TYPE,
+ "session": spec_rel,
+ "kept": True,
+ "mode": reading["mode"],
+ "animation": None if format_ == "png" else format_,
+ "providers": {"a": reading["a"]["provider"], "b": reading["b"]["provider"]},
+ "lat": placed["lat"],
+ "lon": placed["lon"],
+ "zoom": placed["zoom"],
+ "bearing": placed["bearing"],
+ "frame": reading.get("frame"),
+ "rendered_at": _now(),
+ "attribution_burned": True,
+ }
+ for key, value, exact in (("imagery_a", imagery_a, imagery_a_exact),
+ ("imagery_b", imagery_b, imagery_b_exact)):
+ if value:
+ source[key] = value
+ if not exact:
+ source[f"{key}_exact"] = False
+ attrs = {"lat": placed["lat"], "lon": placed["lon"], comparisons.SESSION_ATTR: spec_rel}
+ try:
+ filed = media_engine.import_rendered_bytes(
+ case, data, filename, suffix, source, by="compare", extra_attrs=attrs
+ )
+ except (OSError, ValueError, CaseError) as exc:
+ raise HTTPException(status_code=409, detail=f"could not keep the image: {exc}") from exc
+ saved_changed(case)
+ return {"path": filed["item"]["path"], "entity": filed["entity"]["id"]}
+
+
@router.delete("/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."""
@@ -667,12 +781,7 @@ async def export_gif(
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)
+ 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}
diff --git a/src/azimut/api/inspect.py b/src/azimut/api/inspect.py
index ab21b2e..3d6fe0f 100644
--- a/src/azimut/api/inspect.py
+++ b/src/azimut/api/inspect.py
@@ -1,5 +1,5 @@
-"""REST API for the Inspect tool: probe media, capture frames, apply
-adjustments, build collages, run analyses.
+"""REST API for the Examine tools: probe media, capture frames, apply
+adjustments, keep each file's work, lay out collages, run analyses.
Outputs are filed as ordinary case media (they appear in the Media Library and
the Proof Composer picker with zero extra plumbing). Long scans run as jobs.
@@ -7,21 +7,19 @@ the Proof Composer picker with zero extra plumbing). Long scans run as jobs.
from __future__ import annotations
-import json
-from datetime import datetime, timezone
from typing import Any, Literal
from fastapi import APIRouter, HTTPException, Response
from pydantic import BaseModel, Field
from .. import jobs
+from .. import layout
from ..engine import artifacts as artifact_engine
from ..engine import inspect as inspect_engine
-from ..engine import links as link_engine
+from ..engine import inspectwork
from ..workspace import CaseError
from .cases import delete_by_path, get_case
-from .naming import read_created_at, slugify
-from .. import layout
+from .naming import slugify
router = APIRouter(prefix="/api", tags=["inspect"])
@@ -105,12 +103,17 @@ class AnalyzeIn(BaseModel):
ops: list[Op] = []
-class SessionIn(BaseModel):
- # The filename always follows the title, so renaming a saved session moves
- # its file. ``rename_from`` is the stem the workspace is currently bound to
- # (absent on a first save); a save that lands elsewhere renames that file in
- # place instead of leaving a copy behind under the old name.
- rename_from: str | None = None
+class WorkIn(BaseModel):
+ # The file the work belongs to. The spec holds its frames and their edits as
+ # recipes; `engine/inspectwork` documents the shape and bounds it.
+ path: str = Field(min_length=1)
+ spec: dict[str, Any]
+
+
+class CollageIn(BaseModel):
+ # The name the tool has the collage open under, absent for one never saved.
+ # A title different from it is a rename.
+ name: str | None = Field(default=None, max_length=200)
title: str = Field(min_length=1, max_length=200)
spec: dict[str, Any]
@@ -148,8 +151,8 @@ def suggest_frames(case_id: str, body: SuggestIn) -> dict[str, str]:
def render_preview(case_id: str, body: RenderPreviewIn) -> Response:
"""Render a recipe (frame/image + ops) to a PNG — nothing is filed.
- Backs collage snapshots and rebuilding tray/collage previews when a saved
- session is reopened.
+ Backs frame previews and collage pieces, and rebuilding both when a work or
+ a collage is reopened.
"""
case = get_case(case_id)
ops = [op.model_dump() for op in body.ops]
@@ -164,7 +167,7 @@ def render_preview(case_id: str, body: RenderPreviewIn) -> Response:
@router.post("/cases/{case_id}/inspect/save-frames")
def save_frames(case_id: str, body: SaveFramesIn) -> dict[str, Any]:
- """Commit selected tray frames to the case (Save gate)."""
+ """File frames as case media (Save to case)."""
case = get_case(case_id)
results = []
try:
@@ -185,7 +188,7 @@ def save_frames(case_id: str, body: SaveFramesIn) -> dict[str, Any]:
@router.post("/cases/{case_id}/inspect/compose")
def compose(case_id: str, body: ComposeIn) -> dict[str, Any]:
- """Composite a perspective-warped collage from tray/case images (Save gate)."""
+ """Composite a perspective-warped collage from frames and case images (Save to case)."""
case = get_case(case_id)
nodes: list[dict[str, Any]] = []
for n in body.nodes:
@@ -227,26 +230,6 @@ def auto_stitch(case_id: str, body: StitchIn) -> dict[str, Any]:
raise HTTPException(status_code=422, detail=str(exc)) from exc
[email protected]("/cases/{case_id}/inspect/compose-preview")
-def compose_preview(case_id: str, body: ComposeIn) -> Response:
- """Render the composited collage to a PNG for the Save tab — nothing is filed."""
- case = get_case(case_id)
- nodes: list[dict[str, Any]] = []
- for n in body.nodes:
- src = n.src.model_dump(exclude={"ops"})
- src["ops"] = [op.model_dump() for op in n.src.ops]
- nodes.append({"src": src, "quad": [list(pt) for pt in n.quad]})
- try:
- png = inspect_engine.compose_preview_png(
- case, width=body.width, height=body.height, nodes=nodes, background=body.background,
- )
- except CaseError as exc:
- raise HTTPException(status_code=400, detail=str(exc)) from exc
- except (ValueError, RuntimeError, OSError) as exc:
- raise HTTPException(status_code=422, detail=str(exc)) from exc
- return Response(content=png, media_type="image/png")
-
-
@router.post("/cases/{case_id}/inspect/enhance-video")
def enhance_video(case_id: str, body: EnhanceVideoIn) -> dict[str, Any]:
"""Re-encode a video with its adjustments and orientation, then file it."""
@@ -277,122 +260,102 @@ def analyze(case_id: str, body: AnalyzeIn) -> dict[str, Any]:
# ---------------------------------------------------------------------------
-# Saveable workspace sessions (persist the whole Inspect scratch, reopen later).
-# Mirrors the proofs pattern: a JSON spec on disk + an upserted entity, so a
-# session reopens from the sidebar. Only recipes are stored (no pixels).
+# Work, one per file, saved as it is made; and collages, one document each.
+# `engine/inspectwork` owns both shapes and the merge that brought older
+# sessions into them.
# ---------------------------------------------------------------------------
-def _now() -> str:
- return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
[email protected]("/cases/{case_id}/inspect/works")
+def list_works(case_id: str) -> list[dict[str, Any]]:
+ return inspectwork.list_works(get_case(case_id))
[email protected]("/cases/{case_id}/inspect/sessions")
-def list_sessions(case_id: str) -> list[dict[str, Any]]:
[email protected]("/cases/{case_id}/inspect/work")
+def get_work(case_id: str, path: str) -> dict[str, Any]:
+ """The work saved for one file. Nothing done to it yet answers `work: null`."""
case = get_case(case_id)
- out = []
- for spec_path in sorted(case.subdir(layout.INSPECT_DIR).glob("*.json")):
- try:
- spec = json.loads(spec_path.read_text(encoding="utf-8"))
- except (OSError, json.JSONDecodeError):
- continue
- if spec.get("azimut_inspect") != 1:
- continue
- # Sessions hold an array of collages; older ones held a single `collage`
- # (the loader still reads both). Count the pieces across all of them.
- collages = spec.get("collages") or (
- [spec["collage"]] if isinstance(spec.get("collage"), dict) else []
- )
- out.append({
- "name": spec_path.stem,
- "title": spec.get("title", spec_path.stem),
- "updated_at": spec.get("updated_at"),
- "frames": len(spec.get("frames", [])),
- "collages": len(collages),
- "collage": sum(len(c.get("nodes", [])) for c in collages),
- "source": spec.get("source", {}).get("path"),
- })
- out.sort(key=lambda s: s.get("updated_at") or "", reverse=True)
- return out
-
-
[email protected]("/cases/{case_id}/inspect/sessions/{name}")
-def load_session(case_id: str, name: str) -> dict[str, Any]:
+ try:
+ return {"work": inspectwork.find_work(case, path)}
+ except CaseError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+
+
[email protected]("/cases/{case_id}/inspect/works/{name}")
+def load_work(case_id: str, name: str) -> dict[str, Any]:
case = get_case(case_id)
try:
- spec_path = case.resolve_inside(layout.session_rel(name))
+ work = inspectwork.load_work(case, name)
except CaseError as exc:
raise HTTPException(status_code=403, detail=str(exc)) from exc
- if not spec_path.exists():
- raise HTTPException(status_code=404, detail="session not found")
- return json.loads(spec_path.read_text(encoding="utf-8"))
+ if work is None:
+ raise HTTPException(status_code=404, detail="nothing was inspected under that name")
+ return work
[email protected]("/cases/{case_id}/inspect/sessions")
-def save_session(case_id: str, body: SessionIn) -> dict[str, Any]:
[email protected]("/cases/{case_id}/inspect/work")
+def save_work(case_id: str, body: WorkIn) -> dict[str, Any]:
case = get_case(case_id)
- case.subdir(layout.INSPECT_DIR) # born on first save, so the folder exists
- name = slugify(body.title, "Inspect")
- rel = layout.session_rel(name)
- spec_path = case.resolve_inside(rel)
-
- # A rename lands on a free name or not at all: taking a name another session
- # holds would leave two entities pointing at one file, and there is no sane
- # merge of the two. The first save of an unbound workspace still writes over
- # a same-named session — there the analyst is updating that one.
- old = slugify(body.rename_from, "session") if body.rename_from else None
- old_rel = layout.session_rel(old) if old and old != name else None
- if old_rel and spec_path.exists():
- raise HTTPException(status_code=409, detail="another session already uses that name")
-
- spec = dict(body.spec)
- spec["azimut_inspect"] = 1
- spec["title"] = name
- previous = case.resolve_inside(layout.session_rel(old or name))
- spec.setdefault("created_at", read_created_at(previous) or _now())
- spec["updated_at"] = _now()
- spec_path.write_text(json.dumps(spec, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
-
- # Rebind the entity the old name held rather than filing a second one, so a
- # rename keeps the session's folder, notes and links.
- 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)
- entity_id = existing["id"]
- else:
- entity_id = case.add_entity(
- "inspect-session", name, attrs={"spec": rel}, by="inspect"
- )["id"]
- if old_rel:
- case.resolve_inside(layout.session_rel(str(old))).unlink(missing_ok=True)
-
- # A session is only adjustments and crops over its subject — nothing usable
- # is left of it once the subject is gone, so it depends on it and is deleted
- # with it (ONTOLOGY §3). Collage pieces pulled from the case are *not*
- # subjects: losing one leaves a placeholder, it does not void the session.
- link_engine.sync(
- case,
- entity_id,
- link_engine.DEPENDS_ON,
- [spec.get("source", {}).get("path")],
- by="inspect",
- )
- return {"name": name, "title": name, "spec_path": rel}
-
-
[email protected]("/cases/{case_id}/inspect/sessions/{name}")
-def delete_session(case_id: str, name: str) -> dict[str, Any]:
+ try:
+ return inspectwork.save_work(case, body.path, body.spec)
+ except CaseError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+
+
[email protected]("/cases/{case_id}/inspect/work")
+def delete_work(case_id: str, path: str) -> dict[str, Any]:
+ """Clear one file's work. It goes to the Trash, so the reset can be taken back."""
+ case = get_case(case_id)
+ try:
+ rel = inspectwork.work_rel(case, path)
+ except CaseError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+ if rel is None:
+ return {"status": "deleted", "deleted": [], "tombstoned": []}
+ result = delete_by_path(case, rel)
+ if not result["deleted"]: # never filed as an entity: drop the file anyway
+ artifact_engine.delete(case, {"type": inspectwork.WORK_TYPE, "attrs": {"spec": rel}})
+ return result
+
+
[email protected]("/cases/{case_id}/collages")
+def list_collages(case_id: str) -> list[dict[str, Any]]:
+ return inspectwork.list_collages(get_case(case_id))
+
+
[email protected]("/cases/{case_id}/collages/{name}")
+def load_collage(case_id: str, name: str) -> dict[str, Any]:
case = get_case(case_id)
- # Named the way the save named it — see `api/satellite.delete_search_grid`.
- rel = layout.session_rel(slugify(name, "session"))
+ try:
+ collage = inspectwork.load_collage(case, name)
+ except CaseError as exc:
+ raise HTTPException(status_code=403, detail=str(exc)) from exc
+ if collage is None:
+ raise HTTPException(status_code=404, detail="collage not found")
+ return collage
+
+
[email protected]("/cases/{case_id}/collages")
+def save_collage(case_id: str, body: CollageIn) -> dict[str, Any]:
+ case = get_case(case_id)
+ try:
+ return inspectwork.save_collage(case, body.name, body.title, body.spec)
+ except inspectwork.NameTaken as exc:
+ raise HTTPException(status_code=409, detail=str(exc)) from exc
+ except CaseError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+
+
[email protected]("/cases/{case_id}/collages/{name}")
+def delete_collage(case_id: str, name: str) -> dict[str, Any]:
+ """Delete the layout. A picture already exported from it stays in Media."""
+ case = get_case(case_id)
+ rel = layout.collage_rel(slugify(name, "Collage"))
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"]: # never filed as an entity: drop the file anyway
- artifact_engine.delete(case, {"type": "inspect-session", "attrs": {"spec": rel}})
+ if not result["deleted"]:
+ artifact_engine.delete(case, {"type": inspectwork.COLLAGE_TYPE, "attrs": {"spec": rel}})
return result
diff --git a/src/azimut/api/naming.py b/src/azimut/api/naming.py
index d47576c..6501904 100644
--- a/src/azimut/api/naming.py
+++ b/src/azimut/api/naming.py
@@ -1,7 +1,7 @@
"""Naming rules shared by everything the analyst saves under a name.
-Inspect sessions, proofs, post drafts and satellite grids all turn a free-text
-title into the filename that holds it. They must agree: a session and a proof
+Collages, proofs, post drafts and satellite grids all turn a free-text
+title into the filename that holds it. They must agree: a collage and a proof
called "Rooftop angle" land on the same stem, and the frontend mirrors this in
``lib/naming.js`` so it can predict a collision before it posts.
diff --git a/src/azimut/api/plates.py b/src/azimut/api/plates.py
index 8a35a2f..1b3b5b0 100644
--- a/src/azimut/api/plates.py
+++ b/src/azimut/api/plates.py
@@ -76,6 +76,9 @@ class PlateIn(BaseModel):
format: str = Field(default="svg", pattern="^(svg|png)$")
svg: str = ""
png: str = ""
+ #: False for a name that does not tell two exports apart. Compare names its
+ #: images by their pictures' dates, which two comparisons of one pair share.
+ overwrite: bool = True
def _clean_svg(markup: str) -> bytes:
@@ -115,7 +118,8 @@ def write_plate(case_id: str, body: PlateIn) -> dict[str, Any]:
Inside the case a re-export overwrites, the way a note's PDF does: that folder is
refreshed in one click rather than accumulating copies. In a folder of the
- analyst's own nothing is ever overwritten, because the files there are theirs.
+ analyst's own nothing is ever overwritten, because the files there are theirs,
+ and neither is a plate that asked not to be.
"""
case = get_case(case_id)
data = _clean_png(body.png) if body.format == "png" else _clean_svg(body.svg)
@@ -127,7 +131,7 @@ def write_plate(case_id: str, body: PlateIn) -> dict[str, Any]:
raise HTTPException(status_code=422, detail=str(exc)) from exc
in_case = destination == layout.subdir(case.path, EXPORTS_DIR)
try:
- if in_case:
+ if in_case and body.overwrite:
path = destination / filename
path.write_bytes(data)
else:
diff --git a/src/azimut/api/satellite.py b/src/azimut/api/satellite.py
index 165abdc..59b6970 100644
--- a/src/azimut/api/satellite.py
+++ b/src/azimut/api/satellite.py
@@ -80,6 +80,8 @@ class CaptureIn(BaseModel):
# acquisition date of the underlying imagery (Esri best-effort), resolved
# client-side and recorded next to the capture timestamp (fetched_at)
imagery_date: str | None = None
+ # false when that date is a provider's estimate rather than a named pass
+ imagery_exact: bool = True
# marker (recorded point of interest): style + optional offset from center
marker_style: str = Field(default="crosshair", pattern="^(crosshair|pin|none)$")
marker_x: int = Field(default=0, ge=-tiles.SIZE_MAX, le=tiles.SIZE_MAX)
@@ -1075,6 +1077,8 @@ def capture(case_id: str, body: CaptureIn) -> dict[str, Any]:
# two dates ride with a capture: fetched_at (when it was captured, set by
# fetch_crop) and imagery_date (when the satellite scene was shot, if known)
provenance["imagery_date"] = (body.imagery_date or "").strip() or None
+ if provenance["imagery_date"] and not body.imagery_exact:
+ provenance["imagery_exact"] = False
stamp = datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S")
filename = f"sat_{stamp}_z{provenance['zoom']}_{provider.id}.png"
diff --git a/src/azimut/api/settings.py b/src/azimut/api/settings.py
index 8be7670..460b71a 100644
--- a/src/azimut/api/settings.py
+++ b/src/azimut/api/settings.py
@@ -102,6 +102,7 @@ class PrefsIn(BaseModel):
coord_format: str | None = None # one of config.COORD_FORMATS
units: str | None = None # one of config.UNIT_SYSTEMS
home_view: HomeView | None = None # where the Satellite tab opens
+ map_sync: bool | None = None # Satellite, Compare and Detect share one camera
detect_view: DetectPrefs | None = None
# the Sentinel-1 layer radar detections read; "" forgets it
sentinel1_layer: str | None = Field(default=None, pattern=r"^$|^[A-Z0-9_]{1,40}$")
@@ -137,6 +138,7 @@ def _prefs(settings: dict[str, Any]) -> dict[str, Any]:
"coord_format": settings.get("coord_format", "dd"),
"units": settings.get("units", "metric"),
"home_view": settings.get("home_view", DEFAULT_HOME_VIEW),
+ "map_sync": bool(settings.get("map_sync", True)),
"detect_view": settings.get("detect_view", config.DEFAULT_SETTINGS["detect_view"]),
"sentinel1_layer": settings.get("sentinel1_layer", ""),
"capture_scale_north": bool(settings.get("capture_scale_north", False)),
@@ -268,6 +270,8 @@ def _apply_prefs(settings: dict[str, Any], body: PrefsIn) -> None:
settings["units"] = body.units
if body.home_view is not None:
settings["home_view"] = body.home_view.model_dump()
+ if body.map_sync is not None:
+ settings["map_sync"] = bool(body.map_sync)
if body.detect_view is not None:
settings["detect_view"] = body.detect_view.model_dump()
if body.sentinel1_layer is not None:
@@ -653,6 +657,7 @@ class ImportedSettings(BaseModel):
home_view: ImportedHomeView = Field(
default_factory=lambda: ImportedHomeView.model_validate(DEFAULT_HOME_VIEW)
)
+ map_sync: bool = True
capture_scale_north: bool = False
proof_place_auto: bool = True
post_mention: str = Field(default=DEFAULT_POST_MENTION, max_length=64)
diff --git a/src/azimut/config.py b/src/azimut/config.py
index d4d89ad..fcd8ee6 100644
--- a/src/azimut/config.py
+++ b/src/azimut/config.py
@@ -110,6 +110,9 @@ DEFAULT_SETTINGS: dict[str, Any] = {
# Where the Satellite tab opens before anything points it somewhere else
# (a case artifact, a "go to coords" handoff). {"lat", "lon", "zoom"}.
"home_view": {"lat": 43.0, "lon": 25.0, "zoom": 3},
+ # Whether Satellite, Compare and Detect share one camera, so a map tab that
+ # shows opens where the last one was left. On by default.
+ "map_sync": True,
# Saving a proof files the point it carries as a `place`, joined by `depicts`
# (engine/satellite.place_for_proof). A geolocation is concluded in the
# composer, not while framing the map, so the point becomes a node once —
diff --git a/src/azimut/engine/analysis_dating.py b/src/azimut/engine/analysis_dating.py
new file mode 100644
index 0000000..0c2e73d
--- /dev/null
+++ b/src/azimut/engine/analysis_dating.py
@@ -0,0 +1,210 @@
+"""When a kept Detect candidate was seen, stated where the case reads time.
+
+A pin is a `place`, and a place is permanent: the date belongs to the observation,
+not to the ground or to the edge between the picture and the ground (ONTOLOGY §3,
+no verb carries a date). Keeping a candidate therefore writes time in the two places
+the case already reads it:
+
+- **The evidence picture carries the dates of its passes**, as media facts beside a
+ capture's imagery date. One pass is `imagery_date`; a pair is `imagery_a` and
+ `imagery_b`, two instants rather than a range, because the picture shows two
+ moments and argues nothing about what lies between them.
+- **A Claim states what the sweep found**, `at` the pin and citing the picture. A
+ thing present on one pass was `observed` then. A change was read between two
+ passes, so it `occurred` somewhere in that interval, and only there.
+
+The Claim carries no confidence: keeping is the review, and a grade nobody gave
+would read as one somebody did. One pin owns one statement, found again by the
+`detection` key, and it follows the proof composer's rule for letting go: undoing the
+pin withdraws it only while nothing but this module has written to it.
+"""
+
+from __future__ import annotations
+
+import re
+from typing import TYPE_CHECKING, Any
+
+from . import media as media_engine
+from .analysis_models import is_single
+from .temporal import TemporalError, parse_temporal
+
+if TYPE_CHECKING:
+ from ..workspace import Case
+
+
+#: The attribute that ties a statement to the candidate that stated it.
+STATED_BY = "detection"
+
+#: What the statement holds while nothing but a pin has touched it. Reasoning, a
+#: quote or a confidence make it the analyst's, and undoing the pin leaves it.
+OURS = {"when", "time_role", STATED_BY}
+
+_DAY = re.compile(r"\d{4}-\d{2}-\d{2}\Z")
+_TIME = re.compile(r"([01]\d|2[0-3]):[0-5]\d:[0-5]\d\Z")
+
+
+def moment(source: dict[str, Any] | None) -> str:
+ """One pass as a temporal value: its day, or its UTC instant when a radar pass
+ names its time. Empty for a source that states neither."""
+ source = source or {}
+ day = str(source.get("date") or "")
+ if not _DAY.fullmatch(day):
+ return ""
+ time = str(source.get("time") or "")
+ return f"{day}T{time}Z" if _TIME.fullmatch(time) else day
+
+
+def span(a: str, b: str) -> str:
+ """Two passes as the interval a change happened in, earliest first.
+
+ Two instants form an exact interval. Anything else is read as the days they
+ fall on, since the announced profile does not mix a day with a time.
+ """
+ if not a or not b:
+ return a or b
+ if "T" not in a or "T" not in b:
+ a, b = a[:10], b[:10]
+ if a == b:
+ return a
+ first, last = sorted((a, b))
+ value = f"{first}/{last}"
+ try:
+ parse_temporal(value)
+ except TemporalError:
+ return last
+ return value
+
+
+def candidate_sources(run: dict[str, Any], result: dict[str, Any]) -> dict[str, Any]:
+ """The two passes one candidate was read on.
+
+ A run over several areas reads each on its own dates, which the candidate
+ carries. One saved before that is read off its area's outcome, then the run.
+ """
+ if isinstance(result.get("sources"), dict):
+ return result["sources"]
+ outcome = next((pair for pair in run.get("area_runs") or []
+ if pair.get("area_id") == result.get("area_id")), None)
+ held = outcome or run.get("input") or {}
+ return {"a": held.get("a") or {}, "b": held.get("b") or {}}
+
+
+def pictured(sources: dict[str, Any], *, one_pass: bool) -> dict[str, str]:
+ """The dates an evidence picture carries in its sidecar."""
+ b = moment(sources.get("b"))
+ if one_pass:
+ return {"imagery_date": b} if b else {}
+ a = moment(sources.get("a"))
+ return {key: value for key, value in (("imagery_a", a), ("imagery_b", b)) if value}
+
+
+def reading(sources: dict[str, Any], *, single: bool) -> tuple[str, str] | None:
+ """`(when, time_role)` for a kept candidate, or None when no pass is dated."""
+ b = moment(sources.get("b"))
+ if not b:
+ return None
+ if single:
+ return b, "observed"
+ a = moment(sources.get("a"))
+ return (span(a, b), "occurred") if a else (b, "observed")
+
+
+def _label(title: str, single: bool) -> str:
+ return f"Seen: {title}" if single else f"Changed: {title}"
+
+
+def key(run_id: str, candidate_id: str) -> str:
+ return f"{run_id}/{candidate_id}"
+
+
+def standing(case: Case, run_id: str, candidate_id: str) -> dict[str, Any] | None:
+ found = case.find_entity(attr=STATED_BY, value=key(run_id, candidate_id))
+ return found if found and found.get("type") == "claim" else None
+
+
+def state(
+ case: Case,
+ *,
+ place: dict[str, Any],
+ evidence: dict[str, Any] | None,
+ run_id: str,
+ candidate_id: str,
+ sources: dict[str, Any],
+ single: bool,
+ title: str,
+) -> dict[str, Any] | None:
+ """File or restate the Claim a kept candidate makes. None when undated."""
+ read = reading(sources, single=single)
+ if read is None:
+ return None
+ when, role = read
+ current = standing(case, run_id, candidate_id)
+ # A statement reworded by hand is the analyst's sentence; restating the date is
+ # no reason to put ours back over it.
+ label = current["label"] if current else _label(title, single)
+ saved = case.save_temporal_claim(
+ entity_id=current["id"] if current else None,
+ label=label,
+ attrs={
+ **{k: v for k, v in ((current or {}).get("attrs") or {}).items() if k not in OURS},
+ "when": when,
+ "time_role": role,
+ STATED_BY: key(run_id, candidate_id),
+ },
+ connectors={"about": [], "at": [place["id"]],
+ "cites": [evidence["id"]] if evidence else []},
+ by="compare",
+ )
+ return saved["entity"]
+
+
+def withdrawable(case: Case, run_id: str, candidate_id: str) -> str | None:
+ """The statement undoing a pin takes with it, if it is still only the pin's."""
+ current = standing(case, run_id, candidate_id)
+ if current is None or not set(current.get("attrs") or {}) <= OURS:
+ return None
+ return str(current["id"])
+
+
+def backfill(case: Case) -> int:
+ """Date every pin kept before pins were dated. Returns how many were stated.
+
+ Everything needed is on the pin: its provenance holds the run's input and the
+ candidate as it was kept. The picture is dated only where its shape is sure. A
+ one-pass detector drew one pass; a change may have been kept as a pair or as its
+ second pass alone, and that choice was not recorded, so the Claim alone says it.
+ A pin already stated is skipped, so a pass interrupted halfway can run again.
+ """
+ stated = 0
+ for place in case.list_entities():
+ if place.get("type") != "place":
+ continue
+ attrs = place.get("attrs") or {}
+ provenance = attrs.get("analysis_provenance")
+ if not isinstance(provenance, dict):
+ continue
+ run_id = str(provenance.get("analysis_run") or attrs.get("analysis_run") or "")
+ candidate = provenance.get("candidate") or {}
+ candidate_id = str(provenance.get("candidate_id") or attrs.get("candidate_id") or "")
+ if not run_id or not candidate_id or standing(case, run_id, candidate_id):
+ continue
+ run = {"input": provenance.get("input") or {}}
+ recipe = run["input"].get("recipe")
+ if not isinstance(recipe, dict):
+ continue
+ try:
+ single = is_single(recipe)
+ except ValueError:
+ continue
+ sources = candidate_sources(run, candidate)
+ evidence_path = str(attrs.get("evidence") or "")
+ evidence = case.find_entity(attr="path", value=evidence_path) if evidence_path else None
+ if evidence and single:
+ item = media_engine.read_item(case, evidence_path)
+ if item and not (item.get("source") or {}).get("imagery_date"):
+ media_engine.merge_item(case, evidence_path, {
+ "source": {**(item.get("source") or {}), **pictured(sources, one_pass=True)}})
+ if state(case, place=place, evidence=evidence, run_id=run_id, candidate_id=candidate_id,
+ sources=sources, single=single, title=str(place.get("label") or "")):
+ stated += 1
+ return stated
diff --git a/src/azimut/engine/analysis_examples.py b/src/azimut/engine/analysis_examples.py
new file mode 100644
index 0000000..f330f03
--- /dev/null
+++ b/src/azimut/engine/analysis_examples.py
@@ -0,0 +1,155 @@
+"""Ready analyzers of your own, each with the checks that show it working.
+
+A new analyzer can start from one of these. Starting copies it into the
+analyst's library, checks included, so the first thing they can do is run the
+checks, see them pass, change a rule and watch one fail. Every example keeps
+places where nothing may be found, and most of them are traps: ground that one
+of its rules is there to turn away, so removing that rule turns the check red.
+
+Every pass, mark and line here was read on the real scenes (2026-09-24), from
+Sentinel-2 Level-2A laid out as Detect's band evalscript returns it, through
+this engine's own `detect_rules.check`. Marks sit at least 64 pixels inside the
+grid tile they fall in, since a check reads each mark on its own tile.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import Any
+
+from .analysis_models import SIZES, Check, Parameters, Recipe, Rule
+
+Point = tuple[float, float]
+
+
+@dataclass(frozen=True)
+class Example:
+ id: str
+ place: str
+ when: str
+ recipe: Recipe
+
+
+def _checks(a: str, b: str, layer: str,
+ *rows: tuple[str, str, tuple[float, float, float, float], list[Point], list[Point]]) -> list[Check]:
+ """One pair of passes, shown in `layer`, and the places read on it."""
+ return [Check.model_validate({
+ "id": ident, "name": name,
+ "a": {"date": a, "layer": layer} if a else {}, "b": {"date": b, "layer": layer},
+ "bounds": dict(zip(("west", "south", "east", "north"), bounds)),
+ "marks": [{"point": point, "expect": "found"} for point in found]
+ + [{"point": point, "expect": "empty"} for point in empty],
+ }) for ident, name, bounds, found, empty in rows]
+
+
+def _example(ident: str, place: str, when: str, size: str, **fields: Any) -> Example:
+ parameters = Parameters.model_validate(SIZES["rules"][size])
+ return Example(ident, place, when, Recipe(method="rules", parameters=parameters, **fields))
+
+
+EXAMPLES: list[Example] = [
+ # The Lahaina fire of 8 August 2023. A is that morning's pass, before the
+ # town burned. Without the second rule a cloud the mask missed reads as a
+ # burn; without the third the surf on the reef does.
+ _example(
+ "burn", "Lahaina, Maui", "August 2023", "medium",
+ name="Fresh burn", phenomenon="Fresh burn", colour="#ef4444",
+ description="The burn ratio dropped and ended low, on ground that was not water. "
+ "A field harvested between the passes can look the same.",
+ rules=[Rule(measure="index", index="nbr", on="change", op="le", value=-0.2),
+ Rule(measure="index", index="nbr", on="b", op="le", value=0.1),
+ Rule(measure="class", classes=["water"], on="a", op="not")],
+ checks=_checks(
+ "2023-08-08", "2023-08-13", "SWIR",
+ ("town", "The town and hills that burned", (-156.68747, 20.86409, -156.66278, 20.90174),
+ [(-156.67478, 20.87209), (-156.67547, 20.89374)], []),
+ ("spared", "Homes and dry grass that did not", (-156.66095, 20.85149, -156.63523, 20.88217),
+ [], [(-156.64723, 20.87417), (-156.64895, 20.85949)]),
+ ("reef", "The reef off the town", (-156.6873, 20.85703, -156.6633, 20.87303),
+ [], [(-156.6753, 20.86503)]),
+ ("cloud", "A cloud the mask missed", (-156.64644, 20.88862, -156.62244, 20.90462),
+ [], [(-156.63444, 20.89662)]),
+ )),
+ # The pine forest cleared for the Grünheide factory in early 2020. Mown
+ # meadows lose as much green; the short-wave rule is what keeps them out.
+ _example(
+ "clearing", "Grünheide, Germany", "2019 → 2020", "medium",
+ name="Forest cleared", phenomenon="Cleared forest", colour="#84cc16",
+ description="Green cover lost from ground that was forest: dense, and dark in short-wave "
+ "infrared, which meadows and crops are not.",
+ rules=[Rule(measure="index", index="ndvi", on="change", op="le", value=-0.3),
+ Rule(measure="index", index="ndvi", on="a", op="ge", value=0.6),
+ Rule(measure="band", band="B11", on="a", op="le", value=0.2)],
+ checks=_checks(
+ "2019-07-26", "2020-08-01", "NDVI",
+ ("site", "The factory site, cleared", (13.78069, 52.38559, 13.80538, 52.40374),
+ [(13.79269, 52.39574), (13.79235, 52.39359)], []),
+ ("forest", "Pine forest still standing", (13.73383, 52.37376, 13.75783, 52.38976),
+ [], [(13.74583, 52.38176)]),
+ ("meadows", "Meadows mown between the passes", (13.72499, 52.38203, 13.77723, 52.41856),
+ [], [(13.76523, 52.39003), (13.73699, 52.41056)]),
+ )),
+ # The Kakhovka reservoir after the dam broke on 6 June 2023. Water that
+ # only cleared reads higher, not lower: "moved either way" flags the river
+ # and the cooling pond.
+ _example(
+ "drained", "Kakhovka reservoir, Ukraine", "June 2023", "medium",
+ name="Water drained", phenomenon="Drained water", colour="#0ea5e9",
+ description="Open water on A that turned to land by B, in the modified water index. "
+ "Water that only cleared or clouded keeps its reading.",
+ rules=[Rule(measure="index", index="mndwi", on="change", op="le", value=-0.3),
+ Rule(measure="index", index="mndwi", on="a", op="ge", value=0.2)],
+ checks=_checks(
+ "2023-06-05", "2023-06-20", "FALSE_COLOR",
+ ("bed", "The reservoir bed, exposed", (34.44845, 47.51769, 34.48845, 47.56371),
+ [(34.46845, 47.55171), (34.46845, 47.52969)], []),
+ ("river", "The river channel, still water", (34.41497, 47.55378, 34.45497, 47.57778),
+ [], [(34.43497, 47.56578)]),
+ ("pond", "The power plant cooling pond", (34.51557, 47.50111, 34.55557, 47.52511),
+ [], [(34.53454, 47.51311)]),
+ )),
+ # Panel fields laid in the Dubai desert between 2019 and 2023. Dunes the
+ # wind moved change their shading, never their short-wave brightness; a
+ # rule on B alone would flag the fields that were already there.
+ _example(
+ "solar", "Dubai, United Arab Emirates", "2019 → 2023", "medium",
+ name="Solar farm built", phenomenon="New solar panels", colour="#a78bfa",
+ description="Desert that turned darker and ends dark in short-wave infrared, as panels do "
+ "and sand does not.",
+ rules=[Rule(measure="brightness", on="change", op="le", value=-0.08),
+ Rule(measure="band", band="B12", on="b", op="le", value=0.35)],
+ checks=_checks(
+ "2019-02-08", "2023-02-07", "TRUE_COLOR",
+ ("panels", "New panel fields", (55.38901, 24.69238, 55.41935, 24.73338),
+ [(55.40435, 24.72138), (55.40401, 24.70438)], []),
+ ("old", "Panels already there on A", (55.36832, 24.74976, 55.39832, 24.77376),
+ [], [(55.38332, 24.76176)]),
+ ("dunes", "Dunes the wind moved", (55.32893, 24.64411, 55.35893, 24.66811),
+ [], [(55.34393, 24.65611)]),
+ )),
+ # The anchorage off Fujairah, on one pass. Near infrared alone takes the
+ # whole town as brighter than its ground; the water index against the
+ # surroundings keeps what floats. Large is too big a size for a hull.
+ _example(
+ "ships", "Fujairah, United Arab Emirates", "one pass, January 2024", "small",
+ name="Ships at anchor", phenomenon="Vessel candidate", colour="#38bdf8",
+ description="Brighter in near infrared than the water around it, and far less watery than it. "
+ "Breakwaters and piers read like hulls.",
+ rules=[Rule(measure="band", band="B08", on="b", op="ge", value=0.04, around=150),
+ Rule(measure="index", index="mndwi", on="b", op="le", value=-0.4, around=150)],
+ checks=_checks(
+ "", "2024-01-23", "TRUE_COLOR",
+ ("ships", "Ships at anchor", (56.55259, 25.13071, 56.59311, 25.18666),
+ [(56.57259, 25.17166), (56.57311, 25.14571)], []),
+ ("town", "Fujairah town, on land", (56.32643, 25.1332, 56.36643, 25.1632),
+ [], [(56.34643, 25.1482)]),
+ ("water", "Open water", (56.51818, 25.13242, 56.55818, 25.16242),
+ [], [(56.53818, 25.14742)]),
+ )),
+]
+
+
+def catalogue() -> list[dict[str, Any]]:
+ """The examples as the builder offers them."""
+ return [{"id": example.id, "place": example.place, "when": example.when,
+ "recipe": example.recipe.model_dump()} for example in EXAMPLES]
diff --git a/src/azimut/engine/analysis_export.py b/src/azimut/engine/analysis_export.py
index af177e1..3044519 100644
--- a/src/azimut/engine/analysis_export.py
+++ b/src/azimut/engine/analysis_export.py
@@ -9,7 +9,7 @@ from typing import Any
from .. import layout
from ..workspace import Case
from . import analyzers, maplayers
-from .analysis_models import SINGLE_METHODS
+from .analysis_models import is_single
def export(case: Case, kind: str, ident: str) -> dict[str, Any]:
@@ -38,15 +38,23 @@ def export(case: Case, kind: str, ident: str) -> dict[str, Any]:
for row in run["results"]:
if row["review"] not in analyzers.KEPT:
continue
- day = row.get("sources", run["input"])["b"]["date"]
+ passes = row.get("sources", run["input"])
+ day = passes["b"]["date"]
geometry = row.get("pinned_geometry") or (row["geometry"] if row.get("origin") == "manual" else (
{"type": "Point", "coordinates": row["coordinates"]}
- if recipe["method"] in SINGLE_METHODS else row["geometry"]))
- document["features"].append({"type": "Feature", "geometry": geometry, "properties": {
+ if is_single(recipe) else row["geometry"]))
+ properties = {
"name": row.get("title") or row["phenomenon"], "description": row.get("description", ""),
"category": day, "pass_date": day, "detector": recipe["name"],
"area_name": row.get("area_name", ""), "run_id": run["id"],
- }})
+ }
+ # A change happened somewhere between the passes, so the layer's
+ # time filter reads it as that span; a radar pass names its time.
+ if not is_single(recipe) and passes["a"].get("date"):
+ properties["pass_before"] = passes["a"]["date"]
+ if passes["b"].get("time"):
+ properties["pass_time"] = passes["b"]["time"]
+ document["features"].append({"type": "Feature", "geometry": geometry, "properties": properties})
days = sorted({f["properties"]["pass_date"] for f in document["features"]})
for feature in document["features"]:
rank = days.index(feature["properties"]["pass_date"])
diff --git a/src/azimut/engine/analysis_geometry.py b/src/azimut/engine/analysis_geometry.py
index 0c10f7b..2b2b2f9 100644
--- a/src/azimut/engine/analysis_geometry.py
+++ b/src/azimut/engine/analysis_geometry.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+import math
from collections import defaultdict
from typing import Any
@@ -111,3 +112,39 @@ def interior(geometry: dict[str, Any], preferred: tuple[float, float]) -> tuple[
if right > left:
return ((left + right) / 2, y)
raise ValueError("the footprint has no interior")
+
+
+def near(geometry: dict[str, Any], point: tuple[float, float], metres: float) -> bool:
+ """Whether a footprint covers a point, or comes within `metres` of it.
+
+ The point is tried where it is and `metres` away on each side, which is
+ close enough for a click beside a track a pixel wide.
+ """
+ polygons = [geometry["coordinates"]] if geometry["type"] == "Polygon" else geometry["coordinates"]
+ lon, lat = point
+ dy = metres / 110_574
+ dx = metres / (111_320 * max(0.08, math.cos(math.radians(lat))))
+ tries = [(lon, lat), (lon + dx, lat), (lon - dx, lat), (lon, lat + dy), (lon, lat - dy)]
+ return any(contains(polygon[0], spot) and not any(contains(hole, spot) for hole in polygon[1:])
+ for polygon in polygons for spot in tries)
+
+
+def elongation(geometry: dict[str, Any]) -> float:
+ """How many times longer than wide a footprint is, along its own axis.
+
+ The smallest turned rectangle around every outer ring's corners, measured
+ in local metres: about 1 for a roof or a crater, 10 for a track ten times
+ longer than it is wide, whichever way it runs.
+ """
+ import cv2
+ import numpy as np
+
+ polygons = [geometry["coordinates"]] if geometry["type"] == "Polygon" else geometry["coordinates"]
+ points = [point for polygon in polygons for point in polygon[0]]
+ if len(points) < 3:
+ return 1.0
+ across = math.cos(math.radians(sum(lat for _, lat in points) / len(points)))
+ local = np.array([[lon * 111_320 * across, lat * 110_574] for lon, lat in points], np.float32)
+ _, (width, height), _ = cv2.minAreaRect(local)
+ short, long = sorted((float(width), float(height)))
+ return long / max(short, 1.0)
diff --git a/src/azimut/engine/analysis_models.py b/src/azimut/engine/analysis_models.py
index 6650a30..f58416b 100644
--- a/src/azimut/engine/analysis_models.py
+++ b/src/azimut/engine/analysis_models.py
@@ -24,8 +24,13 @@ from pydantic import (
)
Method = Literal["vessels", "hotspots", "structure", "spots", "surface", "index",
- "sar-vessels", "sar-change"]
+ "sar-vessels", "sar-change", "rules"]
Index = Literal["ndvi", "ndwi", "mndwi", "nbr", "ndbi", "bsi"]
+#: Sentinel-2 Level-2A's bands, as an analyzer of your own may name them.
+#: `sentinel.L2A_BANDS` is the list the evalscripts accept, in this order.
+Band = Literal["B01", "B02", "B03", "B04", "B05", "B06", "B07", "B08", "B8A", "B09", "B11", "B12"]
+#: Ground as Sentinel-2's scene classification names it.
+SceneClass = Literal["vegetation", "bare", "water", "snow", "cloud", "shadow", "dark"]
ShortId = Annotated[str, Field(pattern=r"^[a-zA-Z0-9_-]{1,48}$")]
Colour = Annotated[str, Field(pattern=r"^#[0-9a-fA-F]{6}$")]
@@ -101,6 +106,9 @@ class Parameters(Model):
# classification calls ground.
cloud_margin: int = Field(default=5, ge=0, le=10)
merge_metres: FiniteFloat = Field(default=0, ge=0, le=500)
+ # Kept after sizing: a roof or a crater is compact, a road, a track or a
+ # trench is long and thin. "any" keeps both, as every built-in does.
+ shape: Literal["any", "compact", "elongated"] = "any"
@model_validator(mode="before")
@classmethod
@@ -135,9 +143,13 @@ SIZES: dict[str, dict[str, dict[str, float]]] = {
"surface": _CHANGE_SIZES,
"index": _CHANGE_SIZES,
# Radar pixels are 10 m like Sentinel-2's, and speckle is what smoothing
- # works against: a small target keeps the finest window.
+ # works against: for radar change a step of it is 45 m of ground
+ # (`SAR_WINDOW_M`), and a small target keeps the finest window.
"sar-vessels": _sizes((0, 150_000, 0, 0, 30), (250, 150_000, 0, 0, 50), (2500, 400_000, 0, 0, 100)),
"sar-change": _sizes((300, 0, 0, 1, 0), (2000, 0, 1, 2, 30), (20000, 0, 1, 3, 100)),
+ # Your own rules measure change like the index methods do. Radar rules
+ # take radar change's sizes instead (`METHODS`, the panel picks them).
+ "rules": _CHANGE_SIZES,
}
@@ -179,27 +191,83 @@ class Zone(Model):
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 = "surface"
- parameters: Parameters = Field(default_factory=Parameters)
- colour: Colour = "#f6a81a"
- style: Literal["pins", "outlines", "both"] = "both"
+# Scene classes, as Sen2Cor numbers them, behind the names a rule uses.
+SCENE_CLASSES: dict[str, tuple[int, ...]] = {
+ "vegetation": (4,), "bare": (5,), "water": (6,), "snow": (11,),
+ "cloud": (8, 9, 10), "shadow": (3,), "dark": (2,),
+}
+#: The bands each measure reads beyond the ones a rule names itself.
+VISIBLE_BANDS = ("B02", "B03", "B04")
+#: How many rules one analyzer holds, and how many bands they may read between
+#: them. Every three bands are one more request per date and tile.
+MAX_RULES = 6
+MAX_BANDS = 6
+#: How far "against its surroundings" may look, in metres: the context a band
+#: product carries around its tile (`analyzers.PAD`, 306 m at the equator).
+MAX_AROUND = 300
+
+
+class Rule(Model):
+ """One line of an analyzer of your own: a quantity, the date it is read on,
+ and the line it has to cross.
+
+ `on` is a date (A or B) or the change between them. A change is B minus A,
+ so a loss is a negative value; `moved` takes either way. `around` reads the
+ quantity against the ground around it, in metres, so "brighter than its
+ surroundings" is the same rule on a dark sea and a bright desert.
+ """
+
+ measure: Literal["index", "nd", "band", "brightness", "colour", "class", "radar"] = "index"
+ index: Index = "ndvi"
+ #: A normalised difference of two bands: (first − second) / (first + second).
+ bands: tuple[Band, Band] = ("B08", "B04")
+ band: Band = "B08"
+ polarisation: Literal["vv", "vh", "ratio"] = "vv"
+ classes: list[SceneClass] = Field(default_factory=list, max_length=7)
+ on: Literal["a", "b", "change"] = "b"
+ op: Literal["ge", "le", "between", "moved", "is", "not"] = "ge"
+ value: FiniteFloat = Field(default=0, ge=-100, le=100)
+ upper: FiniteFloat = Field(default=0, ge=-100, le=100)
+ around: int = Field(default=0, ge=0, le=MAX_AROUND)
- @model_validator(mode="before")
- @classmethod
- def legacy(cls, data: Any) -> Any:
- if not isinstance(data, dict):
- return data
- # Areas belong to a saved detection, not to what it looks for. An
- # analyzer saved with areas of its own still loads, without them.
- data = {key: value for key, value in data.items() if key not in ("providers", "zones")}
- if data.get("method") in LEGACY_METHODS:
- data["method"] = LEGACY_METHODS[data["method"]]
- return data
+ @model_validator(mode="after")
+ def coherent(self) -> Rule:
+ if self.measure == "class":
+ if self.op not in ("is", "not"):
+ raise ValueError("a ground class rule says is or is not")
+ if self.on == "change":
+ raise ValueError("a ground class is read on one date; use two rules to compare them")
+ if not self.classes:
+ raise ValueError("choose at least one ground class")
+ if self.around:
+ raise ValueError("a ground class has no surroundings to compare with")
+ return self
+ if self.op in ("is", "not"):
+ raise ValueError("is and is not are for ground classes")
+ if self.op == "moved" and self.on != "change":
+ raise ValueError("moved by compares two dates")
+ if self.measure == "colour" and self.on != "change":
+ raise ValueError("a colour distance compares two dates")
+ if self.op == "between" and self.upper <= self.value:
+ raise ValueError("the upper bound must be above the lower one")
+ if self.measure == "nd" and self.bands[0] == self.bands[1]:
+ raise ValueError("a normalised difference needs two different bands")
+ return self
+
+ def bands_read(self) -> list[str]:
+ """The Sentinel-2 bands this rule needs, radar and ground classes none."""
+ from .sentinel import SPECTRAL_INDEX
+
+ if self.measure == "index":
+ high, low = SPECTRAL_INDEX[self.index]
+ return [*high, *low]
+ if self.measure == "nd":
+ return list(self.bands)
+ if self.measure == "band":
+ return [self.band]
+ if self.measure in ("brightness", "colour"):
+ return list(VISIBLE_BANDS)
+ return []
class Source(Model):
@@ -239,6 +307,116 @@ class Source(Model):
return data
+#: How many checks one analyzer keeps, and how many marks one check holds.
+MAX_CHECKS = 12
+MAX_MARKS = 20
+Longitude = Annotated[float, Field(ge=-180, le=180)]
+Latitude = Annotated[float, Field(ge=-85, le=85)]
+
+
+class Bounds(Model):
+ west: Longitude
+ south: Latitude
+ east: Longitude
+ north: Latitude
+
+
+class Mark(Model):
+ """A point of a check, and what a run of the analyzer should make of it."""
+
+ point: tuple[Longitude, Latitude]
+ expect: Literal["found", "empty"]
+
+
+class CheckResult(Model):
+ """How a check last came out, and which reading of the analyzer gave it.
+
+ `signature` is the panel's digest of the rules, `match` and parameters,
+ so a result read against rules that have changed since shows as stale.
+ `covered` says, mark by mark, whether a candidate came out on it.
+ """
+
+ signature: str = Field(pattern=r"^[0-9a-z]{1,32}$")
+ count: int = Field(ge=0, le=100_000)
+ covered: list[bool] = Field(default_factory=list, max_length=MAX_MARKS)
+
+
+class Check(Model):
+ """A place the analyst trusts, rerun after each change to the rules.
+
+ It keeps the exact pair of passes it was saved on, so a rerun reads the
+ same images. Marks say where a candidate must come out and where none may;
+ a check without marks still says how many candidates its view gave.
+ """
+
+ id: ShortId
+ name: str = Field(min_length=1, max_length=120)
+ a: Source = Field(default_factory=Source)
+ b: Source
+ bounds: Bounds
+ marks: list[Mark] = Field(default_factory=list, max_length=MAX_MARKS)
+ result: CheckResult | None = None
+
+ @model_validator(mode="after")
+ def placed(self) -> Check:
+ if not self.b.date:
+ raise ValueError("a check is read on a dated pass B")
+ if self.bounds.west >= self.bounds.east or self.bounds.south >= self.bounds.north:
+ raise ValueError("a check's view must not cross the antimeridian")
+ if self.result and self.result.covered and len(self.result.covered) != len(self.marks):
+ raise ValueError("a check's last result must match its marks")
+ return self
+
+
+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 = "surface"
+ parameters: Parameters = Field(default_factory=Parameters)
+ colour: Colour = "#f6a81a"
+ style: Literal["pins", "outlines", "both"] = "both"
+ #: The analyst's own rules, for `method="rules"` and nothing else. The
+ #: first measured one ranks candidates; `match` says whether a pixel has
+ #: to pass all of them or any one.
+ rules: list[Rule] = Field(default_factory=list, max_length=MAX_RULES)
+ match: Literal["all", "any"] = "all"
+ #: Places the analyst trusts, rerun after each change (`Check`).
+ checks: list[Check] = Field(default_factory=list, max_length=MAX_CHECKS)
+
+ @model_validator(mode="before")
+ @classmethod
+ def legacy(cls, data: Any) -> Any:
+ if not isinstance(data, dict):
+ return data
+ # Areas belong to a saved detection, not to what it looks for. An
+ # analyzer saved with areas of its own still loads, without them.
+ data = {key: value for key, value in data.items() if key not in ("providers", "zones")}
+ if data.get("method") in LEGACY_METHODS:
+ data["method"] = LEGACY_METHODS[data["method"]]
+ return data
+
+ @model_validator(mode="after")
+ def own_rules(self) -> Recipe:
+ if self.method != "rules":
+ if self.rules or self.checks:
+ raise ValueError("only an analyzer of your own rules carries rules and checks")
+ return self
+ if not self.rules:
+ raise ValueError("add at least one rule")
+ radar = {rule.measure == "radar" for rule in self.rules if rule.measure != "class"}
+ if len(radar) > 1:
+ raise ValueError("radar and optical rules read two satellites; keep them in two analyzers")
+ if True in radar and any(rule.measure == "class" for rule in self.rules):
+ raise ValueError("ground classes come from Sentinel-2, which a radar analyzer does not read")
+ if len({check.id for check in self.checks}) != len(self.checks):
+ raise ValueError("check ids must be unique")
+ if len(rule_bands(self)) > MAX_BANDS:
+ raise ValueError(f"an analyzer reads at most {MAX_BANDS} bands")
+ return self
+
+
class ZoneSet(Model):
title: str = Field(min_length=1, max_length=120)
zones: list[Zone] = Field(min_length=1, max_length=32)
@@ -298,7 +476,7 @@ class RunInput(Model):
for pair in self.area_dates:
if pair.date_rule == "manual" and not pair.b.date:
raise ValueError("choose a pass date for each area")
- if self.recipe.method not in SINGLE_METHODS and not pair.a.date and not (
+ if not is_single(self.recipe) and not pair.a.date and not (
pair.date_rule == "latest_previous" and self.followup_id
):
raise ValueError("choose a reference date for each area")
@@ -308,7 +486,7 @@ class RunInput(Model):
required = []
if self.date_rule == "manual":
required.append(self.b)
- if self.recipe.method not in SINGLE_METHODS and (
+ if not is_single(self.recipe) and (
self.date_rule != "latest_previous" or not self.followup_id
):
required.append(self.a)
@@ -317,6 +495,73 @@ class RunInput(Model):
return self
+def _as_recipe(recipe: Recipe | dict[str, Any]) -> Recipe:
+ return recipe if isinstance(recipe, Recipe) else Recipe.model_validate(recipe)
+
+
+def is_radar(recipe: Recipe | dict[str, Any]) -> bool:
+ """Whether the recipe reads Sentinel-1."""
+ recipe = _as_recipe(recipe)
+ if recipe.method == "rules":
+ return any(rule.measure == "radar" for rule in recipe.rules)
+ return recipe.method in RADAR_METHODS
+
+
+def is_single(recipe: Recipe | dict[str, Any]) -> bool:
+ """Whether the recipe reads one date: a thing present, not a change.
+
+ Rules that only ever read B need no reference, like a vessel or a fire.
+ """
+ recipe = _as_recipe(recipe)
+ if recipe.method == "rules":
+ return all(rule.on == "b" for rule in recipe.rules)
+ return recipe.method in SINGLE_METHODS
+
+
+def uses_clouds(recipe: Recipe | dict[str, Any]) -> bool:
+ """Whether the cloud and shadow switches mean anything for this recipe."""
+ recipe = _as_recipe(recipe)
+ if recipe.method == "rules":
+ return not is_radar(recipe)
+ return recipe.method in CLOUD_METHODS
+
+
+def recipe_sensor(recipe: Recipe | dict[str, Any]) -> str:
+ return "sentinel1" if is_radar(recipe) else "sentinel2"
+
+
+def rule_bands(recipe: Recipe) -> list[str]:
+ """Every Sentinel-2 band the recipe's rules read, in the collection's order."""
+ from .sentinel import L2A_BANDS
+
+ wanted = {band for rule in recipe.rules for band in rule.bands_read()}
+ return [band for band in L2A_BANDS if band in wanted]
+
+
+def recipe_products(recipe: Recipe | dict[str, Any]) -> list[str]:
+ """The band products one tile of this recipe reads, per date."""
+ from .sentinel import band_product
+
+ recipe = _as_recipe(recipe)
+ if recipe.method != "rules":
+ return [product_for(recipe.method, recipe.parameters.index)]
+ if is_radar(recipe):
+ return ["sar"]
+ bands = rule_bands(recipe)
+ # Ground classes and the cloud mask ride in every product, so a recipe of
+ # ground classes alone still reads one.
+ groups = [bands[i:i + 3] for i in range(0, len(bands), 3)] or [["B08"]]
+ return [band_product(group) for group in groups]
+
+
+def frames_for(recipe: Recipe | dict[str, Any]) -> int:
+ """Requests one tile costs: for each date read, the picture and every product."""
+ recipe = _as_recipe(recipe)
+ if recipe.method != "rules":
+ return frames_per_tile(recipe.method)
+ return (1 if is_single(recipe) else 2) * (1 + len(recipe_products(recipe)))
+
+
def _recipe(size: str = "medium", **fields: Any) -> Recipe:
parameters = {**SIZES[fields["method"]][size], **fields.pop("parameters", {})}
return Recipe(parameters=Parameters(**parameters), **fields)
@@ -436,10 +681,19 @@ def frames_per_tile(method: str) -> int:
# anything, `sensor` which collection its passes come from, `frames` what a
# tile costs, `sizes` fills Small/Medium/Large and `measure` words a candidate's
# reading ({value}, {signed}, {before}, {after} and {index} are filled in).
+#: Ground one step of smoothing averages over, where a method counts it in
+#: metres rather than pixels (`engine/analyzers.py` says why for radar).
+SMOOTHING_M = {"sar-change": 45.0}
+
+# `rules` is the one method whose answers depend on the recipe: which dates,
+# which satellite and how many frames follow from the rules it holds, and the
+# panel works them out from those (lib/map/analyzerRules.js). What it states
+# here is the answer for a change in Sentinel-2 bands.
METHODS = [
{"id": method, "label": label, "single": method in SINGLE_METHODS,
- "clouds": method in CLOUD_METHODS, "sensor": sensor_for(method),
- "frames": frames_per_tile(method), "sizes": SIZES[method], "measure": measure}
+ "clouds": method in CLOUD_METHODS or method == "rules", "sensor": sensor_for(method),
+ "frames": frames_per_tile(method), "sizes": SIZES[method], "measure": measure,
+ "smoothing_m": SMOOTHING_M.get(method), "rules": method == "rules"}
for method, label, measure in [
("vessels", "Vessels: infrared contrast over water",
"{value}× brighter than the water around it"),
@@ -452,5 +706,6 @@ METHODS = [
("sar-vessels", "Radar: strong return over water",
"{value} dB brighter than the sea around it"),
("sar-change", "Radar: backscatter change", "Backscatter {signed} dB, {before} → {after} dB"),
+ ("rules", "Your own rules", ""),
]
]
diff --git a/src/azimut/engine/analyzers.py b/src/azimut/engine/analyzers.py
index ac6fe8b..e08f06b 100644
--- a/src/azimut/engine/analyzers.py
+++ b/src/azimut/engine/analyzers.py
@@ -36,6 +36,7 @@ from .analysis_models import (
CLOUD_METHODS,
RADAR_METHODS,
SINGLE_METHODS,
+ SMOOTHING_M,
Area,
AreaDates,
AreaGeometry,
@@ -43,8 +44,10 @@ from .analysis_models import (
RunInput,
Source,
Zone,
- product_for,
- sensor_for,
+ is_radar,
+ is_single,
+ recipe_products,
+ recipe_sensor,
)
# What one run may sweep. The ceiling is not memory — tiles are read one at a
@@ -69,7 +72,7 @@ PAD = 32
# Bumped when a product's layout changes, so a frame kept from an older run is
# never decoded as a newer one.
PRODUCT_VERSION = 2
-ENGINE_VERSION = 2
+ENGINE_VERSION = 3
LOCK = threading.RLock()
KINDS = {"areas": "analysis-area", "zones": "analysis-zones", "followups": "analysis-follow-up", "runs": "analysis-run"}
ACTIVE = {"queued", "running"}
@@ -181,7 +184,11 @@ DARK_ABSENT = frozenset({"nbr"})
# calm sea in both, and at Port Sudan the radar alone put 72 candidates on the
# town and the sand around it. So the sea is first what Sentinel-2's own scene
# classification calls water on the clearest pass of the past year, and only
-# where that pass saw cloud is the radar asked.
+# where that pass saw cloud is the radar asked. That classification takes dark
+# container stacks and coal yards for water: at Rotterdam it gave a dozen
+# candidates on terminals, and overruling it wherever the radar was bright, even
+# only over blocks a hundred metres wide, dropped as many ships at berth. It is
+# left as it is.
SEA_WINDOW = 31 # a median over 300 m ignores a hull and its sidelobes
SEA_VV_DB = -9.0
SEA_VH_DB = -21.0
@@ -203,6 +210,17 @@ WATER_DB = -18.0
# The largest overall shift between two passes of one track still read as the
# sensor rather than the ground; calibration holds a pair within a few tenths.
MAX_SAR_SHIFT = 1.0
+# How much ground one step of smoothing averages radar power over before two
+# passes are compared. The grid's pixel is 7 m at 45° and a radar sample about
+# 20 m, so a window counted in pixels held too few independent samples: over
+# land that did not change, 5% of pixels still moved by 2.2 to 2.5 dB between
+# passes six days apart, and a pair of Istanbul, one of farmland and a Gaza pair
+# before October 2023 each came back as one connected region of 3 to 5 km².
+# Averaged over 90 m, the medium size, Istanbul's false "razed" fell from 111
+# to 25 and Gaza's control from 82 to 38, while the area flagged across the
+# war's first weeks stayed at 1.2 km²; the May 2023 flood at Conselice was
+# still read as 6 km² of new water, with none on the control pairs.
+SAR_WINDOW_M = SMOOTHING_M["sar-change"]
def now() -> str:
@@ -293,6 +311,12 @@ def summary(kind: str, saved: dict[str, Any]) -> dict[str, Any]:
recipe = body.get("recipe") or {}
row.update(analyzer=recipe.get("name", ""), colour=recipe.get("colour", ""),
method=recipe.get("method", ""), date_rule=body.get("date_rule", "manual"))
+ # An analyzer of your own reads one date or two depending on its rules, so
+ # the row says which rather than leaving the list to guess from the method.
+ try:
+ row["single"] = is_single(recipe)
+ except ValueError:
+ row["single"] = False
row["note"] = body.get("note", "")
if kind == "followups":
# The list draws every watched area on the map, so the shapes travel
@@ -474,6 +498,22 @@ def _decode(raw: bytes, size: int) -> Any:
return np.array(image.convert("RGBA"))
+def decode_product(raw: bytes, size: int, product: str | None) -> Any:
+ """A frame as the engine reads it: 16 bits a channel for a ``bands-…``
+ product, which Pillow would cut to 8, and bytes for everything else."""
+ import cv2
+ import numpy as np
+
+ if not product or not sentinel.product_bands(product):
+ return _decode(raw, size)
+ if len(raw) > MAX_FRAME_BYTES:
+ raise ValueError("imagery frame exceeds the byte limit")
+ pixels = cv2.imdecode(np.frombuffer(raw, np.uint8), cv2.IMREAD_UNCHANGED)
+ if pixels is None or pixels.dtype != np.uint16 or pixels.shape != (size, size, 4):
+ raise ValueError("provider returned an unexpected band frame")
+ return np.ascontiguousarray(pixels[:, :, [2, 1, 0, 3]]) # OpenCV reads BGRA
+
+
def _instance() -> str:
instance = (config.load_settings().get("api_keys") or {}).get("sentinelhub")
if not instance:
@@ -566,13 +606,18 @@ def frame(case: Case, run: dict[str, Any], source: Source, x: int, y: int,
if tiles.is_placeholder_tile(raw):
raise ValueError("provider has no imagery here at native resolution")
tilecache.put(cache_id, z, x, y, raw, "image/png")
- pixels = _decode(raw, edge)
+ pixels = decode_product(raw, edge, product)
# Canonical PNGs preserve the exact decoded input, independently of cache TTL.
+ # A 16-bit product is kept as it came: it is already a checked PNG, and
+ # Pillow cannot write one back.
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")
+ if pixels.dtype == "uint16":
+ destination.write_bytes(raw)
+ else:
+ Image.fromarray(pixels).save(destination, "PNG")
run["frames"][key] = {"path": f"{assets_rel}/{name}", "source": source.model_dump(),
"tile": [z, x, y], "index": product,
"sha256": hashlib.sha256(destination.read_bytes()).hexdigest()}
@@ -1002,18 +1047,23 @@ def _without_ghosts(binary: Any, strength: Any, metres: float) -> Any:
return keep[labels]
-def _sar_change(before: Any, after: Any, valid: Any,
+def sar_window(smoothing: int, metres: float) -> int:
+ """The radar change window in pixels for `smoothing` steps of SAR_WINDOW_M: odd, at least 3."""
+ return max(3, round(SAR_WINDOW_M * max(1, smoothing) / metres) | 1)
+
+
+def _sar_change(before: Any, after: Any, valid: Any, metres: float,
options: Parameters) -> tuple[Any, Any, Any, float, dict[str, tuple[Any, str]]]:
"""Backscatter that moved between two passes of one track, in decibels.
- Both passes are averaged as power over the same window before they are
+ Both passes are averaged as power over the same ground before they are
compared, so speckle does not read as change. What the recipe's ground
setting asks for then gates it: bright ground on the side that has it, or
water coming or going.
"""
import numpy as np
- window = 2 * max(1, options.smoothing) + 1
+ window = sar_window(options.smoothing, metres)
old = _power_mean(before[:, :, 0], valid, window)
new = _power_mean(after[:, :, 0], valid, window)
# Both polarisations vote: a building that falls or a field that floods
@@ -1075,7 +1125,7 @@ def detect(pictures: tuple[Any, Any], products: tuple[Any, Any], mask: Any, body
valid = inside & ~blocked
if method == "sar-change":
valid &= (before[:, :, 0] > 0) & (after[:, :, 0] > 0)
- stat, signed, state, threshold, measures = _sar_change(before, after, valid, options)
+ stat, signed, state, threshold, measures = _sar_change(before, after, valid, metres, options)
elif method == "index":
old = before[:, :, 0].astype(np.float32) / 127.5 - 1
new = after[:, :, 0].astype(np.float32) / 127.5 - 1
@@ -1139,7 +1189,7 @@ def strength(margin: float) -> str:
return "strong" if margin >= 3 else "clear" if margin >= 1.5 else "weak"
-def _candidates(reading: Reading, body: RunInput, x: int, y: int,
+def _candidates(reading: Reading, phenomenon: str, x: int, y: int,
part: int, frame_keys: list[str]) -> list[dict[str, Any]]:
import cv2
import numpy as np
@@ -1176,15 +1226,31 @@ def _candidates(reading: Reading, body: RunInput, x: int, y: int,
"geometry": analysis_geometry.footprint(
labels[py:py + height, px:px + width] == label, x, y, z, size, (px, py)),
"coordinates": [lon, lat], "area": pixels * mpp * mpp,
- "width": width * mpp, "height": height * mpp,
"margin": round(margin, 3), "strength": strength(margin),
"measure": {name: round(float(values[label]), 3)
for name, values in reduced.items()},
- "phenomenon": body.recipe.phenomenon, "review": "new",
+ "phenomenon": phenomenon, "review": "new",
"parts": [{"frames": frame_keys, "box": [px, py, width, height]}]})
return rows
+# How long against how wide a candidate's footprint may be and still be
+# compact, and how long it has to be to count as elongated. A roof, a crater or
+# a burnt vehicle sits near 1; a road, a track or a trench runs past 3.
+COMPACT_MAX = 2.0
+ELONGATED_MIN = 3.0
+
+
+def keeps(row: dict[str, Any], options: Parameters) -> bool:
+ """Whether a merged candidate survives the recipe's size and shape filters."""
+ if row["area"] < options.min_area or (options.max_area and row["area"] > options.max_area):
+ return False
+ if options.shape == "any" or "geometry" not in row:
+ return True
+ ratio = analysis_geometry.elongation(row["geometry"])
+ return ratio <= COMPACT_MAX if options.shape == "compact" else ratio >= ELONGATED_MIN
+
+
def merge(rows: list[dict[str, Any]], distance: float) -> list[dict[str, Any]]:
"""Join touching seam components or explicitly requested nearby candidates.
@@ -1213,8 +1279,6 @@ def merge(rows: list[dict[str, Any]], distance: float) -> list[dict[str, Any]]:
row["geometry"] = analysis_geometry.joined(row["geometry"], other["geometry"])
a = row["bbox"]
row["coordinates"] = [(a[0] + a[2]) / 2, (a[1] + a[3]) / 2]
- row["width"] = (a[2] - a[0]) * 111_320 * math.cos(math.radians(lat))
- row["height"] = (a[3] - a[1]) * 111_320
i = 0
else:
i += 1
@@ -1301,7 +1365,7 @@ def _lookup(body: RunInput, start: str, end: str) -> list[dict[str, Any]]:
raise ValueError("Copernicus is unavailable or its usage limit is reached")
try:
found = sentinel.acquisitions(instance, [list(zone.ring()) for zone in body.zones],
- start, end, collection=sensor_for(body.recipe.method))
+ start, end, collection=recipe_sensor(body.recipe))
finally:
config.record_usage("sentinelhub", 1)
return list(found["dates"])
@@ -1314,7 +1378,7 @@ def _sensed_by(body: RunInput) -> RunInput:
Sentinel-1 layer, whatever the source was saved with, and has no clouds to
set a ceiling on. An optical source never carries a pass time.
"""
- if body.recipe.method in RADAR_METHODS:
+ if is_radar(body.recipe):
radar: dict[str, Any] = {"provider": "sentinel1", "layer": radar_layer(), "maxcc": 100}
return body.model_copy(update={"a": body.a.model_copy(update=radar),
"b": body.b.model_copy(update=radar)})
@@ -1358,9 +1422,9 @@ def _timed(body: RunInput) -> RunInput:
A pass from another track sees the ground at another angle, and that
difference is not change. One lookup settles both sides.
"""
- if body.recipe.method not in RADAR_METHODS:
+ if not is_radar(body.recipe):
return body
- single = body.recipe.method in SINGLE_METHODS
+ single = is_single(body.recipe)
sides = [body.b] if single else [body.a, body.b]
missing = sorted(side.date for side in sides if side.date and not side.time)
found = _lookup(body, missing[0], missing[-1]) if missing and not body.offline else None
@@ -1376,8 +1440,8 @@ def _timed(body: RunInput) -> RunInput:
def resolve_dates(case: Case, body: RunInput, *, selected: bool = False) -> RunInput:
body = _sensed_by(body)
- single = body.recipe.method in SINGLE_METHODS
- radar = body.recipe.method in RADAR_METHODS
+ single = is_single(body.recipe)
+ radar = is_radar(body.recipe)
if single:
body = body.model_copy(update={"a": body.b})
if body.date_rule == "manual":
@@ -1475,7 +1539,7 @@ def duplicates(case: Case, body: RunInput, outcomes: list[dict[str, Any]]) -> li
"a": old.a.model_dump(), "b": old.b.model_dump()}]
match = next((r for r in records if r["area_id"] == zone.id and r["status"] == "ready"
and r["b"] == outcome["b"] and
- (body.recipe.method in SINGLE_METHODS or r["a"] == outcome["a"])), None)
+ (is_single(body.recipe) or r["a"] == outcome["a"])), None)
if match:
found.append({"run_id": run["id"], "title": run["title"], "area_id": zone.id,
"area_name": zone.name, "a": outcome["a"], "b": outcome["b"]})
@@ -1491,7 +1555,7 @@ def execute(case: Case, job: dict[str, Any]) -> None:
outcomes = run.get("area_runs")
if outcomes is None:
_, outcomes = prepare_areas(case, original)
- single = original.recipe.method in SINGLE_METHODS
+ single = is_single(original.recipe)
z, size = GRID
run.update(status="running", area_runs=outcomes, resolution={"grid_zoom": z,
"tile_size": size, "pad": PAD}, engine_version=ENGINE_VERSION)
@@ -1549,10 +1613,18 @@ def execute(case: Case, job: dict[str, Any]) -> None:
def sweep_area(case: Case, run: dict[str, Any], body: RunInput) -> tuple[list[dict[str, Any]], int, int]:
- """Apply the unchanged detector to one area's own pair."""
- single = body.recipe.method in SINGLE_METHODS
+ """Apply the unchanged detector to one area's own pair.
+
+ An analyzer of your own rules reads every product its rules need and is
+ judged by `detect_rules`, the same evaluation the builder's preview runs.
+ """
+ from . import detect_rules
+
+ single = is_single(body.recipe)
+ rules = body.recipe.method == "rules"
z, size = GRID
- product = product_for(body.recipe.method, body.recipe.parameters.index)
+ products = recipe_products(body.recipe)
+ product = products[0]
results: list[dict[str, Any]] = []
asked = imaged = 0
for part, (x, y) in enumerate(plan(body)):
@@ -1560,33 +1632,35 @@ def sweep_area(case: Case, run: dict[str, Any], body: RunInput) -> tuple[list[di
workqueue.let_others_through(case, JOB)
picture_b = frame(case, run, body.b, x, y)
picture_a = picture_b if single else frame(case, run, body.a, x, y)
- product_b = frame(case, run, body.b, x, y, product)
- product_a = product_b if single else frame(case, run, body.a, x, y, product)
- water = None
- if body.recipe.method == "sar-vessels":
- # Without it the radar alone decides what is sea, which it does
- # well enough offshore; a failed read is not a failed tile.
- try:
- water = frame(case, run, water_source(body.b), x, y, "water")
- except (ValueError, sentinel.CoverageError, httpx.HTTPError):
- water = None
mask = mask_for(body.zones, z, size, x, y)
inside = mask.astype(bool)
- asked += int(inside.sum())
- imaged += int((inside & (picture_a[:, :, 3] > 0) & (picture_b[:, :, 3] > 0)).sum())
_, lat = geographic((x + .5) / (1 << z), (y + .5) / (1 << z))
- reading = detect((picture_a, picture_b), (product_a, product_b), mask, body, lat, water)
+ if rules:
+ read: dict[str, tuple[Any, Any]] = {}
+ for name in products:
+ after = frame(case, run, body.b, x, y, name)
+ read[name] = (after if single else frame(case, run, body.a, x, y, name), after)
+ reading: Reading = detect_rules.evaluate(
+ read, mask, body.recipe, (body.a.date, body.b.date), lat).reading
+ # Pictures are for review only; the products say where the sensor saw.
+ first = read[products[0]]
+ seen = (first[1][:, :, 0] > 0) & (first[0][:, :, 0] > 0)
+ asked += int(inside.sum())
+ imaged += int((inside & seen[PAD:PAD + size, PAD:PAD + size]).sum())
+ else:
+ reading = _detect_tile(case, run, body, x, y, product, (picture_a, picture_b), mask, lat)
+ asked += int(inside.sum())
+ imaged += int((inside & (picture_a[:, :, 3] > 0) & (picture_b[:, :, 3] > 0)).sum())
sources = [body.b] if single else [body.a, body.b]
keys = [_key(source, z, x, y, None) for source in sources]
- results.extend(_candidates(reading, body, x, y, part, keys))
+ results.extend(_candidates(reading, body.recipe.phenomenon, x, y, part, keys))
if len(results) > MAX_RESULTS * 4:
raise ValueError("too many fragments; lower the sensitivity or use smaller areas")
run["progress"] += 1
persist_run(case, run)
options = body.recipe.parameters
joined = merge(results, options.merge_metres)
- kept = [r for r in joined if r["area"] >= options.min_area and
- (not options.max_area or r["area"] <= options.max_area)]
+ kept = [r for r in joined if keeps(r, options)]
for row in kept:
row.update(id=f"{body.zones[0].id}-{row['id']}", area_id=body.zones[0].id,
area_name=body.zones[0].name, origin="detector",
@@ -1594,4 +1668,22 @@ def sweep_area(case: Case, run: dict[str, Any], body: RunInput) -> tuple[list[di
return kept, asked, imaged
+def _detect_tile(case: Case, run: dict[str, Any], body: RunInput, x: int, y: int, product: str,
+ pictures: tuple[Any, Any], mask: Any, lat: float) -> Reading:
+ """One tile of a built-in detector: its product on each date, and the water
+ classification radar vessels read beside it."""
+ single = is_single(body.recipe)
+ product_b = frame(case, run, body.b, x, y, product)
+ product_a = product_b if single else frame(case, run, body.a, x, y, product)
+ water = None
+ if body.recipe.method == "sar-vessels":
+ # Without it the radar alone decides what is sea, which it does
+ # well enough offshore; a failed read is not a failed tile.
+ try:
+ water = frame(case, run, water_source(body.b), x, y, "water")
+ except (ValueError, sentinel.CoverageError, httpx.HTTPError):
+ water = None
+ return detect(pictures, (product_a, product_b), mask, body, lat, water)
+
+
workqueue.register(JOB, execute)
diff --git a/src/azimut/engine/artifacts.py b/src/azimut/engine/artifacts.py
index 0fb2bbe..2ec2d30 100644
--- a/src/azimut/engine/artifacts.py
+++ b/src/azimut/engine/artifacts.py
@@ -130,6 +130,9 @@ KINDS: dict[str, Kind] = {
),
"post": Kind(path_attr="draft"),
"inspect-session": Kind(path_attr="spec"),
+ # The exported picture is media of its own, as with a comparison: a proof may
+ # already rest on it, so it outlives the layout.
+ "collage": 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"),
diff --git a/src/azimut/engine/comparisons.py b/src/azimut/engine/comparisons.py
new file mode 100644
index 0000000..6c48cac
--- /dev/null
+++ b/src/azimut/engine/comparisons.py
@@ -0,0 +1,174 @@
+"""A saved comparison as saved work: where it stands, and the images kept from it.
+
+A comparison is imagery of one point at two dates, which is what a capture is at
+one, so the Saved panel lists it beside the captures. Its row is the comparison
+and not each image made from it: five exports of one pair are five files on one
+metre, and five marks there would bury the rest of the map.
+
+**Where it stands** is read off the reading the session saved: the export frame's
+centre when one was drawn, since that is the ground it was about, else the centre
+of the view. The frame itself is kept as a footprint, so the map draws the ground
+the images show. It is written on the `compare-session` entity at every save, and
+on sessions saved before once, when a case opens at schema 11.
+
+**An image kept in the case** is a media file stamped with the reading it shows
+and never replaced, unlike the session's preview, which each save redraws. Both
+point at their session through `compare_session` on the entity and `session` in
+the sidecar; a kept one also says `kept`, and the row lists those.
+"""
+
+from __future__ import annotations
+
+import json
+import math
+from typing import TYPE_CHECKING, Any
+
+from .. import layout
+from . import media as media_engine
+
+if TYPE_CHECKING:
+ from ..workspace import Case
+
+
+EARTH_RADIUS = 6378137.0
+MAX_LAT = 85.0511287798066
+
+#: The entity attribute that names the comparison an image was made from.
+SESSION_ATTR = "compare_session"
+
+
+def _to_mercator(lon: float, lat: float) -> tuple[float, float]:
+ clamped = max(-MAX_LAT, min(MAX_LAT, lat))
+ return (EARTH_RADIUS * math.radians(lon),
+ EARTH_RADIUS * math.log(math.tan(math.pi / 4 + math.radians(clamped) / 2)))
+
+
+def _from_mercator(x: float, y: float) -> tuple[float, float]:
+ return (math.degrees(x / EARTH_RADIUS),
+ math.degrees(2 * math.atan(math.exp(y / EARTH_RADIUS)) - math.pi / 2))
+
+
+def frame_ring(frame: dict[str, Any]) -> tuple[tuple[float, float], list[list[float]]]:
+ """The centre and closed corner ring of an export frame, as `[lon, lat]`.
+
+ The frame is two opposite ground corners and the compass direction that was up
+ when it was drawn; its sides run along that turned screen. The same arithmetic
+ as `turnedBox` in `lib/map/groundFrame.js`, in Web Mercator.
+ """
+ (lon1, lat1), (lon2, lat2) = frame["points"]
+ px, py = _to_mercator(lon1, lat1)
+ qx, qy = _to_mercator(lon2, lat2)
+ turn = math.radians(float(frame.get("angle") or 0))
+ right = (math.cos(turn), -math.sin(turn))
+ down = (-math.sin(turn), -math.cos(turn))
+ cx, cy = (px + qx) / 2, (py + qy) / 2
+ dx, dy = qx - px, qy - py
+ width = dx * right[0] + dy * right[1]
+ height = dx * down[0] + dy * down[1]
+ ring = []
+ for s, t in ((-0.5, -0.5), (0.5, -0.5), (0.5, 0.5), (-0.5, 0.5), (-0.5, -0.5)):
+ lon, lat = _from_mercator(cx + s * width * right[0] + t * height * down[0],
+ cy + s * width * right[1] + t * height * down[1])
+ ring.append([round(lon, 7), round(lat, 7)])
+ centre = _from_mercator(cx, cy)
+ return (round(centre[0], 7), round(centre[1], 7)), ring
+
+
+def placement(spec: dict[str, Any]) -> dict[str, Any]:
+ """Where a comparison stands on the map, from the reading it saved.
+
+ `footprint` is None when no frame was drawn, so a frame taken off by a later
+ save is taken off the map too.
+ """
+ camera = spec.get("camera") or {}
+ frame = spec.get("frame")
+ footprint: dict[str, Any] | None = None
+ if isinstance(frame, dict) and frame.get("points"):
+ (lon, lat), ring = frame_ring(frame)
+ footprint = {"type": "Polygon", "coordinates": [ring]}
+ else:
+ lon, lat = float(camera.get("lon", 0)), float(camera.get("lat", 0))
+ return {"lat": lat, "lon": lon, "zoom": camera.get("zoom"),
+ "bearing": camera.get("bearing", 0), "footprint": footprint}
+
+
+def moved(attrs: dict[str, Any], placed: dict[str, Any]) -> bool:
+ """Whether a save put the comparison somewhere its geography no longer covers.
+
+ Panning is part of reading a pair, so nearly every save moves the camera a
+ little. A country lookup is paced and costs a second of the save, so it is
+ asked again only past about a kilometre.
+ """
+ if not isinstance(attrs.get("geo"), dict) or attrs.get("lat") is None:
+ return True
+ return (abs(float(attrs["lat"]) - placed["lat"]) > 0.01
+ or abs(float(attrs["lon"]) - placed["lon"]) > 0.01)
+
+
+def follow_rename(case: Case, old_rel: str, new_rel: str) -> None:
+ """Point every image made from a renamed comparison at its new name, on its
+ entity and in its sidecar, which is what the Saved panel groups by."""
+ found: list[dict[str, Any]] = []
+ cursor: str | None = None
+ while True:
+ page = case.page_entities(limit=200, cursor=cursor, types=["media"],
+ attr=SESSION_ATTR, attr_value=old_rel)
+ found.extend(page["items"])
+ cursor = page.get("next_cursor")
+ if not cursor:
+ break
+ for entity in found:
+ case.update_entity(entity["id"], {"attrs": {SESSION_ATTR: new_rel}})
+ path = str((entity.get("attrs") or {}).get("path") or "")
+ item = media_engine.read_item(case, path) if path else None
+ if item and isinstance(item.get("source"), dict):
+ media_engine.merge_item(case, path, {"source": {**item["source"], "session": new_rel}})
+
+
+def grouped(items: list[dict[str, Any]]) -> tuple[dict[str, dict[str, Any]], dict[str, list[dict[str, Any]]]]:
+ """The case's comparison images, read off one media listing: every one by its
+ path (a session's preview is found there), and the kept ones by session, in
+ the order they were kept."""
+ by_path: dict[str, dict[str, Any]] = {}
+ kept: dict[str, list[dict[str, Any]]] = {}
+ for item in sorted(items, key=lambda entry: (str(entry.get("added_at") or ""), entry["path"])):
+ source = item.get("source") or {}
+ if source.get("type") != "compare":
+ continue
+ by_path[item["path"]] = item
+ if source.get("kept") and source.get("session"):
+ kept.setdefault(source["session"], []).append(
+ {"path": item["path"], "title": item.get("title") or "",
+ "thumbnail": item.get("thumbnail")})
+ return by_path, kept
+
+
+def backfill(case: Case) -> int:
+ """Place every comparison saved before comparisons stood on the map.
+
+ Their geography is left for the Locate pass, which works through whatever has
+ none: a migration must not wait on a geocoder.
+ """
+ placed = 0
+ for entity in case.list_entities():
+ if entity.get("type") != "compare-session":
+ continue
+ attrs = entity.get("attrs") or {}
+ if attrs.get("lat") is not None:
+ continue
+ rel = str(attrs.get("spec") or "")
+ try:
+ saved = json.loads(case.resolve_inside(rel).read_text(encoding="utf-8"))
+ point = placement(saved.get("spec") or {})
+ except (OSError, ValueError, KeyError, TypeError):
+ continue
+ case.update_entity(entity["id"], {"attrs": point})
+ placed += 1
+ return placed
+
+
+def session_name(spec_rel: str) -> str:
+ """The name Compare opens a session by, from where its spec is kept."""
+ prefix = f"{layout.COMPARE_DIR}/"
+ stem = spec_rel[len(prefix):] if spec_rel.startswith(prefix) else spec_rel
+ return stem.removesuffix(".json")
diff --git a/src/azimut/engine/detect_rules.py b/src/azimut/engine/detect_rules.py
new file mode 100644
index 0000000..194acc6
--- /dev/null
+++ b/src/azimut/engine/detect_rules.py
@@ -0,0 +1,680 @@
+"""Analyzers made of the analyst's own rules, and the preview that tunes them.
+
+A built-in detector is a method calibrated on real scenes (engine/analyzers.py).
+An analyzer of your own is a list of rules instead: a quantity read from
+Sentinel-2's bands or Sentinel-1's backscatter, on one date or as the change
+between two, and the line it has to cross. Nothing here is calibrated. The
+line the analyst sets is the line that runs.
+
+The preview runs `evaluate` on the frames a sweep would read, over the ground
+on screen, and hands back what each rule kept, so the builder shows what a run
+of the same analyzer returns there: the same rules, cleanup, sizes, shape and
+grouping. A check reruns the same evaluation on a place the analyst saved,
+and says whether a candidate came out on each point they marked. Both read the
+tile cache only. Fetching the frames they lack is a separate act, which the
+analyst asks for and which is metered like any other.
+"""
+
+from __future__ import annotations
+
+import base64
+import io
+import math
+import threading
+from collections import OrderedDict
+from concurrent.futures import ThreadPoolExecutor
+from dataclasses import dataclass
+from typing import Any
+
+from PIL import Image
+
+from .. import config
+from . import analysis_geometry, analyzers, sentinel, tilecache
+from .analysis_models import (
+ SCENE_CLASSES,
+ VISIBLE_BANDS,
+ Check,
+ Recipe,
+ Rule,
+ Source,
+ is_radar,
+ is_single,
+ recipe_products,
+ recipe_sensor,
+ uses_clouds,
+)
+
+#: What one unit past a rule's line is worth to a candidate's strength. Two of
+#: them past it is Strong, as a built-in's reading at three times its threshold
+#: is: 0.2 of an index, 4% reflectance, 4 dB of radar.
+UNITS = {"index": 0.1, "nd": 0.1, "band": 0.02, "brightness": 0.02, "colour": 0.02, "radar": 2.0}
+#: Quantities in reflectance, which a change reads with the passes' overall
+#: shift in light taken out, as the built-in change methods do.
+REFLECTANCE = frozenset({"band", "brightness", "colour"})
+#: The preview's reach: three tiles by three around the view, about 15 km on a
+#: side at the equator and 10 at 45°. Past that the frames it needs to read
+#: stop being a figure an analyst glances at.
+PREVIEW_SPAN = 3
+PREVIEW_CANDIDATES = 300
+#: Bits of the preview mask. Rules take the low ones in order.
+MEASURED_BIT = 6
+KEPT_BIT = 7
+
+# Decoded frames the preview has read lately, so moving a slider re-reads
+# nothing from disk. A frame is 2.6 MB decoded; this holds a full preview of two
+# dates with room to spare.
+_DECODED: OrderedDict[tuple[str, int, int], Any] = OrderedDict()
+_DECODED_MAX = 40
+_DECODED_LOCK = threading.Lock()
+
+
+@dataclass
+class Evaluation:
+ """One tile judged by an analyzer's rules, cropped back to the tile.
+
+ `reading` is what a sweep turns into candidates. The rest is for the
+ builder: what each rule kept, the value it read, and where the sensor saw.
+ """
+
+ reading: analyzers.Reading
+ passes: list[Any]
+ values: list[Any]
+ before: list[Any]
+ after: list[Any]
+ measured: Any
+ imaged: Any
+
+
+# -- reading quantities ------------------------------------------------------------
+
+
+def _odd(value: float, low: int, high: int) -> int:
+ return int(min(high, max(low, round(value) | 1)))
+
+
+class _Reader:
+ """The quantities a recipe's rules read, computed once per tile and date."""
+
+ def __init__(self, products: dict[str, tuple[Any, Any]], recipe: Recipe,
+ metres: float, measured: Any) -> None:
+ self.products = products
+ self.options = recipe.parameters
+ self.metres = metres
+ self.measured = measured
+ self.where = {band: (name, channel) for name in products
+ for channel, band in enumerate(sentinel.product_bands(name))}
+ self.cache: dict[tuple[Any, ...], Any] = {}
+
+ def band(self, band: str, side: int) -> Any:
+ import numpy as np
+
+ name, channel = self.where[band]
+ return self.products[name][side][:, :, channel].astype(np.float32) / sentinel.BANDS_SCALE
+
+ def scene(self, side: int) -> Any:
+ first = self.products[next(iter(self.products))][side]
+ return first[:, :, 3] & 15
+
+ def _normalised(self, high: tuple[str, ...], low: tuple[str, ...], side: int) -> Any:
+ import numpy as np
+
+ top = sum(self.band(band, side) for band in high)
+ bottom = sum(self.band(band, side) for band in low)
+ total = top + bottom
+ with np.errstate(divide="ignore", invalid="ignore"):
+ return np.where(total > 0, (top - bottom) / total, np.nan).astype(np.float32)
+
+ def raw(self, rule: Rule, side: int) -> Any:
+ """The quantity itself on one date, before smoothing."""
+ import numpy as np
+
+ if rule.measure == "index":
+ high, low = sentinel.SPECTRAL_INDEX[rule.index]
+ return self._normalised(high, low, side)
+ if rule.measure == "nd":
+ return self._normalised((rule.bands[0],), (rule.bands[1],), side)
+ if rule.measure == "band":
+ return self.band(rule.band, side)
+ if rule.measure == "brightness":
+ return sum(self.band(band, side) for band in VISIBLE_BANDS) / len(VISIBLE_BANDS)
+ if rule.measure == "radar":
+ # Speckle is averaged as power over the window radar change uses,
+ # never as decibels, whose mean runs low (engine/analyzers.py).
+ level = self.products["sar"][side]
+ seen = self.measured & (level[:, :, 0] > 0)
+ window = analyzers.sar_window(self.options.smoothing, self.metres)
+ vv = analyzers._power_mean(level[:, :, 0], seen, window)
+ if rule.polarisation == "vv":
+ return vv.astype(np.float32)
+ vh = analyzers._power_mean(level[:, :, 1], seen, window)
+ return (vh if rule.polarisation == "vh" else vv - vh).astype(np.float32)
+ raise ValueError(f"no quantity for {rule.measure}")
+
+ def quantity(self, rule: Rule, side: int) -> Any:
+ key = (rule.measure, rule.index, rule.bands, rule.band, rule.polarisation, side)
+ if key not in self.cache:
+ value = self.raw(rule, side)
+ self.cache[key] = value if rule.measure == "radar" else self.smooth(value)
+ return self.cache[key]
+
+ def smooth(self, values: Any) -> Any:
+ """A blur that only averages what was measured, so a cloud's edge or a
+ swath's end does not bleed into the ground beside it."""
+ import cv2
+ import numpy as np
+
+ steps = self.options.smoothing
+ if not steps:
+ return values
+ weight = (self.measured & np.isfinite(values)).astype(np.float32)
+ kernel = (steps * 2 + 1,) * 2
+ total = cv2.GaussianBlur(np.where(weight > 0, values, 0).astype(np.float32), kernel, 0)
+ count = cv2.GaussianBlur(weight, kernel, 0)
+ with np.errstate(divide="ignore", invalid="ignore"):
+ return np.where(count > 1e-3, total / count, np.nan).astype(np.float32)
+
+ def shifted(self, delta: Any, limit: float) -> Any:
+ """A change with the passes' overall shift taken out, up to `limit`."""
+ import numpy as np
+
+ usable = self.measured & np.isfinite(delta)
+ shift = float(np.median(delta[usable])) if usable.any() else 0.0
+ return delta - max(-limit, min(limit, shift))
+
+ def colour(self) -> Any:
+ """How far the visible bands moved together, in reflectance."""
+ import numpy as np
+
+ moved = [self.shifted(self.band(band, 1) - self.band(band, 0), analyzers.MAX_SHIFT)
+ for band in VISIBLE_BANDS]
+ return self.smooth(np.sqrt(np.mean(np.stack(moved, -1) ** 2, -1)).astype(np.float32))
+
+ def around(self, values: Any, metres: int) -> Any:
+ """A quantity against the ground within `metres` of it, the ring with a
+ hole punched in the middle that the vessel detectors read, so a target
+ cannot raise its own background."""
+ import numpy as np
+
+ outer = _odd(2 * metres / self.metres + 1, 5, 2 * analyzers.PAD + 1)
+ guard = _odd(outer / 3, 3, outer - 2)
+ weight = self.measured & np.isfinite(values)
+ mean, _, share = analyzers.ring_statistics(np.where(weight, values, 0.0).astype(np.float64),
+ weight, outer, guard)
+ return np.where(share > 0, values - mean, np.nan).astype(np.float32)
+
+ def value(self, rule: Rule) -> tuple[Any, Any, Any]:
+ """What a rule compares with its line, and the two dates behind a change."""
+ before = after = None
+ if rule.on in ("a", "b"):
+ value = self.quantity(rule, 0 if rule.on == "a" else 1)
+ elif rule.measure == "colour":
+ value = self.colour()
+ else:
+ before, after = self.quantity(rule, 0), self.quantity(rule, 1)
+ value = after - before
+ if rule.measure in REFLECTANCE:
+ value = self.shifted(value, analyzers.MAX_SHIFT)
+ elif rule.measure == "radar":
+ value = self.shifted(value, analyzers.MAX_SAR_SHIFT)
+ if rule.around:
+ value = self.around(value, rule.around)
+ return value, before, after
+
+
+def _passes(rule: Rule, value: Any) -> Any:
+ import numpy as np
+
+ with np.errstate(invalid="ignore"):
+ if rule.op == "ge":
+ return value >= rule.value
+ if rule.op == "le":
+ return value <= rule.value
+ if rule.op == "between":
+ return (value >= rule.value) & (value <= rule.upper)
+ return np.abs(value) >= rule.value
+
+
+def _past(rule: Rule, value: Any) -> Any:
+ """How far past its line a reading got, in the rule's own units."""
+ import numpy as np
+
+ if rule.op == "ge":
+ return value - rule.value
+ if rule.op == "le":
+ return rule.value - value
+ if rule.op == "between":
+ return np.minimum(value - rule.value, rule.upper - value)
+ return np.abs(value) - rule.value
+
+
+def signal(recipe: Recipe) -> int | None:
+ """The rule that ranks candidates: the first one that measures something."""
+ return next((i for i, rule in enumerate(recipe.rules) if rule.measure != "class"), None)
+
+
+def evaluate(products: dict[str, tuple[Any, Any]], mask: Any, recipe: Recipe,
+ days: tuple[str, str], lat: float) -> Evaluation:
+ """One tile, judged by every rule of the recipe.
+
+ `products` names each band product with its (A, B) frames, padded by
+ `analyzers.PAD`; an analyzer that reads one date passes B twice. `mask`
+ is the tile's own ground to judge, unpadded.
+ """
+ import cv2
+ import numpy as np
+
+ options = recipe.parameters
+ single = is_single(recipe)
+ z, size = analyzers.GRID
+ pad = analyzers.PAD
+ metres = analyzers.WORLD * math.cos(math.radians(lat)) / ((1 << z) * size)
+ sides = (1,) if single else (0, 1)
+ first = products[next(iter(products))]
+ shape = first[1].shape[:2]
+ core = (slice(pad, pad + size), slice(pad, pad + size))
+ inside = np.zeros(shape, bool)
+ inside[core] = mask.astype(bool)
+ imaged = np.ones(shape, bool)
+ for pair in products.values():
+ for side in sides:
+ imaged &= pair[side][:, :, 0] > 0
+ measured = inside & imaged
+ if uses_clouds(recipe):
+ blocked = analyzers.weather_mask([first[side] for side in sides], [days[side] for side in sides],
+ lat, metres, options)
+ if blocked is not None:
+ measured &= ~blocked
+ reader = _Reader(products, recipe, metres, measured)
+
+ passes, values, befores, afters, distances = [], [], [], [], []
+ for rule in recipe.rules:
+ if rule.measure == "class":
+ ground = np.isin(reader.scene(0 if rule.on == "a" else 1), SCENE_CLASSES_FLAT[tuple(rule.classes)])
+ passed = measured & (ground if rule.op == "is" else ~ground)
+ value = before = after = None
+ distance = np.where(passed, 0.0, np.nan)
+ else:
+ value, before, after = reader.value(rule)
+ passed = measured & _passes(rule, value)
+ with np.errstate(invalid="ignore"):
+ distance = np.where(passed, _past(rule, value) / UNITS[rule.measure], np.nan)
+ passes.append(passed)
+ values.append(value)
+ befores.append(before)
+ afters.append(after)
+ distances.append(distance)
+
+ if recipe.match == "all":
+ combined = np.logical_and.reduce(passes)
+ else:
+ combined = np.logical_or.reduce(passes)
+ binary = measured & combined
+ if options.cleanup:
+ kernel = np.ones((2 * options.cleanup + 1,) * 2, np.uint8)
+ cleaned = cv2.morphologyEx(binary.astype(np.uint8), cv2.MORPH_OPEN, kernel,
+ borderType=cv2.BORDER_REPLICATE)
+ cleaned = cv2.morphologyEx(cleaned, cv2.MORPH_CLOSE, np.ones((3, 3), np.uint8),
+ borderType=cv2.BORDER_REPLICATE)
+ binary = cleaned.astype(bool) & measured
+
+ # A candidate's margin is how far past the line it got: the signal's, or
+ # under "any" the best of whichever rules it passed. 1 is on the line.
+ ranked = signal(recipe)
+ if recipe.match == "all":
+ past = distances[ranked] if ranked is not None else np.zeros(shape)
+ else:
+ past = np.fmax.reduce(np.stack(distances), axis=0)
+ stat = np.where(binary, 1.0 + np.clip(np.nan_to_num(past, nan=0.0), 0.0, 20.0), 0.0).astype(np.float32)
+
+ measures: dict[str, tuple[Any, str]] = {}
+ if ranked is not None:
+ rule = recipe.rules[ranked]
+ clean = lambda array: np.nan_to_num(array, nan=0.0) # noqa: E731
+ if rule.on == "change" and rule.measure != "colour":
+ measures = {"before": (clean(befores[ranked]), "mean"), "after": (clean(afters[ranked]), "mean"),
+ "signed": (clean(values[ranked]), "mean")}
+ else:
+ measures = {"value": (clean(values[ranked]), "mean")}
+
+ crop = lambda array: None if array is None else array[core] # noqa: E731
+ reading = analyzers.Reading(binary=binary[core].astype(np.uint8), stat=stat[core], threshold=1.0,
+ measures={name: (array[core], how) for name, (array, how) in measures.items()})
+ return Evaluation(reading=reading, passes=[crop(p) for p in passes], values=[crop(v) for v in values],
+ before=[crop(b) for b in befores], after=[crop(a) for a in afters],
+ measured=measured[core], imaged=imaged[core])
+
+
+class _Classes(dict[tuple[str, ...], tuple[int, ...]]):
+ """Scene codes for a set of class names, worked out once per set."""
+
+ def __missing__(self, names: tuple[str, ...]) -> tuple[int, ...]:
+ codes = tuple(code for name in names for code in SCENE_CLASSES[name])
+ self[names] = codes
+ return codes
+
+
+SCENE_CLASSES_FLAT = _Classes()
+
+
+# -- the preview ---------------------------------------------------------------------
+
+
+def preview_sources(recipe: Recipe, a: Source, b: Source) -> tuple[Source, Source]:
+ """The sources a preview reads, named for the satellite the rules use.
+
+ Every pass is read whatever its cloud cover: the analyst picked it, and
+ the cloud switch is what decides what counts under a cloud.
+ """
+ if is_radar(recipe):
+ patch: dict[str, Any] = {"provider": "sentinel1", "layer": analyzers.radar_layer(), "maxcc": 100}
+ else:
+ patch = {"provider": "sentinel2", "layer": sentinel.DEFAULT_LAYER, "maxcc": 100, "time": ""}
+ b = b.model_copy(update=patch)
+ if not b.date:
+ raise ValueError("choose the pass to preview on")
+ if is_single(recipe):
+ return b, b
+ a = a.model_copy(update=patch)
+ if not a.date:
+ raise ValueError("these rules read A as well; choose a reference pass")
+ if a.provider == "sentinel1" and a.time and b.time and not sentinel.same_track(a.time, b.time):
+ raise ValueError("A and B were seen from different radar tracks; choose two passes at the same time of day")
+ return a, b
+
+
+def preview_tiles(bounds: tuple[float, float, float, float]) -> tuple[list[tuple[int, int]], bool]:
+ """The grid tiles under a view, at most PREVIEW_SPAN a side around its centre."""
+ west, south, east, north = bounds
+ if west >= east or south >= north:
+ raise ValueError("move the view off the antimeridian to preview it")
+ z, _ = analyzers.GRID
+ count = 1 << z
+ left, top = analyzers.mercator(west, north)
+ right, bottom = analyzers.mercator(east, south)
+
+ def span(low: float, high: float) -> tuple[list[int], bool]:
+ first = max(0, math.floor(low * count))
+ last = min(count - 1, max(first, math.ceil(high * count) - 1))
+ if last - first + 1 <= PREVIEW_SPAN:
+ return list(range(first, last + 1)), False
+ middle = (first + last) // 2
+ return list(range(middle - PREVIEW_SPAN // 2, middle - PREVIEW_SPAN // 2 + PREVIEW_SPAN)), True
+
+ columns, wide = span(left, right)
+ rows, tall = span(top, bottom)
+ return [(x, y) for y in rows for x in columns], wide or tall
+
+
+def held(source: Source, x: int, y: int, product: str) -> Any | None:
+ """A product frame the tile cache holds, decoded, or None."""
+ z, size = analyzers.GRID
+ cache_id = analyzers.product_cache_id(source, product)
+ key = (cache_id, x, y)
+ with _DECODED_LOCK:
+ if key in _DECODED:
+ _DECODED.move_to_end(key)
+ return _DECODED[key]
+ cached = tilecache.get(cache_id, z, x, y)
+ if not cached:
+ return None
+ pixels = analyzers.decode_product(cached[0], size + 2 * analyzers.PAD, product)
+ with _DECODED_LOCK:
+ _DECODED[key] = pixels
+ while len(_DECODED) > _DECODED_MAX:
+ _DECODED.popitem(last=False)
+ return pixels
+
+
+def missing(recipe: Recipe, a: Source, b: Source,
+ tiles: list[tuple[int, int]]) -> list[tuple[Source, int, int, str]]:
+ sources = [b] if is_single(recipe) else [a, b]
+ z, _ = analyzers.GRID
+
+ def have(source: Source, x: int, y: int, product: str) -> bool:
+ cache_id = analyzers.product_cache_id(source, product)
+ with _DECODED_LOCK:
+ if (cache_id, x, y) in _DECODED:
+ return True
+ return tilecache.get(cache_id, z, x, y) is not None
+
+ return [(source, x, y, product) for x, y in tiles for product in recipe_products(recipe)
+ for source in sources if not have(source, x, y, product)]
+
+
+def fetch(frames: list[tuple[Source, int, int, str]]) -> None:
+ """Read the frames a preview lacks from Copernicus into the tile cache.
+
+ Only ever called because the analyst pressed Read. Each frame is one
+ request on the Sentinel Hub meter, counted whether it succeeds or not.
+ """
+ if not frames:
+ return
+ instance = analyzers._instance()
+ if config.usage_blocked("sentinelhub"):
+ raise ValueError("Sentinel Hub usage limit reached; review Settings")
+ z, size = analyzers.GRID
+ edge = size + 2 * analyzers.PAD
+
+ def one(frame: tuple[Source, int, int, str]) -> None:
+ source, x, y, product = frame
+ try:
+ raw = sentinel.band_frame(instance, analyzers._box(z, x, y, analyzers.PAD), edge, edge,
+ source.date, product, source.maxcc, layer=source.layer,
+ time=source.time)
+ finally:
+ config.record_usage("sentinelhub", 1)
+ tilecache.put(analyzers.product_cache_id(source, product), z, x, y, raw, "image/png")
+
+ with ThreadPoolExecutor(max_workers=4) as pool:
+ list(pool.map(one, frames))
+
+
+def _tile(recipe: Recipe, a: Source, b: Source, x: int, y: int) -> Evaluation:
+ import numpy as np
+
+ z, size = analyzers.GRID
+ read: dict[str, tuple[Any, Any]] = {}
+ for product in recipe_products(recipe):
+ after = held(b, x, y, product)
+ before = after if is_single(recipe) else held(a, x, y, product)
+ if after is None or before is None:
+ raise ValueError("read this view's frames first")
+ read[product] = (before, after)
+ _, lat = analyzers.geographic((x + .5) / (1 << z), (y + .5) / (1 << z))
+ return evaluate(read, np.ones((size, size), np.uint8), recipe, (a.date, b.date), lat)
+
+
+def _png(mask: Any) -> str:
+ out = io.BytesIO()
+ Image.fromarray(mask).save(out, "PNG", compress_level=6)
+ return base64.b64encode(out.getvalue()).decode("ascii")
+
+
+def preview(recipe: Recipe, a: Source, b: Source, bounds: tuple[float, float, float, float],
+ *, read: bool = False) -> dict[str, Any]:
+ """What the recipe keeps over the view, and what each rule kept on the way.
+
+ Every tile whose frames are held is judged, so a view that is half read
+ still shows its half; `missing` counts the frames the rest lacks. Without
+ `read` nothing reaches the network, and the answer says how many requests
+ would fetch them.
+ """
+ import numpy as np
+
+ a, b = preview_sources(recipe, a, b)
+ tiles, clipped = preview_tiles(bounds)
+ z, size = analyzers.GRID
+ count = 1 << z
+ lacking = missing(recipe, a, b, tiles)
+ if lacking and read:
+ fetch(lacking)
+ lacking = missing(recipe, a, b, tiles)
+ xs = sorted({x for x, _ in tiles})
+ ys = sorted({y for _, y in tiles})
+ world = analyzers.WORLD
+ answer: dict[str, Any] = {
+ "tiles": [list(tile) for tile in tiles], "clipped": clipped, "missing": len(lacking),
+ "box": {"west": xs[0] / count * world - world / 2, "east": (xs[-1] + 1) / count * world - world / 2,
+ "north": world / 2 - ys[0] / count * world, "south": world / 2 - (ys[-1] + 1) / count * world},
+ "size": [len(xs) * size, len(ys) * size], "ready": False,
+ }
+ unread = {(x, y) for _, x, y, _ in lacking}
+ judged = [tile for tile in tiles if tile not in unread]
+ if not judged:
+ return answer
+
+ options = recipe.parameters
+ mosaic = np.zeros((len(ys) * size, len(xs) * size), np.uint8)
+ measured_total = 0
+ own = [0] * len(recipe.rules)
+ running = [0] * len(recipe.rules)
+ kept_total = 0
+ rows: list[dict[str, Any]] = []
+ note = ""
+ for part, (x, y) in enumerate(judged):
+ evaluation = _tile(recipe, a, b, x, y)
+ bits = evaluation.measured.astype(np.uint8) << MEASURED_BIT
+ bits |= evaluation.reading.binary.astype(np.uint8) << KEPT_BIT
+ so_far = None
+ for i, passed in enumerate(evaluation.passes):
+ bits |= passed.astype(np.uint8) << i
+ own[i] += int(passed.sum())
+ so_far = passed if so_far is None else (so_far & passed if recipe.match == "all" else so_far | passed)
+ running[i] += int(so_far.sum())
+ measured_total += int(evaluation.measured.sum())
+ kept_total += int(evaluation.reading.binary.sum())
+ top, left = ys.index(y) * size, xs.index(x) * size
+ mosaic[top:top + size, left:left + size] = bits
+ if not note:
+ try:
+ rows.extend(analyzers._candidates(evaluation.reading, recipe.phenomenon, x, y, part, []))
+ except ValueError as exc:
+ note, rows = str(exc), []
+ candidates = [row for row in analyzers.merge(rows, options.merge_metres) if analyzers.keeps(row, options)]
+ candidates.sort(key=lambda row: row["margin"], reverse=True)
+ share = lambda value: round(value / measured_total, 5) if measured_total else 0.0 # noqa: E731
+ return {**answer, "ready": True, "mask": _png(mosaic),
+ "measured": round(measured_total / (len(judged) * size * size), 5),
+ "rules": [{"share": share(own[i]), "kept": share(running[i])} for i in range(len(recipe.rules))],
+ "kept": share(kept_total), "count": len(candidates), "note": note,
+ "candidates": [{key: value for key, value in row.items() if key != "parts"}
+ for row in candidates[:PREVIEW_CANDIDATES]]}
+
+
+def probe(recipe: Recipe, a: Source, b: Source, point: tuple[float, float]) -> dict[str, Any]:
+ """What every rule read at one point of the preview, and whether it passed."""
+ import numpy as np
+
+ a, b = preview_sources(recipe, a, b)
+ z, size = analyzers.GRID
+ count = 1 << z
+ gx, gy = analyzers.mercator(*point)
+ x, y = int(gx * count), int(gy * count)
+ if missing(recipe, a, b, [(x, y)]):
+ return {"ready": False}
+ evaluation = _tile(recipe, a, b, x, y)
+ px = min(size - 1, int((gx * count - x) * size))
+ py = min(size - 1, int((gy * count - y) * size))
+
+ def number(array: Any) -> float | None:
+ if array is None:
+ return None
+ value = float(array[py, px])
+ return round(value, 4) if np.isfinite(value) else None
+
+ return {"ready": True, "imaged": bool(evaluation.imaged[py, px]),
+ "measured": bool(evaluation.measured[py, px]),
+ "kept": bool(evaluation.reading.binary[py, px]),
+ "rules": [{"passes": bool(evaluation.passes[i][py, px]), "value": number(evaluation.values[i]),
+ "before": number(evaluation.before[i]), "after": number(evaluation.after[i])}
+ for i in range(len(recipe.rules))]}
+
+
+# -- checks --------------------------------------------------------------------------
+
+#: How close a candidate has to come to a mark to be on it: a pixel and a half.
+MARK_REACH_M = 15.0
+
+
+def check_tiles(check: Check) -> list[tuple[int, int]]:
+ """The grid tiles a check reads: the ones under its marks, else its view's.
+
+ A mark is read on its own tile, so a candidate cut by that tile's edge is
+ judged on the part inside it. Marks are best placed away from an edge.
+ """
+ if not check.marks:
+ bounds = check.bounds
+ return preview_tiles((bounds.west, bounds.south, bounds.east, bounds.north))[0]
+ z, _ = analyzers.GRID
+ count = 1 << z
+ tiles: list[tuple[int, int]] = []
+ for mark in check.marks:
+ gx, gy = analyzers.mercator(*mark.point)
+ tile = (int(gx * count), int(gy * count))
+ if tile not in tiles:
+ tiles.append(tile)
+ return tiles
+
+
+def check(recipe: Recipe, check: Check, *, read: bool = False) -> dict[str, Any]:
+ """A check rerun with the recipe as it stands: what came out on each mark.
+
+ It reads the tile cache, as the preview does, and `read` fetches the frames
+ it lacks. `covered` says, mark by mark, whether a candidate a run would
+ return comes within MARK_REACH_M of it; `count` is how many came out.
+ """
+ if check.b.provider != recipe_sensor(recipe):
+ seen = "radar" if check.b.provider == "sentinel1" else "Sentinel-2"
+ raise ValueError(f"this check was saved on {seen} passes; save it again on passes these rules read")
+ a, b = preview_sources(recipe, check.a, check.b)
+ tiles = check_tiles(check)
+ lacking = missing(recipe, a, b, tiles)
+ if lacking and read:
+ fetch(lacking)
+ lacking = missing(recipe, a, b, tiles)
+ if lacking:
+ return {"ready": False, "missing": len(lacking)}
+ rows: list[dict[str, Any]] = []
+ for part, (x, y) in enumerate(tiles):
+ evaluation = _tile(recipe, a, b, x, y)
+ rows.extend(analyzers._candidates(evaluation.reading, recipe.phenomenon, x, y, part, []))
+ options = recipe.parameters
+ candidates = [row for row in analyzers.merge(rows, options.merge_metres) if analyzers.keeps(row, options)]
+ covered = [any(analysis_geometry.near(row["geometry"], mark.point, MARK_REACH_M) for row in candidates)
+ for mark in check.marks]
+ return {"ready": True, "missing": 0, "count": len(candidates), "covered": covered}
+
+
+# -- built-ins as rules --------------------------------------------------------------
+
+
+def index_as_rules(recipe: Recipe) -> dict[str, Any] | None:
+ """A built-in index detector written out as the rules it applies.
+
+ The line is the one its sensitivity sets, and the states either side are
+ the ones the engine requires of a loss or a gain (`INDEX_STATES`). The
+ copy starts from the same reading; it grows regions pixel by pixel rather
+ than from the strongest ones out, so it can outline a little less.
+ """
+ if recipe.method != "index":
+ return None
+ parameters = recipe.parameters
+ index = parameters.index
+ line = round(analyzers._scale(parameters.sensitivity, 0.05, 0.5), 2)
+ absent, present = analyzers.INDEX_STATES[index]
+ at = lambda on, op, value: Rule(measure="index", index=index, on=on, op=op, value=value) # noqa: E731
+ dark = lambda on: Rule(measure="band", band="B08", on=on, op="le", # noqa: E731
+ value=sentinel.DARK_REFLECTANCE)
+ if parameters.direction == "loss":
+ rules = [at("change", "le", -line), at("a", "ge", present), at("b", "le", absent)]
+ if index in analyzers.DARK_ABSENT:
+ rules.append(dark("b"))
+ elif parameters.direction == "gain":
+ rules = [at("change", "ge", line), at("b", "ge", present), at("a", "le", absent)]
+ if index in analyzers.DARK_ABSENT:
+ rules.append(dark("a"))
+ else:
+ rules = [at("change", "moved", line)]
+ return Recipe(name=f"{recipe.name} (rules)", description=recipe.description,
+ phenomenon=recipe.phenomenon, method="rules", colour=recipe.colour,
+ style=recipe.style, parameters=parameters, rules=rules).model_dump()
diff --git a/src/azimut/engine/entities.py b/src/azimut/engine/entities.py
index c421b36..e0cfe28 100644
--- a/src/azimut/engine/entities.py
+++ b/src/azimut/engine/entities.py
@@ -553,8 +553,15 @@ ENTITY_TYPES: tuple[EntityType, ...] = (
# names a subject is visible from that subject's side too.
EntityType("sheet", "Sheet", DOCUMENT, "table", ANNEX,
hint="a CSV table in the case, edited as a grid"),
+ # One per file: the frames cut from it and the edits over them, saved as they
+ # are made. Nothing in it outlives the file, so it depends on it.
EntityType("inspect-session", "Inspect session", DOCUMENT, "inspect", ANNEX,
- hint="saved adjustments over one file, which die with it"),
+ hint="the frames and edits made over one file, which die with it"),
+ # A layout of pieces from any number of files. Its pieces are recipes rather
+ # than pixels, so a lost source leaves a gap rather than voiding the layout,
+ # and the picture it exports is media of its own.
+ EntityType("collage", "Collage", DOCUMENT, "grid", ANNEX,
+ hint="frames and images laid out together, exported as one picture"),
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,
diff --git a/src/azimut/engine/inspect.py b/src/azimut/engine/inspect.py
index 2ca84f1..671d148 100644
--- a/src/azimut/engine/inspect.py
+++ b/src/azimut/engine/inspect.py
@@ -318,7 +318,7 @@ def run_analysis(
) -> dict[str, Any]:
"""Run a read-only analysis on a filed image or a transient frame recipe.
- ``time_s``/``ops`` let the Inspect session analyse a not-yet-saved frame
+ ``time_s``/``ops`` let Inspect analyse a not-yet-saved frame
(extracted from ``rel_path`` at ``time_s``, optionally adjusted) without filing
anything. Plain image analysis (no ``time_s``/``ops``) keeps the original file
open so metadata analyses (EXIF) still see it.
@@ -484,7 +484,7 @@ def _apply_meta(
folder: str | None = None,
notes: str | None = None,
) -> None:
- """Write the Save gate's chosen name, folder and note onto the filed item.
+ """Write the name, folder and note chosen at Save to case onto the filed item.
This applies to a deduped save too. Re-saving an unchanged collage lands on
the same pixels and so on the same entity, and dropping the name there is
@@ -606,13 +606,13 @@ def suggest_frames(
# ---------------------------------------------------------------------------
-# Session workspace: recipes -> filed entities (Inspect Selection/Frame/Collage/Save)
+# Recipes -> filed entities (Inspect's frames and video, Collage's export)
# ---------------------------------------------------------------------------
#
-# The Inspect UI is a scratch workspace: frames, adjustments and a collage layout
-# live in the browser as *recipes* (``{path, time?, ops[]}``) and nothing enters the
-# case until an explicit Save. These functions turn a recipe back into pixels and
-# file the result — full-res and reproducible, so provenance stays honest (spec §6).
+# Frames, adjustments and collage layouts are *recipes* (``{path, time?, ops[]}``),
+# kept with a file's work or a collage (engine/inspectwork). No media enters the
+# case until Save to case. These functions turn a recipe back into pixels and file
+# the result — full-res and reproducible, so provenance stays honest (spec §6).
def _source_image(
@@ -638,7 +638,8 @@ def render_preview_png(
) -> bytes:
"""Render a recipe (video frame or image + ops) to PNG bytes — no filing.
- Backs collage snapshots and rebuilding previews when a saved session reopens.
+ Backs frame previews, collage pieces and rebuilding both when a work or a
+ collage reopens.
A remapped (panorama) piece keeps its alpha, so the canvas shows the same
curved footprint the export will paint.
"""
@@ -660,14 +661,14 @@ def save_frame(
folder: str | None = None,
notes: str | None = None,
) -> dict[str, Any]:
- """File one tray frame (a video frame or an adjusted image) as case media."""
+ """File one frame (a video frame or an adjusted image) as case media."""
image = _source_image(case, rel_path, time_s, ops)
stem = _name_stem(label, Path(rel_path).stem)
if time_s is not None:
tag, op = f"_t{time_s:.2f}s", "frame"
else:
tag, op = "_edit", "adjust"
- # A named item keeps its name on disk, and nothing else: the tray already
+ # A named item keeps its name on disk, and nothing else: Inspect already
# spells the instant into the name it sends, and `unique_path` settles a
# collision, so a wall-clock stamp would only clutter the folder the analyst
# opens. The timecode tag stands in on the fallback stem, where nothing else
@@ -723,17 +724,12 @@ def _compose_canvas(
height: int,
nodes: list[dict[str, Any]],
background: str | None,
- scale: float = 1.0,
) -> tuple[Image.Image, list[str]]:
- """Warp each node's source into its quad and paint onto one canvas.
-
- Shared by the filed export and the (unsaved) Save-tab preview. ``scale``
- shrinks the whole layout (canvas + quads) for a cheaper preview render.
- """
+ """Warp each node's source into its quad and paint onto one canvas."""
if not nodes:
raise ValueError("collage needs at least one image")
- width = max(16, min(int(round(width * scale)), 8192))
- height = max(16, min(int(round(height * scale)), 8192))
+ width = max(16, min(int(width), 8192))
+ height = max(16, min(int(height), 8192))
canvas = (
Image.new("RGB", (width, height), background)
if background
@@ -754,7 +750,7 @@ def _compose_canvas(
img = img.convert("RGB")
w, h = img.size
src_corners = [[0.0, 0.0], [float(w), 0.0], [float(w), float(h)], [0.0, float(h)]]
- quad = [[float(x) * scale, float(y) * scale] for x, y in node["quad"]]
+ quad = [[float(x), float(y)] for x, y in node["quad"]]
coeffs = _perspective_coeffs(quad, src_corners)
warped = img.transform(
(width, height), Image.Transform.PERSPECTIVE, coeffs, Image.Resampling.BICUBIC
@@ -767,29 +763,6 @@ def _compose_canvas(
return canvas, sources
-def compose_preview_png(
- case: Case,
- *,
- width: int,
- height: int,
- nodes: list[dict[str, Any]],
- background: str | None = None,
- max_dim: int = 640,
-) -> bytes:
- """Render the exact composited collage to PNG bytes — nothing is filed.
-
- Same warp as :func:`compose_perspective`, downscaled to ``max_dim`` so the
- Save tab can show a true-to-export thumbnail cheaply.
- """
- scale = min(1.0, max_dim / max(1, max(int(width), int(height))))
- canvas, _ = _compose_canvas(
- case, width=width, height=height, nodes=nodes, background=background, scale=scale
- )
- buf = io.BytesIO()
- canvas.save(buf, "PNG")
- return buf.getvalue()
-
-
def compose_perspective(
case: Case,
*,
@@ -801,7 +774,7 @@ def compose_perspective(
folder: str | None = None,
notes: str | None = None,
) -> dict[str, Any]:
- """Composite tray/case images, each warped into a 4-point quad, onto a canvas.
+ """Composite frames and case images, each warped into a 4-point quad, onto a canvas.
``nodes`` are painted in order (later = on top); each is
``{"src": {path, time?, ops[]}, "quad": [[x,y]×4]}`` with the quad in canvas
diff --git a/src/azimut/engine/inspectwork.py b/src/azimut/engine/inspectwork.py
new file mode 100644
index 0000000..4253530
--- /dev/null
+++ b/src/azimut/engine/inspectwork.py
@@ -0,0 +1,775 @@
+"""Inspect's saved work, and the collages laid out from it.
+
+Two artifacts with two lifetimes.
+
+**Work** belongs to one file: the frames cut from a video or an image and the edits
+over them. It is saved as it is made, one spec per file, and it depends on that file
+(ONTOLOGY §3), so deleting the file deletes the work. A file never has more than one,
+which is what lets opening a file simply reopen what was done to it.
+
+**A collage** lays out pieces from any number of files. Each piece is a recipe (path,
+instant, ops) frozen when it was placed, so a collage is a document of its own: a lost
+source leaves a gap in the layout rather than voiding it, and the picture it exports is
+media.
+
+Before 0.3.1 both lived in a "session", saved by hand under a name, as many per file as
+the analyst liked, with the collages inside. `normalize` turns that shape into this one
+and is the migration for it: the sessions of one file merge into its work, every
+collage becomes a collage document, and nothing the analyst typed is dropped. It is
+idempotent and restartable, because it runs on open and again after a restore from the
+Trash, which can bring an old session back into a case that has moved on. The merge
+cannot be taken back, so every session it rewrites is first copied, byte for byte, to
+`.inspect/.v1/`.
+"""
+
+from __future__ import annotations
+
+import json
+import re
+import shutil
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import TYPE_CHECKING, Any
+
+from .. import layout
+from ..workspace import CaseError
+from . import links as link_engine
+from . import media as media_engine
+
+if TYPE_CHECKING:
+ from ..workspace import Case
+
+#: The spec shapes. A work spec is stamped `azimut_inspect: 2`; version 1 is the
+#: pre-0.3.1 session, which only `normalize` still reads.
+WORK_VERSION = 2
+LEGACY_VERSION = 1
+COLLAGE_VERSION = 1
+
+#: Bounds on what a save may write. A work or a collage is recipes, never pixels, so
+#: these are far above anything a real one reaches and only stop a runaway client.
+MAX_SPEC_BYTES = 2_000_000
+MAX_FRAMES = 500
+MAX_PIECES = 200
+
+WORK_TYPE = "inspect-session"
+COLLAGE_TYPE = "collage"
+PRODUCER = "inspect"
+
+#: What a frame and a piece hold. Anything else a client sends is dropped rather
+#: than stored, so the format on disk stays the one documented here.
+_FRAME_KEYS = (
+ "id", "path", "time", "adjust", "crop", "sourceOps", "rotation", "w", "h", "filed",
+)
+_PIECE_KEYS = ("id", "frameId", "save", "w", "h", "quad", "frameOps", "crop")
+_RIGHT_ANGLES = (-180, -90, 0, 90, 180)
+
+#: Names the app hands out before the analyst types one. They describe nothing, so a
+#: merge prefers any typed name over them.
+_DEFAULT_SESSION = re.compile(r"^Inspect \d+$")
+_DEFAULT_COLLAGE = re.compile(r"^Collage \d+$")
+
+
+class NameTaken(CaseError):
+ """A rename onto a name another collage already holds."""
+
+
+def _now() -> str:
+ """UTC, to the millisecond: a merge keeps the most recently saved work, and two
+ saves inside one second must still be told apart."""
+ now = datetime.now(timezone.utc)
+ return now.strftime("%Y-%m-%dT%H:%M:%S.") + f"{now.microsecond // 1000:03d}Z"
+
+
+def _read(path: Path) -> dict[str, Any] | None:
+ try:
+ data = json.loads(path.read_text(encoding="utf-8"))
+ except (OSError, ValueError):
+ return None
+ return data if isinstance(data, dict) else None
+
+
+def _write(path: Path, data: dict[str, Any]) -> None:
+ media_engine.write_json_atomic(path, data)
+
+
+def _check_size(spec: dict[str, Any]) -> None:
+ if len(json.dumps(spec, ensure_ascii=False)) > MAX_SPEC_BYTES:
+ raise CaseError("that is too large to save")
+
+
+def _free_title(taken: set[str], title: str, fallback: str) -> str:
+ """`title` as a filename stem, numbered past whatever `taken` already holds.
+
+ `taken` is casefolded: two stems differing only by case are one file on Windows
+ and macOS.
+ """
+ base = layout.slugify(title, fallback)
+ if base.casefold() not in taken:
+ return base
+ n = 2
+ while True:
+ suffix = f" {n}"
+ candidate = layout.slugify(f"{base[: layout.MAX_SLUG - len(suffix)]}{suffix}", fallback)
+ if candidate.casefold() not in taken:
+ return candidate
+ n += 1
+
+
+def _stems(case: "Case", directory: str) -> set[str]:
+ folder = case.tool_root / directory
+ if not folder.is_dir():
+ return set()
+ return {path.stem.casefold() for path in folder.glob("*.json")}
+
+
+def _trashed_stems(case: "Case", directory: str) -> set[str]:
+ """Names in `directory` that a delete moved into the Trash.
+
+ A new artifact must not take one: the restore would find its path occupied and
+ refuse, and clearing a file's work then starting over is exactly when someone
+ wants the old frames back.
+ """
+ prefix = f"{directory}/"
+ out = set()
+ for head in case.list_trash():
+ group = case.get_trash_group(head["id"]) or {}
+ for rel in (group.get("payload") or {}).get("files") or []:
+ rel = str(rel)
+ if rel.startswith(prefix) and rel.endswith(".json") and "/" not in rel[len(prefix):]:
+ out.add(Path(rel).stem.casefold())
+ return out
+
+
+def _taken(case: "Case", directory: str) -> set[str]:
+ return _stems(case, directory) | _trashed_stems(case, directory)
+
+
+def _describes_nothing(name: str, file_label: str) -> bool:
+ """Whether a session's name is one the app made up rather than the analyst.
+
+ "Inspect 3" was the old default; a work is born under its file's name, numbered
+ when that name was taken. Neither tells anyone anything the file does not. The
+ name is the file's label as `_free_title` wrote it: a long label is cut to fit
+ a filename and a character Windows forbids is replaced.
+ """
+ if _DEFAULT_SESSION.match(name):
+ return True
+ if not file_label:
+ return False
+ base = layout.slugify(file_label, "Inspect")
+ if name in (file_label, base):
+ return True
+ numbered = re.fullmatch(r".+( \d+)", name)
+ if numbered is None:
+ return False
+ suffix = numbered.group(1)
+ cut = layout.slugify(f"{base[: layout.MAX_SLUG - len(suffix)]}{suffix}", "Inspect")
+ return name in (f"{file_label}{suffix}", cut)
+
+
+# -- work ---------------------------------------------------------------------
+
+
+def _work_specs(case: "Case") -> list[tuple[str, dict[str, Any]]]:
+ """Every readable Inspect spec, current or legacy, as (case path, spec)."""
+ folder = case.tool_root / layout.INSPECT_DIR
+ if not folder.is_dir():
+ return []
+ out = []
+ for path in sorted(folder.glob("*.json")):
+ spec = _read(path)
+ if spec is None or spec.get("azimut_inspect") not in (WORK_VERSION, LEGACY_VERSION):
+ continue
+ out.append((layout.session_rel(path.stem), spec))
+ return out
+
+
+def _subject(spec: dict[str, Any]) -> str | None:
+ source = spec.get("source")
+ path = source.get("path") if isinstance(source, dict) else None
+ return path if isinstance(path, str) and path else None
+
+
+def _group(case: "Case", subject: str) -> list[tuple[str, dict[str, Any]]]:
+ return [(rel, spec) for rel, spec in _work_specs(case) if _subject(spec) == subject]
+
+
+def _work_row(rel: str, spec: dict[str, Any]) -> dict[str, Any]:
+ source = spec.get("source") or {}
+ # The name is the filename stem, which a rename from Details moves without
+ # rewriting the spec, so the stem is what is true.
+ return {
+ "name": Path(rel).stem,
+ "title": Path(rel).stem,
+ "source": source.get("path"),
+ "kind": source.get("kind"),
+ "frames": len(spec.get("frames") or []),
+ "updated_at": spec.get("updated_at"),
+ }
+
+
+def list_works(case: "Case") -> list[dict[str, Any]]:
+ """One row per file that has work, most recently touched first."""
+ rows = [
+ _work_row(rel, spec)
+ for rel, spec in _work_specs(case)
+ if spec.get("azimut_inspect") == WORK_VERSION and _subject(spec)
+ ]
+ rows.sort(key=lambda row: row.get("updated_at") or "", reverse=True)
+ return rows
+
+
+def _answer(rel: str, spec: dict[str, Any]) -> dict[str, Any]:
+ return {"name": Path(rel).stem, "title": Path(rel).stem, "spec": spec}
+
+
+def find_work(case: "Case", subject: str) -> dict[str, Any] | None:
+ """The work saved for one file, or None when nothing was done to it yet."""
+ with case.lock:
+ found = _settle(case, subject)
+ return _answer(*found) if found else None
+
+
+def load_work(case: "Case", name: str) -> dict[str, Any] | None:
+ """The work saved under one name: how the sidebar reopens it."""
+ rel = layout.session_rel(layout.slugify(name, "Inspect"))
+ spec = _read(case.resolve_inside(rel))
+ if spec is None or spec.get("azimut_inspect") != WORK_VERSION:
+ return None
+ return _answer(rel, spec)
+
+
+def _settle(case: "Case", subject: str) -> tuple[str, dict[str, Any]] | None:
+ """The one current spec for a file, merging any others found beside it.
+
+ There should never be two, but a restore from the Trash can bring back an older
+ work, or a pre-0.3.1 session, next to the one the analyst has been adding to since.
+ """
+ group = _group(case, subject)
+ if not group:
+ return None
+ if len(group) == 1 and group[0][1].get("azimut_inspect") == WORK_VERSION:
+ return group[0]
+ return _merge_subject(case, subject, group, _migrated_collages(case))
+
+
+def _subject_entity(case: "Case", subject: str) -> dict[str, Any]:
+ entity = case.find_entity(attr="path", value=subject)
+ if entity is None or entity.get("type") not in ("media", "capture"):
+ raise CaseError("that file is not in the case")
+ item = media_engine.read_item(case, subject) or {}
+ kind = item.get("kind") or (entity.get("attrs") or {}).get("kind")
+ if kind not in ("image", "video"):
+ raise CaseError("only images and videos can be inspected")
+ return {**entity, "kind": kind}
+
+
+def _pick(value: dict[str, Any], keys: tuple[str, ...]) -> dict[str, Any]:
+ return {key: value[key] for key in keys if key in value}
+
+
+def _clean_frames(frames: Any, subject: str) -> list[dict[str, Any]]:
+ if not isinstance(frames, list):
+ raise CaseError("frames must be a list")
+ if len(frames) > MAX_FRAMES:
+ raise CaseError(f"a file holds at most {MAX_FRAMES} frames")
+ out = []
+ for frame in frames:
+ if not isinstance(frame, dict) or not isinstance(frame.get("id"), str):
+ raise CaseError("every frame needs an id")
+ # Every frame is cut from the file the work belongs to. One naming another
+ # file would be work that outlives the file it silently depends on.
+ if frame.get("path") != subject:
+ raise CaseError("a frame must come from the file it is saved with")
+ out.append(_pick(frame, _FRAME_KEYS))
+ return out
+
+
+def save_work(case: "Case", subject: str, spec: dict[str, Any]) -> dict[str, Any]:
+ """Write one file's work, filing its entity the first time.
+
+ The first save is named after the file, numbered past any work already holding
+ that name. Later saves keep whatever name the entity carries, including one the
+ analyst gave it from Details.
+ """
+ if not isinstance(spec, dict):
+ raise CaseError("the work must be an object")
+ _check_size(spec)
+ frames = _clean_frames(spec.get("frames", []), subject)
+ rotation = spec.get("videoRotation", 0)
+ if rotation not in _RIGHT_ANGLES:
+ raise CaseError("video rotation must be a right angle")
+ adjust = spec.get("videoAdjust") or {}
+ if not isinstance(adjust, dict):
+ raise CaseError("video adjustments must be an object")
+
+ with case.lock:
+ entity = _subject_entity(case, subject)
+ found = _settle(case, subject)
+ if found:
+ rel, previous = found
+ title = Path(rel).stem
+ created = previous.get("created_at") or _now()
+ else:
+ label = str(entity.get("label") or Path(subject).stem)
+ title = _free_title(_taken(case, layout.INSPECT_DIR), label, "Inspect")
+ rel = layout.session_rel(title)
+ created = _now()
+ active = spec.get("activeFrameId")
+ written = {
+ "azimut_inspect": WORK_VERSION,
+ "title": title,
+ "created_at": created,
+ "updated_at": _now(),
+ "source": {"path": subject, "kind": entity["kind"]},
+ "videoAdjust": adjust,
+ "videoRotation": rotation,
+ "videoFiled": spec.get("videoFiled") if isinstance(spec.get("videoFiled"), dict) else None,
+ "frames": frames,
+ "activeFrameId": active if any(f["id"] == active for f in frames) else None,
+ }
+ if found and previous.get("merged_from"):
+ written["merged_from"] = previous["merged_from"]
+ case.subdir(layout.INSPECT_DIR)
+ _write(case.resolve_inside(rel), written)
+ filed = case.find_entity(attr="spec", value=rel)
+ if filed is None:
+ filed = case.add_entity(WORK_TYPE, title, attrs={"spec": rel}, by=PRODUCER)
+ link_engine.sync(case, filed["id"], link_engine.DEPENDS_ON, [subject], by=PRODUCER)
+ return {"name": Path(rel).stem, "title": title}
+
+
+def follow_file_rename(case: "Case", subject: str, old_labels: list[str], label: str) -> None:
+ """Carry a work named after its file over to the file's new name.
+
+ A name the analyst typed stays as it is. Replayed by an interrupted media
+ rename, so a second run finds the name already moved and does nothing.
+ """
+ with case.lock:
+ found = _settle(case, subject)
+ if not found:
+ return
+ rel = found[0]
+ entity = case.find_entity(attr="spec", value=rel)
+ if entity is None:
+ return
+ current = str(entity.get("label") or Path(rel).stem)
+ if not any(_describes_nothing(current, old) for old in old_labels if old):
+ return
+ stem = Path(rel).stem.casefold()
+ wanted = _free_title(_taken(case, layout.INSPECT_DIR) - {stem}, label, "Inspect")
+ if wanted != current:
+ case.update_entity(entity["id"], {"label": wanted})
+
+
+def work_rel(case: "Case", subject: str) -> str | None:
+ """Where one file's work is saved, for the route that deletes it."""
+ with case.lock:
+ found = _settle(case, subject)
+ return found[0] if found else None
+
+
+# -- collages -----------------------------------------------------------------
+
+
+def _collage_specs(case: "Case") -> list[tuple[str, dict[str, Any]]]:
+ folder = case.tool_root / layout.COLLAGE_DIR
+ if not folder.is_dir():
+ return []
+ out = []
+ for path in sorted(folder.glob("*.json")):
+ spec = _read(path)
+ if spec is not None and spec.get("azimut_collage") == COLLAGE_VERSION:
+ out.append((layout.collage_rel(path.stem), spec))
+ return out
+
+
+def list_collages(case: "Case") -> list[dict[str, Any]]:
+ rows = []
+ for rel, spec in _collage_specs(case):
+ rows.append({
+ "name": Path(rel).stem,
+ "title": Path(rel).stem,
+ "pieces": len(spec.get("nodes") or []),
+ "updated_at": spec.get("updated_at"),
+ })
+ rows.sort(key=lambda row: row.get("updated_at") or "", reverse=True)
+ return rows
+
+
+def load_collage(case: "Case", name: str) -> dict[str, Any] | None:
+ rel = layout.collage_rel(layout.slugify(name, "Collage"))
+ spec = _read(case.resolve_inside(rel))
+ if spec is None or spec.get("azimut_collage") != COLLAGE_VERSION:
+ return None
+ return {"name": Path(rel).stem, "title": Path(rel).stem, "spec": spec}
+
+
+def _clean_collage(spec: dict[str, Any]) -> dict[str, Any]:
+ if not isinstance(spec, dict):
+ raise CaseError("the collage must be an object")
+ _check_size(spec)
+ nodes = spec.get("nodes", [])
+ if not isinstance(nodes, list):
+ raise CaseError("pieces must be a list")
+ if len(nodes) > MAX_PIECES:
+ raise CaseError(f"a collage holds at most {MAX_PIECES} pieces")
+ pieces = []
+ for node in nodes:
+ save = node.get("save") if isinstance(node, dict) else None
+ if not isinstance(save, dict) or not isinstance(save.get("path"), str):
+ raise CaseError("every piece needs the file it was cut from")
+ quad = node.get("quad")
+ if not isinstance(quad, list) or len(quad) != 4:
+ raise CaseError("every piece needs four corners")
+ pieces.append(_pick(node, _PIECE_KEYS))
+ out = {
+ "width": spec.get("width"),
+ "height": spec.get("height"),
+ "background": spec.get("background"),
+ "transparent": bool(spec.get("transparent", True)),
+ "nodes": pieces,
+ }
+ if isinstance(spec.get("exported"), dict):
+ out["exported"] = spec["exported"]
+ return out
+
+
+def save_collage(
+ case: "Case", name: str | None, title: str, spec: dict[str, Any]
+) -> dict[str, Any]:
+ """Write a collage, filing it the first time and renaming it when asked.
+
+ `name` is the stem the tool has it open under, absent for one never saved. A new
+ collage takes the next free name; a rename lands on a free name or not at all,
+ since two entities pointing at one file cannot be merged sensibly.
+ """
+ body = _clean_collage(spec)
+ with case.lock:
+ case.subdir(layout.COLLAGE_DIR)
+ if name is None:
+ final = _free_title(_taken(case, layout.COLLAGE_DIR), title, "Collage")
+ old_rel = None
+ else:
+ current = layout.slugify(name, "Collage")
+ final = layout.slugify(title, "Collage")
+ old_rel = layout.collage_rel(current) if final != current else None
+ taken = _stems(case, layout.COLLAGE_DIR)
+ if old_rel and final.casefold() in taken and final.casefold() != current.casefold():
+ raise NameTaken("another collage already uses that name")
+ rel = layout.collage_rel(final)
+ previous = _read(case.resolve_inside(old_rel or rel)) or {}
+ written = {
+ "azimut_collage": COLLAGE_VERSION,
+ "title": final,
+ "created_at": previous.get("created_at") or _now(),
+ "updated_at": _now(),
+ **body,
+ }
+ if previous.get("migrated_from"):
+ written["migrated_from"] = previous["migrated_from"]
+ if old_rel:
+ # Written under the new name before the old file goes, so a crash in
+ # between leaves the collage twice rather than not at all.
+ _write(case.resolve_inside(rel), written)
+ existing = case.find_entity(attr="spec", value=old_rel)
+ if existing:
+ case.update_entity(existing["id"], {"label": final, "attrs": {"spec": rel}})
+ case.resolve_inside(old_rel).unlink(missing_ok=True)
+ else:
+ _write(case.resolve_inside(rel), written)
+ if case.find_entity(attr="spec", value=rel) is None:
+ case.add_entity(COLLAGE_TYPE, final, attrs={"spec": rel}, by=PRODUCER)
+ return {"name": final, "title": final}
+
+
+# -- 0.3.1: one work per file, collages on their own ------------------------------
+
+
+def _migrated_collages(case: "Case") -> set[tuple[str, str]]:
+ """The (session, collage) pairs already carried out, so a rerun makes none twice."""
+ out = set()
+ for _rel, spec in _collage_specs(case):
+ marker = spec.get("migrated_from")
+ if isinstance(marker, dict):
+ out.add((str(marker.get("session")), str(marker.get("collage"))))
+ return out
+
+
+def _legacy_collages(spec: dict[str, Any]) -> list[dict[str, Any]]:
+ """A pre-0.3.1 session's collages: an array, or once a single `collage`."""
+ collages = spec.get("collages")
+ if isinstance(collages, list):
+ return [c for c in collages if isinstance(c, dict)]
+ single = spec.get("collage")
+ return [single] if isinstance(single, dict) else []
+
+
+def _collage_title(session: str, collage: str, count: int) -> str | None:
+ """What a collage carried out of a session is called, or None for "next free".
+
+ A name the analyst typed on the collage wins. Otherwise the session's name is the
+ best description of the collage there is, since a session was usually named for
+ what it was building; with several collages it prefixes theirs.
+ """
+ if collage and not _DEFAULT_COLLAGE.match(collage):
+ return collage
+ if _DEFAULT_SESSION.match(session):
+ return None
+ return session if count == 1 else f"{session} · {collage or 'Collage'}"
+
+
+def _keep_legacy(case: "Case", rel: str) -> None:
+ """Copy a session aside, unchanged, before the merge rewrites or removes it.
+
+ The first copy stands: a resumed merge must not overwrite it with a spec the
+ interrupted run already changed.
+ """
+ source = case.resolve_inside(rel)
+ target = case.resolve_inside(layout.legacy_session_rel(Path(rel).stem))
+ if target.exists() or not source.is_file():
+ return
+ target.parent.mkdir(parents=True, exist_ok=True)
+ shutil.copy2(source, target)
+
+
+def _extract_collages(
+ case: "Case",
+ rel: str,
+ spec: dict[str, Any],
+ session: str,
+ folder: str | None,
+ done: set[tuple[str, str]],
+) -> None:
+ collages = [c for c in _legacy_collages(spec) if c.get("nodes")]
+ for collage in collages:
+ marker = (rel, str(collage.get("id") or ""))
+ if marker in done:
+ continue
+ wanted = _collage_title(session, str(collage.get("name") or ""), len(collages))
+ taken = _taken(case, layout.COLLAGE_DIR)
+ if wanted is None:
+ n = 1
+ while f"collage {n}" in taken:
+ n += 1
+ wanted = f"Collage {n}"
+ title = _free_title(taken, wanted, "Collage")
+ body = {
+ "width": collage.get("width"),
+ "height": collage.get("height"),
+ "background": collage.get("background"),
+ "transparent": bool(collage.get("transparent", False)),
+ "nodes": [_pick(n, _PIECE_KEYS) for n in collage["nodes"] if isinstance(n, dict)],
+ }
+ case.subdir(layout.COLLAGE_DIR)
+ target = layout.collage_rel(title)
+ _write(case.resolve_inside(target), {
+ "azimut_collage": COLLAGE_VERSION,
+ "title": title,
+ "created_at": spec.get("created_at") or _now(),
+ "updated_at": spec.get("updated_at") or _now(),
+ **body,
+ "migrated_from": {"session": marker[0], "collage": marker[1]},
+ })
+ attrs: dict[str, Any] = {"spec": target}
+ if folder:
+ attrs["folder"] = folder
+ case.add_entity(COLLAGE_TYPE, title, attrs=attrs, by=PRODUCER)
+ done.add(marker)
+
+
+def _survivor(group: list[tuple[str, dict[str, Any]]]) -> tuple[str, dict[str, Any]]:
+ """The spec the others merge into.
+
+ A current work wins, so a merge interrupted after it wrote the survivor resumes
+ into the same one. Otherwise the most recently saved session, whose adjustments are
+ the analyst's latest intent.
+ """
+ def key(item: tuple[str, dict[str, Any]]) -> tuple[int, str, str]:
+ rel, spec = item
+ return (int(spec.get("azimut_inspect") == WORK_VERSION), str(spec.get("updated_at") or ""), rel)
+
+ return max(group, key=key)
+
+
+def _merged_notes(notes: str, merged: list[tuple[str, str, bool]]) -> str:
+ """The survivor's notes, with what each merged session said kept under its name.
+
+ `merged` is (title, notes, typed) per session folded in. A typed name nobody wrote
+ notes under is still named, so the analyst can see where it went. Each addition is
+ skipped when already present, which is what makes a resumed merge write it once.
+ """
+ parts = [notes.strip()] if notes.strip() else []
+ named = [f"“{title}”" for title, text, typed in merged if typed and not text.strip()]
+ if named:
+ line = f"Merged with {', '.join(named)}."
+ if line not in notes:
+ parts.append(line)
+ for title, text, _typed in merged:
+ block = f"“{title}”: {text.strip()}"
+ if text.strip() and block not in notes:
+ parts.append(block)
+ return "\n\n".join(parts)
+
+
+def _repoint_links(case: "Case", old_id: str, new_id: str) -> None:
+ """Carry an entity's relations over to another, keeping how sure each one is."""
+ for link in case.links_of(old_id):
+ if link["type"] in link_engine.CHAIN_TYPES:
+ continue
+ start = new_id if link["from"] == old_id else link["from"]
+ end = new_id if link["to"] == old_id else link["to"]
+ if start == end:
+ continue
+ prov = link.get("provenance") or {}
+ moved = case.add_link(
+ start, end, link["type"],
+ by=str(prov.get("by") or PRODUCER),
+ status="suggested" if prov.get("status") == "suggested" else "confirmed",
+ unique=True,
+ )
+ rating: dict[str, Any] = {key: link[key] for key in ("confidence", "nature") if key in link}
+ if rating:
+ case.update_link(moved["id"], rating)
+ case.remove_link(link["id"])
+
+
+def _merge_subject(
+ case: "Case",
+ subject: str,
+ group: list[tuple[str, dict[str, Any]]],
+ done: set[tuple[str, str]],
+) -> tuple[str, dict[str, Any]]:
+ """Fold every spec of one file into a single current work.
+
+ In this order, because the order is what makes an interrupted merge resume rather
+ than repeat: collages are carried out first (each marked, so none is made twice),
+ then the survivor is written with every frame (merged by id), and only then are
+ the others' notes and relations moved and the others removed.
+ """
+ entities = {rel: case.find_entity(attr="spec", value=rel) for rel, _spec in group}
+ owner = case.find_entity(attr="path", value=subject)
+ file_label = str((owner or {}).get("label") or Path(subject).stem)
+ # What the analyst sees a session as: its entity's label, which a rename from
+ # Details moves without rewriting the spec, else the file it is saved under.
+ names = {
+ rel: str((entities.get(rel) or {}).get("label") or Path(rel).stem) for rel, _spec in group
+ }
+
+ def folder_of(rel: str) -> str | None:
+ attrs = (entities.get(rel) or {}).get("attrs") or {}
+ folder = attrs.get("folder")
+ return folder if isinstance(folder, str) and folder else None
+
+ for rel, spec in group:
+ if spec.get("azimut_inspect") == LEGACY_VERSION:
+ _keep_legacy(case, rel)
+ _extract_collages(case, rel, spec, names[rel], folder_of(rel), done)
+
+ rel, base = _survivor(group)
+ others = [(r, s) for r, s in group if r != rel]
+ frames = [f for f in base.get("frames") or [] if isinstance(f, dict)]
+ seen = {f.get("id") for f in frames}
+ for _r, spec in others:
+ for frame in spec.get("frames") or []:
+ if isinstance(frame, dict) and frame.get("id") not in seen:
+ frames.append(frame)
+ seen.add(frame.get("id"))
+ merged_from = list(base.get("merged_from") or [])
+ for r, _spec in others:
+ if names[r] not in merged_from:
+ merged_from.append(names[r])
+ survivor = {
+ "azimut_inspect": WORK_VERSION,
+ "title": Path(rel).stem,
+ "created_at": min(
+ [str(s.get("created_at")) for _r, s in group if s.get("created_at")] or [_now()]
+ ),
+ "updated_at": base.get("updated_at") or _now(),
+ "source": base.get("source") or {"path": subject},
+ "videoAdjust": base.get("videoAdjust") or {},
+ "videoRotation": base.get("videoRotation") if base.get("videoRotation") in _RIGHT_ANGLES else 0,
+ "videoFiled": base.get("videoFiled"),
+ "frames": [_pick(f, _FRAME_KEYS) for f in frames],
+ "activeFrameId": base.get("activeFrameId"),
+ }
+ if merged_from:
+ survivor["merged_from"] = merged_from
+ _write(case.resolve_inside(rel), survivor)
+
+ entity = entities.get(rel)
+ if entity is None:
+ entity = case.add_entity(WORK_TYPE, Path(rel).stem, attrs={"spec": rel}, by=PRODUCER)
+ attrs = entity.get("attrs") or {}
+ patch: dict[str, Any] = {}
+ notes = str(attrs.get("notes") or "")
+ folded = []
+ for r, _spec in others:
+ other_notes = str(((entities.get(r) or {}).get("attrs") or {}).get("notes") or "")
+ folded.append((names[r], other_notes, not _describes_nothing(names[r], file_label)))
+ joined = _merged_notes(notes, folded)
+ if joined != notes:
+ patch["notes"] = joined
+ if not folder_of(rel):
+ folder = next((folder_of(r) for r, _s in others if folder_of(r)), None)
+ if folder:
+ patch["folder"] = folder
+ if patch:
+ entity = case.update_entity(entity["id"], {"attrs": patch})
+
+ for r, _spec in others:
+ other = entities.get(r)
+ if other is not None and case.get_entity(other["id"]) is not None:
+ _repoint_links(case, other["id"], entity["id"])
+ case.remove_entity(other["id"])
+ case.resolve_inside(r).unlink(missing_ok=True)
+
+ # A name the app made up says nothing about the work; the file's own name does,
+ # and a typed name on one of the merged sessions is the analyst's, so that is
+ # the one the work keeps.
+ label = str(entity.get("label") or survivor["title"])
+ if _describes_nothing(label, file_label):
+ newest_first = sorted(others, key=lambda i: str(i[1].get("updated_at") or ""), reverse=True)
+ typed = next(
+ (names[r] for r, _s in newest_first if not _describes_nothing(names[r], file_label)),
+ None,
+ )
+ wanted = typed or file_label
+ taken = _taken(case, layout.INSPECT_DIR) - {Path(rel).stem.casefold()}
+ title = _free_title(taken, wanted, "Inspect")
+ if title != Path(rel).stem:
+ entity = case.update_entity(entity["id"], {"label": title})
+ rel = str((entity.get("attrs") or {}).get("spec") or rel)
+ survivor["title"] = title
+ _write(case.resolve_inside(rel), survivor)
+ link_engine.sync(case, entity["id"], link_engine.DEPENDS_ON, [subject], by=PRODUCER)
+ return rel, survivor
+
+
+def normalize(case: "Case") -> dict[str, int]:
+ """Give every file one work and every collage its own document.
+
+ The 0.3.1 case migration, and what a restore from the Trash runs so an older
+ session brought back into a current case lands the same way. A spec whose file
+ cannot be named is left as it is: there is nothing to merge it into.
+ """
+ with case.lock:
+ groups: dict[str, list[tuple[str, dict[str, Any]]]] = {}
+ for rel, spec in _work_specs(case):
+ subject = _subject(spec)
+ if subject:
+ groups.setdefault(subject, []).append((rel, spec))
+ done = _migrated_collages(case)
+ before = len(done)
+ merged = 0
+ for subject, group in groups.items():
+ if len(group) == 1 and group[0][1].get("azimut_inspect") == WORK_VERSION:
+ continue
+ _merge_subject(case, subject, group, done)
+ merged += len(group) - 1
+ return {"merged": merged, "collages": len(done) - before}
+
+
+def migrate_case(case: "Case") -> None:
+ """The first half of folder migration 9 → 11 (`workspace.FOLDER_MIGRATIONS`)."""
+ normalize(case)
diff --git a/src/azimut/engine/links.py b/src/azimut/engine/links.py
index e8cf475..29ffd60 100644
--- a/src/azimut/engine/links.py
+++ b/src/azimut/engine/links.py
@@ -15,10 +15,10 @@ picking one:
something once the source is gone. Deleting the source leaves the artifact
in place, with a tombstone recording what it came from.
-``depends-on`` (session → subject)
- The artifact is nothing but a pointer at its subject: an Inspect session is
- a set of adjustments over a video, worthless without it. Deleting the
- subject deletes the session.
+``depends-on`` (work → subject)
+ The artifact is nothing but a pointer at its subject: a file's Inspect work
+ is frames and edits over that file, worthless without it. Deleting the
+ subject deletes the work.
The test a new tool applies: *delete the target — is anything usable left in my
file?* Yes → ``derived-from``. No → ``depends-on``. Emitted at save time with
diff --git a/src/azimut/engine/maplayers.py b/src/azimut/engine/maplayers.py
index f1558a5..dafc101 100644
--- a/src/azimut/engine/maplayers.py
+++ b/src/azimut/engine/maplayers.py
@@ -419,14 +419,18 @@ def _properties(
colour: str = "",
icon: str = "",
date: str = "",
+ date_end: str = "",
) -> dict[str, Any]:
- """The five fields every feature carries, whatever it was read from, and a
- sixth when the source dated it.
+ """The five fields every feature carries, whatever it was read from, and the
+ days the source dated it.
`icon` names a stored pictogram rather than holding an address: the browser
is told which image to draw, never where the source kept it. `date` is a day,
`YYYY-MM-DD`, which is what the row's time filter compares; absent rather
than empty, since most layers state none and a map may hold 100,000 features.
+ `date_end` is the last day of a feature that spans several, such as a KML
+ TimeSpan or a Detect change read between two passes, and is kept only when it
+ falls after `date`.
"""
properties = {
"name": _text(name, MAX_NAME),
@@ -438,6 +442,9 @@ def _properties(
day = iso_day(date)
if day:
properties["date"] = day
+ end = iso_day(date_end)
+ if end > day:
+ properties["date_end"] = end
return properties
@@ -610,7 +617,11 @@ def _from_geojson(data: bytes, filename: str) -> tuple[list[dict[str, Any]], str
name=_first(source, _NAME_KEYS),
description=_first(source, _DESCRIPTION_KEYS),
category=_text(source.get("category"), MAX_NAME) if document.get("azimut_detect_layer") == 1 else category,
- date=source.get("pass_date", "") if document.get("azimut_detect_layer") == 1 else "",
+ # A change was read between two passes and spans both; a thing
+ # present on one pass is dated by that pass alone.
+ date=(source.get("pass_before") or source.get("pass_date", ""))
+ if document.get("azimut_detect_layer") == 1 else "",
+ date_end=source.get("pass_date", "") if document.get("azimut_detect_layer") == 1 else "",
# simplestyle-spec, which is what every tool that writes a
# styled GeoJSON — geojson.io included — puts the colour in
colour=_hex(source.get("marker-color") or source.get("stroke")
@@ -621,6 +632,8 @@ def _from_geojson(data: bytes, filename: str) -> tuple[list[dict[str, Any]], str
if document.get("azimut_detect_layer") == 1:
features[-1]["properties"].update({key: _text(source.get(key), MAX_NAME)
for key in ("pass_date", "detector", "area_name", "run_id")})
+ features[-1]["properties"].update({key: _text(source[key], MAX_NAME)
+ for key in ("pass_before", "pass_time") if source.get(key)})
return features, _text(document.get("name"), MAX_NAME)
@@ -839,7 +852,7 @@ def _placemark(
description = _kml_extended_data(element)
style = _kml_style(element, styles)
colour = str(style.get("colour") or "")
- day = _kml_day(element)
+ day, last = _kml_days(element)
icon = _icon_of(style)
key = ""
if icon is not None:
@@ -861,20 +874,21 @@ def _placemark(
# drawn by their own stroke and fill
icon=key if _kind(geometry) == "point" else "",
date=day,
+ date_end=last,
),
}
)
-def _kml_day(element: Element) -> str:
- """When a placemark says it happened: a TimeStamp, else where a TimeSpan starts."""
+def _kml_days(element: Element) -> tuple[str, str]:
+ """When a placemark says it happened: a TimeStamp, else the days a TimeSpan runs."""
stamp = _child(element, "TimeStamp")
if stamp is not None:
- return iso_day(_child_text(stamp, "when"))
+ return iso_day(_child_text(stamp, "when")), ""
span = _child(element, "TimeSpan")
if span is not None:
- return iso_day(_child_text(span, "begin"))
- return ""
+ return iso_day(_child_text(span, "begin")), iso_day(_child_text(span, "end"))
+ return "", ""
def _kml_extended_data(element: Element) -> str:
diff --git a/src/azimut/engine/media.py b/src/azimut/engine/media.py
index a3aad46..47d6095 100644
--- a/src/azimut/engine/media.py
+++ b/src/azimut/engine/media.py
@@ -1378,6 +1378,7 @@ def _structured_record_paths(case: Case) -> list[Path]:
roots = (
layout.subdir(case.path, "proofs") / layout.META_DIR,
tool / layout.INSPECT_DIR,
+ tool / layout.COLLAGE_DIR,
tool / layout.DRAFTS_DIR,
tool / layout.SEARCH_DIR,
)
@@ -1452,6 +1453,10 @@ def _finish_media_rename(case: Case, record: dict[str, str]) -> dict[str, Any]:
indexed = {**data, "path": new}
case.upsert_media_item(indexed, entity_id=owner_id)
rewrite_file_references(case, old, new)
+ from . import inspectwork
+
+ old_labels = [str(owner.get("label") or "") if owner else "", Path(old).stem]
+ inspectwork.follow_file_rename(case, new, old_labels, title)
_rename_journal(case).unlink(missing_ok=True)
return indexed
diff --git a/src/azimut/engine/satellite.py b/src/azimut/engine/satellite.py
index f4d88a9..d077bef 100644
--- a/src/azimut/engine/satellite.py
+++ b/src/azimut/engine/satellite.py
@@ -24,16 +24,17 @@ from typing import Any
from ..repository import EntityStatus
from ..workspace import Case, CaseError
-from . import continents
+from . import comparisons, continents
from . import coords as coords_engine
from . import countries
from . import geo as geo_engine
from . import links
from . import media as media_engine
+from . import timeline
-# Saved work is places plus captures; a screenshot filed by the capture
-# extension is a capture with a different origin, not a third entity type.
-SAVED_TYPES = ["place", "capture"]
+# Saved work is places, captures and saved comparisons; a screenshot filed by the
+# capture extension is a capture with a different origin, not a type of its own.
+SAVED_TYPES = ["place", "capture", "compare-session"]
# One page of the catalog per query while collecting saved entities: bounded
# memory per round-trip, and the whole set is still tens of KB on the wire.
@@ -443,8 +444,12 @@ def list_captures(case: Case) -> list[dict[str, Any]]:
panel keeps rendering exactly the fields it did when captures had their own
store.
"""
+ return _captures_of(media_engine.list_media(case))
+
+
+def _captures_of(items: list[dict[str, Any]]) -> list[dict[str, Any]]:
captures: list[dict[str, Any]] = []
- for item in media_engine.list_media(case):
+ for item in items:
if not is_capture(item):
continue
source = item.get("source") or {}
@@ -477,7 +482,7 @@ def _page_all(case: Case, types: list[str]) -> list[dict[str, Any]]:
def saved_entities(case: Case) -> list[dict[str, Any]]:
- """Every ``place`` and ``capture`` entity, in insertion order."""
+ """Every ``place``, ``capture`` and saved comparison, in insertion order."""
return _page_all(case, SAVED_TYPES)
@@ -517,23 +522,29 @@ def _saved_row(
capture: dict[str, Any] | None,
proofs: int = 0,
relations: int = 0,
+ comparison: dict[str, Any] | None = None,
) -> dict[str, Any]:
attrs = entity.get("attrs") or {}
source = capture or {}
geo = attrs.get("geo") if isinstance(attrs.get("geo"), dict) else None
lat, lon = attrs.get("lat"), attrs.get("lon")
- if capture is None:
+ # A comparison's picture is its preview, which is a media file of its own: its
+ # title, folder and notes are the session's, and only the image is borrowed.
+ preview = (comparison or {}).get("preview") or {}
+ if comparison is not None:
+ kind = "comparison"
+ elif capture is None:
kind = "place"
else:
kind = "screenshot" if source.get("method") == "screenshot" else "capture"
- thumbnail = source.get("thumbnail")
+ thumbnail = preview.get("thumbnail") if comparison is not None else source.get("thumbnail")
# a thumbnail the LRU budget has evicted must read as absent, not as a
# broken image — the row falls back to its kind glyph
if thumbnail and not case.resolve_inside(str(thumbnail)).exists():
thumbnail = None
- return {
+ row = {
"id": entity["id"],
# a saved point is one row, so its render key is its id. Proof rows
# repeat one entity across its source points and key themselves apart.
@@ -581,19 +592,36 @@ def _saved_row(
# those rather than letting them read as the analyst's own work.
"status": (entity.get("provenance") or {}).get("status") or "confirmed",
}
+ if comparison is not None:
+ pictured = preview.get("source") or {}
+ row.update({
+ "path": preview.get("path"),
+ # the name Compare reopens it by
+ "session": comparisons.session_name(str(attrs.get("spec") or "")),
+ # each picture's date, an estimate marked as the Time panel marks it
+ "imagery_a": timeline.imagery_reading(pictured, "imagery_a"),
+ "imagery_b": timeline.imagery_reading(pictured, "imagery_b"),
+ # the images kept from it, newest last: the row counts them, the card
+ # lists them, and none is a mark of its own
+ "kept": comparison.get("kept") or [],
+ })
+ return row
def saved_index(case: Case) -> list[dict[str, Any]]:
- """Places and captures as one flat list, newest first.
+ """Places, captures and comparisons as one flat list, newest first.
Everything the Saved tree, the search modal and the map overlay read, and
nothing else: no media rows, no derivation, no edges. Work that hangs off a
point is a count (proofs, relations) rather than a list, so hundreds of rows
stay in the tens of KB — which is what lets the panel load the whole set on
case open instead of paging it. The popup loads the edges themselves from the
- bounded chain endpoint when it opens.
+ bounded chain endpoint when it opens. A comparison lists the images kept from
+ it, which are few and are what its card is for.
"""
- by_path = {c["path"]: c for c in list_captures(case)}
+ items = media_engine.list_media(case)
+ by_path = {c["path"]: c for c in _captures_of(items)}
+ pictures, kept = comparisons.grouped(items)
# two grouped queries for the whole case rather than one per row: this list
# is read on case open and must not walk the graph row by row
worked = case.count_dependents(link_type=links.DERIVED_FROM, from_type="proof")
@@ -606,10 +634,14 @@ def saved_index(case: Case) -> list[dict[str, Any]]:
)
rows = []
for entity in saved_entities(case):
+ attrs = entity.get("attrs") or {}
is_image = entity["type"] == "capture"
- capture = by_path.get((entity.get("attrs") or {}).get("path")) if is_image else None
+ capture = by_path.get(attrs.get("path")) if is_image else None
if is_image and capture is None:
continue # the image is gone; the media listing is the authority
+ comparison = ({"preview": pictures.get(str(attrs.get("preview") or "")),
+ "kept": kept.get(str(attrs.get("spec") or ""), [])}
+ if entity["type"] == "compare-session" else None)
rows.append(
_saved_row(
case,
@@ -617,6 +649,7 @@ def saved_index(case: Case) -> list[dict[str, Any]]:
capture,
worked.get(entity["id"], 0),
related.get(entity["id"], 0),
+ comparison,
)
)
# newest first, and within one second the later save wins — saving a place
diff --git a/src/azimut/engine/sentinel.py b/src/azimut/engine/sentinel.py
index 63657d6..983dbf0 100644
--- a/src/azimut/engine/sentinel.py
+++ b/src/azimut/engine/sentinel.py
@@ -310,6 +310,64 @@ SPECTRAL_INDEX: dict[str, tuple[tuple[str, ...], tuple[str, ...]]] = {
}
+# Sentinel-2 Level-2A's bands, which an analyzer of your own may read by name.
+# B10 is a cirrus band the atmospheric correction consumes; Level-2A drops it.
+L2A_BANDS: tuple[str, ...] = ("B01", "B02", "B03", "B04", "B05", "B06", "B07", "B08",
+ "B8A", "B09", "B11", "B12")
+# Reflectance in a 16-bit channel, as whole ten-thousandths: the scale
+# Sentinel-2's own digital numbers use. A byte could not hold a normalised
+# difference of two dark bands, where a step of 0.2% reflectance is a tenth of
+# the whole index over water.
+BANDS_SCALE = 10_000
+_BANDS_PRODUCT = re.compile(r"^bands(?:-(?:B0[1-9]|B8A|B1[12])){1,3}$")
+
+
+def band_product(bands: list[str] | tuple[str, ...]) -> str:
+ """The product that carries these bands, named in the collection's order."""
+ ordered = [band for band in L2A_BANDS if band in set(bands)]
+ if not 1 <= len(ordered) <= 3 or len(ordered) != len(set(bands)):
+ raise ValueError("a band product carries one to three known bands")
+ return "bands-" + "-".join(ordered)
+
+
+def product_bands(product: str) -> tuple[str, ...]:
+ """The bands a ``bands-…`` product carries, or () for any other product."""
+ if not _BANDS_PRODUCT.match(product):
+ return ()
+ bands = tuple(product.split("-")[1:])
+ if band_product(bands) != product:
+ return ()
+ return bands
+
+
+def is_product(product: str) -> bool:
+ return product in PRODUCTS or bool(product_bands(product))
+
+
+def _bands_evalscript(product: str) -> str:
+ # Up to three bands at 16 bits, then the sky byte every Detect product
+ # carries. Only names from L2A_BANDS reach the script: `product_bands`
+ # refuses anything else before a request is built.
+ bands = product_bands(product)
+ if not bands:
+ raise ValueError(f"unknown band product '{product}'")
+ wanted = list(dict.fromkeys([*bands, "B08", "SCL", "dataMask"]))
+ listed = ", ".join(f'"{band}"' for band in wanted)
+ values = [f"Math.max({1 if i == 0 else 0}, Math.min(65535, Math.round(p.{band} * {BANDS_SCALE})))"
+ for i, band in enumerate(bands)]
+ values += ["0"] * (3 - len(bands))
+ script = f"""//VERSION=3
+function setup() {{
+ return {{ input: [{{ bands: [{listed}] }}], output: {{ bands: 4, sampleType: "UINT16" }} }};
+}}
+function evaluatePixel(p) {{
+ if (!p.dataMask) return [0, 0, 0, 0];
+ return [{", ".join(values)}, p.SCL + (p.B08 < {DARK_REFLECTANCE} ? {DARK_FLAG} : 0)];
+}}
+"""
+ return base64.b64encode(script.encode("ascii")).decode("ascii")
+
+
def _byte(expression: str, gain: float, floor: int = 0) -> str:
return f"Math.max({floor}, Math.min(255, Math.round(({expression}) * {255 * gain:g})))"
@@ -480,6 +538,8 @@ def _evalscript(product: str) -> str:
return _change_evalscript(product)
if product in SAR_PRODUCTS:
return _sar_evalscript(product)
+ if product_bands(product):
+ return _bands_evalscript(product)
return _detect_evalscript(product)
@@ -600,7 +660,7 @@ def band_frame(
The image is validated before it is handed on: a PNG, the size asked for,
within the byte budget.
"""
- if product not in PRODUCTS:
+ if not is_product(product):
raise ValueError(f"unknown band product '{product}'")
west, south, east, north = bbox
if not all(abs(value) <= _WEB_MERCATOR_LIMIT for value in bbox):
diff --git a/src/azimut/engine/tiles.py b/src/azimut/engine/tiles.py
index e5915dd..ed763cf 100644
--- a/src/azimut/engine/tiles.py
+++ b/src/azimut/engine/tiles.py
@@ -97,6 +97,8 @@ GOOGLE_JS_LOADER_URL = "https://maps.googleapis.com/maps/api/js?key={key}&v=week
# the plain one (TRUE_COLOR, the layer's own default window = most recent, and
# no cloud filter — the instance's own would silently drop cloudy passes).
SENTINELHUB_WMTS_URL = sentinel.wmts_url()
+# Default eco threshold for both Sentinel layers; Settings can override it.
+SENTINEL_ECO_MAX_ZOOM = 7
BUILTIN_PROVIDERS: tuple[Provider, ...] = (
Provider(
@@ -249,11 +251,10 @@ def all_providers() -> list[Provider]:
meter="sentinelhub",
tile_size=512,
zoom_offset=1, # WMTS names this level 14 where z_shift says 13
- # Its own eco threshold, three levels under its z14 ceiling: at
- # z11 and out a Sentinel-2 pixel is ~40 m of ground and Esri
- # shows the same scene for free, so the quota buys nothing.
- # z12-14 is where the dated mosaic is the reason you're here.
- eco_max_zoom=11,
+ # Its own eco threshold: at z7 and out the view spans a whole
+ # region and Esri shows it for free, so the quota buys nothing.
+ # From z8 in, the dated mosaic is the reason you're here.
+ eco_max_zoom=SENTINEL_ECO_MAX_ZOOM,
)
)
@@ -275,7 +276,7 @@ def all_providers() -> list[Provider]:
meter="sentinelhub",
tile_size=512,
zoom_offset=1,
- eco_max_zoom=11,
+ eco_max_zoom=SENTINEL_ECO_MAX_ZOOM,
)
)
diff --git a/src/azimut/engine/timeline.py b/src/azimut/engine/timeline.py
index 1bd45cc..67a334f 100644
--- a/src/azimut/engine/timeline.py
+++ b/src/azimut/engine/timeline.py
@@ -164,6 +164,30 @@ def project_entity(entity: dict[str, Any]) -> list[ProjectionRow]:
_COMPACT_DATE = re.compile(r"(?P<year>\d{4})(?P<month>\d{2})(?P<day>\d{2})\Z")
+_PLAIN_DATE = re.compile(r"\d{4}(-\d{2}(-\d{2})?)?\Z")
+
+#: The two pictures a comparison or a Detect pair shows, each with its own date.
+#: A picture of two moments is two dates, never an interval: it does not say
+#: that anything happened between them.
+IMAGERY_SIDES = (("imagery-a", "imagery_a"), ("imagery-b", "imagery_b"))
+
+
+def _imagery(raw: object, exact: object) -> object:
+ """An imagery date, marked approximate when its provider only estimated it.
+
+ The sidecar keeps the date as the provider gave it, with `exact: false` beside
+ it, because captures show that date on their face. The `~` is added here, where
+ the reading is placed on the axis.
+ """
+ if exact is False and isinstance(raw, str) and _PLAIN_DATE.fullmatch(raw):
+ return f"{raw}~"
+ return raw
+
+
+def imagery_reading(source: dict[str, Any], key: str) -> str | None:
+ """One picture's date (`imagery_a`, `imagery_b`) as the Time panel reads it."""
+ raw = _imagery(source.get(key), source.get(f"{key}_exact"))
+ return raw if isinstance(raw, str) and raw else None
def _media_date(raw: object) -> object:
@@ -202,7 +226,9 @@ def project_media(item: dict[str, Any], entity_id: str | None) -> list[Projectio
# describe the same reading, and showing both would look like two events.
add(MEDIA, "captured", item.get("taken_at") or source.get("captured_at"))
add(MEDIA, "published", _media_date(source.get("upload_date")))
- add(MEDIA, "imagery", source.get("imagery_date"))
+ add(MEDIA, "imagery", _imagery(source.get("imagery_date"), source.get("imagery_exact")))
+ for kind, key in IMAGERY_SIDES:
+ add(MEDIA, kind, imagery_reading(source, key))
add(CASE_ACTIVITY, "collected", source.get("fetched_at"))
add(CASE_ACTIVITY, "added", item.get("added_at"))
return rows
diff --git a/src/azimut/engine/trash.py b/src/azimut/engine/trash.py
index 0e09dda..fc3eef1 100644
--- a/src/azimut/engine/trash.py
+++ b/src/azimut/engine/trash.py
@@ -14,8 +14,8 @@ to break the 260-character Windows limit on its own. The journal already records
where every file came from, so the directory holds ``0``, ``1``, ``2`` and the
payload's ``slots`` list says which is which.
-One row is one **delete action**, not one entity: deleting a video that carries
-three Inspect sessions writes a single group, and restoring it brings the whole
+One row is one **delete action**, not one entity: deleting a video takes its
+Inspect work with it in a single group, and restoring it brings the whole
cascade back at once.
What travels: everything the artifact registry says an entity owns. What does
@@ -34,6 +34,7 @@ from .. import layout
from ..workspace import Case, CaseError, _new_id, ensure_dir
from . import artifacts as artifact_engine
from . import entity_images as entity_image_engine
+from . import inspectwork
from . import links as link_engine
from . import thumbnails as thumbnail_engine
@@ -321,6 +322,11 @@ def _finish_restore(case: Case, group: dict[str, Any]) -> dict[str, Any]:
result = _restore_records(case, group)
_drop_dir(case, group["id"])
case.remove_trash_group(group["id"])
+ # A file keeps one Inspect work. Bringing back an older one, or a session from
+ # before 0.3.1, next to the work done since merges them rather than leaving two.
+ entities = (group.get("payload") or {}).get("entities") or []
+ if any(entity.get("type") == inspectwork.WORK_TYPE for entity in entities):
+ inspectwork.normalize(case)
return {"status": "restored", **result, "group": group["id"]}
diff --git a/src/azimut/layout.py b/src/azimut/layout.py
index d7d1854..cdb80c2 100644
--- a/src/azimut/layout.py
+++ b/src/azimut/layout.py
@@ -50,8 +50,10 @@ TOOL_DIR = "azimut"
#: Post drafts. Named for what they are; `exports/` is now free to mean exports.
DRAFTS_DIR = ".drafts"
-#: Saved Inspect session specs.
+#: Inspect's per-file work: the frames cut from one video or image, and their edits.
INSPECT_DIR = ".inspect"
+#: Collage layouts. The picture a collage exports is a media working file.
+COLLAGE_DIR = ".collages"
#: 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.
@@ -86,6 +88,7 @@ CASE_SUBDIRS = (
"exports",
DRAFTS_DIR,
INSPECT_DIR,
+ COLLAGE_DIR,
COMPARE_DIR,
ANALYSIS_DIR,
SEARCH_DIR,
@@ -126,7 +129,7 @@ MAX_CASE_SLUG = 48
MAX_MEDIA_NAME = 90
#: The stem of anything the analyst saves under a name — notes, proofs, inspect
-#: sessions, post drafts. Mirrored in `frontend/src/lib/naming.js`.
+#: work, collages, post drafts. Mirrored in `frontend/src/lib/naming.js`.
MAX_SLUG = 68
#: A note's filing folder: total path length, and how deep it may nest.
@@ -469,6 +472,15 @@ def session_rel(name: str) -> str:
return f"{INSPECT_DIR}/{name}.json"
+def legacy_session_rel(name: str) -> str:
+ """A pre-0.3.1 session exactly as it was, kept by the merge that replaced it."""
+ return f"{INSPECT_DIR}/.v1/{name}.json"
+
+
+def collage_rel(name: str) -> str:
+ return f"{COLLAGE_DIR}/{name}.json"
+
+
def compare_session_rel(name: str) -> str:
return f"{COMPARE_DIR}/{name}.json"
diff --git a/src/azimut/server.py b/src/azimut/server.py
index 8c3a664..513fb87 100644
--- a/src/azimut/server.py
+++ b/src/azimut/server.py
@@ -64,6 +64,7 @@ class BulkBodyLimit:
("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", ("compare", "sessions", "*", "images"), "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"),
diff --git a/src/azimut/workspace.py b/src/azimut/workspace.py
index 3a818f3..3ab3e9b 100644
--- a/src/azimut/workspace.py
+++ b/src/azimut/workspace.py
@@ -57,7 +57,12 @@ if TYPE_CHECKING:
# nobody has on disk.
JSON_SCHEMA = 2
STORAGE_SCHEMA = 3
-CASE_SCHEMA = 9
+#: The last folder shape before Inspect gave each file one work (0.3.0 wrote it).
+LAYOUT_SCHEMA = 9
+#: One Inspect work per file, before kept Detect pins stated when they were seen
+#: and saved comparisons stood on the map.
+WORK_SCHEMA = 10
+CASE_SCHEMA = 11
# from_version -> function(data) returning data reshaped for from_version + 1.
# The runner (Case.migrate) owns stamping the new schema number, so a migration
@@ -965,6 +970,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"),
+ "collage": ("spec", layout.collage_rel, "Collage"),
"compare-session": ("spec", layout.compare_session_rel, "Comparison"),
"post": ("draft", layout.draft_rel, "Post"),
"sheet": ("path", layout.sheet_rel, "Sheet"),
@@ -1298,10 +1304,38 @@ def open_workspace() -> None:
logger.warning("workspace housekeeping step failed", exc_info=True)
-_FINAL_LAYOUT_MIGRATION = FolderMigration(CASE_SCHEMA, _normalize_case_layout)
+def _one_work_per_file(case: Case) -> None:
+ """Merge each file's Inspect sessions into one work, and lift the collages out.
+
+ Imported here rather than at the top: the engine imports this module.
+ """
+ from .engine import inspectwork
+
+ inspectwork.migrate_case(case)
+
+
+def _dated_and_placed_work(case: Case) -> None:
+ """State when each kept Detect pin was seen, and stand each saved comparison
+ on the map, as a pin kept or a comparison saved today does."""
+ from .engine import analysis_dating, comparisons
+
+ analysis_dating.backfill(case)
+ comparisons.backfill(case)
+
+
+def _one_work_then_dated_work(case: Case) -> None:
+ _one_work_per_file(case)
+ _dated_and_placed_work(case)
+
+
+_FINAL_LAYOUT_MIGRATION = FolderMigration(LAYOUT_SCHEMA, _normalize_case_layout)
FOLDER_MIGRATIONS.update(
- {version: _FINAL_LAYOUT_MIGRATION for version in range(STORAGE_SCHEMA, CASE_SCHEMA)}
+ {version: _FINAL_LAYOUT_MIGRATION for version in range(STORAGE_SCHEMA, LAYOUT_SCHEMA)}
)
+# Schema 10 was never released: a 0.3.0 case takes both steps in one stamp, and
+# only a case a development build already moved to 10 runs the second alone.
+FOLDER_MIGRATIONS[LAYOUT_SCHEMA] = FolderMigration(CASE_SCHEMA, _one_work_then_dated_work)
+FOLDER_MIGRATIONS[WORK_SCHEMA] = FolderMigration(CASE_SCHEMA, _dated_and_placed_work)
if TYPE_CHECKING:
diff --git a/tests/fullcase.py b/tests/fullcase.py
index a5da0e7..a35adf3 100644
--- a/tests/fullcase.py
+++ b/tests/fullcase.py
@@ -72,9 +72,10 @@ class FullCase:
case_id: str
photo: str = ""
piece: str = ""
- collage: str = ""
+ collage: str = "" # the exported picture, which is media
+ collage_doc: str = "" # the layout it was exported from
capture: str = ""
- session: str = ""
+ session: str = "" # the photo's Inspect work
compare_session: str = ""
compare_image: str = "" # the session's render, a media working file
analyzer_zones: str = ""
@@ -175,18 +176,35 @@ def build_full_case(client, name: str = "Full case") -> FullCase:
assert shot.status_code == 200, shot.text
full.capture = client.get(f"/api/cases/{case_id}/satellite").json()[0]["path"]
- # -- inspect session: adjustments over the photo (depends-on) -------------
- session = client.post(
- f"/api/cases/{case_id}/inspect/sessions",
+ # -- inspect work: the photo's edits (depends-on) --------------------------
+ work = client.put(
+ f"/api/cases/{case_id}/inspect/work",
json={
- "title": "Photo pass",
- "spec": {"source": {"path": full.photo}, "ops": [
- {"op": "brightness", "params": {"value": 1.2}}
+ "path": full.photo,
+ "spec": {"frames": [{
+ "id": "fr_1", "path": full.photo, "time": None,
+ "adjust": {"brightness": 1.2}, "crop": {"x": 0.1, "y": 0.1, "w": 0.5, "h": 0.5},
+ }]},
+ },
+ )
+ assert work.status_code == 200, work.text
+ full.session = f".inspect/{work.json()['name']}.json"
+
+ # -- a collage layout: pieces from both uploads, its own document ---------
+ layout_doc = client.post(
+ f"/api/cases/{case_id}/collages",
+ json={
+ "title": "Harbour strip",
+ "spec": {"width": 400, "height": 200, "nodes": [
+ {"id": "nd_1", "save": {"path": full.photo, "time": None, "ops": []},
+ "w": 80, "h": 60, "quad": [[0, 0], [80, 0], [80, 60], [0, 60]]},
+ {"id": "nd_2", "save": {"path": full.piece, "time": None, "ops": []},
+ "w": 60, "h": 60, "quad": [[90, 0], [150, 0], [150, 60], [90, 60]]},
]},
},
)
- assert session.status_code == 200, session.text
- full.session = f".inspect/{session.json()['name']}.json"
+ assert layout_doc.status_code == 200, layout_doc.text
+ full.collage_doc = f".collages/{layout_doc.json()['name']}.json"
comparison = client.post(
f"/api/cases/{case_id}/compare/sessions",
diff --git a/tests/legacy_case.py b/tests/legacy_case.py
index 034d9b6..e855fd1 100644
--- a/tests/legacy_case.py
+++ b/tests/legacy_case.py
@@ -168,11 +168,11 @@ 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", ".compare", ".analysis", ".layers"})
+POST_WRAPPER_DIRS = frozenset({"sheets", ".compare", ".analysis", ".layers", ".collages"})
def rewind_case(case: Case, schema: int) -> None:
- """Reconstruct one folder checkpoint from the final schema-9 layout.
+ """Reconstruct one folder checkpoint from the current layout.
These shapes were never released, but the consolidated normalizer accepts
them so a case opened by a development build cannot be stranded.
diff --git a/tests/test_analyzers.py b/tests/test_analyzers.py
index 85daa9c..5858031 100644
--- a/tests/test_analyzers.py
+++ b/tests/test_analyzers.py
@@ -97,6 +97,11 @@ def test_local_run_keeps_frames_and_review_without_network(client, scenario):
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"]
+ # The picture shows the place it pins, as an edge its connections read, and once.
+ picture = case.find_entity(attr="path", value=promoted["image"])
+ shows = [link for link in case.links_of(picture["id"]) if link["type"] == "depicts"]
+ assert [(link["from"], link["to"], link["provenance"]["by"]) for link in shows] == [
+ (picture["id"], promoted["entity"]["id"], "compare")]
# 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()
@@ -136,9 +141,12 @@ def test_keeping_a_candidate_is_the_only_thing_that_reaches_the_case(client, sce
# 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.
+ # Undoing takes the pin away and gives the candidate back, the edge with them.
+ picture = case.find_entity(attr="path", value=kept["image"])
+ assert any(link["type"] == "depicts" for link in case.links_of(picture["id"]))
assert client.delete(endpoint + "/promote").json()["result"]["review"] == "new"
assert case.get_entity(kept["entity"]["id"]) is None
+ assert not [link for link in case.list_links() if kept["entity"]["id"] in (link["from"], link["to"])]
assert client.patch(endpoint, json={"review": "dismissed"}).status_code == 200
assert client.get(endpoint + "/preview").status_code == 404
@@ -530,7 +538,9 @@ def test_a_recipe_saved_before_detect_went_copernicus_only_still_loads():
def test_every_method_publishes_sizes_and_words_for_its_reading():
methods = {entry["id"]: entry for entry in METHODS}
assert set(methods) == {"vessels", "hotspots", "structure", "spots", "surface", "index",
- "sar-vessels", "sar-change"}
+ "sar-vessels", "sar-change", "rules"}
+ # an analyzer of your own words its reading from its own first rule
+ assert methods["rules"]["rules"] and methods["rules"]["measure"] == ""
for entry in METHODS:
assert set(entry["sizes"]) == {"small", "medium", "large", "all"}
for size in entry["sizes"].values():
@@ -541,7 +551,7 @@ def test_every_method_publishes_sizes_and_words_for_its_reading():
# falls between two bands and is found by neither.
assert entry["sizes"]["all"]["min_area"] == 0
assert entry["sizes"]["all"]["max_area"] == 0
- assert "{" in entry["measure"]
+ assert "{" in entry["measure"] or entry["rules"]
# the fire test rejects cloud itself and radar sees through it; every other
# method can use the mask
assert [m for m, entry in methods.items() if not entry["clouds"]] == [
diff --git a/tests/test_compare_api.py b/tests/test_compare_api.py
index ca776fd..e97062a 100644
--- a/tests/test_compare_api.py
+++ b/tests/test_compare_api.py
@@ -68,14 +68,14 @@ def _save(client, cid: str, title: str, spec: dict | None = None, **extra):
)
-def _preview(client, cid: str, name: str, colour=(30, 60, 90), fmt: str = "png"):
+def _preview(client, cid: str, name: str, colour=(30, 60, 90), fmt: str = "png", **dates):
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},
+ data={"format": fmt, **dates},
)
@@ -434,6 +434,39 @@ def test_renaming_the_session_renames_its_image_on_the_next_save(client):
assert [entity["attrs"]["path"] for entity in _entities(cid, "media")] == [renamed["path"]]
+def test_the_rendered_comparison_carries_the_date_of_each_picture(client):
+ """Two instants, never a range: the image does not say anything happened
+ between them. An estimated date says so on the axis."""
+ cid = _case(client, "Compare dated")
+ _save(client, cid, "Harbour reading")
+ body = _preview(client, cid, "Harbour reading", imagery_a="2024-05-03", imagery_a_exact="false",
+ imagery_b="2026-09-02T05:42:10Z").json()
+
+ item = next(row for row in client.get(f"/api/cases/{cid}/media").json() if row["path"] == body["path"])
+ assert item["source"]["imagery_a"] == "2024-05-03"
+ assert item["source"]["imagery_a_exact"] is False
+ assert item["source"]["imagery_b"] == "2026-09-02T05:42:10Z"
+ assert "imagery_b_exact" not in item["source"]
+
+ media = _entities(cid, "media")[0]
+ page = client.get(f"/api/cases/{cid}/timeline", params={"entity": media["id"], "category": "media"}).json()
+ rows = {row["kind"]: row for row in page["items"]}
+ assert rows["imagery-a"]["raw"] == "2024-05-03~" and rows["imagery-a"]["approximate"]
+ assert rows["imagery-b"]["precision"] == "second"
+
+ # Saving again restates the dates of the pictures shown now, and drops the old.
+ _preview(client, cid, "Harbour reading", imagery_b="2026-09-03")
+ item = next(row for row in client.get(f"/api/cases/{cid}/media").json() if row["path"] == body["path"])
+ assert "imagery_a" not in item["source"] and item["source"]["imagery_b"] == "2026-09-03"
+
+
[email protected]("value", ["yesterday", "2026-09-02T05:42:10", "2026-09-02T05:42:10+02:00"])
+def test_a_picture_date_is_a_day_or_a_utc_instant(client, value):
+ cid = _case(client, "Compare date refused")
+ _save(client, cid, "Harbour reading")
+ assert _preview(client, cid, "Harbour reading", imagery_a=value).status_code == 422
+
+
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
@@ -468,6 +501,26 @@ def test_compare_gif_exports_blink_and_slide(client):
assert gif.info["duration"] == 1500
+def test_a_second_gif_by_the_same_name_is_kept_beside_the_first(client):
+ """Exports are named by their pictures' dates, which two comparisons of one
+ pair share, so the case's own folder never overwrites one with the other."""
+ cid = _case(client, "Compare GIF twice")
+ written = []
+ for colour in ((220, 30, 30), (30, 220, 30)):
+ response = client.post(
+ f"/api/cases/{cid}/compare/gif",
+ files={
+ "image_a": ("a.png", _png(colour), "image/png"),
+ "image_b": ("b.png", _png((20, 40, 220)), "image/png"),
+ },
+ data={"animation": "blink", "filename": "compare-2024-05-03_2026-09-02"},
+ )
+ assert response.status_code == 200, response.text
+ written.append(Path(response.json()["path"]) / response.json()["file"])
+ assert written[0] != written[1]
+ assert all(path.is_file() for path in written)
+
+
def test_compare_gif_rejects_non_png_and_unknown_animation(client):
cid = _case(client, "Compare GIF bad")
assert client.post(
diff --git a/tests/test_compare_saved_work.py b/tests/test_compare_saved_work.py
new file mode 100644
index 0000000..8a28868
--- /dev/null
+++ b/tests/test_compare_saved_work.py
@@ -0,0 +1,154 @@
+"""A saved comparison is saved work: it stands on the map and keeps its images."""
+
+import json
+
+import pytest
+
+from azimut import workspace
+from azimut.engine import comparisons, media
+from azimut.workspace import Case
+from test_compare_api import _case, _png, _preview, _save, _spec
+
+
+def _row(client, cid, title):
+ rows = client.get(f"/api/cases/{cid}/satellite/index").json()
+ return next(row for row in rows if row["title"] == title)
+
+
+def _keep(client, cid, name, spec=None, fmt="png", **extra):
+ files = {"image_a": ("a.png", _png((200, 40, 40)), "image/png")}
+ if fmt != "png":
+ files["image_b"] = ("b.png", _png((40, 40, 200)), "image/png")
+ return client.post(
+ f"/api/cases/{cid}/compare/sessions/{name}/images",
+ files=files,
+ data={"format": fmt, "filename": extra.pop("filename", f"{name} 2024-05-03_2026-09-02"),
+ "spec": json.dumps(spec or _spec()), **extra},
+ )
+
+
+# -- where it stands --------------------------------------------------------------
+
+
+def test_a_frame_is_placed_on_its_centre_and_drawn_as_its_ground():
+ # drawn upright, the ring is the box between the two corners
+ (lon, lat), ring = comparisons.frame_ring({"points": [[2.0, 48.0], [2.1, 47.9]], "angle": 0})
+ assert lon == pytest.approx(2.05)
+ assert 47.9 < lat < 48.0
+ assert ring[0] == ring[-1] and len(ring) == 5
+ assert {round(p[0], 5) for p in ring} == {2.0, 2.1}
+ # drawn on a turned camera, its sides run along the turned screen
+ _, turned = comparisons.frame_ring({"points": [[2.0, 48.0], [2.1, 47.9]], "angle": 45})
+ assert {round(p[0], 5) for p in turned} != {2.0, 2.1}
+
+
+def test_a_saved_comparison_is_listed_with_the_captures_at_its_view(client):
+ cid = _case(client, "Saved comparison")
+ assert _save(client, cid, "Harbour reading").status_code == 200
+ _preview(client, cid, "Harbour reading", imagery_a="2024-05-03", imagery_a_exact="false",
+ imagery_b="2026-09-02")
+
+ row = _row(client, cid, "Harbour reading")
+ assert row["kind"] == "comparison"
+ assert (row["lat"], row["lon"]) == (48.8584, 2.2945)
+ assert row["session"] == "Harbour reading"
+ assert (row["imagery_a"], row["imagery_b"]) == ("2024-05-03~", "2026-09-02")
+ assert row["path"] == "media/Harbour reading.png" and row["thumbnail"]
+ assert row["footprint"] is None and row["kept"] == []
+ # its country is asked on save, and offline it waits for the Locate pass
+ session = Case.open(cid).find_entity(attr="spec", value=".compare/Harbour reading.json")
+ assert session["attrs"]["geo"]["state"] == "failed"
+
+
+def test_a_framed_comparison_stands_on_its_frame(client):
+ cid = _case(client, "Framed comparison")
+ spec = _spec()
+ spec["frame"] = {"points": [[2.2945, 48.8584], [2.2961, 48.8572]], "angle": 0}
+ _save(client, cid, "Framed reading", spec)
+ row = _row(client, cid, "Framed reading")
+ assert row["lon"] == pytest.approx((2.2945 + 2.2961) / 2)
+ assert row["footprint"]["type"] == "Polygon"
+ # taking the frame off takes it off the map
+ _save(client, cid, "Framed reading", _spec(), overwrite=True)
+ assert _row(client, cid, "Framed reading")["footprint"] is None
+
+
+# -- keeping an export ------------------------------------------------------------
+
+
+def test_a_kept_image_carries_the_reading_it_shows_and_is_never_replaced(client):
+ cid = _case(client, "Kept images")
+ _save(client, cid, "Harbour reading")
+ moved = _spec()
+ moved["camera"] = {**moved["camera"], "lat": 48.86, "lon": 2.30}
+
+ first = _keep(client, cid, "Harbour reading", moved, imagery_b="2026-09-02T05:42:10Z")
+ second = _keep(client, cid, "Harbour reading", moved, fmt="slide")
+ assert first.status_code == 200, first.text
+ assert second.status_code == 200, second.text
+ assert first.json()["path"] == "media/Harbour reading 2024-05-03_2026-09-02.png"
+ assert second.json()["path"].endswith(".gif")
+
+ source = media.read_item(Case.open(cid), first.json()["path"])["source"]
+ assert source["kept"] is True and source["session"] == ".compare/Harbour reading.json"
+ # the reading on screen when it was kept, not the session's saved one
+ assert (source["lat"], source["lon"]) == (48.86, 2.30)
+ assert source["imagery_b"] == "2026-09-02T05:42:10Z"
+
+ again = _keep(client, cid, "Harbour reading", moved)
+ assert again.json()["path"] != first.json()["path"]
+ kept = _row(client, cid, "Harbour reading")["kept"]
+ assert {image["path"] for image in kept} == {
+ first.json()["path"], second.json()["path"], again.json()["path"]}
+
+
+def test_an_image_is_kept_only_under_a_saved_comparison(client):
+ cid = _case(client, "Keep refused")
+ assert _keep(client, cid, "Nothing here").status_code == 404
+ _save(client, cid, "Harbour reading")
+ assert _keep(client, cid, "Harbour reading", fmt="png", spec="{}").status_code == 422
+ blink = client.post(
+ f"/api/cases/{cid}/compare/sessions/Harbour reading/images",
+ files={"image_a": ("a.png", _png((0, 0, 0)), "image/png")},
+ data={"format": "blink", "filename": "x", "spec": json.dumps(_spec())},
+ )
+ assert blink.status_code == 422
+
+
+def test_kept_images_follow_a_renamed_comparison_and_outlive_a_deleted_one(client):
+ cid = _case(client, "Kept follow")
+ _save(client, cid, "Harbour reading")
+ kept = _keep(client, cid, "Harbour reading").json()
+ _save(client, cid, "Harbour at dusk", rename_from="Harbour reading")
+
+ row = _row(client, cid, "Harbour at dusk")
+ assert [image["path"] for image in row["kept"]] == [kept["path"]]
+ assert row["session"] == "Harbour at dusk"
+
+ assert client.delete(f"/api/cases/{cid}/entities/{row['id']}").status_code == 200
+ rows = client.get(f"/api/cases/{cid}/satellite/index").json()
+ assert not [r for r in rows if r["kind"] == "comparison"]
+ assert Case.open(cid).resolve_inside(kept["path"]).is_file()
+
+
+# -- comparisons saved before -----------------------------------------------------
+
+
+def test_opening_a_case_from_an_earlier_build_places_its_comparisons(client):
+ cid = _case(client, "Earlier comparisons")
+ _save(client, cid, "Harbour reading")
+ case = Case.open(cid)
+ session = case.find_entity(attr="spec", value=".compare/Harbour reading.json")
+ attrs = {k: v for k, v in session["attrs"].items() if k not in {"lat", "lon", "zoom", "bearing",
+ "footprint", "geo"}}
+ case.remove_entity(session["id"])
+ case.add_entity("compare-session", session["label"], attrs=attrs, by="compare")
+ manifest = case.read()
+ manifest["azimut"]["schema"] = workspace.WORK_SCHEMA
+ case._write_json(manifest)
+
+ opened = Case.open(cid)
+ placed = opened.find_entity(attr="spec", value=".compare/Harbour reading.json")
+ assert (placed["attrs"]["lat"], placed["attrs"]["lon"]) == (48.8584, 2.2945)
+ # left for the Locate pass: a migration never waits on a geocoder
+ assert "geo" not in placed["attrs"]
diff --git a/tests/test_detect_dating.py b/tests/test_detect_dating.py
new file mode 100644
index 0000000..f20baed
--- /dev/null
+++ b/tests/test_detect_dating.py
@@ -0,0 +1,213 @@
+"""A kept Detect candidate says when it was seen, on its picture and on a Claim."""
+
+import json
+
+import pytest
+
+from azimut import workspace
+from azimut.engine import analysis_dating, maplayers, media
+from azimut.workspace import Case
+from analyzerfixture import DAY_A, DAY_B, hull, sea, seed, sentinel_input
+from test_analyzers import run, scenario as analyzer_scenario
+
+
+def scenario(client, monkeypatch):
+ return analyzer_scenario.__wrapped__(client, monkeypatch)
+
+
+def kept(client, case, saved, **pin):
+ result = saved["results"][0]
+ endpoint = f"/api/cases/{case.id}/analysis/runs/{saved['id']}/results/{result['id']}"
+ response = client.post(endpoint + "/promote", json={"title": "Levelled yard", **pin})
+ assert response.status_code == 200, response.text
+ return endpoint, response.json()
+
+
+def links_of(case, claim_id, type_):
+ return [link["to"] for link in case.links_of(claim_id) if link["type"] == type_ and link["from"] == claim_id]
+
+
+def time_rows(client, case, entity_id):
+ page = client.get(f"/api/cases/{case.id}/timeline", params={
+ "entity": entity_id, "category": ["statement", "media"], "include_undated": "true"}).json()
+ return {row["kind"]: row for row in page["items"] if row["owner_id"] == entity_id}
+
+
+def one_pass_run(client, case):
+ body = sentinel_input("boats", min_area=0, merge_metres=0)
+ body["a"]["date"] = ""
+ pixels = sea()
+ hull(pixels, 120, 140, 6, 3)
+ seed(body, after=pixels)
+ body["area_dates"] = [{"area_id": "patch", "b": body["b"], "date_rule": "manual"}]
+ saved = run(client, case, body)
+ assert saved["count"] == 1, saved
+ return saved
+
+
+# -- the pieces --------------------------------------------------------------------
+
+
+def test_a_pass_is_its_day_or_the_instant_a_radar_pass_names():
+ assert analysis_dating.moment({"date": "2026-05-11"}) == "2026-05-11"
+ assert analysis_dating.moment({"date": "2026-05-11", "time": "05:42:10"}) == "2026-05-11T05:42:10Z"
+ assert analysis_dating.moment({"date": ""}) == ""
+ assert analysis_dating.moment({"date": "11/05/2026"}) == ""
+
+
+def test_a_change_happened_between_its_passes_in_the_order_they_happened():
+ assert analysis_dating.span("2026-05-04", "2026-05-11") == "2026-05-04/2026-05-11"
+ assert analysis_dating.span("2026-05-11", "2026-05-04") == "2026-05-04/2026-05-11"
+ # two radar looks on one day are an exact interval
+ assert (analysis_dating.span("2026-05-11T05:42:10Z", "2026-05-11T17:31:02Z")
+ == "2026-05-11T05:42:10Z/2026-05-11T17:31:02Z")
+ # a day and an instant do not mix in the profile, so both are read as days
+ assert analysis_dating.span("2026-05-04", "2026-05-11T05:42:10Z") == "2026-05-04/2026-05-11"
+ assert analysis_dating.span("2026-05-11", "2026-05-11T05:42:10Z") == "2026-05-11"
+
+
+def test_a_picture_of_two_passes_carries_two_dates_and_one_pass_carries_one():
+ sources = {"a": {"date": DAY_A}, "b": {"date": DAY_B, "time": "05:42:10"}}
+ assert analysis_dating.pictured(sources, one_pass=False) == {
+ "imagery_a": DAY_A, "imagery_b": f"{DAY_B}T05:42:10Z"}
+ assert analysis_dating.pictured(sources, one_pass=True) == {"imagery_date": f"{DAY_B}T05:42:10Z"}
+ assert analysis_dating.pictured({"a": {}, "b": {}}, one_pass=True) == {}
+
+
+# -- keeping -------------------------------------------------------------------------
+
+
+def test_keeping_a_change_states_it_happened_between_the_passes(client, scenario):
+ case, body = scenario
+ saved = run(client, case, body)
+ _, pinned = kept(client, case, saved)
+ place = pinned["entity"]
+ picture = case.find_entity(attr="path", value=pinned["image"])
+
+ # The place carries no date of its own: a pin is permanent ground.
+ assert not {"when", "imagery_date"} & set(place["attrs"])
+ claim = case.get_entity(pinned["claim"]["id"])
+ assert claim["type"] == "claim" and claim["label"] == "Changed: Levelled yard"
+ assert claim["attrs"]["when"] == f"{DAY_A}/{DAY_B}"
+ assert claim["attrs"]["time_role"] == "occurred"
+ # keeping is the review, but nobody graded the statement
+ assert "confidence" not in claim["attrs"]
+ assert links_of(case, claim["id"], "at") == [place["id"]]
+ assert links_of(case, claim["id"], "cites") == [picture["id"]]
+
+ # The picture shows both passes, as two dates rather than a range.
+ source = media.read_item(case, pinned["image"])["source"]
+ assert (source["imagery_a"], source["imagery_b"]) == (DAY_A, DAY_B)
+ rows = time_rows(client, case, picture["id"])
+ assert rows["imagery-a"]["raw"] == DAY_A and rows["imagery-b"]["raw"] == DAY_B
+ assert time_rows(client, case, claim["id"])["claim"]["shape"] == "interval"
+
+
+def test_a_change_kept_as_its_second_pass_names_that_pass_alone(client, scenario):
+ case, body = scenario
+ saved = run(client, case, body)
+ _, pinned = kept(client, case, saved, after_only=True)
+ source = media.read_item(case, pinned["image"])["source"]
+ assert source["imagery_date"] == DAY_B
+ assert "imagery_a" not in source
+ # what the sweep read is still a change between two passes
+ assert case.get_entity(pinned["claim"]["id"])["attrs"]["when"] == f"{DAY_A}/{DAY_B}"
+
+
+def test_keeping_a_thing_on_one_pass_states_it_was_seen_then(client, scenario):
+ case, _ = scenario
+ saved = one_pass_run(client, case)
+ _, pinned = kept(client, case, saved, title="Tanker")
+ claim = case.get_entity(pinned["claim"]["id"])
+ assert claim["label"] == "Seen: Tanker"
+ assert (claim["attrs"]["when"], claim["attrs"]["time_role"]) == (DAY_B, "observed")
+ assert media.read_item(case, pinned["image"])["source"]["imagery_date"] == DAY_B
+
+
+def test_undoing_a_pin_takes_its_statement_to_the_same_trash_group(client, scenario):
+ case, body = scenario
+ saved = run(client, case, body)
+ endpoint, pinned = kept(client, case, saved)
+ claim_id = pinned["claim"]["id"]
+ undone = client.delete(endpoint + "/promote").json()
+ assert set(undone["deleted"]["deleted"]) >= {pinned["entity"]["id"], claim_id}
+ assert case.get_entity(claim_id) is None
+ restored = client.post(f"/api/cases/{case.id}/trash/{undone['deleted']['trash']}/restore")
+ assert restored.status_code == 200, restored.text
+ assert case.get_entity(claim_id) and case.get_entity(pinned["entity"]["id"])
+
+
+def test_a_statement_the_analyst_worked_on_outlives_the_pin(client, scenario):
+ case, body = scenario
+ saved = run(client, case, body)
+ endpoint, pinned = kept(client, case, saved)
+ claim_id = pinned["claim"]["id"]
+ assert client.patch(f"/api/cases/{case.id}/timeline/claims/{claim_id}",
+ json={"confidence": "probable"}).status_code == 200
+ client.delete(endpoint + "/promote")
+ assert case.get_entity(pinned["entity"]["id"]) is None
+ assert case.get_entity(claim_id)["attrs"]["confidence"] == "probable"
+
+
+# -- pins kept before this -----------------------------------------------------------
+
+
+def _forget_dates(case, pinned):
+ """Rewind a pin to what an older build kept: no statement, an undated picture."""
+ client_claim = pinned["claim"]["id"]
+ case.remove_entity(client_claim)
+ item = media.read_item(case, pinned["image"])
+ source = {k: v for k, v in item["source"].items() if not k.startswith("imagery")}
+ media.merge_item(case, pinned["image"], {"source": source})
+
+
+def test_backfill_states_pins_kept_before_and_runs_once(client, scenario):
+ case, _ = scenario
+ saved = one_pass_run(client, case)
+ _, pinned = kept(client, case, saved, title="Tanker")
+ _forget_dates(case, pinned)
+
+ assert analysis_dating.backfill(case) == 1
+ claim = analysis_dating.standing(case, saved["id"], saved["results"][0]["id"])
+ assert claim["attrs"]["when"] == DAY_B
+ assert links_of(case, claim["id"], "at") == [pinned["entity"]["id"]]
+ assert media.read_item(case, pinned["image"])["source"]["imagery_date"] == DAY_B
+ assert analysis_dating.backfill(case) == 0
+
+
+def test_backfill_leaves_a_change_picture_undated_since_its_shape_was_not_kept(client, scenario):
+ case, body = scenario
+ saved = run(client, case, body)
+ _, pinned = kept(client, case, saved)
+ _forget_dates(case, pinned)
+ assert analysis_dating.backfill(case) == 1
+ assert not any(k.startswith("imagery") for k in media.read_item(case, pinned["image"])["source"])
+
+
+def test_opening_a_case_from_an_earlier_build_dates_its_pins(client, scenario):
+ case, body = scenario
+ saved = run(client, case, body)
+ _, pinned = kept(client, case, saved)
+ _forget_dates(case, pinned)
+ manifest = case.read()
+ manifest["azimut"]["schema"] = workspace.WORK_SCHEMA
+ case._write_json(manifest)
+
+ opened = Case.open(case.id)
+ assert opened.read()["azimut"]["schema"] == workspace.CASE_SCHEMA
+ claim = analysis_dating.standing(opened, saved["id"], saved["results"][0]["id"])
+ assert claim["attrs"]["when"] == f"{DAY_A}/{DAY_B}"
+
+
+# -- the SAT layer -------------------------------------------------------------------
+
+
+def test_a_thing_on_one_pass_is_exported_on_that_day_alone(client, scenario):
+ case, _ = scenario
+ saved = one_pass_run(client, case)
+ kept(client, case, saved, title="Tanker")
+ exported = client.post(f"/api/cases/{case.id}/analysis/runs/{saved['id']}/export").json()
+ feature = json.loads(maplayers.drawing(case, exported["name"]).read_text())["features"][0]
+ assert feature["properties"]["date"] == DAY_B
+ assert "date_end" not in feature["properties"] and "pass_before" not in feature["properties"]
diff --git a/tests/test_detect_rework.py b/tests/test_detect_rework.py
index 7df8788..3352cc4 100644
--- a/tests/test_detect_rework.py
+++ b/tests/test_detect_rework.py
@@ -241,9 +241,14 @@ def test_export_snapshots_kept_candidates_with_pass_categories_and_replaces_a_pa
assert {c["name"] for c in updated["categories"]} == {"2026-05-11", "2026-05-18"}
assert client.post(second_url + "/export").json()["features"] == 2
drawing = json.loads(maplayers.drawing(case, updated["name"]).read_text())
- features = sorted(drawing["features"], key=lambda f: f["properties"]["date"])
+ features = sorted(drawing["features"], key=lambda f: f["properties"]["pass_date"])
assert int(features[0]["properties"]["colour"][1:3], 16) > int(features[1]["properties"]["colour"][1:3], 16)
assert all(f["properties"]["run_id"] and f["properties"]["area_name"] for f in features)
+ # A change spans the passes it was read between, which is what the layer's
+ # time filter compares; the day it was found stays its group.
+ assert [(f["properties"]["date"], f["properties"]["date_end"]) for f in features] == [
+ (body["a"]["date"], "2026-05-11"), (body["a"]["date"], "2026-05-18")]
+ assert all(f["properties"]["pass_before"] == body["a"]["date"] for f in features)
assert client.delete(first_url).status_code == 200
assert client.delete(second_url).status_code == 200
# Rebuild from the portable snapshot, without a run or the derived cache.
diff --git a/tests/test_detect_rules.py b/tests/test_detect_rules.py
new file mode 100644
index 0000000..b8d7147
--- /dev/null
+++ b/tests/test_detect_rules.py
@@ -0,0 +1,752 @@
+"""Analyzers of your own rules: the model, the band product, the evaluation,
+the sweep that runs it and the preview that tunes it.
+
+Scenes are built band by band in reflectance and written in the 16-bit layout
+the band evalscript returns (engine/sentinel.py), padded as the engine reads
+them, so what passes here is what a real frame would give.
+"""
+
+import base64
+import io
+
+import cv2
+import numpy as np
+import pytest
+from PIL import Image
+from pydantic import ValidationError
+
+from azimut import config
+from azimut.engine import analysis_geometry, analyzers, detect_rules, sentinel, tilecache, workqueue
+from azimut.engine.analysis_models import (
+ BUILTINS,
+ MAX_BANDS,
+ MAX_CHECKS,
+ MAX_MARKS,
+ Check,
+ Parameters,
+ Recipe,
+ Rule,
+ RunInput,
+ frames_for,
+ is_radar,
+ is_single,
+ recipe_products,
+)
+from azimut.workspace import Case
+from analyzerfixture import BARE, CLOUD, DARK, EDGE, SENTINEL_TILE, VEGETATION, WATER, at, put_picture, zone
+from test_radar_detect import LAYER, TIME, level
+
+DAY_A, DAY_B = "2026-05-04", "2026-05-11"
+LAT = 20.0
+
+
[email protected](autouse=True)
+def forget_decoded():
+ """Each test starts with no frame decoded: the cache it seeds is its own."""
+ detect_rules._DECODED.clear()
+ yield
+ detect_rules._DECODED.clear()
+
+# Green cover in every Sentinel-2 band, as a crop field reads in May.
+GREEN = {"B01": 0.04, "B02": 0.04, "B03": 0.07, "B04": 0.04, "B05": 0.10, "B06": 0.28,
+ "B07": 0.33, "B08": 0.38, "B8A": 0.39, "B09": 0.12, "B11": 0.20, "B12": 0.10}
+# The same ground cleared to bare soil.
+SOIL = {"B02": 0.12, "B03": 0.15, "B04": 0.19, "B08": 0.24, "B8A": 0.25, "B11": 0.32, "B12": 0.26}
+
+
+def scene(sky=VEGETATION, **bands):
+ values = {**GREEN, **bands}
+ frame = {band: np.full((EDGE, EDGE), value, np.float32) for band, value in values.items()}
+ frame["SCL"] = np.full((EDGE, EDGE), sky, np.uint16)
+ return frame
+
+
+def paint(frame, px, py, width, height, sky=None, **bands):
+ for band, value in bands.items():
+ frame[band][at(px, py, width, height)] = value
+ if sky is not None:
+ frame["SCL"][at(px, py, width, height)] = sky
+ return frame
+
+
+def product(frame, name):
+ """A frame as `_bands_evalscript` writes it."""
+ out = np.zeros((EDGE, EDGE, 4), np.uint16)
+ for channel, band in enumerate(sentinel.product_bands(name)):
+ out[..., channel] = np.clip(np.round(frame[band] * sentinel.BANDS_SCALE), 1 if channel == 0 else 0, 65535)
+ out[..., 3] = frame["SCL"] + np.where(frame["B08"] < sentinel.DARK_REFLECTANCE, DARK, 0)
+ return out
+
+
+def png16(pixels):
+ ok, encoded = cv2.imencode(".png", np.ascontiguousarray(pixels[..., [2, 1, 0, 3]]))
+ assert ok
+ return encoded.tobytes()
+
+
+def recipe(*rules, **fields):
+ parameters = {"min_area": 0, "max_area": 0, "cleanup": 0, "smoothing": 0, "merge_metres": 0,
+ **fields.pop("parameters", {})}
+ fields.setdefault("name", "Mine")
+ return Recipe(method="rules", rules=[Rule(**rule) for rule in rules],
+ parameters=Parameters(**parameters), **fields)
+
+
+def evaluate(built, before, after, mask=None):
+ products = {name: (product(before, name), product(after, name)) for name in recipe_products(built)}
+ return detect_rules.evaluate(products, np.ones((512, 512), np.uint8) if mask is None else mask,
+ built, (DAY_A, DAY_B), LAT)
+
+
+def labels(binary):
+ return cv2.connectedComponents(binary.astype(np.uint8), connectivity=8)[0] - 1
+
+
+LOSS = {"measure": "index", "index": "ndvi", "on": "change", "op": "le", "value": -0.2}
+GREEN_BEFORE = {"measure": "index", "index": "ndvi", "on": "a", "op": "ge", "value": 0.5}
+
+
+# -- the model -------------------------------------------------------------------------
+
+
[email protected]("rule, reason", [
+ ({"measure": "class", "classes": ["water"], "on": "b", "op": "ge"}, "is or is not"),
+ ({"measure": "class", "classes": ["water"], "on": "change", "op": "is"}, "one date"),
+ ({"measure": "class", "classes": [], "on": "b", "op": "is"}, "at least one"),
+ ({"measure": "index", "on": "b", "op": "is"}, "ground classes"),
+ ({"measure": "index", "on": "b", "op": "moved", "value": 0.1}, "compares two dates"),
+ ({"measure": "colour", "on": "b", "op": "ge"}, "compares two dates"),
+ ({"measure": "index", "on": "b", "op": "between", "value": 0.3, "upper": 0.2}, "upper bound"),
+ ({"measure": "nd", "bands": ["B08", "B08"], "on": "b"}, "two different bands"),
+ ({"measure": "band", "band": "B10", "on": "b"}, None),
+ ({"measure": "index", "on": "b", "around": 301}, None),
+])
+def test_a_rule_that_says_nothing_coherent_is_refused(rule, reason):
+ with pytest.raises(ValidationError, match=reason):
+ Rule(**rule)
+
+
+def test_only_an_analyzer_of_your_own_carries_rules_and_it_needs_one():
+ with pytest.raises(ValidationError, match="only an analyzer of your own"):
+ Recipe(name="x", method="surface", rules=[Rule(**LOSS)])
+ with pytest.raises(ValidationError, match="at least one rule"):
+ Recipe(name="x", method="rules")
+ with pytest.raises(ValidationError):
+ Recipe(name="x", method="rules", rules=[Rule(**LOSS)] * 7)
+ radar = {"measure": "radar", "on": "change", "op": "le", "value": -3}
+ with pytest.raises(ValidationError, match="two satellites"):
+ Recipe(name="x", method="rules", rules=[Rule(**LOSS), Rule(**radar)])
+ with pytest.raises(ValidationError, match="ground classes come from Sentinel-2"):
+ Recipe(name="x", method="rules", rules=[Rule(**radar), Rule(measure="class", classes=["water"], op="is")])
+ many = [Rule(measure="nd", bands=pair, on="b") for pair in
+ (("B01", "B02"), ("B03", "B04"), ("B05", "B06"), ("B07", "B08"))]
+ assert len({band for rule in many for band in rule.bands_read()}) > MAX_BANDS
+ with pytest.raises(ValidationError, match="at most"):
+ Recipe(name="x", method="rules", rules=many)
+ # built-ins keep saying what they always said
+ assert all(not r.rules and r.match == "all" and r.parameters.shape == "any" for r in BUILTINS)
+
+
+def test_what_a_recipe_reads_follows_from_its_rules():
+ change = recipe(LOSS, GREEN_BEFORE)
+ assert not is_single(change) and not is_radar(change)
+ assert recipe_products(change) == ["bands-B04-B08"]
+ assert frames_for(change) == 4 # picture and one product, on each date
+ present = recipe({"measure": "band", "band": "B12", "on": "b", "op": "ge", "value": 0.3},
+ {"measure": "index", "index": "bsi", "on": "b", "op": "ge", "value": 0})
+ assert is_single(present)
+ assert recipe_products(present) == ["bands-B02-B04-B08", "bands-B11-B12"]
+ assert frames_for(present) == 3 # one date: its picture and two products
+ classes = recipe({"measure": "class", "classes": ["water"], "on": "b", "op": "is"})
+ assert recipe_products(classes) == ["bands-B08"]
+ radar = recipe({"measure": "radar", "polarisation": "ratio", "on": "change", "op": "moved", "value": 3})
+ assert is_radar(radar) and recipe_products(radar) == ["sar"]
+ # stored runs are dictionaries: the same answers, from the saved shape
+ assert is_single(present.model_dump()) and is_radar(radar.model_dump())
+
+
+# -- the band product -------------------------------------------------------------------
+
+
+def test_a_band_product_names_known_bands_in_the_collections_order_and_nothing_else():
+ assert sentinel.band_product(["B11", "B04"]) == "bands-B04-B11"
+ assert sentinel.product_bands("bands-B04-B11") == ("B04", "B11")
+ for bad in ("bands-B11-B04", "bands-B10", "bands-B04-B04", "bands-B02-B03-B04-B08",
+ "bands-B04;alert(1)", "bands-", "bands-b04"):
+ assert sentinel.product_bands(bad) == ()
+ assert not sentinel.is_product(bad)
+ with pytest.raises(ValueError):
+ sentinel.band_product(["B04", "B02", "B03", "B08"])
+ script = base64.b64decode(sentinel._evalscript("bands-B02-B04-B08")).decode("ascii")
+ assert 'sampleType: "UINT16"' in script
+ assert '"B02", "B04", "B08", "SCL", "dataMask"' in script
+ assert f"* {sentinel.BANDS_SCALE}" in script
+ with pytest.raises(ValueError, match="unknown band product"):
+ sentinel.band_frame("inst", (0, 0, 10, 10), 8, 8, DAY_B, "bands-B10")
+
+
+def test_a_sixteen_bit_frame_decodes_without_losing_its_precision():
+ frame = scene()
+ frame["B04"][:] = 0.0123
+ raw = png16(product(frame, "bands-B04-B08"))
+ with Image.open(io.BytesIO(raw)) as image:
+ assert image.format == "PNG" # what band_frame checks on arrival
+ pixels = analyzers.decode_product(raw, EDGE, "bands-B04-B08")
+ assert pixels.dtype == np.uint16
+ assert pixels[0, 0, 0] == 123 and pixels[0, 0, 1] == 3800
+ with pytest.raises(ValueError):
+ analyzers.decode_product(raw, EDGE - 1, "bands-B04-B08")
+
+
+# -- the evaluation ---------------------------------------------------------------------
+
+
+def test_a_loss_on_ground_that_was_green_is_found_and_ranked_by_its_first_test():
+ before = scene()
+ after = paint(scene(), 100, 100, 40, 30, sky=BARE, **SOIL)
+ paint(before, 300, 300, 30, 30, B04=0.12, B08=0.20) # already bare in May
+ paint(after, 300, 300, 30, 30, B04=0.20, B08=0.20) # and barer since
+ evaluation = evaluate(recipe(LOSS, GREEN_BEFORE), before, after)
+ binary = evaluation.reading.binary
+ assert labels(binary) == 1
+ assert binary[110, 110] and not binary[310, 310]
+ # the second rule is what spared the patch that was never green
+ assert evaluation.passes[0][310, 310] and not evaluation.passes[1][310, 310]
+ stat = evaluation.reading.stat
+ # NDVI 0.81 → 0.12 is 0.69 past a 0.2 line: nearly five units, Strong
+ assert stat[110, 110] > 3
+ assert evaluation.reading.measures["before"][0][110, 110] == pytest.approx(0.81, abs=0.01)
+ assert evaluation.reading.measures["signed"][0][110, 110] == pytest.approx(-0.69, abs=0.01)
+
+
+def test_any_keeps_what_one_rule_alone_would_keep():
+ before, after = scene(), scene()
+ paint(after, 50, 50, 20, 20, B04=0.20, B08=0.24) # lost its green
+ paint(after, 300, 300, 20, 20, B11=0.45, B12=0.40) # got hot and bright
+ hot = {"measure": "band", "band": "B12", "on": "b", "op": "ge", "value": 0.3}
+ assert labels(evaluate(recipe(LOSS, hot), before, after).reading.binary) == 0
+ assert labels(evaluate(recipe(LOSS, hot, match="any"), before, after).reading.binary) == 2
+
+
+def test_a_ground_class_rule_reads_the_scene_classification_of_its_date():
+ before, after = scene(), scene()
+ paint(after, 60, 60, 30, 30, sky=WATER, B08=0.02, B04=0.03)
+ flooded = recipe({"measure": "class", "classes": ["water"], "on": "b", "op": "is"},
+ {"measure": "class", "classes": ["water"], "on": "a", "op": "not"})
+ binary = evaluate(flooded, before, after).reading.binary
+ assert labels(binary) == 1 and binary[70, 70]
+
+
+def test_brighter_than_its_surroundings_holds_on_dark_and_bright_ground_alike():
+ after = scene()
+ after["B08"][:] = np.linspace(0.05, 0.45, EDGE, dtype=np.float32) # dark sea to bright sand
+ for px in (60, 440):
+ region = after["B08"][at(px, 200, 4, 4)]
+ region += 0.10 # a small thing on each
+ standing = recipe({"measure": "band", "band": "B08", "on": "b", "op": "ge", "value": 0.08, "around": 150})
+ assert is_single(standing)
+ binary = evaluate(standing, after, after).reading.binary
+ assert binary[201, 61] and binary[201, 441]
+ assert labels(binary) == 2 # the gradient itself stands out nowhere
+ absolute = recipe({"measure": "band", "band": "B08", "on": "b", "op": "ge", "value": 0.3})
+ found = evaluate(absolute, after, after).reading.binary
+ assert not found[201, 61] and found[300, 400] # one line cannot hold both
+
+
+def test_a_colour_change_is_distance_in_the_visible_bands_and_ignores_light():
+ before = scene()
+ after = scene(B02=0.06, B03=0.09, B04=0.06) # the whole scene 2% lighter
+ paint(after, 200, 200, 20, 20, B02=0.20, B03=0.21, B04=0.22) # a new roof
+ moved = recipe({"measure": "colour", "on": "change", "op": "ge", "value": 0.05})
+ binary = evaluate(moved, before, after).reading.binary
+ assert labels(binary) == 1 and binary[210, 210]
+
+
+def test_between_keeps_a_band_of_values():
+ after = scene()
+ paint(after, 20, 20, 10, 10, B04=0.10, B08=0.20) # NDVI 0.33
+ paint(after, 200, 20, 10, 10, B04=0.30, B08=0.31) # NDVI 0.02
+ middle = recipe({"measure": "index", "index": "ndvi", "on": "b", "op": "between", "value": 0.2, "upper": 0.5})
+ binary = evaluate(middle, after, after).reading.binary
+ assert binary[25, 25] and not binary[25, 205] and not binary[300, 300]
+
+
+def test_a_change_under_cloud_on_either_date_is_not_measured():
+ before = paint(scene(), 100, 100, 200, 200, sky=CLOUD)
+ after = paint(scene(), 150, 150, 40, 40, sky=BARE, **SOIL)
+ evaluation = evaluate(recipe(LOSS), before, after)
+ assert not evaluation.reading.binary.any()
+ assert not evaluation.measured[160, 160]
+ open_sky = recipe(LOSS, parameters={"ignore_clouds": False, "ignore_shadows": False})
+ assert evaluate(open_sky, before, after).reading.binary[160, 160]
+
+
+def test_smoothing_never_spreads_a_reading_into_ground_the_sensor_did_not_see():
+ before, after = scene(), scene()
+ paint(after, 100, 100, 30, 30, B04=0.20, B08=0.24)
+ smoothed = recipe(LOSS, parameters={"smoothing": 3})
+ mask = np.ones((512, 512), np.uint8)
+ mask[:, 120:] = 0 # the area stops across the patch
+ evaluation = evaluate(smoothed, before, after, mask)
+ assert evaluation.reading.binary[110, 110]
+ assert not evaluation.reading.binary[:, 120:].any()
+
+
+def test_radar_rules_average_speckle_as_power_and_read_both_passes():
+ rng = np.random.default_rng(4)
+ shape = (EDGE, EDGE)
+
+ def pass_(vv, vh):
+ frame = np.zeros((EDGE, EDGE, 4), np.uint8)
+ frame[..., 0] = level(vv + rng.normal(0, 1.5, shape))
+ frame[..., 1] = level(vh + rng.normal(0, 1.5, shape))
+ frame[..., 3] = 255
+ return frame
+
+ vv_before, vv_after = np.full(shape, -2.0), np.full(shape, -2.0)
+ vv_after[at(200, 200, 60, 60)] = -12.0 # walls gone quiet
+ razed = recipe({"measure": "radar", "polarisation": "vv", "on": "change", "op": "le", "value": -6},
+ {"measure": "radar", "polarisation": "vv", "on": "a", "op": "ge", "value": -4})
+ products = {"sar": (pass_(vv_before, np.full(shape, -9.0)), pass_(vv_after, np.full(shape, -9.0)))}
+ evaluation = detect_rules.evaluate(products, np.ones((512, 512), np.uint8), razed, (DAY_A, DAY_B), LAT)
+ binary = evaluation.reading.binary
+ assert binary[230, 230]
+ assert labels(binary) == 1
+ assert evaluation.reading.measures["signed"][0][230, 230] < -8
+
+
+def test_the_shape_filter_tells_a_track_from_a_roof():
+ square = {"type": "Polygon", "coordinates": [[[0, 0], [0.001, 0], [0.001, 0.001], [0, 0.001], [0, 0]]]}
+ track = {"type": "Polygon", "coordinates": [[[0, 0], [0.01, 0.0099], [0.0101, 0.01], [0.0001, 0.0001], [0, 0]]]}
+ assert analysis_geometry.elongation(square) == pytest.approx(1, abs=0.05)
+ assert analysis_geometry.elongation(track) > 10
+ row = {"area": 10_000}
+ compact = Parameters(shape="compact")
+ elongated = Parameters(shape="elongated")
+ assert analyzers.keeps({**row, "geometry": square}, compact)
+ assert not analyzers.keeps({**row, "geometry": track}, compact)
+ assert analyzers.keeps({**row, "geometry": track}, elongated)
+ assert not analyzers.keeps({**row, "geometry": square}, elongated)
+ assert analyzers.keeps({**row, "geometry": track}, Parameters())
+
+
+# -- sweeps --------------------------------------------------------------------------------
+
+
+def offline(client, monkeypatch):
+ monkeypatch.setattr(workqueue, "start_workers", False)
+ ident = client.post("/api/cases", json={"name": "Rules of my own"}).json()["id"]
+
+ def forbidden(*args, **kwargs):
+ raise AssertionError("unexpected network")
+
+ monkeypatch.setattr(analyzers.httpx, "stream", forbidden)
+ monkeypatch.setattr(analyzers.sentinel, "band_frame", forbidden)
+ monkeypatch.setattr(analyzers.sentinel, "acquisitions", forbidden)
+ return Case.open(ident)
+
+
+def sweep_body(built, maxcc=30):
+ source = lambda day: {"provider": "sentinel2", "date": day, "layer": "TRUE_COLOR", "maxcc": maxcc} # noqa: E731
+ return {"title": "My sweep", "recipe": built.model_dump(), "zones": [zone()],
+ "a": source(DAY_A), "b": source(DAY_B), "offline": True}
+
+
+def seed_frames(body, before, after, tile=SENTINEL_TILE, pictures=True):
+ parsed = RunInput.model_validate(body)
+ z, x, y = tile
+ for letter, frame in (("a", before), ("b", after)):
+ source = parsed.a if letter == "a" else parsed.b
+ if pictures:
+ put_picture(body[letter], tile)
+ for name in recipe_products(parsed.recipe):
+ tilecache.put(analyzers.product_cache_id(source, name), z, x, y, png16(product(frame, name)),
+ "image/png")
+
+
+def cleared():
+ before = scene()
+ after = paint(scene(), 150, 150, 40, 30, sky=BARE, **SOIL)
+ return before, after
+
+
+def test_a_sweep_of_your_own_rules_finds_keeps_its_frames_and_says_what_it_read(client, offline):
+ case = offline
+ body = sweep_body(recipe(LOSS, GREEN_BEFORE))
+ seed_frames(body, *cleared())
+ started = client.post(f"/api/cases/{case.id}/analysis/runs", json=body)
+ assert started.status_code == 200, started.text
+ workqueue.drain(case)
+ saved = client.get(f"/api/cases/{case.id}/analysis/runs/{started.json()['id']}").json()
+ assert saved["status"] == "ready", saved
+ assert saved["count"] == 1
+ row = saved["results"][0]
+ assert row["strength"] == "strong"
+ assert row["measure"]["before"] == pytest.approx(0.81, abs=0.01)
+ assert row["measure"]["after"] == pytest.approx(0.12, abs=0.01)
+ # the 16-bit product is kept as it came, next to the pictures reviewed
+ products = [frame for frame in saved["frames"].values() if frame["index"]]
+ assert [frame["index"] for frame in products] == ["bands-B04-B08"] * 2
+ kept = case.resolve_inside(products[0]["path"]).read_bytes()
+ assert cv2.imdecode(np.frombuffer(kept, np.uint8), cv2.IMREAD_UNCHANGED).dtype == np.uint16
+ preview = client.get(f"/api/cases/{case.id}/analysis/runs/{saved['id']}/results/{row['id']}/preview")
+ assert preview.content.startswith(b"\x89PNG")
+ listed = client.get(f"/api/cases/{case.id}/analysis/runs").json()[0]
+ assert listed["method"] == "rules" and listed["single"] is False
+
+
+def test_rules_on_one_date_run_without_a_reference(client, offline):
+ case = offline
+ after = paint(scene(), 200, 200, 10, 10, B11=0.45, B12=0.42)
+ body = sweep_body(recipe({"measure": "band", "band": "B12", "on": "b", "op": "ge", "value": 0.3}))
+ body["a"]["date"] = ""
+ seed_frames(body, after, after)
+ started = client.post(f"/api/cases/{case.id}/analysis/runs", json=body)
+ assert started.status_code == 200, started.text
+ workqueue.drain(case)
+ saved = client.get(f"/api/cases/{case.id}/analysis/runs/{started.json()['id']}").json()
+ assert saved["status"] == "ready" and saved["count"] == 1
+ assert {frame["source"]["date"] for frame in saved["frames"].values()} == {DAY_B}
+
+
+def test_the_shape_filter_applies_to_a_sweep(client, offline):
+ case = offline
+ before = scene()
+ after = scene()
+ paint(after, 50, 50, 30, 30, B04=0.20, B08=0.24) # a cleared plot
+ paint(after, 200, 300, 200, 4, B04=0.20, B08=0.24) # a new track
+ for shape, expected in (("compact", (65, 65)), ("elongated", (302, 300))):
+ body = sweep_body(recipe(LOSS, parameters={"shape": shape}))
+ body["title"] = shape
+ seed_frames(body, before, after)
+ started = client.post(f"/api/cases/{case.id}/analysis/runs", json=body)
+ workqueue.drain(case)
+ saved = client.get(f"/api/cases/{case.id}/analysis/runs/{started.json()['id']}").json()
+ assert saved["count"] == 1, (shape, saved)
+ west, south, east, north = saved["results"][0]["bbox"]
+ z, x, y = SENTINEL_TILE
+ cx, cy = analyzers.mercator((west + east) / 2, (south + north) / 2)
+ pixel = ((cx * 2**z - x) * 512, (cy * 2**z - y) * 512)
+ assert pixel == pytest.approx(expected, abs=3), shape
+
+
+# -- the preview ---------------------------------------------------------------------------
+
+
+def tile_bounds(tile=SENTINEL_TILE, inset=0.2):
+ z, x, y = tile
+ west, north = analyzers.geographic((x + inset) / 2**z, (y + inset) / 2**z)
+ east, south = analyzers.geographic((x + 1 - inset) / 2**z, (y + 1 - inset) / 2**z)
+ return {"west": west, "south": south, "east": east, "north": north}
+
+
+def preview_body(built, **extra):
+ return {"recipe": built.model_dump(), "a": {"date": DAY_A}, "b": {"date": DAY_B},
+ "bounds": tile_bounds(), **extra}
+
+
+def test_a_preview_reads_only_the_cache_and_says_what_reading_the_rest_would_cost(client, offline):
+ built = recipe(LOSS, GREEN_BEFORE)
+ answer = client.post("/api/compare/analyzers/preview", json=preview_body(built))
+ assert answer.status_code == 200, answer.text
+ body = answer.json()
+ assert body["ready"] is False
+ assert body["missing"] == 2 # one product on each date, over one tile
+ assert body["tiles"] == [list(SENTINEL_TILE[1:])] and body["clipped"] is False
+
+
+def test_reading_fetches_what_is_missing_meters_it_and_then_previews(client, offline, monkeypatch):
+ built = recipe(LOSS, GREEN_BEFORE, parameters={"merge_metres": 30})
+ before, after = cleared()
+ config.update_settings(lambda settings: settings.setdefault("api_keys", {}).update(sentinelhub="inst"))
+ asked = []
+
+ def band_frame(instance, box, width, height, day, name, maxcc, *, layer, time=""):
+ asked.append((day, name, maxcc, layer))
+ assert (width, height) == (EDGE, EDGE)
+ return png16(product(before if day == DAY_A else after, name))
+
+ monkeypatch.setattr(detect_rules.sentinel, "band_frame", band_frame)
+ usage = config.month_usage("sentinelhub")
+ answer = client.post("/api/compare/analyzers/preview", json=preview_body(built, read=True)).json()
+ assert sorted(asked) == [(DAY_A, "bands-B04-B08", 100, "TRUE_COLOR"), (DAY_B, "bands-B04-B08", 100, "TRUE_COLOR")]
+ assert config.month_usage("sentinelhub") == usage + 2
+ assert answer["ready"] is True and answer["missing"] == 0
+ assert answer["count"] == 1
+ candidate = answer["candidates"][0]
+ assert candidate["strength"] == "strong" and "parts" not in candidate
+ # both rules passed on the cleared plot; the second on all the green around it
+ first, second = answer["rules"]
+ assert first["share"] == pytest.approx(1200 / 512**2, rel=0.01)
+ assert second["share"] == pytest.approx(1.0, abs=0.01)
+ assert second["kept"] == pytest.approx(first["share"], rel=0.01)
+ mask = np.array(Image.open(io.BytesIO(base64.b64decode(answer["mask"]))))
+ assert mask.shape == (512, 512)
+ assert mask[160, 160] == 0b11000011 # measured, kept, both rules
+ assert mask[10, 10] == 0b01000010 # measured, green before, nothing lost
+ # moving a slider re-reads the cache and fetches nothing more
+ stricter = recipe({**LOSS, "value": -0.8}, GREEN_BEFORE)
+ again = client.post("/api/compare/analyzers/preview", json=preview_body(stricter)).json()
+ assert again["ready"] and again["count"] == 0 and len(asked) == 2
+
+ point = analyzers.geographic((SENTINEL_TILE[1] + 160.5 / 512) / 2**13, (SENTINEL_TILE[2] + 160.5 / 512) / 2**13)
+ probed = client.post("/api/compare/analyzers/probe", json={**preview_body(built), "point": list(point)}).json()
+ assert probed["ready"] and probed["measured"] and probed["kept"]
+ loss, green = probed["rules"]
+ assert loss["passes"] and loss["before"] == pytest.approx(0.81, abs=0.01)
+ assert loss["value"] == pytest.approx(-0.69, abs=0.01)
+ assert green["passes"] and green["before"] is None and green["value"] == pytest.approx(0.81, abs=0.01)
+
+
+def test_a_preview_finds_what_a_sweep_of_the_same_tiles_finds(client, offline):
+ """The builder's promise: what it shows is what a run returns."""
+ case = offline
+ built = recipe(LOSS, GREEN_BEFORE, parameters={"merge_metres": 30, "cleanup": 1, "min_area": 3000})
+ before, after = cleared()
+ paint(after, 400, 60, 6, 6, B04=0.20, B08=0.24) # too small to keep
+ body = sweep_body(built)
+ body["zones"] = [zone(0, 0, 1, 1)]
+ seed_frames(body, before, after)
+ seed_frames(sweep_body(built, maxcc=100), before, after, pictures=False)
+ started = client.post(f"/api/cases/{case.id}/analysis/runs", json=body)
+ workqueue.drain(case)
+ run = client.get(f"/api/cases/{case.id}/analysis/runs/{started.json()['id']}").json()
+ shown = client.post("/api/compare/analyzers/preview", json=preview_body(built)).json()
+ assert run["count"] == shown["count"] == 1
+ assert run["results"][0]["bbox"] == pytest.approx(shown["candidates"][0]["bbox"])
+ assert run["results"][0]["margin"] == shown["candidates"][0]["margin"]
+
+
+def test_a_wide_view_previews_the_three_tiles_around_its_middle():
+ z = analyzers.GRID[0]
+ x, y = SENTINEL_TILE[1:]
+ west, north = analyzers.geographic((x - 3) / 2**z, (y - 3) / 2**z)
+ east, south = analyzers.geographic((x + 4) / 2**z, (y + 4) / 2**z)
+ tiles, clipped = detect_rules.preview_tiles((west, south, east, north))
+ assert clipped and len(tiles) == 9
+ assert (x, y) in tiles
+ with pytest.raises(ValueError, match="antimeridian"):
+ detect_rules.preview_tiles((179, 0, -179, 1))
+
+
+def test_a_preview_needs_its_passes_and_refuses_a_built_in(client, offline):
+ built = recipe(LOSS)
+ missing_a = client.post("/api/compare/analyzers/preview", json={**preview_body(built), "a": {"date": ""}})
+ assert missing_a.status_code == 422 and "reference" in missing_a.text
+ builtin = next(r for r in BUILTINS if r.id == "large-change").model_dump()
+ refused = client.post("/api/compare/analyzers/preview", json={**preview_body(built), "recipe": builtin})
+ assert refused.status_code == 422
+
+
+def test_a_radar_preview_reads_the_users_layer_and_holds_one_track(client, offline):
+ client.put("/api/settings/prefs", json={"sentinel1_layer": LAYER})
+ radar = recipe({"measure": "radar", "on": "change", "op": "moved", "value": 3})
+ body = {**preview_body(radar), "a": {"date": DAY_A, "time": TIME}, "b": {"date": DAY_B, "time": "17:40:00"}}
+ crossed = client.post("/api/compare/analyzers/preview", json=body)
+ assert crossed.status_code == 422 and "track" in crossed.text
+ same = client.post("/api/compare/analyzers/preview",
+ json={**body, "b": {"date": DAY_B, "time": TIME}}).json()
+ assert same["missing"] == 2 and same["ready"] is False
+
+
+# -- built-ins as rules ----------------------------------------------------------------------
+
+
+def test_an_index_built_in_opens_as_the_rules_it_applies():
+ burn = next(r for r in BUILTINS if r.id == "burn-scars")
+ converted = Recipe.model_validate(detect_rules.index_as_rules(burn))
+ assert converted.method == "rules" and converted.id == "custom"
+ first, *rest = converted.rules
+ assert (first.measure, first.index, first.on, first.op, first.value) == ("index", "nbr", "change", "le", -0.27)
+ assert [(t.on, t.op) for t in rest] == [("a", "ge"), ("b", "le"), ("b", "le")]
+ assert rest[-1].measure == "band" and rest[-1].band == "B08" # a burn ends dark
+ water = Recipe.model_validate(detect_rules.index_as_rules(next(r for r in BUILTINS if r.id == "new-water")))
+ assert water.rules[0].op == "ge" and water.rules[0].value == 0.25
+ assert detect_rules.index_as_rules(next(r for r in BUILTINS if r.id == "boats")) is None
+
+
+def test_the_catalogue_offers_the_rules_vocabulary_and_the_convertible_built_ins(client):
+ catalogue = client.get("/api/compare/analyzers").json()
+ assert catalogue["rules"]["bands"] == list(sentinel.L2A_BANDS)
+ assert "water" in catalogue["rules"]["classes"]
+ assert set(catalogue["as_rules"]) == {"burn-scars", "vegetation-loss", "new-water"}
+ assert any(method["id"] == "rules" and method["rules"] for method in catalogue["methods"])
+
+
+def test_an_analyzer_of_your_own_is_saved_for_every_case_and_carried_by_the_backup(client):
+ built = recipe(LOSS, GREEN_BEFORE, name="Cleared forest")
+ saved = client.post("/api/compare/analyzers", json=built.model_dump()).json()
+ assert saved["id"].startswith("custom-")
+ listed = client.get("/api/compare/analyzers").json()["custom"]
+ assert listed[0]["rules"][0]["value"] == -0.2
+ exported = client.get("/api/settings/export").json()
+ assert "Cleared forest" in str(exported)
+
+
+def test_a_view_half_read_is_judged_where_it_is_held(client, offline):
+ """Panning off the frames already read keeps the detections on them live."""
+ built = recipe(LOSS, GREEN_BEFORE)
+ before, after = cleared()
+ seed_frames(sweep_body(built, maxcc=100), before, after, pictures=False)
+ z, x, y = SENTINEL_TILE
+ west, north = analyzers.geographic((x + 0.5) / 2**z, (y + 0.2) / 2**z)
+ east, south = analyzers.geographic((x + 1.5) / 2**z, (y + 0.8) / 2**z)
+ body = {**preview_body(built), "bounds": {"west": west, "south": south, "east": east, "north": north}}
+ answer = client.post("/api/compare/analyzers/preview", json=body).json()
+ assert answer["tiles"] == [[x, y], [x + 1, y]]
+ assert answer["ready"] is True and answer["missing"] == 2 and answer["count"] == 1
+ mask = np.array(Image.open(io.BytesIO(base64.b64decode(answer["mask"]))))
+ assert mask.shape == (512, 1024)
+ assert mask[160, 160] & (1 << detect_rules.KEPT_BIT)
+ assert not mask[:, 512:].any() # the unread tile is left blank, not guessed
+
+
+# -- checks --------------------------------------------------------------------------------
+
+
+def pixel_point(px, py, tile=SENTINEL_TILE):
+ z, x, y = tile
+ return list(analyzers.geographic((x + (px + .5) / 512) / 2**z, (y + (py + .5) / 512) / 2**z))
+
+
+PLOT = pixel_point(165, 165) # inside the plot `cleared` clears
+STANDING = pixel_point(400, 400) # green on both dates
+
+
+def check_body(marks, **extra):
+ return {"id": "plot", "name": "The cleared plot", "a": {"date": DAY_A}, "b": {"date": DAY_B},
+ "bounds": tile_bounds(), "marks": marks, **extra}
+
+
+def test_a_check_is_a_place_its_passes_and_its_marks():
+ found = {"point": PLOT, "expect": "found"}
+ check = Check.model_validate(check_body([found]))
+ assert check.marks[0].expect == "found" and check.result is None
+ with pytest.raises(ValidationError, match="dated pass B"):
+ Check.model_validate(check_body([], b={"date": ""}))
+ with pytest.raises(ValidationError, match="antimeridian"):
+ Check.model_validate(check_body([], bounds={"west": 179, "south": 0, "east": -179, "north": 1}))
+ with pytest.raises(ValidationError, match="match its marks"):
+ Check.model_validate(check_body([found], result={"signature": "abc", "count": 1, "covered": [True, False]}))
+ with pytest.raises(ValidationError):
+ Check.model_validate(check_body([{"point": [200, 0], "expect": "found"}]))
+ with pytest.raises(ValidationError):
+ Check.model_validate(check_body([found] * (MAX_MARKS + 1)))
+ # checks belong to rules of your own, one id each
+ with pytest.raises(ValidationError, match="rules and checks"):
+ Recipe(name="x", method="surface", checks=[check])
+ with pytest.raises(ValidationError, match="unique"):
+ recipe(LOSS, checks=[check, check])
+ with pytest.raises(ValidationError):
+ recipe(LOSS, checks=[check.model_copy(update={"id": f"c{i}"}) for i in range(MAX_CHECKS + 1)])
+
+
+def test_a_check_reads_the_cache_then_what_it_lacks_and_says_what_came_out_on_each_mark(client, offline, monkeypatch):
+ built = recipe(LOSS, GREEN_BEFORE)
+ marks = [{"point": PLOT, "expect": "found"}, {"point": STANDING, "expect": "empty"}]
+ body = {"recipe": built.model_dump(), "check": check_body(marks)}
+ unread = client.post("/api/compare/analyzers/check", json=body)
+ assert unread.status_code == 200, unread.text
+ assert unread.json() == {"ready": False, "missing": 2}
+
+ before, after = cleared()
+ config.update_settings(lambda settings: settings.setdefault("api_keys", {}).update(sentinelhub="inst"))
+ asked = []
+
+ def band_frame(instance, box, width, height, day, name, maxcc, *, layer, time=""):
+ asked.append((day, name))
+ return png16(product(before if day == DAY_A else after, name))
+
+ monkeypatch.setattr(detect_rules.sentinel, "band_frame", band_frame)
+ usage = config.month_usage("sentinelhub")
+ read = client.post("/api/compare/analyzers/check", json={**body, "read": True}).json()
+ assert sorted(asked) == [(DAY_A, "bands-B04-B08"), (DAY_B, "bands-B04-B08")]
+ assert config.month_usage("sentinelhub") == usage + 2
+ assert read == {"ready": True, "missing": 0, "count": 1, "covered": [True, False]}
+ # a stricter line loses the plot, read again from the cache alone
+ stricter = {**body, "recipe": recipe({**LOSS, "value": -0.8}, GREEN_BEFORE).model_dump()}
+ assert client.post("/api/compare/analyzers/check", json=stricter).json()["covered"] == [False, False]
+ # a line so loose it takes the standing forest flags the empty mark
+ loose = {**body, "recipe": recipe({**LOSS, "value": 0.5}).model_dump()}
+ assert client.post("/api/compare/analyzers/check", json=loose).json()["covered"] == [True, True]
+ assert len(asked) == 2
+ # a built-in has no checks to rerun
+ builtin = next(r for r in BUILTINS if r.id == "large-change").model_dump()
+ assert client.post("/api/compare/analyzers/check", json={**body, "recipe": builtin}).status_code == 422
+
+
+def test_a_check_reads_the_tiles_under_its_marks_or_else_its_view():
+ z, x, y = SENTINEL_TILE
+ far = pixel_point(100, 100, (z, x + 2, y))
+ marked = Check.model_validate(check_body([{"point": PLOT, "expect": "found"}, {"point": STANDING, "expect": "empty"},
+ {"point": far, "expect": "empty"}]))
+ assert detect_rules.check_tiles(marked) == [(x, y), (x + 2, y)]
+ assert detect_rules.check_tiles(Check.model_validate(check_body([]))) == [(x, y)]
+
+
+def test_a_check_without_marks_counts_what_its_view_gave(client, offline):
+ built = recipe(LOSS, GREEN_BEFORE)
+ seed_frames(sweep_body(built, maxcc=100), *cleared(), pictures=False)
+ answer = client.post("/api/compare/analyzers/check",
+ json={"recipe": built.model_dump(), "check": check_body([])}).json()
+ assert answer == {"ready": True, "missing": 0, "count": 1, "covered": []}
+
+
+def test_a_check_saved_on_other_passes_asks_to_be_saved_again(client, offline):
+ client.put("/api/settings/prefs", json={"sentinel1_layer": LAYER})
+ radar = recipe({"measure": "radar", "on": "change", "op": "moved", "value": 3})
+ answer = client.post("/api/compare/analyzers/check",
+ json={"recipe": radar.model_dump(), "check": check_body([{"point": PLOT, "expect": "found"}])})
+ assert answer.status_code == 422 and "saved on Sentinel-2 passes" in answer.text
+
+
+def test_a_mark_is_on_a_footprint_that_covers_it_or_passes_within_reach():
+ z, x, y = SENTINEL_TILE
+ square = np.zeros((20, 20), bool)
+ square[5:15, 5:15] = True
+ footprint = analysis_geometry.footprint(square, x, y, z, 512, (100, 100))
+ assert analysis_geometry.near(footprint, pixel_point(110, 110), 15)
+ assert analysis_geometry.near(footprint, pixel_point(115, 110), 15) # a pixel off its edge
+ assert not analysis_geometry.near(footprint, pixel_point(118, 110), 15)
+ holed = square.copy()
+ holed[8:12, 8:12] = False
+ ring = analysis_geometry.footprint(holed, x, y, z, 512, (100, 100))
+ assert not analysis_geometry.near(ring, pixel_point(110, 110), 0) # the hole is not the footprint
+
+
+def test_the_examples_are_whole_analyzers_whose_marks_sit_well_inside_their_tiles(client):
+ examples = client.get("/api/compare/analyzers").json()["examples"]
+ assert [example["id"] for example in examples] == ["burn", "clearing", "drained", "solar", "ships"]
+ z = analyzers.GRID[0]
+ for example in examples:
+ built = Recipe.model_validate(example["recipe"])
+ assert built.method == "rules" and built.checks, example["id"]
+ assert example["place"] and example["when"]
+ expects = {mark.expect for check in built.checks for mark in check.marks}
+ assert expects == {"found", "empty"}, example["id"] # something to find, and a trap
+ single = is_single(built)
+ tiles = set()
+ for check in built.checks:
+ assert bool(check.a.date) is not single, (example["id"], check.id)
+ if not single:
+ assert check.a.date < check.b.date
+ for mark in check.marks:
+ west, south, east, north = (check.bounds.west, check.bounds.south, check.bounds.east, check.bounds.north)
+ assert west < mark.point[0] < east and south < mark.point[1] < north, (example["id"], check.id)
+ gx, gy = analyzers.mercator(*mark.point)
+ px, py = (gx * 2**z % 1) * 512, (gy * 2**z % 1) * 512
+ assert 64 <= px <= 448 and 64 <= py <= 448, (example["id"], check.id)
+ tiles.update(detect_rules.check_tiles(check))
+ # running all of an example's checks stays a handful of requests
+ assert len(tiles) * len(recipe_products(built)) * (1 if single else 2) <= 16, example["id"]
+
+
+def test_an_example_copied_into_the_library_keeps_its_checks_and_the_backup_carries_them(client):
+ example = client.get("/api/compare/analyzers").json()["examples"][0]
+ saved = client.post("/api/compare/analyzers", json={**example["recipe"], "id": "custom"}).json()
+ assert saved["id"].startswith("custom-") and len(saved["checks"]) == len(example["recipe"]["checks"])
+ listed = client.get("/api/compare/analyzers").json()["custom"]
+ assert listed[0]["checks"][0]["name"] == example["recipe"]["checks"][0]["name"]
+ exported = client.get("/api/settings/export").json()
+ assert example["recipe"]["checks"][0]["name"] in str(exported)
diff --git a/tests/test_folder_adoption.py b/tests/test_folder_adoption.py
index 4078447..dd4ed18 100644
--- a/tests/test_folder_adoption.py
+++ b/tests/test_folder_adoption.py
@@ -2,7 +2,7 @@
from pathlib import Path
-from azimut import config, layout
+from azimut import config, layout, workspace
from azimut.workspace import Case
@@ -99,7 +99,8 @@ def test_a_folder_holding_a_case_that_lost_its_manifest_is_recovered_not_reborn(
assert folders(client) == {}
reopened = client.get(f"/api/cases/{case_id}").json()
assert reopened["name"] == "Lost manifest"
- assert reopened["azimut"]["schema"] == 9
+ # stamped low on recovery, then carried through every folder migration on open
+ assert reopened["azimut"]["schema"] == workspace.CASE_SCHEMA
notes = client.get(f"/api/cases/{case_id}/catalog/entities?type=note").json()
assert [n["label"] for n in notes["items"]] == ["Lead"]
diff --git a/tests/test_graph.py b/tests/test_graph.py
index ef426bf..2cc3f9b 100644
--- a/tests/test_graph.py
+++ b/tests/test_graph.py
@@ -168,7 +168,7 @@ 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", "compare-session", "post",
+ assert filing == {"note", "sheet", "inspect-session", "collage", "compare-session", "post",
"analysis-zones", "analysis-area", "analysis-follow-up", "analysis-run", "map-layer"}
for lens_id in ("all", "subjects", "ground", "claims"):
diff --git a/tests/test_inspect_api.py b/tests/test_inspect_api.py
index b377cb5..4c2afc4 100644
--- a/tests/test_inspect_api.py
+++ b/tests/test_inspect_api.py
@@ -679,32 +679,6 @@ def test_auto_stitch_needs_two_pieces(client):
assert res.status_code == 422
-def test_compose_preview_returns_png_without_filing(client):
- cid = client.post("/api/cases", json={"name": "Preview"}).json()["id"]
- a = _upload(client, cid, "a.png", _png_bytes(color=(10, 20, 30), size=(80, 60)))
- before = len(client.get(f"/api/cases/{cid}/media").json())
-
- res = client.post(
- f"/api/cases/{cid}/inspect/compose-preview",
- json={
- "width": 400, "height": 300, "background": None,
- "nodes": [
- {"src": {"path": a["path"]},
- "quad": [[20, 20], [120, 20], [120, 100], [20, 100]]},
- ],
- },
- )
- assert res.status_code == 200
- assert res.headers["content-type"] == "image/png"
- img = Image.open(io.BytesIO(res.content))
- # downscaled to max_dim=640 (so <= the 400x300 request) and transparent alpha
- assert img.mode == "RGBA"
- assert max(img.size) <= 640
- assert img.getpixel((0, 0))[3] == 0
- # nothing was filed to the case
- assert len(client.get(f"/api/cases/{cid}/media").json()) == before
-
-
def test_analyze_accepts_transient_ops_without_filing(client):
cid = client.post("/api/cases", json={"name": "AnalyzeOps"}).json()["id"]
item = _upload(client, cid, "img.png", _png_bytes(color=(255, 0, 0), size=(20, 20)))
@@ -802,176 +776,6 @@ def test_render_preview_applies_ops_without_filing(client):
assert len(client.get(f"/api/cases/{cid}/media").json()) == before # nothing filed
-def test_session_save_list_load_delete_roundtrip(client):
- cid = client.post("/api/cases", json={"name": "Session"}).json()["id"]
- item = _upload(client, cid, "clip.png")
- spec = {
- "source": {"path": item["path"], "kind": "image"},
- "videoAdjust": {},
- "frames": [{"id": "fr1", "path": item["path"], "time": None, "adjust": {"brightness": 1.4}, "crop": None}],
- "collage": {"width": 800, "height": 400, "background": "#101010", "nodes": []},
- }
- saved = client.post(
- f"/api/cases/{cid}/inspect/sessions", json={"title": "My session", "spec": spec}
- ).json()
- assert saved["name"] == "My session"
-
- listing = client.get(f"/api/cases/{cid}/inspect/sessions").json()
- assert len(listing) == 1 and listing[0]["title"] == "My session" and listing[0]["frames"] == 1
-
- # an inspect-session entity is upserted so it reopens from the sidebar
- entities = graph_read.entities(cid)
- ent = next(e for e in entities if e["type"] == "inspect-session")
- assert ent["attrs"]["spec"] == ".inspect/My session.json"
-
- loaded = client.get(f"/api/cases/{cid}/inspect/sessions/{saved['name']}").json()
- assert loaded["azimut_inspect"] == 1
- assert loaded["frames"][0]["adjust"]["brightness"] == 1.4
-
- # re-saving under the same title updates in place (no duplicate entity)
- client.post(f"/api/cases/{cid}/inspect/sessions", json={"title": "My session", "spec": spec})
- entities = graph_read.entities(cid)
- assert sum(1 for e in entities if e["type"] == "inspect-session") == 1
-
- client.delete(f"/api/cases/{cid}/inspect/sessions/{saved['name']}")
- assert client.get(f"/api/cases/{cid}/inspect/sessions").json() == []
- entities = graph_read.entities(cid)
- assert not any(e["type"] == "inspect-session" for e in entities)
-
-
-def test_session_listing_counts_pieces_across_collages(client):
- # The app saves an array of `collages`; the listing used to count only the
- # legacy singular `collage`, so every real session advertised "0 pieces".
- cid = client.post("/api/cases", json={"name": "Counting"}).json()["id"]
- item = _upload(client, cid, "clip.png")
- node = {"id": "n1", "frameId": "fr1", "save": {"path": item["path"]},
- "quad": [[0, 0], [10, 0], [10, 10], [0, 10]]}
- spec = {
- "source": {"path": item["path"], "kind": "image"},
- "frames": [{"id": "fr1", "path": item["path"], "time": None, "adjust": {}}],
- "collages": [
- {"id": "cl1", "name": "A", "width": 800, "height": 400, "nodes": [node, node]},
- {"id": "cl2", "name": "B", "width": 800, "height": 400, "nodes": [node]},
- ],
- }
- client.post(f"/api/cases/{cid}/inspect/sessions", json={"title": "Multi", "spec": spec})
-
- row = client.get(f"/api/cases/{cid}/inspect/sessions").json()[0]
- assert row["collages"] == 2
- assert row["collage"] == 3 # pieces, summed across every collage
-
-
-def test_session_listing_still_counts_a_legacy_single_collage(client):
- cid = client.post("/api/cases", json={"name": "Legacy"}).json()["id"]
- item = _upload(client, cid, "clip.png")
- node = {"id": "n1", "quad": [[0, 0], [10, 0], [10, 10], [0, 10]]}
- spec = {
- "source": {"path": item["path"], "kind": "image"},
- "frames": [],
- "collage": {"width": 800, "height": 400, "nodes": [node, node]},
- }
- client.post(f"/api/cases/{cid}/inspect/sessions", json={"title": "Old", "spec": spec})
-
- row = client.get(f"/api/cases/{cid}/inspect/sessions").json()[0]
- assert row["collages"] == 1 and row["collage"] == 2
-
-
-def test_session_delete_via_sidebar_entity_removes_spec(client):
- # Deleting the inspect-session row from the sidebar (the generic entity
- # delete) must also drop the spec file, or the session keeps showing up in
- # the Inspect "Open" dialog and can be reloaded.
- cid = client.post("/api/cases", json={"name": "Sidebar delete"}).json()["id"]
- item = _upload(client, cid, "clip.png")
- spec = {"source": {"path": item["path"], "kind": "image"}, "frames": [], "collage": {"nodes": []}}
- client.post(f"/api/cases/{cid}/inspect/sessions", json={"title": "Doomed", "spec": spec})
-
- entities = graph_read.entities(cid)
- ent = next(e for e in entities if e["type"] == "inspect-session")
-
- client.delete(f"/api/cases/{cid}/entities/{ent['id']}")
-
- # gone from the Open list (spec file unlinked) and not reloadable
- assert client.get(f"/api/cases/{cid}/inspect/sessions").json() == []
- assert client.get(f"/api/cases/{cid}/inspect/sessions/doomed").status_code == 404
-
-
-def test_session_rename_moves_the_spec_and_keeps_one_entity(client):
- # The name shown in the Inspect header is the filename. Renaming a saved
- # session moves its spec instead of leaving a copy behind, and the entity is
- # rebound rather than duplicated, so its folder and links survive.
- cid = client.post("/api/cases", json={"name": "Rename"}).json()["id"]
- item = _upload(client, cid, "clip.png")
- spec = {"source": {"path": item["path"], "kind": "image"}, "frames": [], "collage": {"nodes": []}}
-
- first = client.post(
- f"/api/cases/{cid}/inspect/sessions", json={"title": "Original", "spec": spec}
- ).json()
- assert first["name"] == "Original"
- before = next(e for e in graph_read.entities(cid) if e["type"] == "inspect-session")
- client.patch(f"/api/cases/{cid}/entities/{before['id']}", json={"attrs": {"folder": "Angles"}})
-
- renamed = client.post(
- f"/api/cases/{cid}/inspect/sessions",
- json={"rename_from": first["name"], "title": "Rooftop angle", "spec": spec},
- ).json()
- assert renamed["name"] == "Rooftop angle"
-
- listing = client.get(f"/api/cases/{cid}/inspect/sessions").json()
- assert len(listing) == 1
- assert listing[0]["name"] == "Rooftop angle" and listing[0]["title"] == "Rooftop angle"
- assert client.get(f"/api/cases/{cid}/inspect/sessions/{first['name']}").status_code == 404
-
- after = [e for e in graph_read.entities(cid) if e["type"] == "inspect-session"]
- assert len(after) == 1
- assert after[0]["id"] == before["id"] # same entity, so its filing survives
- assert after[0]["attrs"]["spec"] == ".inspect/Rooftop angle.json"
- assert after[0]["attrs"]["folder"] == "Angles"
-
-
-def test_session_rename_keeps_the_creation_date(client):
- cid = client.post("/api/cases", json={"name": "Born"}).json()["id"]
- item = _upload(client, cid, "clip.png")
- spec = {"source": {"path": item["path"], "kind": "image"}, "frames": [], "collage": {"nodes": []}}
-
- original = client.post(
- f"/api/cases/{cid}/inspect/sessions", json={"title": "Original", "spec": spec}
- ).json()
- born = client.get(
- f"/api/cases/{cid}/inspect/sessions/{original['name']}"
- ).json()["created_at"]
-
- client.post(
- f"/api/cases/{cid}/inspect/sessions",
- json={"rename_from": original["name"], "title": "Renamed", "spec": spec},
- )
- assert client.get(
- f"/api/cases/{cid}/inspect/sessions/Renamed"
- ).json()["created_at"] == born
-
-
-def test_session_rename_onto_a_taken_name_is_refused(client):
- # Two sessions under one file would leave two entities pointing at it, and
- # there is no sane merge — the save is refused and both survive untouched.
- cid = client.post("/api/cases", json={"name": "Clash"}).json()["id"]
- item = _upload(client, cid, "clip.png")
- spec = {"source": {"path": item["path"], "kind": "image"}, "frames": [], "collage": {"nodes": []}}
-
- client.post(f"/api/cases/{cid}/inspect/sessions", json={"title": "Inspect 1", "spec": spec})
- second = client.post(
- f"/api/cases/{cid}/inspect/sessions", json={"title": "Inspect 2", "spec": spec}
- ).json()
-
- res = client.post(
- f"/api/cases/{cid}/inspect/sessions",
- json={"rename_from": second["name"], "title": "Inspect 1", "spec": spec},
- )
- assert res.status_code == 409
-
- listing = client.get(f"/api/cases/{cid}/inspect/sessions").json()
- assert sorted(s["name"] for s in listing) == ["Inspect 1", "Inspect 2"]
- assert sum(1 for e in graph_read.entities(cid) if e["type"] == "inspect-session") == 2
-
-
@pytest.mark.skipif(not media_engine.ffmpeg_available(), reason="ffmpeg not installed")
def test_enhance_video_rejects_neutral_params(client, tmp_path):
import subprocess
diff --git a/tests/test_inspect_work.py b/tests/test_inspect_work.py
new file mode 100644
index 0000000..34ca02a
--- /dev/null
+++ b/tests/test_inspect_work.py
@@ -0,0 +1,639 @@
+"""Inspect's work, one per file, the collages laid out from it, and the 0.3.1 merge.
+
+The API half drives the routes the Examine tools call. The migration half builds
+cases the way 0.3.0 left them — named sessions, several per file, collages inside —
+stamps them back to that schema and opens them, which is exactly what an upgrade does.
+"""
+
+from __future__ import annotations
+
+import io
+import json
+
+import graph_read
+import pytest
+from PIL import Image
+
+from azimut import layout, workspace
+from azimut.engine import inspectwork
+from azimut.engine import links as link_engine
+from azimut.workspace import Case
+
+
+def _png(color=(120, 60, 30), size=(80, 60)) -> bytes:
+ buf = io.BytesIO()
+ Image.new("RGB", size, color).save(buf, "PNG")
+ return buf.getvalue()
+
+
+def _case(client, name="Work") -> str:
+ return client.post("/api/cases", json={"name": name}).json()["id"]
+
+
+def _upload(client, cid, name, color=(120, 60, 30)) -> str:
+ res = client.post(
+ f"/api/cases/{cid}/media/upload",
+ files={"file": (name, io.BytesIO(_png(color)), "image/png")},
+ )
+ assert res.status_code == 200, res.text
+ return res.json()["item"]["path"]
+
+
+def _frame(path, frame_id="fr_a", **extra):
+ return {"id": frame_id, "path": path, "time": None, "adjust": {}, "crop": None, **extra}
+
+
+def _save(client, cid, path, frames, **spec):
+ return client.put(
+ f"/api/cases/{cid}/inspect/work", json={"path": path, "spec": {"frames": frames, **spec}}
+ )
+
+
+def _work(client, cid, path):
+ return client.get(f"/api/cases/{cid}/inspect/work", params={"path": path}).json()["work"]
+
+
+def _of_type(cid, type_):
+ return [e for e in graph_read.entities(cid) if e["type"] == type_]
+
+
+def _piece(path, piece_id="nd_1"):
+ return {
+ "id": piece_id, "save": {"path": path, "time": None, "ops": []},
+ "w": 80, "h": 60, "quad": [[0, 0], [80, 0], [80, 60], [0, 60]],
+ }
+
+
+# -- work ---------------------------------------------------------------------
+
+
+def test_a_file_with_nothing_done_to_it_has_no_work(client):
+ cid = _case(client)
+ photo = _upload(client, cid, "roof.png")
+
+ assert _work(client, cid, photo) is None
+ assert client.get(f"/api/cases/{cid}/inspect/works").json() == []
+ assert _of_type(cid, "inspect-session") == []
+
+
+def test_the_first_save_files_one_work_named_after_the_file(client):
+ cid = _case(client)
+ photo = _upload(client, cid, "roof.png")
+
+ saved = _save(client, cid, photo, [_frame(photo, adjust={"brightness": 1.3})])
+
+ assert saved.status_code == 200, saved.text
+ assert saved.json() == {"name": "roof", "title": "roof"}
+ work = _work(client, cid, photo)
+ assert work["spec"]["azimut_inspect"] == inspectwork.WORK_VERSION
+ assert work["spec"]["source"] == {"path": photo, "kind": "image"}
+ assert work["spec"]["frames"][0]["adjust"] == {"brightness": 1.3}
+ [entity] = _of_type(cid, "inspect-session")
+ assert entity["attrs"]["spec"] == ".inspect/roof.json"
+ [row] = client.get(f"/api/cases/{cid}/inspect/works").json()
+ assert row["source"] == photo and row["frames"] == 1 and row["kind"] == "image"
+
+
+def test_saving_again_rewrites_the_same_work(client):
+ cid = _case(client)
+ photo = _upload(client, cid, "roof.png")
+ _save(client, cid, photo, [_frame(photo)])
+ created = _work(client, cid, photo)["spec"]["created_at"]
+
+ _save(client, cid, photo, [_frame(photo), _frame(photo, "fr_b")], activeFrameId="fr_b")
+
+ work = _work(client, cid, photo)
+ assert [f["id"] for f in work["spec"]["frames"]] == ["fr_a", "fr_b"]
+ assert work["spec"]["activeFrameId"] == "fr_b"
+ assert work["spec"]["created_at"] == created
+ assert len(_of_type(cid, "inspect-session")) == 1
+ assert len(link_engine_links(cid, "depends-on")) == 1
+
+
+def link_engine_links(cid, type_):
+ return [link for link in graph_read.links(cid) if link["type"] == type_]
+
+
+def test_a_work_takes_the_next_free_name(client):
+ cid = _case(client)
+ other = _upload(client, cid, "gate.png", (1, 2, 3))
+ photo = _upload(client, cid, "roof.png", (4, 5, 6))
+ _save(client, cid, other, [_frame(other)])
+ [gate] = _of_type(cid, "inspect-session")
+ client.patch(f"/api/cases/{cid}/entities/{gate['id']}", json={"label": "roof"})
+
+ assert _save(client, cid, photo, [_frame(photo)]).json()["name"] == "roof 2"
+
+
+def test_a_frame_cut_from_another_file_is_refused(client):
+ cid = _case(client)
+ photo = _upload(client, cid, "roof.png", (1, 1, 1))
+ other = _upload(client, cid, "gate.png", (2, 2, 2))
+
+ res = _save(client, cid, photo, [_frame(other)])
+
+ assert res.status_code == 400
+ assert "file it is saved with" in res.json()["detail"]
+ assert _work(client, cid, photo) is None
+
+
+def test_only_an_image_or_a_video_holds_work(client):
+ cid = _case(client)
+ upload = client.post(
+ f"/api/cases/{cid}/media/upload",
+ files={"file": ("notes.txt", io.BytesIO(b"plain words"), "text/plain")},
+ ).json()["item"]["path"]
+
+ res = _save(client, cid, upload, [])
+
+ assert res.status_code == 400
+ assert "images and videos" in res.json()["detail"]
+
+
+def test_a_file_outside_the_case_is_refused(client):
+ cid = _case(client)
+
+ res = _save(client, cid, "media/nowhere.png", [])
+
+ assert res.status_code == 400
+ assert _of_type(cid, "inspect-session") == []
+
+
+def test_unknown_frame_fields_are_not_stored(client):
+ cid = _case(client)
+ photo = _upload(client, cid, "roof.png")
+
+ _save(client, cid, photo, [_frame(photo, url="blob:http://x", secret="y")])
+
+ frame = _work(client, cid, photo)["spec"]["frames"][0]
+ assert "url" not in frame and "secret" not in frame
+
+
+def test_a_runaway_frame_count_is_refused(client):
+ cid = _case(client)
+ photo = _upload(client, cid, "roof.png")
+ frames = [_frame(photo, f"fr_{i}") for i in range(inspectwork.MAX_FRAMES + 1)]
+
+ assert _save(client, cid, photo, frames).status_code == 400
+
+
+def test_a_work_renamed_from_details_keeps_saving_under_its_new_name(client):
+ cid = _case(client)
+ photo = _upload(client, cid, "roof.png")
+ _save(client, cid, photo, [_frame(photo)])
+ [entity] = _of_type(cid, "inspect-session")
+ client.patch(f"/api/cases/{cid}/entities/{entity['id']}", json={"label": "Roof pass"})
+
+ saved = _save(client, cid, photo, [_frame(photo), _frame(photo, "fr_b")])
+
+ assert saved.json()["name"] == "Roof pass"
+ assert len(_of_type(cid, "inspect-session")) == 1
+ assert client.get(f"/api/cases/{cid}/inspect/works/Roof pass").json()["spec"]["frames"][1]["id"] == "fr_b"
+
+
+def test_a_renamed_file_carries_its_work_along(client):
+ cid = _case(client)
+ photo = _upload(client, cid, "roof.png")
+ _save(client, cid, photo, [_frame(photo)])
+
+ renamed = client.patch(f"/api/cases/{cid}/media", json={"path": photo, "title": "North roof"})
+ assert renamed.status_code == 200, renamed.text
+ moved = renamed.json()["path"]
+
+ work = _work(client, cid, moved)
+ assert work["spec"]["source"]["path"] == moved
+ assert work["spec"]["frames"][0]["path"] == moved
+ assert _work(client, cid, photo) is None
+ # named after the file, so it takes the file's new name with it
+ assert work["name"] == "North roof"
+ [entity] = _of_type(cid, "inspect-session")
+ assert entity["label"] == "North roof"
+ assert entity["attrs"]["spec"] == ".inspect/North roof.json"
+ assert [row["name"] for row in client.get(f"/api/cases/{cid}/inspect/works").json()] == ["North roof"]
+
+
+def test_a_long_file_name_cut_to_fit_is_still_followed(client):
+ cid = _case(client)
+ photo = _upload(client, cid, "clip.png")
+ # a download keeps the title it came with, longer than any filename may be
+ title = "@Suriyak - The second phase of Operation: what the convoy footage shows, day 2"
+ case = Case.open(cid)
+ case.update_entity(case.find_entity(attr="path", value=photo)["id"], {"label": title})
+ _save(client, cid, photo, [_frame(photo)])
+ [entity] = _of_type(cid, "inspect-session")
+ assert entity["label"] != title and len(entity["label"]) <= layout.MAX_SLUG
+
+ moved = client.patch(f"/api/cases/{cid}/media", json={"path": photo, "title": "Convoy"}).json()["path"]
+
+ assert _work(client, cid, moved)["name"] == "Convoy"
+
+
+def test_a_name_the_app_derived_from_the_file_describes_nothing():
+ long = "@Suriyak - The second phase of Operation: what the convoy footage shows, day 2"
+ cut = layout.slugify(long, "Inspect")
+ assert inspectwork._describes_nothing(cut, long)
+ assert inspectwork._describes_nothing(inspectwork._free_title({cut.casefold()}, long, "Inspect"), long)
+ assert inspectwork._describes_nothing(layout.slugify("Strike: day 2?", "Inspect"), "Strike: day 2?")
+ assert inspectwork._describes_nothing("Roof 3", "Roof")
+ assert not inspectwork._describes_nothing("Roof pass", "Roof")
+ assert not inspectwork._describes_nothing("Roof 2 pass", "Roof")
+ assert not inspectwork._describes_nothing("Roo 2", "Roof")
+
+
+def test_a_renamed_file_leaves_a_typed_work_name_alone(client):
+ cid = _case(client)
+ photo = _upload(client, cid, "roof.png")
+ _save(client, cid, photo, [_frame(photo)])
+ [entity] = _of_type(cid, "inspect-session")
+ client.patch(f"/api/cases/{cid}/entities/{entity['id']}", json={"label": "Roof pass"})
+
+ moved = client.patch(f"/api/cases/{cid}/media", json={"path": photo, "title": "North roof"}).json()["path"]
+
+ assert _work(client, cid, moved)["name"] == "Roof pass"
+
+
+def test_a_file_rename_cut_short_still_carries_its_work_along(client, monkeypatch):
+ from azimut.engine import media as media_engine
+
+ cid = _case(client)
+ photo = _upload(client, cid, "roof.png")
+ _save(client, cid, photo, [_frame(photo)])
+ case = Case.open(cid)
+ follow = inspectwork.follow_file_rename
+
+ def interrupt(*_args):
+ raise RuntimeError("simulated interruption")
+
+ monkeypatch.setattr(inspectwork, "follow_file_rename", interrupt)
+ with pytest.raises(RuntimeError, match="simulated interruption"):
+ media_engine.rename_media(case, photo, "North roof")
+ monkeypatch.setattr(inspectwork, "follow_file_rename", follow)
+ media_engine.recover_media_rename(case)
+ media_engine.recover_media_rename(case)
+
+ assert _work(client, cid, "media/North roof.png")["name"] == "North roof"
+ assert len(_of_type(cid, "inspect-session")) == 1
+
+
+def test_clearing_a_work_sends_it_to_the_trash(client):
+ cid = _case(client)
+ photo = _upload(client, cid, "roof.png")
+ _save(client, cid, photo, [_frame(photo)])
+
+ cleared = client.delete(f"/api/cases/{cid}/inspect/work", params={"path": photo}).json()
+
+ assert cleared["trash"]
+ assert _work(client, cid, photo) is None
+ assert graph_read.entity(cid, path=photo) is not None # the file stands
+ client.post(f"/api/cases/{cid}/trash/{cleared['trash']}/restore")
+ assert [f["id"] for f in _work(client, cid, photo)["spec"]["frames"]] == ["fr_a"]
+
+
+def test_restoring_a_cleared_work_merges_it_into_the_one_made_since(client):
+ cid = _case(client)
+ photo = _upload(client, cid, "roof.png")
+ _save(client, cid, photo, [_frame(photo, "fr_old")])
+ cleared = client.delete(f"/api/cases/{cid}/inspect/work", params={"path": photo}).json()
+ # starting over takes a name the Trash is not holding, so the restore can land
+ assert _save(client, cid, photo, [_frame(photo, "fr_new")]).json()["name"] == "roof 2"
+
+ restored = client.post(f"/api/cases/{cid}/trash/{cleared['trash']}/restore")
+
+ assert restored.status_code == 200, restored.text
+ work = _work(client, cid, photo)
+ assert [f["id"] for f in work["spec"]["frames"]] == ["fr_new", "fr_old"]
+ assert work["name"] == "roof" # the made-up number goes once the name is free
+ assert len(_of_type(cid, "inspect-session")) == 1
+
+
+def test_a_work_reopens_by_name(client):
+ cid = _case(client)
+ photo = _upload(client, cid, "roof.png")
+ _save(client, cid, photo, [_frame(photo)])
+
+ assert client.get(f"/api/cases/{cid}/inspect/works/roof").json()["spec"]["source"]["path"] == photo
+ assert client.get(f"/api/cases/{cid}/inspect/works/nothing").status_code == 404
+
+
+# -- collages -----------------------------------------------------------------
+
+
+def _save_collage(client, cid, title, pieces, name=None, **spec):
+ return client.post(
+ f"/api/cases/{cid}/collages",
+ json={"name": name, "title": title, "spec": {"width": 400, "height": 200, "nodes": pieces, **spec}},
+ )
+
+
+def test_a_new_collage_takes_the_next_free_name(client):
+ cid = _case(client)
+ photo = _upload(client, cid, "roof.png")
+
+ first = _save_collage(client, cid, "Collage 1", [_piece(photo)]).json()
+ second = _save_collage(client, cid, "Collage 1", [_piece(photo)]).json()
+
+ assert first["name"] == "Collage 1"
+ assert second["name"] == "Collage 1 2"
+ assert {e["attrs"]["spec"] for e in _of_type(cid, "collage")} == {
+ ".collages/Collage 1.json", ".collages/Collage 1 2.json",
+ }
+ assert [row["pieces"] for row in client.get(f"/api/cases/{cid}/collages").json()] == [1, 1]
+
+
+def test_saving_a_collage_again_rewrites_it_in_place(client):
+ cid = _case(client)
+ photo = _upload(client, cid, "roof.png")
+ _save_collage(client, cid, "Strip", [_piece(photo)])
+
+ saved = _save_collage(client, cid, "Strip", [_piece(photo), _piece(photo, "nd_2")], name="Strip")
+
+ assert saved.json()["name"] == "Strip"
+ loaded = client.get(f"/api/cases/{cid}/collages/Strip").json()
+ assert [n["id"] for n in loaded["spec"]["nodes"]] == ["nd_1", "nd_2"]
+ assert len(_of_type(cid, "collage")) == 1
+
+
+def test_renaming_a_collage_moves_its_file_and_keeps_its_entity(client):
+ cid = _case(client)
+ photo = _upload(client, cid, "roof.png")
+ _save_collage(client, cid, "Strip", [_piece(photo)])
+ [before] = _of_type(cid, "collage")
+
+ renamed = _save_collage(client, cid, "Harbour strip", [_piece(photo)], name="Strip")
+
+ assert renamed.json()["name"] == "Harbour strip"
+ [after] = _of_type(cid, "collage")
+ assert after["id"] == before["id"]
+ assert after["attrs"]["spec"] == ".collages/Harbour strip.json"
+ assert client.get(f"/api/cases/{cid}/collages/Strip").status_code == 404
+
+
+def test_a_collage_cannot_be_renamed_onto_another(client):
+ cid = _case(client)
+ photo = _upload(client, cid, "roof.png")
+ _save_collage(client, cid, "A", [_piece(photo)])
+ _save_collage(client, cid, "B", [_piece(photo)])
+
+ res = _save_collage(client, cid, "A", [_piece(photo)], name="B")
+
+ assert res.status_code == 409
+ assert len(_of_type(cid, "collage")) == 2
+
+
+def test_deleting_a_collage_leaves_its_exported_picture(client):
+ cid = _case(client)
+ photo = _upload(client, cid, "roof.png")
+ _save_collage(client, cid, "Strip", [_piece(photo)])
+ exported = client.post(
+ f"/api/cases/{cid}/inspect/compose",
+ json={"width": 80, "height": 60, "label": "Strip",
+ "nodes": [{"src": {"path": photo}, "quad": [[0, 0], [80, 0], [80, 60], [0, 60]]}]},
+ ).json()["item"]["path"]
+
+ deleted = client.delete(f"/api/cases/{cid}/collages/Strip").json()
+
+ assert deleted["trash"]
+ assert _of_type(cid, "collage") == []
+ assert graph_read.entity(cid, path=exported) is not None
+
+
+def test_a_piece_without_a_source_is_refused(client):
+ cid = _case(client)
+
+ res = _save_collage(client, cid, "Strip", [{"id": "nd_1", "quad": [[0, 0]] * 4}])
+
+ assert res.status_code == 400
+ assert _of_type(cid, "collage") == []
+
+
+def test_a_renamed_file_is_followed_into_the_collages_using_it(client):
+ cid = _case(client)
+ photo = _upload(client, cid, "roof.png")
+ _save_collage(client, cid, "Strip", [_piece(photo)])
+
+ moved = client.patch(f"/api/cases/{cid}/media", json={"path": photo, "title": "North roof"}).json()["path"]
+
+ piece = client.get(f"/api/cases/{cid}/collages/Strip").json()["spec"]["nodes"][0]
+ assert piece["save"]["path"] == moved
+
+
+# -- 0.3.0 → 0.3.1 ----------------------------------------------------------------
+
+
+def _legacy_session(
+ case, title, subject, *, frames=(), collages=None, collage=None,
+ updated="2026-01-01T00:00:00Z", notes=None, folder=None, kind="image",
+):
+ """A session exactly as 0.3.0's save route wrote one: spec, entity, depends-on."""
+ rel = layout.session_rel(title)
+ spec = {
+ "azimut_inspect": 1, "title": title, "created_at": updated, "updated_at": updated,
+ "source": {"path": subject, "kind": kind}, "videoAdjust": {}, "videoRotation": 0,
+ "frames": list(frames), "activeFrameId": frames[0]["id"] if frames else None,
+ }
+ if collages is not None:
+ spec["collages"] = collages
+ if collage is not None:
+ spec["collage"] = collage
+ path = case.resolve_inside(rel)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(json.dumps(spec), encoding="utf-8")
+ attrs = {"spec": rel}
+ if notes:
+ attrs["notes"] = notes
+ if folder:
+ attrs["folder"] = folder
+ entity = case.add_entity("inspect-session", title, attrs=attrs, by="inspect")
+ link_engine.sync(case, entity["id"], link_engine.DEPENDS_ON, [subject], by="inspect")
+ return entity
+
+
+def _legacy_collage(name, pieces, cid="cl_1"):
+ return {"id": cid, "name": name, "width": 800, "height": 400, "background": "#12141c",
+ "transparent": True, "nodes": pieces}
+
+
+def _as_0_3_0(case) -> Case:
+ manifest = case.read()
+ manifest["azimut"]["schema"] = workspace.LAYOUT_SCHEMA
+ case._write_json(manifest)
+ return Case.open(case.id)
+
+
+def test_opening_a_0_3_0_case_merges_the_sessions_of_one_file(client):
+ cid = _case(client)
+ photo = _upload(client, cid, "roof.png")
+ case = Case.open(cid)
+ older = _legacy_session(case, "Inspect 1", photo, frames=[_frame(photo, "fr_1")],
+ updated="2026-01-01T00:00:00Z")
+ newer = _legacy_session(case, "Inspect 2", photo, frames=[_frame(photo, "fr_2")],
+ updated="2026-02-01T00:00:00Z")
+
+ opened = _as_0_3_0(case)
+
+ assert opened.read()["azimut"]["schema"] == workspace.CASE_SCHEMA
+ [work] = _of_type(cid, "inspect-session")
+ assert work["id"] == newer["id"] # the latest session is the one that carries on
+ assert graph_read.entity(cid, spec=older["attrs"]["spec"]) is None
+ assert not opened.resolve_inside(older["attrs"]["spec"]).exists()
+ spec = _work(client, cid, photo)["spec"]
+ assert spec["azimut_inspect"] == inspectwork.WORK_VERSION
+ assert [f["id"] for f in spec["frames"]] == ["fr_2", "fr_1"]
+ assert spec["created_at"] == "2026-01-01T00:00:00Z"
+ assert len(link_engine_links(cid, "depends-on")) == 1
+ # two made-up names described nothing, so the work takes the file's
+ assert work["label"] == "roof"
+ # the merge cannot be taken back, so both sessions are kept as they were
+ for rel in (older["attrs"]["spec"], newer["attrs"]["spec"]):
+ kept = opened.resolve_inside(layout.legacy_session_rel(rel.split("/")[-1][:-5]))
+ assert json.loads(kept.read_text(encoding="utf-8"))["azimut_inspect"] == 1
+
+
+def test_sessions_on_different_files_stay_apart(client):
+ cid = _case(client)
+ roof = _upload(client, cid, "roof.png", (1, 1, 1))
+ gate = _upload(client, cid, "gate.png", (2, 2, 2))
+ case = Case.open(cid)
+ _legacy_session(case, "Roof pass", roof, frames=[_frame(roof)])
+ _legacy_session(case, "Gate pass", gate, frames=[_frame(gate)])
+
+ _as_0_3_0(case)
+
+ assert sorted(e["label"] for e in _of_type(cid, "inspect-session")) == ["Gate pass", "Roof pass"]
+
+
+def test_the_merge_keeps_every_note_and_typed_name(client):
+ cid = _case(client)
+ photo = _upload(client, cid, "roof.png")
+ case = Case.open(cid)
+ _legacy_session(case, "Chimney count", photo, updated="2026-01-01T00:00:00Z",
+ notes="Three chimneys on the east side.", folder="Rooftops")
+ _legacy_session(case, "Antenna check", photo, updated="2026-01-02T00:00:00Z")
+ _legacy_session(case, "Inspect 7", photo, updated="2026-03-01T00:00:00Z", notes="Latest pass.")
+
+ _as_0_3_0(case)
+
+ [work] = _of_type(cid, "inspect-session")
+ # the survivor's own name was made up, so it takes the newest typed one
+ assert work["label"] == "Antenna check"
+ notes = work["attrs"]["notes"]
+ assert notes.startswith("Latest pass.")
+ assert "“Chimney count”: Three chimneys on the east side." in notes
+ assert "Merged with “Antenna check”." in notes
+ assert "Inspect" not in notes.split("Latest pass.", 1)[1]
+ assert work["attrs"]["folder"] == "Rooftops"
+
+
+def test_relations_follow_the_merge(client):
+ cid = _case(client)
+ photo = _upload(client, cid, "roof.png")
+ case = Case.open(cid)
+ merged_away = _legacy_session(case, "Old pass", photo, updated="2026-01-01T00:00:00Z")
+ survivor = _legacy_session(case, "New pass", photo, updated="2026-02-01T00:00:00Z")
+ note = case.create_note("Working notes", "", "# notes")
+ mention = case.add_link(note["id"], merged_away["id"], "mentions", by="user")
+ case.update_link(mention["id"], {"nature": "cited"})
+
+ _as_0_3_0(case)
+
+ mentions = link_engine_links(cid, "mentions")
+ assert [(m["from"], m["to"]) for m in mentions] == [(note["id"], survivor["id"])]
+ assert mentions[0].get("nature") == "cited"
+
+
+def test_collages_leave_their_sessions_as_documents(client):
+ cid = _case(client)
+ photo = _upload(client, cid, "roof.png")
+ case = Case.open(cid)
+ _legacy_session(case, "Harbour pan", photo, folder="Harbour",
+ collages=[_legacy_collage("Collage 1", [_piece(photo)])])
+ _legacy_session(case, "Two layouts", _upload(client, cid, "gate.png", (3, 3, 3)), collages=[
+ _legacy_collage("Collage 1", [_piece(photo)], "cl_a"),
+ _legacy_collage("Wide view", [_piece(photo)], "cl_b"),
+ _legacy_collage("Collage 3", [], "cl_c"), # nothing on it, nothing to keep
+ ])
+ _legacy_session(case, "Inspect 4", _upload(client, cid, "mast.png", (4, 4, 4)),
+ collages=[_legacy_collage("Collage 2", [_piece(photo)])])
+
+ _as_0_3_0(case)
+
+ collages = {e["label"]: e for e in _of_type(cid, "collage")}
+ assert set(collages) == {"Harbour pan", "Two layouts · Collage 1", "Wide view", "Collage 1"}
+ assert collages["Harbour pan"]["attrs"]["folder"] == "Harbour"
+ loaded = client.get(f"/api/cases/{cid}/collages/Harbour pan").json()["spec"]
+ assert loaded["nodes"][0]["save"]["path"] == photo
+ assert loaded["width"] == 800
+ # the work keeps its frames and loses its collages
+ for row in client.get(f"/api/cases/{cid}/inspect/works").json():
+ spec = client.get(f"/api/cases/{cid}/inspect/works/{row['name']}").json()["spec"]
+ assert "collages" not in spec and "collage" not in spec
+
+
+def test_a_session_from_before_the_collage_array_still_yields_its_collage(client):
+ cid = _case(client)
+ photo = _upload(client, cid, "roof.png")
+ case = Case.open(cid)
+ _legacy_session(case, "Old layout", photo,
+ collage={"width": 800, "height": 400, "nodes": [_piece(photo)]})
+
+ _as_0_3_0(case)
+
+ assert [e["label"] for e in _of_type(cid, "collage")] == ["Old layout"]
+
+
+def test_an_interrupted_migration_resumes_without_repeating_itself(client):
+ cid = _case(client)
+ photo = _upload(client, cid, "roof.png")
+ case = Case.open(cid)
+ _legacy_session(case, "Pass A", photo, frames=[_frame(photo, "fr_a")], notes="A said this.",
+ updated="2026-01-01T00:00:00Z",
+ collages=[_legacy_collage("Collage 1", [_piece(photo)])])
+ _legacy_session(case, "Pass B", photo, frames=[_frame(photo, "fr_b")],
+ updated="2026-02-01T00:00:00Z")
+ group = inspectwork._group(case, photo)
+ done = inspectwork._migrated_collages(case)
+ # the first run got as far as the collage and died
+ [(rel_a, spec_a)] = [(r, s) for r, s in group if s["title"] == "Pass A"]
+ inspectwork._extract_collages(case, rel_a, spec_a, "Pass A", None, done)
+
+ inspectwork.normalize(case)
+ inspectwork.normalize(case)
+
+ assert [e["label"] for e in _of_type(cid, "collage")] == ["Pass A"]
+ [work] = _of_type(cid, "inspect-session")
+ assert work["attrs"]["notes"].count("A said this.") == 1
+ spec = _work(client, cid, photo)["spec"]
+ assert [f["id"] for f in spec["frames"]] == ["fr_b", "fr_a"]
+
+
+def test_a_session_whose_file_cannot_be_named_is_left_alone(client):
+ cid = _case(client)
+ case = Case.open(cid)
+ rel = layout.session_rel("Broken")
+ path = case.resolve_inside(rel)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(json.dumps({"azimut_inspect": 1, "title": "Broken"}), encoding="utf-8")
+
+ _as_0_3_0(case)
+
+ assert path.exists()
+ assert client.get(f"/api/cases/{cid}/inspect/works").json() == []
+
+
+def test_restoring_a_pre_0_3_1_session_from_the_trash_merges_it(client):
+ cid = _case(client)
+ photo = _upload(client, cid, "roof.png")
+ _save(client, cid, photo, [_frame(photo, "fr_now")])
+ case = Case.open(cid)
+ # A session deleted under 0.3.0 comes back out of the Trash after the upgrade.
+ old = _legacy_session(case, "Old pass", photo, frames=[_frame(photo, "fr_then")],
+ collages=[_legacy_collage("Collage 1", [_piece(photo)])])
+ deleted = client.delete(f"/api/cases/{cid}/entities/{old['id']}").json()
+
+ client.post(f"/api/cases/{cid}/trash/{deleted['trash']}/restore")
+
+ [work] = _of_type(cid, "inspect-session")
+ spec = _work(client, cid, photo)["spec"]
+ assert [f["id"] for f in spec["frames"]] == ["fr_now", "fr_then"]
+ assert [e["label"] for e in _of_type(cid, "collage")] == ["Old pass"]
+ assert "Merged with “Old pass”." in work["attrs"]["notes"]
diff --git a/tests/test_layout.py b/tests/test_layout.py
index c834030..56fa550 100644
--- a/tests/test_layout.py
+++ b/tests/test_layout.py
@@ -96,7 +96,9 @@ def _tool_relative(slug: int, media: int) -> dict[str, int]:
"proof spec": len(layout.proof_spec_rel(longest_name)),
"proof export": len(layout.proof_export_rel(longest_name)),
"draft": len(layout.draft_rel(longest_name)),
- "session": len(layout.session_rel(longest_name)),
+ "inspect work": len(layout.session_rel(longest_name)),
+ "pre-0.3.1 session": len(layout.legacy_session_rel(longest_name)),
+ "collage": len(layout.collage_rel(longest_name)),
"compare session": len(layout.compare_session_rel(longest_name)),
"grid": len(layout.grid_rel(longest_name)),
"map layer spec": len(layout.layer_spec_rel(longest_name)),
diff --git a/tests/test_links_api.py b/tests/test_links_api.py
index 9be3142..2f6f6a5 100644
--- a/tests/test_links_api.py
+++ b/tests/test_links_api.py
@@ -64,8 +64,20 @@ def _save_proof(client, cid, title, srcs):
def _save_session(client, cid, title, source_path):
- body = {"title": title, "spec": {"source": {"path": source_path, "kind": "image"}}}
- return client.post(f"/api/cases/{cid}/inspect/sessions", json=body).json()
+ """File a file's Inspect work, then name it the way Details would.
+
+ A work is born under its file's name; renaming it here keeps these tests reading
+ in the names they were written in, and goes through the rename that moves the
+ spec with the label.
+ """
+ saved = client.put(
+ f"/api/cases/{cid}/inspect/work", json={"path": source_path, "spec": {"frames": []}}
+ )
+ assert saved.status_code == 200, saved.text
+ work = _entity(client, cid, spec=f".inspect/{saved.json()['name']}.json")
+ renamed = client.patch(f"/api/cases/{cid}/entities/{work['id']}", json={"label": title})
+ assert renamed.status_code == 200, renamed.text
+ return renamed.json()
# ── emission at save time ───────────────────────────────────────────────────
@@ -347,7 +359,7 @@ def test_deleting_a_subject_deletes_its_session_but_spares_its_outputs(client):
assert res["status"] == "deleted"
# the session is nothing without its subject: it goes, file and all
assert _entity(client, cid, spec=".inspect/S.json") is None
- assert client.get(f"/api/cases/{cid}/inspect/sessions/S").status_code == 404
+ assert client.get(f"/api/cases/{cid}/inspect/works/S").status_code == 404
# the proof stands on its own: it stays, and its export is untouched
proof = _entity(client, cid, spec="proofs/.meta/P.json")
assert proof is not None
@@ -495,9 +507,9 @@ def test_the_inspect_delete_honours_the_graph(client):
a = _upload(client, cid, "a.png")["item"]["path"]
_save_session(client, cid, "S", a)
- client.delete(f"/api/cases/{cid}/inspect/sessions/S")
+ client.delete(f"/api/cases/{cid}/inspect/work", params={"path": a})
- # a session deleted on its own takes nothing with it: its subject stands
+ # work cleared on its own takes nothing with it: its subject stands
assert _entity(client, cid, spec=".inspect/S.json") is None
assert _entity(client, cid, path=a) is not None
assert _links(client, cid) == []
diff --git a/tests/test_map_layers.py b/tests/test_map_layers.py
index 0d94a0f..ccb43f3 100644
--- a/tests/test_map_layers.py
+++ b/tests/test_map_layers.py
@@ -1078,7 +1078,10 @@ def test_a_kml_timestamp_or_the_start_of_a_timespan_dates_its_placemark():
# the day as the source wrote it, not moved into another timezone
assert properties["Stamped"]["date"] == "2024-05-10"
+ assert "date_end" not in properties["Stamped"]
+ # a span keeps both ends, so a period that only reaches its end still finds it
assert properties["Spanned"]["date"] == "2024-05-01"
+ assert properties["Spanned"]["date_end"] == "2024-05-09"
assert "date" not in properties["Undated"]
diff --git a/tests/test_migrations.py b/tests/test_migrations.py
index 346f5fb..7b08daa 100644
--- a/tests/test_migrations.py
+++ b/tests/test_migrations.py
@@ -267,7 +267,7 @@ def _case_at_folder_checkpoint(schema: int) -> tuple[Case, dict[str, str]]:
}
[email protected]("schema", range(workspace.STORAGE_SCHEMA, workspace.CASE_SCHEMA))
[email protected]("schema", range(workspace.STORAGE_SCHEMA, workspace.LAYOUT_SCHEMA))
def test_every_unreleased_folder_checkpoint_jumps_to_the_final_layout(tmp_workspace, schema):
case, expected = _case_at_folder_checkpoint(schema)
legacy_manifest = (
@@ -308,7 +308,9 @@ def test_released_schema_three_is_stamped_only_once(tmp_workspace, monkeypatch):
Case.open(case.id)
- assert writes == [workspace.CASE_SCHEMA]
+ # The unreleased checkpoints collapse into the one layout stamp; the released
+ # steps after it each stamp their own.
+ assert writes == [workspace.LAYOUT_SCHEMA, workspace.CASE_SCHEMA]
@pytest.mark.parametrize(
@@ -590,7 +592,7 @@ def test_schema_seven_case_gets_a_readme_without_overwriting_one(tmp_workspace):
readme = layout.readme(case.path)
readme.unlink()
manifest = case.read()
- manifest["azimut"]["schema"] = workspace.CASE_SCHEMA - 1
+ manifest["azimut"]["schema"] = workspace.LAYOUT_SCHEMA - 1
case._write_json(manifest)
opened = Case.open(case.id)
@@ -600,7 +602,7 @@ def test_schema_seven_case_gets_a_readme_without_overwriting_one(tmp_workspace):
readme.write_text("My own instructions\n", encoding="utf-8")
manifest = opened.read()
- manifest["azimut"]["schema"] = workspace.CASE_SCHEMA - 1
+ manifest["azimut"]["schema"] = workspace.LAYOUT_SCHEMA - 1
opened._write_json(manifest)
Case.open(case.id)
diff --git a/tests/test_placement.py b/tests/test_placement.py
index 5f6833b..f54389a 100644
--- a/tests/test_placement.py
+++ b/tests/test_placement.py
@@ -186,12 +186,11 @@ def test_an_inspect_session_is_placed_through_the_media_it_points_at(client, sat
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})
- client.post(
- f"/api/cases/{cid}/inspect/sessions",
- json={"title": "Pass", "spec": {"source": {"path": video, "kind": "image"}}},
- )
+ work = client.put(
+ f"/api/cases/{cid}/inspect/work", json={"path": video, "spec": {"frames": []}}
+ ).json()
- assert _points(client, cid, _id(cid, spec=".inspect/Pass.json")) == [(50.4501, 30.5234)]
+ assert _points(client, cid, _id(cid, spec=f".inspect/{work['name']}.json")) == [(50.4501, 30.5234)]
# ── what the list refuses to do ─────────────────────────────────────────────
diff --git a/tests/test_plates.py b/tests/test_plates.py
index d6c7689..8ae2062 100644
--- a/tests/test_plates.py
+++ b/tests/test_plates.py
@@ -81,6 +81,21 @@ def test_a_plate_goes_to_the_folder_the_analyst_chose_and_never_overwrites(
}
+def test_a_plate_that_asks_not_to_overwrite_takes_a_name_of_its_own_in_the_case(client):
+ """Compare names an image by its pictures' dates, so a second comparison of the
+ same pair must not replace the first."""
+ case_id = _case(client)
+
+ first = _write(client, case_id, format="png", png=_png(), svg="", overwrite=False)
+ second = _write(client, case_id, format="png", png=_png(), svg="", overwrite=False)
+
+ assert first.status_code == 200 and second.status_code == 200
+ assert second.json()["file"] != first.json()["file"]
+ assert {first.json()["file"], second.json()["file"]} <= {
+ path.name for path in exports_of(case_id).iterdir()
+ }
+
+
def test_a_png_plate_is_written_as_an_image(client):
case_id = _case(client)
diff --git a/tests/test_radar_detect.py b/tests/test_radar_detect.py
index 6611a40..c07264e 100644
--- a/tests/test_radar_detect.py
+++ b/tests/test_radar_detect.py
@@ -303,6 +303,42 @@ def test_radar_change_gates_bright_loss_bright_gain_and_new_water():
assert result.measures["before"][0].max() > analyzers.BRIGHT_DB
+def test_the_radar_change_window_is_ground_not_pixels():
+ """A step of smoothing is 45 m of ground, odd in pixels and never under three."""
+ assert analyzers.sar_window(2, 7.2) == 13
+ assert analyzers.sar_window(2, 9.55) == 9
+ assert analyzers.sar_window(3, 7.2) == 19
+ assert analyzers.sar_window(1, 9.55) == 5
+ assert analyzers.sar_window(0, 40.0) == 3
+
+
+def test_the_catalogue_says_radar_change_smooths_on_the_ground(client):
+ methods = {m["id"]: m for m in client.get("/api/compare/analyzers").json()["methods"]}
+ assert methods["sar-change"]["smoothing_m"] == analyzers.SAR_WINDOW_M
+ assert methods["surface"]["smoothing_m"] is None
+
+
+def test_ground_that_did_not_change_stays_quiet_between_two_passes():
+ """A radar sample is about 20 m, twice the grid's pixel, so speckle comes in
+ pairs of pixels. Averaged over five of them, two passes of fields or a town
+ that did not change gave a dozen candidates, as Istanbul, Emilia and Gaza
+ before October 2023 did; averaged over 90 m of ground, none."""
+ def correlated(mean_db, seed, step=2):
+ small = speckled(mean_db, seed, size=EDGE // step + 1)
+ return np.kron(small, np.ones((step, step)))[:EDGE, :EDGE]
+
+ def scene(seed, vv_db, vh_db):
+ product = np.zeros((EDGE, EDGE, 4), np.uint8)
+ product[..., 0], product[..., 1] = level(correlated(vv_db, seed)), level(correlated(vh_db, seed + 100))
+ product[..., 3] = 255
+ return product
+
+ for vv, vh in ((-10.0, -16.0), (-2.0, -9.0)):
+ before, after = scene(1, vv, vh), scene(2, vv, vh)
+ for rid in ("radar-change", "radar-razed", "radar-new-objects", "radar-flood"):
+ assert found(reading(rid, before, after)) == 0, rid
+
+
def test_every_radar_built_in_names_its_method_and_the_old_ones_stay():
ids = [r.id for r in BUILTINS]
assert ids[:8] == ["boats", "anomaly", "structures", "impacts", "large-change",
diff --git a/tests/test_regressions.py b/tests/test_regressions.py
index e6617cb..2ea9ac0 100644
--- a/tests/test_regressions.py
+++ b/tests/test_regressions.py
@@ -80,7 +80,7 @@ def test_grid_delete_cannot_name_the_case_manifest(client):
[
("proofs", "proof"),
("drafts", "draft"),
- ("inspect/sessions", "session"),
+ ("collages", "collage"),
],
)
def test_artifact_delete_cannot_name_the_case_manifest(client, route, kind):
@@ -91,6 +91,21 @@ def test_artifact_delete_cannot_name_the_case_manifest(client, route, kind):
assert manifest.is_file(), f"{kind} delete removed the manifest"
+def test_work_routes_cannot_reach_outside_the_case(client):
+ """A work is addressed by the file it belongs to, never by a path the client
+ builds, and a name only ever resolves inside the Inspect folder."""
+ case_id = _case(client)
+ manifest = Case.locate(case_id).path / layout.TOOL_DIR / "case.json"
+
+ assert client.get(f"/api/cases/{case_id}/inspect/works/..%5C..%5Ccase").status_code in (403, 404)
+ client.request("DELETE", f"/api/cases/{case_id}/inspect/work", params={"path": "../case.json"})
+ saved = client.put(
+ f"/api/cases/{case_id}/inspect/work", json={"path": "../case.json", "spec": {"frames": []}}
+ )
+ assert saved.status_code == 400
+ assert manifest.is_file()
+
+
# -- destructive-before-valid ------------------------------------------------
diff --git a/tests/test_satellite_api.py b/tests/test_satellite_api.py
index b41d9af..38cb6f0 100644
--- a/tests/test_satellite_api.py
+++ b/tests/test_satellite_api.py
@@ -12,6 +12,7 @@ from PIL import Image
from azimut import layout
from azimut.api import satellite as satellite_api
from azimut.engine import geo, tiles
+from azimut.workspace import Case
def _fake_tile(client, url): # offline: every tile is a solid green square
@@ -119,6 +120,25 @@ def test_capture_records_both_dates(client, monkeypatch):
assert listed["imagery_date"] == "2021-06-01"
+def test_an_estimated_imagery_date_is_marked_approximate_on_the_axis(client, monkeypatch):
+ """Esri's date is an estimate. The capture keeps the date it shows on its face,
+ and the Time panel places it with a `~` rather than as a known day."""
+ monkeypatch.setattr(tiles, "_default_fetch", _fake_tile)
+ cid = client.post("/api/cases", json={"name": "Sat"}).json()["id"]
+ estimated = client.post(
+ f"/api/cases/{cid}/satellite/capture",
+ json={"lat": 48.8584, "lon": 2.2945, "zoom": 16, "width": 512, "height": 512,
+ "imagery_date": "2021-06-01", "imagery_exact": False},
+ ).json()
+ assert estimated["imagery_date"] == "2021-06-01"
+ item = next(m for m in client.get(f"/api/cases/{cid}/media").json() if m["path"] == estimated["path"])
+ assert item["source"]["imagery_exact"] is False
+ entity = Case.open(cid).find_entity(attr="path", value=estimated["path"])
+ page = client.get(f"/api/cases/{cid}/timeline", params={"entity": entity["id"], "category": "media"}).json()
+ imagery = next(row for row in page["items"] if row["kind"] == "imagery")
+ assert imagery["raw"] == "2021-06-01~" and imagery["approximate"]
+
+
def test_capture_imagery_date_optional(client, monkeypatch):
monkeypatch.setattr(tiles, "_default_fetch", _fake_tile)
cid = client.post("/api/cases", json={"name": "Sat"}).json()["id"]
diff --git a/tests/test_settings_api.py b/tests/test_settings_api.py
index c6f7de4..81dac45 100644
--- a/tests/test_settings_api.py
+++ b/tests/test_settings_api.py
@@ -780,11 +780,11 @@ def test_per_provider_eco_thresholds(client):
assert by_id["sentinel2"]["eco_max_zoom"] == 0 # user turned eco off for it
assert by_id["google-js"]["eco_max_zoom"] == 0 # pinned, not settable
- # None removes the override: sentinel2 falls back to its own default (11)
+ # None removes the override: sentinel2 falls back to its own default (7)
r = client.put("/api/settings/prefs", json={"eco_max_zooms": {"sentinelhub": None}}).json()
assert r["eco_max_zooms"] == {"mapbox": 12}
by_id = {p["id"]: p for p in client.get("/api/satellite/providers").json()}
- assert by_id["sentinel2"]["eco_max_zoom"] == 11
+ assert by_id["sentinel2"]["eco_max_zoom"] == 7
def test_providers_expose_tile_size(client):
@@ -840,6 +840,17 @@ def test_extension_hand_off_switches_default_on_and_round_trip(client):
assert client.get("/api/settings").json()["reverse_prefill"] is False
+def test_map_tabs_share_one_camera_by_default_and_the_switch_round_trips(client):
+ assert client.get("/api/settings").json()["map_sync"] is True
+
+ saved = client.put("/api/settings/prefs", json={"map_sync": False}).json()
+ assert saved["map_sync"] is False
+ assert client.get("/api/settings").json()["map_sync"] is False
+ # a PUT about something else leaves it as it was
+ client.put("/api/settings/prefs", json={"units": "imperial"})
+ assert client.get("/api/settings").json()["map_sync"] is False
+
+
def test_display_prefs_reject_unknown_values(client):
assert client.put("/api/settings/prefs", json={"coord_format": "utm"}).status_code == 422
assert client.put("/api/settings/prefs", json={"units": "furlongs"}).status_code == 422
diff --git a/tests/test_settings_backup.py b/tests/test_settings_backup.py
index 2529e85..7d3bd53 100644
--- a/tests/test_settings_backup.py
+++ b/tests/test_settings_backup.py
@@ -80,6 +80,16 @@ def test_export_then_import_restores_keys_and_prefs(client):
assert restored["units"] == "imperial"
+def test_the_map_tabs_switch_travels_with_the_backup(client):
+ client.put("/api/settings/prefs", json={"map_sync": False})
+ blob = bundle_of(client)
+ assert blob["settings"]["map_sync"] is False
+
+ client.put("/api/settings/prefs", json={"map_sync": True})
+ client.post("/api/settings/import", json=blob)
+ assert client.get("/api/settings").json()["map_sync"] is False
+
+
# -- what the bundle carries ------------------------------------------------
diff --git a/tests/test_tiles.py b/tests/test_tiles.py
index 7fd6aa8..d9281a0 100644
--- a/tests/test_tiles.py
+++ b/tests/test_tiles.py
@@ -240,7 +240,7 @@ def test_all_providers_adds_sentinelhub_when_keyed(monkeypatch, tmp_path):
assert s2.max_zoom == 18
# its own eco threshold: the global z15 sits above its native ceiling, so
# sharing it would swap Sentinel-2 away at most zooms it can actually serve
- assert s2.eco_max_zoom == 11
+ assert s2.eco_max_zoom == 7
def test_sentinelhub_names_its_zoom_level_by_resolution(monkeypatch, tmp_path):
diff --git a/tests/test_timeline.py b/tests/test_timeline.py
index b22062d..eb4c4d3 100644
--- a/tests/test_timeline.py
+++ b/tests/test_timeline.py
@@ -120,6 +120,30 @@ def test_media_dates_keep_world_time_separate_from_case_activity():
assert by_kind["added"].category == "case_activity"
+def test_a_picture_of_two_moments_projects_two_dates_and_an_estimate_stays_one():
+ rows = timeline.project_media(
+ {
+ "source": {
+ "imagery_date": "2021-06",
+ "imagery_exact": False,
+ "imagery_a": "2024-05-03",
+ "imagery_a_exact": False,
+ "imagery_b": "2026-09-02T05:42:10Z",
+ },
+ },
+ "e_media",
+ )
+ by_kind = {row.kind: row for row in rows}
+
+ assert by_kind["imagery"].raw == "2021-06~" and by_kind["imagery"].approximate
+ assert by_kind["imagery-a"].raw == "2024-05-03~"
+ assert by_kind["imagery-b"].raw == "2026-09-02T05:42:10Z"
+ assert not by_kind["imagery-b"].approximate
+ assert {row.category for row in rows} == {"media"}
+ # two instants, not a range: neither row claims the time between them
+ assert {row.shape for row in rows} == {"instant"}
+
+
def test_old_malformed_time_stays_visible_without_blocking_a_rebuild():
row = timeline.project_entity(
{
diff --git a/tests/test_updates.py b/tests/test_updates.py
index 808505e..72a10c1 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.1"
-EXTENSION_PAYLOAD = "207f769e50979032a6052386396ece5972de7ce0f267c60e39e25e78806d5dca"
+EXTENSION_PAYLOAD = "839ff8e1d14d98d6b19ca5a0e0be4610e8b31ac17cf7654caeb210aad724ef3b"
# 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