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 the Timeline and entries, read every date on a Clock, and rebuild the analyzer builder (#97)

OsintMeThat5f5a70a6960f
diff --git a/README.md b/README.md
index 98c0173..40cd7d4 100644
--- a/README.md
+++ b/README.md
@@ -52,9 +52,9 @@ to fix a point on the map.*
| Tool | What it does |
|------|--------------|
-| **Board** | The whole case as one sortable table: typed identity fields per entity, one filter bar whose values are all taken from the case, shared Details, and a ticked selection deleted as one recoverable act. |
+| **Timeline** | The case on a time axis, and where events are noted: one line with a date, a sentence and `@` mentions. A point is an instant, a bracket a date known to the day or month, a bar a period; the ruler reads in any zone or at a saved place, the list copies out as a table, and a picked file plays in place. |
+| **Board** | The case as an index: people, accounts, places and things first, each with how many events name it and when, then the files and work folded under. One filter bar whose values are all taken from the case, Details beside the list, and a ticked selection deleted as one recoverable act. |
| **Graph** | The same case drawn. Lenses pick what a reading is about, nodes cluster, edges carry their verb, and a click opens what a node connects to without losing the picture you were reading. Graph and Timeline both export a reading as an SVG or PNG plate carrying its question, period and legend. |
-| **Timeline** | The same case on a time axis. Dated statements and media stack in coloured tracks, the ruler reads in any zone or at a saved place, date quality is drawn instead of flattened, and the window can be handed to Board, Graph or the map. |
| **Sheet** | The case's own CSVs in a plain grid: a comparison table, a worklist with its own state, or the half-facts too soft to be entities. Columns can be typed, a workbook arrives one sheet per tab, and a declared sheet promotes into entities, places and dated statements. A worklist can also be built back out of what the case holds. |
| **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. |
diff --git a/docs/IMAGERY_PROVIDERS.md b/docs/IMAGERY_PROVIDERS.md
index c8338eb..e1a5789 100644
--- a/docs/IMAGERY_PROVIDERS.md
+++ b/docs/IMAGERY_PROVIDERS.md
@@ -322,12 +322,12 @@ own scale), because an index computed on the server from two dark bands loses it
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
+bands as one more request per date and tile, which the wizard counts. A check in
+the builder reads the same products from the tile cache, on the tiles under its
+pins and across an edge from a pin within 48 pixels of it, at most twelve
+(`detect_rules.check_tiles`). What it still lacks is counted by `check/plan`
+before anything is fetched, and **Test** fetches it, one metered request each.
+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.
diff --git a/docs/ONTOLOGY.md b/docs/ONTOLOGY.md
index d7761fa..40b336b 100644
--- a/docs/ONTOLOGY.md
+++ b/docs/ONTOLOGY.md
@@ -14,7 +14,7 @@ same jump. Schema 11 gives each file one Inspect work, dates every kept Detect p
and stands every saved comparison on the map; 10 was a development checkpoint.
The entity/link shape is unchanged since v1. Breaking changes require
a manifest schema bump and migration. The internal SQLite schema is at version
-18: 8 adds `links.confidence`, 9 rebuilds the entity search index so a case
+19: 8 adds `links.confidence`, 9 rebuilds the entity search index so a case
search reaches the declared fields (§2) rather than stopping at the label and the
notes, 11 adds `links.nature` — what kind of tie an edge states, in the analyst's
own words, and only where the verb declares a qualifier (§3) — and 10 adds
@@ -50,7 +50,13 @@ authoritative. Schema 16 lets Analysis Views own Timeline recipes and immutable
temporal snapshots. Schema 17 rebuilds temporal bounds at fixed microsecond width so
SQLite text ordering stays chronological. Schema 18 rebuilds the projection for the
date a Proof states: a statement, because the analyst concluded it, beside the media
-rows that report what a file claims about itself. A Timeline view stores presentation
+rows that report what a file claims about itself. Schema 19 rebuilds the entity and
+media search indexes folded (case, and the marks a reader skips: Latin, Greek and
+Cyrillic accents, Arabic harakat, Hebrew points), the fold every search term gets as
+it is typed. The same unreleased schema 19 adds `entity_redirects` and
+`entity_merges` for explicit subject merges and their local undo journal, and the
+projection's `tz` column: the zone a value was stated in.
+A Timeline view stores presentation
and track queries, never copies temporal rows into the graph and never creates a
temporal relation.
@@ -181,7 +187,7 @@ answer by omission (`tests/test_entities.py`).
|---|---|---|---|---|---|---|
| `media` | collected | subject | ✅ | media-library | `path`, `sha256`, `source_url?` | yes (+ sidecar) |
| `capture` | collected | attestation | ✅ | satellite | `coords`, `lat`, `lon`, `plus_code`, `zoom`, `bearing`, `path`, `geo?` | yes (image) |
-| `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) |
+| `place` | place | subject | ✅ | satellite, ingest, enrich | `aliases?`, `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), one per file | yes |
@@ -189,18 +195,18 @@ answer by omission (`tests/test_entities.py`).
| `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) |
| `analysis-area` | document | annex | ✅ | detect | `spec` (json): a named, coloured area routines share | yes (`.analysis/areas-<id>.json`) |
-| `analysis-zones` | document | annex | ✅ | detect | `spec` (json): a saved set of areas | yes (`.analysis/zones-<id>.json`) |
+| `analysis-zones` | document | annex | ✅ | detect | `spec` (json): an ordered group of shared area IDs; older shape sets migrate on read | yes (`.analysis/zones-<id>.json`) |
| `analysis-follow-up` | document | annex | ✅ | detect | `spec` (json): an analyzer, its areas and a date rule | yes (`.analysis/followups-<id>.json`) |
| `analysis-run` | document | annex | ✅ | detect | `spec` (json): candidates, frozen inputs and review decisions | yes (`.analysis/runs-<id>.json` + `.assets/` previews) |
| `note` | document | annex | ✅ | notebook | `path`, `folder?` | yes (Markdown) |
| `sheet` | document | annex | ✅ | sheet | `path` (csv) | yes (CSV + sidecar) |
| `bookmark` | document | attestation | ✅ | capture extension | `url`, `fetched_at?`, `archive_url?`, `reliability?` | no (a URL) |
| `person` | actor | subject | ✅ | analyst | `aliases`, `role`, `nationality` | no |
-| `organization` | actor | subject | ✅ | analyst | `echelon`, `country` | no |
+| `organization` | actor | subject | ✅ | analyst | `aliases`, `echelon`, `country` | no |
| `vehicle` | asset | subject | ✅ | analyst | `plate`, `make`, `model`, `colour`, `condition` | no |
-| `vessel` | asset | subject | ✅ | analyst | `imo`, `mmsi`, `flag`, `kind`, `condition` | no |
+| `vessel` | asset | subject | ✅ | analyst | `aliases`, `imo`, `mmsi`, `flag`, `kind`, `condition` | no |
| `aircraft` | asset | subject | ✅ | analyst | `registration`, `icao24`, `model`, `condition` | no |
-| `structure` | asset | subject | ✅ | analyst | `kind`, `address`, `condition` | no |
+| `structure` | asset | subject | ✅ | analyst | `aliases`, `kind`, `address`, `condition` | no |
| `equipment-type` | class | subject | ✅ | analyst | `category`, `aliases` | no |
| `account` | identifier | subject | ✅ | analyst | handle in the label; `platform?`, `url`, `reliability?` | no |
| `email` | identifier | subject | ✅ | analyst | address in the label | no |
@@ -208,7 +214,7 @@ answer by omission (`tests/test_entities.py`).
| `domain` | identifier | subject | ✅ | analyst | hostname in the label; `registrar?` | no |
| `ip` | identifier | subject | ✅ | analyst | address in the label; legacy read-only `network?`; `asn?`, `provider?` | no |
| `network` | identifier | subject | ✅ | analyst | network/CIDR in the label; `asn?`, `provider?`, `country?` | no |
-| `claim` | claim | subject | ✅ | analyst | `count`, `condition`, `when`, `time_role`, `confidence`, `method`, `verbatim` | no |
+| `claim` | claim | subject | ✅ | analyst | `count`, `condition`, `when`, `when_zone`, `time_role`, `confidence`, `method`, `verbatim` | no |
Every row is created by something: the tool-born ones by the save that produces them,
the analyst's own from the board's **New entity**, which builds its form out of the
@@ -290,9 +296,9 @@ answers it against the case.
Three rules hold it together:
-- **It warns, it never refuses.** The case has no merge action, so a create that
- failed would leave the analyst holding a value with nowhere to put it. Both the
- create dialog and Details name the row already holding it and offer to open it.
+- **It warns, it never refuses.** The create dialog and Details name the row already
+ holding the value and offer to open it. Details also offers an explicit merge;
+ the warning never performs one automatically.
- **It catches the same value typed twice, not every spelling that resolves to the
same thing.** `+33612345678` is not compared against `0612345678` and
`www.example.org` is not compared against `example.org`: supplying a country code or
@@ -379,8 +385,19 @@ as unplaced rather than undated, but is not globally sortable. Two zoned timesta
may form an exact interval. Local-time intervals, mixed date/time intervals, open
intervals and the rest of EDTF Level 2 remain outside the announced profile.
-Time reads a derived SQLite projection, never a second authority. Claim `when` and
-`time_role` remain on the Claim; a Proof's `when` remains on the Proof;
+**A day is some place's day.** `when_zone` (an IANA name) says which clock `when`
+was stated on. A date then spans that zone's midnights, the 12th in Kyiv starting at
+22:00 UTC on the 11th, and a time with no offset of its own is placed on that zone's
+clock. A timestamp carrying `Z` or an offset keeps it; one put on a named clock is
+written with the offset that zone keeps then and keeps `when_zone` beside it, so it
+stays sortable and still says which clock it was read on. Without `when_zone` a date
+spans UTC's day, as every date stated before it did. A proof states its date on its
+first point's zone unless the analyst picks another, and the Claim it files for the
+footage carries the same zone.
+
+Time reads a derived SQLite projection, never a second authority. Claim `when`,
+`when_zone` and `time_role` remain on the Claim; a Proof's `when` and `when_zone`
+remain on the Proof;
capture/publication/imagery dates remain in the media sidecar; filing and collection
dates remain provenance. The projection labels them `statement`, `media` or
`case_activity`, and can be deleted and rebuilt from those records. A manually assessed
diff --git a/docs/SPEC.md b/docs/SPEC.md
index e994ed3..4a7601c 100644
--- a/docs/SPEC.md
+++ b/docs/SPEC.md
@@ -59,7 +59,7 @@ azimut/ # everything Azimut owns; the rest of the folder is yours
.data/ # case.db, the authoritative SQLite graph, and entity photos
.drafts/ # post drafts
.inspect/ # each file's Inspect work: its frames and their edits
- .collages/ # collage layouts; the picture one exports is media
+ .collages/ # collage layouts and their previews; 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
@@ -173,6 +173,7 @@ proof for publication.
| ✅ **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, place names, roads, railways, power lines, sea marks, GPS traces), NASA FIRMS fires and VIIRS night lights for a chosen day, and filters drawn pins by kind and folder. |
| ✅ **Added map layers** | Opens a KML, KMZ, GeoJSON or GPX file, or follows a public My Maps or map URL refreshed only while enabled, and draws it with its own colours, optionally its own icons composed once at import, a legend that filters and a search that goes to one feature — read, cited and never adopted into the case. |
+| ✅ **Added layer rows** | Folds each row to one line with icon acts, drags the rows into the order the map stacks them and refreshes every followed layer at once. |
| ✅ **Dates on a layer** | Narrows a dated added layer (GeoConfirmed, KML timestamps, GPX waypoints) to a period dragged on a strip of its events over time or picked on a calendar, kept with the legend. |
| ✅ **GeoConfirmed layer** | Adds one GeoConfirmed conflict over a window of days or dates or its whole history, optionally only the view, in GeoConfirmed's own icons, grouped by faction with each event's sources and geolocation one click away. |
| ✅ **Media on the map** | Draws the case's located photos and videos where a relation, a GPS reading or a proof puts them, opens the Map panel, the home map and the extension on them, and plays the stack in the panel beside the imagery. |
@@ -182,7 +183,7 @@ proof for publication.
| ✅ **Passes over an area** | Picks Detect's Copernicus dates from the passes the drawn areas really have, up to a year back or between two days picked in a calendar, each with the share of them its swath reached, and reports what a finished run actually swept. |
| ✅ **Cloud & shadow filter** | One click in Difference and Detect, both on Sentinel-2's scene classification: unsure edges taken, classified "clouds" too small to be one dropped, and shadows cast away from the sun, including the ones the classification read as water. |
| ✅ **Difference over any view** | A switch beside Compare's four views, offered on a matched pair only, laying its highlights on A, B or both (the default). |
-| ✅ **Detect** | Map-first tab, collapsible dock, shared case areas reshaped in place, an A/B When step with per-area dates that warns when the two passes' shadows differ, one-off and routine runs grouped in Saved, repeat notices and explicit SAT layer snapshots. |
+| ✅ **Detect** | Map-first tab, resizable dock, shared case areas in ordered groups, live A/B preview with per-area dates, one-off and routine runs grouped in Saved, repeat notices and explicit SAT layer snapshots. |
| ✅ **Capture scale & north** | Adds a scale bar and true-north needle to app and extension captures when resolution and heading are known. |
| ✅ **Footprint tracing** | Traces a place's uncertainty as a polygon around its pin, in place of the radius. |
| ✅ **Extension map tools** | Draws measure, the case's points one position at a time, sun and moon, search grids and case media over third-party maps, calibrated per site by a replayable command. |
@@ -195,15 +196,15 @@ proof for publication.
| ✅ **A date in one field** | Reads a day, a month, a year, a time or a range from one line of text, or builds one from a calendar with its marks of doubt, and says what it understood. |
| ✅ **Words that hold still** | One name for a Claim on every surface, a tooltip on every icon, a stated reason on a layer that cannot be switched on, the recent work first on Home, and Coords & Sky opening on the point the map is on. |
| ✅ **A picture sent to Reverse Search** | Opens Reverse Search on a Media Library file, from a row's Open in… menu, or on an Inspect frame as it is cropped, saved or not. |
-| ✅ **A claim from where you are** | Files a claim from Details, a Board row or a Graph node with the entity already seated, asking a count and a condition where its family calls for them and writing the sentence from the fields. |
+| ✅ **Add event from anywhere** | One line for an event under the Timeline axis, atop Details and over any tool (Alt+N), with `@` mentions that can file a new subject, what the tool shows already cited, and a date only the analyst gives. |
| ✅ **Radar Detect** | Five Sentinel-1 analyzers (vessels, any change, razed buildings, new structures, floods) through the user's own radar layer, calibrated on real scenes, held to one track. |
| ✅ **Sentinel-1 basemap** | Radar passes as a dated basemap in Satellite, Compare and Detect, named by day, UTC time and direction. |
| ✅ **All dates** | Lists every dated picture of the point in Compare, oldest first, to set on either side. |
| ✅ **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, painted rule by rule or as the detections alone, with a point reading; optional checks (marked places reread as the rules change) and five calibrated examples that ship with theirs; also opened from a built-in or a Difference reading, with a shape filter for every analyzer. |
-| ✅ **Examine: Inspect and Collage** | Keeps one work per file, saved as it is made, with its frames on a strip; lays collages out of frames and images from any file; merges a case's 0.3.0 sessions on open. |
+| ✅ **Analyzers of your own** | Builds a Detect analyzer for one satellite and one date or two, fixed when it is made, from up to six rules on any band, index, ground class or radar polarisation, read before, after or as the change; proved on checks made on the map (two passes on a split map and pins), tested on the ground under the pins with its cost said first, each rule painted and its effect on the pins read; five calibrated examples 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, listed as cards with a preview and exported at full resolution; 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 keeps its own, and Settings turns it off. |
| ✅ **Comparisons in Saved work** | A saved comparison stands on the map with the captures, at its frame's centre with the frame outlined, dated A → B, and reopens in Compare; an export can also be kept in the case under it. |
| ✅ **Dated pins and pictures** | A kept Detect candidate files a claim at its pin (a change between two passes, or a thing seen on one); comparisons and pinned evidence carry each picture's date, estimates marked; Detect layers filter a change by its span; exports are named by their pictures' dates. |
@@ -212,6 +213,12 @@ proof for publication.
| ✅ **One turn on every map** | A middle-drag turns any map or Inspect frame like a wheel about the grabbed point, settling on north, in 15° steps with Ctrl; a middle click or Shift+↑ puts north back, Shift+← / → steps. |
| ✅ **Checked proof points** | A proof point taken from a capture's centre reads greyed until checked; Save and To post show each one on the map first, and one saved for later stays off the case map. |
| ✅ **Compare and Detect full screen** | Both take the whole screen with their bars and panel, as Satellite does, and any change of tab gives it back. |
+| ✅ **A Timeline that reads at a glance** | A point is an instant, a bracket a date known to the day, month or year, a bar a period; it opens on the files where the analyst dated them over the events, imagery on a lane of its own, on the clock of the case's places, under one bar; reads axis and list as one, copies out as a table, and shows the file an entry is about. |
+| ✅ **Names in any script** | Search folds case and accents in Latin, Greek and Cyrillic and vowel marks in Arabic and Hebrew, reads month names in the browser's languages, and keeps right-to-left text in its own direction. |
+| ✅ **Subjects corrected safely** | Changes a subject's type without losing a field or a link, and merges two duplicates with a preview, redirects for the absorbed id and an Undo. |
+| ✅ **The Board as an index** | Groups the case by family, people, places and things first with how many events name each and when, the files folded under; Most noted first, Details beside the list, walked with the arrow keys. |
+| ✅ **Every date on a clock** | One Clock chip wherever a date is typed: a day or a time reads on its place's zone, UTC, this computer or any zone in the world, and the Timeline spans that zone's day. |
+| ✅ **Dates in posts, better templates** | A `#date` token carries the proof's date into a post only where a template asks; templates start from a layout, duplicate, preview on the open post with each platform's count, flag a misspelled token and set the default. |
---
diff --git a/docs/STORAGE_AND_PERFORMANCE.md b/docs/STORAGE_AND_PERFORMANCE.md
index 9d02237..85bb5dc 100644
--- a/docs/STORAGE_AND_PERFORMANCE.md
+++ b/docs/STORAGE_AND_PERFORMANCE.md
@@ -110,7 +110,7 @@ for a case to fit under it on Windows, and names it as a warning elsewhere.
entity-images/ # private, bounded entity photos and their thumbnails
.drafts/ # post drafts
.inspect/ # one Inspect work per file (.v1/ keeps 0.3.0 sessions)
- .collages/ # collage layouts; the picture is media
+ .collages/ # collage layouts and their previews; the picture is media
.compare/ # saved Compare session specs
.analysis/ # saved areas, saved detections, runs and the frames behind their results
.search/ # saved Grid Search state
@@ -276,7 +276,7 @@ review.
## Database shape
-`case.db` is at SQLite schema 18: schema 8 adds nullable `links.confidence`,
+`case.db` is at SQLite schema 19: schema 8 adds nullable `links.confidence`,
schema 9 rebuilds every row's `search_text`, schema 10 stores graph pins per lens,
schema 11 adds `links.nature`, schema 12 adds entity photo galleries, schema 13
adds saved analysis views with their bounded-list count, and schema 14 indexes the
@@ -284,7 +284,10 @@ two columns the catalog orders the whole case by. Schema 15 adds the rebuildable
temporal projection, schema 16 extends saved analysis views to Timeline recipes
and snapshots, schema 17 rewrites temporal bounds to fixed microsecond width, and
schema 18 rebuilds the projection once more, now that a proof's stated date is
-projected beside the dates its files carry.
+projected beside the dates its files carry. Schema 19 folds the entity and media
+search indexes, adds subject merge redirects and undo records, and gives the temporal
+projection a `tz` column for the zone a value was stated in. These changes share
+one migration from released schema 18; the case manifest stays at 11.
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.
@@ -304,6 +307,16 @@ use `.data/rename.json`, so a restart can finish references after the bytes move
### Tables
+`entity_redirects`
+: Absorbed id, surviving id, original label, optional coordinate key, merge id and
+ timestamp. Chains are compressed when another merge moves the survivor. These
+ rows travel in bundles when their target is still present; the merge id is cleared.
+
+`entity_merges`
+: Local undo journal containing the absorbed entity, original links and photos,
+ graph positions, changed live views, survivor fields and sheet edits. Completed
+ records remain until Undo or permanent deletion. Bundles omit this table's rows.
+
`meta`
: Schema version, case name and timestamps.
@@ -379,7 +392,8 @@ use `.data/rename.json`, so a restart can finish references after the bytes move
`temporal_items`
: Rebuildable, homogeneous rows for dated Claims, intrinsic media dates and case
activity. Each row keeps the raw value beside normalized half-open bounds,
- precision, timezone and uncertainty flags. Claims in `entities.attrs`, indexed
+ precision, timezone kind, the named zone it was stated in (`tz`) and uncertainty
+ flags. Claims in `entities.attrs`, indexed
media sidecars and entity provenance remain authoritative. Deleting this table's
contents and running `rebuild_temporal_projection()` recreates the same rows.
Window/category/owner indexes let Time and Timeline page without scanning entity
@@ -557,8 +571,19 @@ endpoints:
second cannot tie the paging into a loop. Both sort columns are indexed (schema
14), so an ordered page walks an index instead of sorting the filtered set in a
temp B-tree; `tests/test_repository.py` reads the query plan and holds it there.
+ `events` (the Board's *Most noted*) is the one ordering no index can serve: the
+ count of Claims naming each row. It is refused without a `type` set, so what it
+ costs is one Board group's rows, each an index search on `links.to_id`, and the
+ same test holds that plan too.
+- `counts=type` adds `by_type` to a page, the matching count per type under the same
+ terms, which is how the Board sizes every group of an answer in one request.
+- `POST /api/cases/{id}/catalog/events` takes a page of ids (200 at most) and says,
+ per id, how many Claims name it, when the dated ones fall, how many sources and
+ places they reach, and twelve buckets over the case's own span of dated Claims:
+ the Board reads it once per page of subject rows, and Details once per entity.
- `GET /api/cases/{id}/catalog/summary` returns `{total, by_type, by_status,
- by_folder, by_source, linked_to, unlinked, countable}` without shipping the graph.
+ by_folder, by_source, linked_to, unlinked, countable, lacks}` without shipping the
+ graph. `lacks` prices the two Claim questions, no source and not assessed.
`linked_to` counts entities that **have a neighbour** of each type, which is not how
many of that type the case holds: it is what the filter menu has to price itself
with, and the other number looks like an answer without being one. `countable` is how
@@ -729,6 +754,20 @@ geography itself, which makes the pass resumable and idempotent.
## Filesystem and database consistency
+A subject merge writes entities, links, galleries, graph positions, live views,
+redirects, temporal rows and its undo journal in one database transaction. Preview
+uses the same operation in a rolled-back savepoint. Incompatible links or cycles
+refuse the whole merge. Parallel relations with different confidence, nature or
+provenance remain separate. A snapshot is never rewritten.
+
+Sheet sidecar edits are recorded before the database commit, then applied with an
+atomic file replacement. Case open resumes pending edits, including interrupted Undo.
+The CSV and Notebook text are untouched. Subsequent sheet edits are preserved and
+reported when they prevent restoration. A pending sidecar write blocks another merge
+or bundle export until it can finish. Direct photos keep their existing paths; their
+database owner changes. Purging a survivor removes its redirects and merge history.
+Doctor reports redirects whose target is neither live nor in the Trash.
+
SQLite cannot atomically commit a filesystem rename, so file-backed operations are
recoverable. Creation produces a file under a unique temp name, validates it,
renames it to its final path, then registers it in a short transaction. Deletion
diff --git a/docs/UI.md b/docs/UI.md
index ec747ac..190ac00 100644
--- a/docs/UI.md
+++ b/docs/UI.md
@@ -6,10 +6,10 @@ phasing lives in [SPEC.md](SPEC.md).
## Layout anatomy
```
-┌ topbar: rose+wordmark (home) · case switcher + Board · (spacer) · guide mark · settings gear · sidebar toggle ┐
-├ rail ┬ tab strip (only when the workspace has several tools) ┬ case sidebar ┤
-│ │ tool canvas │ │
-└──────┴───────────────────────────────────────────────────────┴──────────────┘
+┌ topbar: rose+wordmark (home) · case switcher · (spacer) · Add event · guide mark · settings gear · sidebar toggle ┐
+├ rail: Sources · Examine · Map · Compose · ── · Case · … · theme ┬ tab strip (several tools only) ┬ case sidebar ┤
+│ │ tool canvas │ │
+└─────────────────────────────────────────────────────────────────┴────────────────────────────────┴──────────────┘
```
## Workspace model (UX)
@@ -20,18 +20,21 @@ in `frontend/src/lib/workspaces.js` and appear as tabs, never as new rail entrie
| Workspace | Tools today | Future tools land here |
|---|---|---|
| **Home** (the mark) | Overview, Guide | |
-| **Case** (topbar) | Board, Graph, Timeline, Sheet | v5: Orchestrator |
+| **Case** (rail, under the stages) | Timeline, Board, Graph, Sheet | v5: Orchestrator |
| **Sources** | Media Library, Files, Reverse Search | Channel Monitor, Evidence Locker |
| **Examine** | Inspect, Collage | Edit Provenance, Shot contact sheet, OCR, Image Compare, Hints, Sky Clock, audio |
| **Map** | Satellite, Compare, Detect, Coords & Sky | Event layers, Ground Imagery, Measures, Viewshed, OSM Query, Map Board |
| **Compose** | Geo Proof, Geo Report, Notebook | Report Builder, GIF maker |
-**Case is not on the rail.** The rail reads as a sequence of stages, and the case is
-not a stage: it is what every stage files into. It hangs off the case switcher in
-the topbar instead, so the header answers *which case* and the rail answers *what
-am I doing*. It stays a workspace in every other respect — tabs, `#case` deep
-links, and its own remembered sidebar. Timeline lives here because it is another
-reading of the case, not a collection or examination stage.
+**Case sits on the rail, under the four stages and a rule apart from them.** The
+stages read in the order an investigation runs, and the case is not one of them: it
+is what every stage files into. Kept in the topbar beside the case switcher, it was a
+door nobody took, so it is one press from any stage instead, while the header still
+answers *which case*. It is a workspace like the others: tabs, `#case` deep links,
+and its own remembered sidebar. Timeline lives here because it is another reading of
+the case, not a collection or examination stage. **Case** opens the tab last used
+there, and the Timeline the first time, since that is where events are noted and
+read; `#board` and the stored tool id `board` still reach the Board.
That sidebar stays closed by default, because the board already lists the same case
and two lists side by side only ask which one is real.
@@ -66,11 +69,12 @@ before; **Guide** is for somebody who has not.
- **What is waiting is the Board's own standing questions, priced.** *To review*,
*Nothing linked yet* and *Unfiled* are the same three terms the `+ Filter` menu
offers, worded once in `lib/entityFilter.js`; the fourth is the Timeline's undated
- count. They are drawn as four tiles, two by two, each one line — number, then what it
+ count of Claims. They are drawn as four tiles, two by two, each one line — number, then what it
counts — with the sentence saying what that means on the pointer. Pressing one hands
the **question** to the surface that answers it,
through the slot Board and Graph already share, so the table lands on exactly the rows
- the number counted and the two can never disagree.
+ the number counted and the two can never disagree. *No date yet* opens the Timeline
+ on its `Undated` queue, unfolded and scrolled to, with its first entry focused.
- **A count of nothing stops being a control.** It is dimmed and says zero rather than
offering a press that lands on an empty table to confirm what the page already said.
With all four at zero the tiles give way to one line, and that line is about the four
@@ -176,11 +180,40 @@ both under **Imports**. Pasting the same crop twice is one file.
## Board
-The case as one table: a row per entity, whatever type it is. It is what makes the
-hand-made vocabulary reachable — a `person`, an `account` or a `claim` had no screen
-before it. One view, a table; the graph is a different question and comes as its own
-view. Following a relation to a type with no tool of its own lands here, on that
-row's Details.
+The case as an index: who, what and where, then the material it is built from. It is
+what makes the hand-made vocabulary reachable — a `person`, an `account` or a `claim`
+had no screen before it. Following a relation to a type with no tool of its own lands
+here, on that row's Details, with its group open.
+
+- **Rows are grouped by family, never hidden.** *People & organizations*, *Accounts
+ & identifiers*, *Places*, *Things* and *Equipment types* open first; *Events*,
+ *Files*, *Work* and *Other* fold underneath, each one click from the tool that reads
+ it (Timeline, Media Library). A case is mostly files, and one table of everything
+ answered "what is in the database" rather than "who is this about". The question is
+ still the one Board and Graph share, so a count, a total or a drawing never depends
+ on which groups are open. Under a question every group holding an answer opens and
+ the empty ones go; a fold made during that question lasts as long as it does. A
+ case holding no subject opens its files and says how the index fills: a name typed
+ with `@` when an event is added, or **New**.
+- **A subject row reads by its events**: how many Claims name it, a dozen bars of
+ when they fall across the case's own span (one span for every row, so the column
+ reads as who was active when), and the dates they cover. One bounded read per page
+ of rows (`POST /catalog/events`), never one per row, and none on a frozen snapshot.
+ A material row keeps type, folder and created; an event row says when it happened,
+ as written.
+- **Sort** orders each group over the whole case: *Most noted* (the subjects most
+ events name first, the files newest first), *Name*, *Recently added*. Most noted
+ is asked of a group's types only, each row one index search on the links.
+ **Group: None** is the one flat table, headings and all, and a Board view saved
+ before the groups opens that way. Grouping, sort and folds are kept per case in
+ this browser, like the question.
+- **Waiting** lists the standing questions that count something (*to review*,
+ *linked to nothing*, *events without a source*, *not assessed*), one click from the
+ rows they count, while nothing else is being asked.
+- **Details opens beside the list** when the Board is wide enough for both, and over
+ it otherwise. `↑`/`↓` walk the rows and Details follows, so reading five people is
+ five presses; `Esc` closes it, and a row changed with edits unsaved asks first. Its
+ width is dragged from its edge and kept in the browser.
- **New entity** offers the types an analyst creates by hand and generates the form
from the registry. It is **one dialog shared with the graph**, so a claim is filed
@@ -188,13 +221,18 @@ row's Details.
It opens on the type being filtered for, or the first of the chosen family. The primary field names the value being entered — **IP address**,
**Full name**, **Handle** — never a generic **Name**. An identifier the case
already holds is flagged with the existing row one click away: a warning, not a
- block, since merging is not shipped. What it creates opens into its own Details.
+ block. Details can merge the two records after creation. What it creates opens
+ into its own Details.
- **Add file** takes a document, scan, plan or image into the case, by the button or
by dropping it on the list. It runs the Media Library's import, so the file is
hashed, deduplicated, given a sidecar and a thumbnail, and filed as a `media`. One
file opens its Details; a batch reports what landed and what was already there.
- **Search+** covers the label, type, folder, notes and declared text fields
(ONTOLOGY §2), in memory on a case that fits one page and server-side past it.
+ Both sides fold the text the same way (`engine/textfold.py`, `lib/textFold.js`):
+ case, the accents on Latin, Greek and Cyrillic letters, Arabic harakat and Hebrew
+ points, so `cafe` finds `Café` and `محمد` finds `مُحَمَّد`. A Devanagari vowel sign or a
+ dakuten changes the letter and still has to match, and punctuation always does.
The first matching field is named under the row, so a vehicle found by its plate
never looks like an unexplained result. Board and Graph send the same terms to the
same case predicate.
@@ -204,16 +242,19 @@ row's Details.
and a control that vanished took its own way back with it. An axis that cannot be
asked yet stays in the menu **with its reason next to it**, because a control you can
see and cannot use teaches something and one that is not there teaches nothing.
-- **The menu opens on four Questions** — *To review · Nothing linked yet · Added this
- week · Unfiled* — and picking one drops its terms in as ordinary chips. That is the
+- **The menu opens on six Questions** — *To review · Nothing linked yet · Added this
+ week · Unfiled · No source · Not assessed* — and picking one drops its terms in as
+ ordinary chips. The last two ask of Claims only: one that cites nothing, and one with
+ no confidence given (`lacks=source`, `lacks=assessment` on the catalog and graph
+ routes). The Overview keeps its four tiles. That is the
whole of the onboarding: the answer arrives, and the sentence that produced it is
sitting there to edit. They are code, not saved state, so nothing new has to reach
the backup.
-- **Nine axes, every value chosen from the case and counted**: a stored field and one
- of its values (*kind = video*), one or several types, one or several families, a
+- **Eleven axes, every value chosen from the case and counted**: a stored field and
+ one of its values (*kind = video*), one or several types, one or several families, a
folder with or without its subfolders or none at all, review state, a one-hop test
- for touching a type, having no connection at all, when it was filed, and what filed
- it. A count that would answer a *different* question is not shown: **Linked to a
+ for touching a type, having no connection at all, when it was filed, what filed it,
+ and a Claim with no source or no assessment. A count that would answer a *different* question is not shown: **Linked to a
place** is priced by how many rows touch a place, never by how many places the case
holds. A field with no value picked yet asks nothing, and a field the case holds too
many distinct values for is not offered — a menu of five thousand paths is not a way
@@ -272,6 +313,9 @@ row's Details.
so two analysts export the same file. The header states what the drawing holds and what
it leaves out: how many nodes and links are on it, entries with no date, nodes a fold or
a focus is holding back, verbs dropped where the drawing is too dense to carry them.
+ Nobody can hover a page, so a Timeline plate that left some names off its marks lists
+ every entry of the window under the drawing, date as written beside each, and its
+ header says `labels shown for N of M; the full list follows`.
- **The menu is where a list of readings is kept in order.** Every row states its mode,
its surface where the family holds two, and when it was last written — a distance up
to a week, then the date, with the exact UTC minute in the tooltip. Past one saved
@@ -287,19 +331,20 @@ row's Details.
case, while the complete case bundle is the one transmission boundary.
- **A proposal is settled from its row**: confirm takes its suggested relations with
it, dismiss is the standard delete, recoverable from the trash.
-- **Sorting** is a click on any heading, reversed by a second. Two of them name a
+- **Sorting**, in the flat table, is a click on any heading, reversed by a second. Two of them name a
column the store can order the **case** by — identity and created — so *newest first*
is the newest in the case rather than the newest of the hundred rows loaded. The
others sort what is loaded and say so beside the count while there are more. One
gesture either way: which of the two it is belongs to the column, not to a second
control the analyst has to find.
-- **Columns** are the four every entity has — identity, type, folder, created — plus
+- **Columns**, in the flat table, are the four every entity has — identity, type, folder, created — plus
the chosen type's declared fields once a single type is picked. Read-only: a value is
edited in that row's Details, and the Case Sheet works on the case's CSV files rather
than on these rows. A primary entity photo replaces the type
icon in the identity column; without one, the icon remains.
-- **A row is a control**: focusable, opened with Enter, and the review clicks inside
- it never open it.
+- **A row is a control**: focusable, opened with Enter, walked with the arrow keys,
+ and the review clicks inside it never open it. Adding an event about it is Details'
+ own **Add event**, not a press on every row.
- **A box per row deletes several at once.** A mistake is rarely one row — a folder
imported twice, a scraper run that filed forty of the wrong thing, a paste into the
case next door — and undoing that one Details panel at a time is what made a slip
@@ -443,7 +488,9 @@ single root to expand from. Expansion is the drill-down.
the picture and the toast's *Undo* is what takes the entity back, through the
standard recoverable delete.
- **A node reaches its row**, as a row reaches its node: *In the Board* opens the same
- entity in the table, and *In the graph* in any Details panel opens it here.
+ entity in the table, its group open and its Details beside it, and *In the graph* in
+ any Details panel opens it here. A Claim followed from anywhere opens on its own
+ Timeline entry, in Undated or off the UTC axis when it has no place there.
- **Find a node** by name, ranked most-connected first. On a case drawn at a few
hundred nodes, hunting one by eye does not work, and a canvas cannot be reached
from the keyboard at all — so this is both the way in without a mouse and the only
@@ -948,26 +995,131 @@ is a fact about the row rather than about anyone's filter. A place reached by `a
source reached by `cites` is listed without being counted: neither says how many of
anything.
-**Add claim files the common observation from where it is read.** The Claims group
-offers it on any entity a Claim can point at — before the first claim exists, since
-that is when it is wanted — and so do a Board row, beside its way into the graph, and
-a node's menu in the Graph. All three open one small form. The entity takes its own
-seat, read off the verb registry rather than a list of types: the first of `at`,
-`cites` and `about` that takes it, so a place is where the thing was seen, a file or a
-proof is the evidence, and a model, an object, a person or a handle is what the claim
-is about. A post or a saved session has no seat and no button. The family decides what
-else is asked: **How many** for a model, which is what a count is of, and
-**Condition** for a model or an object; nothing more for anyone else. The sentence
-writes itself from those fields and the connectors picked — `2 × T-72B3 destroyed at
-Crossroads`, `Seen at Crossroads` — until the analyst types their own, which then
-stays put whatever changes under it, with **Rewrite from the fields** to go back. A
-date is optional and is stated as *observed*, since the sentence says *seen*.
-Reworking a claim afterwards is the full editor's job, on the Time tab and the
-Timeline.
-
-**A Claim's fields use three sections**: statement, time and reasoning. The Time
+**Correcting a subject.** Details → Info offers **Change type…** for manually created
+people, groups, objects, models and identifiers. Places, Claims and file owners keep
+their type. A change lists incompatible relations or photos and stops before writing.
+Fields outside the new type remain under **Kept from …**, with an explicit Remove
+button; changing back makes them editable again.
+
+**Merge…** finds another subject of the same type, including places. The older record
+is selected to stay; either card can change that choice. The preview shows retained
+fields, additions, conflicts and affected references. Conflicting values go into
+attributed notes. A cycle or incompatible relation blocks the whole merge. Claims,
+files and documents cannot merge.
+
+**Undo** appears in the toast and in the survivor's **Merged from …** history. It
+preserves later edits and lists anything it could not restore. Later merges involving
+the same subject must be undone first. Frozen views and Notebook text stay unchanged;
+opening an absorbed subject reaches the survivor and says **Merged into …**. Bundle
+imports retain these redirects but cannot undo merges performed before export.
+
+**The entry line.** One line notes what happened: `[date · optional] │ sentence with
+@mentions │ 📎 │ Add`. It sits under the Timeline's axis; **Add event** at the top of
+any Details and a node's menu in the Graph open the same line with their entity
+already seated. Every entry is an ordinary Claim; the line only stops asking for the
+ontology up front. Every surface says one verb for it, *Add event*.
+
+**Add event from anywhere.** The topbar's **Add event** button (`Alt+N`, never inside
+a field) opens the line over the bottom of whatever tool is on screen, over its own
+Details or lightbox too, with what that tool shows already seated: the file whose
+Details or picture is open cites itself, and its one confirmed place is where it
+happened; the Board's or the Graph's open entity, the inspected file, the open proof
+or note, the place selected on the map. A place only suggested, or two of them, is
+not seated, since seating it would confirm it without the analyst deciding. The date
+stays empty, and the dates the place knows are offered beside it, one press each and
+never filled in by themselves: first what the analyst already concluded (the date a
+proof gives the footage, then a correction), then the file's camera, orbit and post
+dates, the camera first and the post last (a post rarely goes online when it happened,
+which its tooltip says),
+and in Compare each picture's day and the span between them, a release date marked as
+an estimate. A press fills the field, which stays the analyst's to correct, and the
+reading says where the date came from until it is changed. It closes after **Add**, on
+`Esc`, and when the analyst moves to another tool. On the Timeline the button goes to
+the line already under the axis, about the picked entry's file when it has one (as
+does **Add event from this file** under its preview), and on a frozen snapshot it is
+greyed with its reason.
+
+**Details opens on a summary.** Above Info · Connections · Time: the name, the type and
+other names, how many events name the entity with the sources and places they reach,
+when they fall across the case, **Timeline** to read them there, and **Add event**.
+Connections lists those events under *Events*.
+
+- **One thing to say is enough**: a sentence, a mention or a source. Left empty, the
+ sentence writes itself from what is on the line — `2 × T-72B3 destroyed at
+ Crossroads`, `Seen at Crossroads`, `Seen in clip.mp4` — and a sentence the analyst
+ typed is kept as typed, whatever changes under it (**Rewrite from the mentions**
+ goes back). **Add** is greyed only when there is nothing to say, and says so.
+- **The date is empty until given.** It is read like every other date field
+ (`dd/mm/yyyy`, month names, `~`, ranges), its reading is shown under the line, and a
+ date it cannot read holds the line back until it is corrected or cleared. Focused
+ and empty, the line lists what it takes, one example each (a day, a time, a month,
+ a year, about, unsure, a span), and says an empty date waits in Undated; the
+ calendar beside it builds a day, a month or a year for someone who would rather
+ point. The sentence, focused and empty, says the same about `@`, the paperclip and
+ `Enter`. It is
+ never taken from a file or from the previous entry; a click on the axis is the one
+ thing that offers one. Filed with a date, the entry is *observed*.
+- **Every date is read on a clock, and a chip beside the reading names it.** The same
+ **Clock** control sits wherever a date is typed: this line, the Timeline's
+ **Change the date**, the full claim editor, Details and the Proof composer. It shows
+ the clock and its offset on that day (`Kharkiv UTC+03:00`), and one press opens a
+ searchable list: the entry's own places (**Local at Kharkiv**), the case's clock, the
+ zones picked lately in this case, **UTC**, this computer, **Clock unknown** for a time
+ only, and every zone in the world. A day takes a zone as well as a time does: `10/09/2026` on
+ Tokyo's clock spans Tokyo's 10th on the axis.
+- **The clock opens on the place.** When the line has a place with a point (or cites a
+ proof with its own), a typed date reads on that place's zone, looked up once per
+ point from the bundled boundaries through `GET /api/geo/zone`. Two places in
+ different zones, or none, open on **the case's clock**: the one the Timeline's axis
+ reads on, where most of the case's places are unless the analyst moved it
+ (`lib/caseAxis.svelte.js`). A date typed with no place then lands on the axis where it
+ was meant, and each place is still offered. A clock typed with
+ the time (`14:30 UTC`) is kept, and a pick holds while the date is corrected.
+ `lib/clock.js` holds the one rule: the value is kept as typed with its zone beside it
+ (`when_zone`), a time also carries the offset its zone keeps then, summer time
+ included, and UTC is stored as no zone.
+- **`@` mentions anything the case holds**, through the catalog's own search, so other
+ names are found too. The list puts an exact name or other name first, then what the
+ line already mentions, then the rest, and says which field matched when it was not
+ the name. `↑`/`↓` move, `Enter` or `Tab` pick, `Escape` keeps the `@` as text, and an
+ `@` inside a word (an address) never opens it. The name goes into the sentence in
+ plain text, and the subject becomes a chip in its seat, read off the verb registry:
+ a place is where, a file or a document is the source, a Claim is only ever cited, and
+ anything else is what the entry is about. A click on a chip takes it off; `Alt+↓`
+ moves it to its next seat when it has one.
+- **A name the case has never held** is offered last as `New · name`, with a guessed
+ type that says its rule: an address, an IP, a network, a domain, a phone number, a
+ handle or a profile address by its shape, otherwise the subject type the case uses
+ most, otherwise a person. A place is never guessed, and a line cannot make one: a
+ place is a point. The chip's menu changes the type. An identifier the case already
+ holds is offered in its place (**Use the one in the case**) without refusing the new
+ one. Nothing is created until **Add**: the subjects and the Claim go in one
+ transaction (`create` on the claim route, ten at most).
+- **📎 cites a source** from what `cites` accepts: files, captures, proofs, web pages,
+ notes and other claims. The finder shows the kinds the case holds as chips with
+ their counts, plus Images, Videos, Audio and Other files. Format filters query the
+ whole catalog. The picker opens above the line when there is too little room below
+ and scrolls within the viewport. Fields and buttons share a 36 px height.
+ Every row says what it is: its picture when the case already has
+ one (`previews=true` on the catalog page, nothing made), its type, the kind of file,
+ its folder and the day it came in, newest first. The Claim editor's About, Place and
+ Evidence pickers use the same finder. A file dropped on the line is imported the way
+ the Media Library imports it, then cited.
+- **More** holds **How many** (a model) and **Condition** (a model or an object),
+ opened at once when the seated entity asks for them, **Confidence**, and **Full
+ editor**, which opens the complete Claim editor on the line as it stands.
+- `Enter` in the sentence adds, `Ctrl+Enter` adds from any field. After **Add** the
+ line empties and keeps the focus for the next entry, and the toast offers **Undo**,
+ which puts the Claim and the subjects it created in the Trash as one group. A refusal
+ keeps everything on the line and says why there. An unsaved line is kept per case for
+ the session, never on disk.
+
+**A Claim's fields use three sections**: statement, time and reasoning. Each says what
+it is for in a line under it: the sentence, the chosen date format (and that an empty
+date waits in Undated), the time role and the confidence, in the words the confidence
+scale is served with. The Time
section uses a guided editor for a year, month, day, date and time, bounded date
-range or zoned time range. Precision, certainty and timezone are chosen separately, so the analyst does
+range or time range, with one **Clock** row for all of them. Precision and certainty are chosen separately, so the analyst does
not need to remember suffixes or timestamp punctuation. **Advanced** preserves and
accepts the announced raw syntax. It opens a complete reference beside the field:
patterns and examples for reduced dates, local/UTC/offset timestamps, subseconds,
@@ -988,8 +1140,13 @@ recoverable Trash workflow.
## Timeline
Timeline is the third Case tab. Its main axis is horizontal and stores its window in
-UTC. One searchable picker decides what the labels read: UTC, this computer's zone, any
-zone in the world, or local time at a place the case has saved. A zone is named rather
+UTC. One searchable picker decides what the labels read, and it opens on **where the
+case is**: the zone most of the case's places stand in, read offline from their points
+(`lib/caseClock.js`) and saying how much of the case that is (`3 of 5 places`), because
+an investigation argues in the local time of where things happened. A case with no
+placed point reads UTC. UTC, this computer's zone, any zone in the world, or local time
+at a place the case has saved is one pick away, and the pick is kept per case in this
+browser. A zone is named rather
than offered as an offset, so a stated hour survives the two days a year the offset
moves, and each row shows the offset in force **at the window** rather than today's.
The list is the platform's own copy of the IANA database, so it matches the renames
@@ -1003,21 +1160,46 @@ strip, civil twilight and day are laid over it, and instants stay UTC underneath
whatever clock labels them. It is read from `/api/geo/daylight`, which is pure local computation and
answers a window wider than a month as cut rather than drawing stripes a few pixels
wide.
-Category tracks stack vertically. An instant is a point and an explicit interval is a bar.
-A reduced date stays a point, with a thin bounded line showing the whole year, month
-or day its precision covers. Approximate dates use a dashed edge and uncertain dates
-use a pattern. Suggested status uses a corner mark; refuted confidence strikes the
-label. The legend separates date quality from assessment confidence because the two
-are independent.
-
-The toolbar states the window in words, on the axis's own clock, between two step
+Category tracks stack vertically. A mark is drawn where its date is, to the pixel, and
+its shape says what kind of date it is: **a point is an instant, a bracket is a
+reduced date, a bar is a period**, and a box is never an instant. A reduced date is a
+thin line with a stop at each end, across the whole year, month or day it covers; once
+that period is narrower than a few pixels it is drawn as a point in its middle. A bar
+is as long as its period, down to two pixels, and a span running past the window has
+no stop on that side. Approximate dates have dashed ends, uncertain ones a broken or
+hatched fill, a suggestion is hollow and a refuted statement is faded with its name
+struck. The legend names the three shapes and keeps date quality apart from assessment
+confidence, because the two are independent.
+
+A mark never moves sideways for its neighbours or for what is selected. Marks that
+would overlap stack downwards, pinned ones first; a bracket or a bar takes the first
+row free across its whole span. A name is written beside its mark, right first, then
+left, and inside a period that can hold it, only where it covers nothing; otherwise the
+mark stands alone and its name is on hover, in the list and in the inspector. The
+selected entry is named first, and the same order on every render keeps names from
+jumping during a zoom. A track with at most twelve marks whose cards all fit hangs a
+card from each mark on a stem: the name, the date as written, and the cached preview
+of a file. Hovering or focusing a mark draws a line up to the ruler, one for an instant
+and one at each end of a span, with the date as written on the ruler. On a focused
+mark, `Alt` with an arrow moves to the entry before or after it on the same track.
+
+**One bar** sits over the axis: the window, its clock and the **Plot**/**List** split,
+then Views, Export and `⋯`. Under `⋯` wait what is asked for rarely: a track to add,
+grouping, the period handed to another tool, the legend and full screen. It replaced
+three rows of controls, a title repeating the tab and a line of mouse hints, which put
+the first entry halfway down the screen. The bar has no Add of its own: the line under
+the axis adds, and the topbar's **Add event** goes to it.
+
+The bar states the window in words, on the axis's own clock, between two step
arrows: pressing it opens the exact boundaries, the spans `Hour` to `Year`, and `All`
for the complete filtered extent. A span is asked for by name rather than reached by
repeated zoom steps, and the reading is what stays out because a window is checked far
more often than it is typed. Dragging the ruler pans directly. The wheel zooms around
the pointer; Shift-wheel and a horizontal trackpad gesture pan. Arrow keys, Page Up/Down, `+`, `-` and Home provide
the same navigation without a pointer. Full screen keeps the whole workspace available
-for dense cases.
+for dense cases, and is left from the bar. The corner of the ruler names its clock
+(`GMT+3`, `Aden time`), and a ruler, band or strip name that would land on another is
+shortened or left out (`lib/timelineFit.js`).
Only the visible window is read, 200 items at a time. A separate density request keeps
the full chronology visible underneath without loading every event. The minimap is a
histogram: one column per bin, as wide as the bin, stacked by category, with exact
@@ -1027,6 +1209,11 @@ happens to span drew one mark for a scraped batch of two hundred in a week and t
mark for a single entry that could be anywhere in a month. Column heights go by the
square root of the share, so that batch does not flatten everything beside it.
+The strip appears only once the window leaves part of the case out: opened on the
+whole case, the axis is its own overview, and the strip drew the same marks twice. It
+sits under the axis, so the axis does not move when it arrives, and its height comes
+out of the list rather than out of the lanes being read.
+
The visible window is a movable, resizable brush, and what it leaves out is dimmed.
Bars, date scale and brush are placed on one mapping from instant to position, which is
the only way the three can agree: what the brush covers is what the axis is showing.
@@ -1036,18 +1223,60 @@ as fit are printed. The columns answer the pointer and the space around them dra
brush, so a bar under the brush is still clickable; clicking one opens the axis onto
what that bin holds. `Case activity` is off by default. `Undated`
contains missing dates; a separate `Not on UTC axis` list keeps local timestamps and
-invalid legacy values visible without inventing a timezone. The date a fact entered
+invalid legacy values visible without inventing a timezone. A value stated in a zone
+names it wherever it is read (`12 Mar 2024 (Europe/Kyiv)`), and the inspector's
+**Timezone** says which clock a row is on, a plain day saying *Not stated, read as
+UTC days*. The chronology copy carries it in a `time_zone` column. The date a fact entered
Azimut never masquerades as the date of the fact.
-Overview stays above Plot or List, so expanding a dense track never pushes the global
-navigator below the chronology. Events are packed against their rendered labels.
-Overflow becomes a `+N` control that expands the track in place; **Collapse** in that
-track's left label restores the bounded view and its `+N`. Plot and List are
-two readings of the same loaded page.
-
-The Timeline opens with **Events** and **Media** tracks. **Track** adds editable
-presets for Events, Person, Place, Media, Sources and Case activity, using labels from
-the entity registry. **Custom** opens the shared Search+ builder, then states whether
+A track holds six rows of marks; past that, marks
+become a `+N` under their column that expands the track in place, and **Collapse** in
+that track's left label restores the bounded view and its `+N`.
+
+**The axis and the list are one reading**, stacked: the axis on top with its ruler
+pinned while its tracks scroll, a bar to drag between the two, and the list of the
+window's dated entries underneath, grouped by month on the axis's clock. A row gives the
+date, the statement, its subjects, places and sources, and in words what it still waits
+for: `suggested`, `refuted`, and for a Claim `no source` and `not assessed`. A link
+column no entry of the window fills is left out. An instant reads on the axis's clock,
+which the column heading names (`Date · Kyiv time`), so the list and the ruler agree
+about the hour; a day reads as it was stated, with its zone.
+The entry under the pointer lights both its mark and its row, picking a mark brings its
+row into the list without moving the axis, and a row opens with Enter and walks with the
+arrow keys. **Plot** and **List** say which of the two gets the room, and that is what a
+saved view's mode now means; dragging the bar moves it for the moment without rewriting
+the view. **Copy** puts the whole window on the clipboard, every page of every track up
+to 5,000 entries, as a Markdown table with its provenance quoted above it or as the
+tab-separated block a spreadsheet reads back as columns (`date_as_written`,
+`earliest_utc`, `latest_utc`, `statement`, `subjects`, `places`, `sources`,
+`confidence`, `status`). A frozen view copies what it froze.
+
+The Timeline opens on two tracks. **Media** holds the sources' pictures and videos
+where the analyst dated them, and nowhere else. A file is dated by the date typed on a
+proof (stated for the footage it rests on), by a correction, or by an event about the
+file or citing it. Each of those is a Claim, and the lane draws it as that file, with
+its name and picture, where the analyst put it (`as_files: "sources"`, `file` on the
+row). Picking it opens the event, and a click on the lane creates nothing, since there
+is no file to tie a new event to. What Inspect cut from a source (a frame, a collage)
+counts as the source's. **Events** holds every Claim as its sentence, a kept Detect pin
+among them. A proof's own date is not drawn beside the Claim it wrote for its footage
+while the two say the same date, so a proof dated once is one mark.
+
+Two more lanes are added from `⋯` on purpose. **Imagery** is the Media lane for what
+the app pictured from above: satellite captures, map screenshots, Compare renders and
+the pictures Detect keeps (`as_files: "imagery"`, the `FROM_ABOVE` routes). An event
+about a video that cites a render is the video on one lane and the render on the
+other. **File dates** holds what each file the case collected says about itself: the
+camera's clock, the day a picture was taken from orbit, the post's date. That is a clue
+rather than a finding, and a post's date is rarely when anything happened, so none of
+it is drawn by default. Like the Media Library, it holds back the working files the
+case made itself (frames, captures, collages, Compare renders). **Include working
+files** in a track's editor lets them in. A saved view keeps the tracks it was saved
+with. A row handed over from a file's Time tab adds the track that holds it, and lets
+a working file onto it. When the axis is empty, it says how many file dates the tracks
+leave out, and **Show them** puts them on. `⋯` adds editable presets for Events, Media,
+Imagery, Person, Place, File dates, Sources and Case activity, using labels from the
+entity registry. **Custom** opens the shared Search+ builder, then states whether
that question matches the entry itself, its subject, place, evidence, or any of those
connections. Category and time-role filters remain separate from that question.
@@ -1055,7 +1284,8 @@ Each track shows its name over two lines before the ellipsis, and hovering it na
categories and the Search+ question the lane was filled from. A track can be given a
**colour**: left on **Auto** its entries keep the category colours the legend explains,
and a chosen colour wins for that track alone. Each track has one reorder grip and a
-fold control. Dragging the grip changes its
+fold control; the grip and the edit, duplicate and delete buttons come with the pointer,
+and a count shows only where the lane holds something. Dragging the grip changes its
position; `Alt` with an arrow key provides the same action. The track menu can rename,
duplicate or delete it. Selecting an entry exposes **Pin in track** and **Hide from
track** in the inspector. Pinning keeps an entry out of density overflow, while hiding
@@ -1076,21 +1306,33 @@ temporal rows with their exact track assignments and opens read-only. It does no
the current case when reopened. Timeline views can be renamed, duplicated, deleted
through Trash, restored and carried in a complete case bundle.
-A track that includes Claims can create them; Media-only and Case activity
-tracks cannot. Clicking empty space creates a point; dragging creates a bounded range.
-At day scale and below these are zoned timestamps and time ranges, so hours can be
-created, moved and resized directly. Date-only Claims support the same confirmed move,
+**The entry line sits under the axis**, outside a snapshot, and is where a new entry
+is written (see *The entry line* below). A track that includes Claims can date it;
+File dates and Case activity tracks cannot. Clicking empty space puts a point on the
+line's date and moves to its sentence; dragging puts a bounded range. Nothing opens
+over the axis. When the entry lands somewhere the reading does not show, the toast says
+where: no Events track shown (**Show** adds one), outside the window (**Go there**), or
+in Undated. The date proposed is as precise as the window it was pointed at: a zoned timestamp on
+a window up to three days, a day up to 400 days, a month up to twelve years and a year
+beyond, so hours can be created, moved and resized directly on a short window and a
+click on a decade does not claim a day. Date-only Claims support the same confirmed move,
and intervals expose both resize edges. Every direct write shows the old and new
values before saving.
-Selecting an entry opens a fixed-width inspector without changing the axis geometry.
-It shows the readable and raw date, precision, timezone, authority, role, status,
-confidence, reasoning and named subjects, places and evidence. Statements can be
+Selecting an entry opens the inspector beside the axis; with nothing picked there is
+none, and the axis has the width. It is headed the way the entry's track is, **Event**
+or **File date**. **A file is shown at its top**: the picture, the video ready to play
+or the sound, for a file's own date and for an event about or citing one, the file an
+event is *about* first (a proof's date shows the footage, not the proof), with the
+list's thumbnail as its first frame and one press to full screen. Below it, the date on
+the axis's clock with the value as stated under it, one way to change it (the date and its **Clock**), reasoning and
+named subjects, places and evidence. How the date is held (the raw value, precision,
+timezone, authority, role, status) is folded under **About this date**. Statements can be
edited there. **Right-clicking an entry** — on the axis, in the list or in either
holding queue — names the same four acts where the pointer is: pin, hide, Details and
Edit claim. It changes no selection, so a pair being measured survives it, and the
two lane acts follow the inspector's rule of appearing only for an entry that has a
-lane. A media date offers **Add correction**, prefilled from the intrinsic
+lane. A media date offers **Correct this date**, prefilled from the intrinsic
date; saving creates a sourced Claim about the media and does not rewrite its sidecar.
The Details view keeps Claim time fields in **Time**, not **Info**. `Open in Timeline`
applies a visible entity chip that can be cleared in one click.
@@ -1111,9 +1353,7 @@ other Claims.
### One period, four surfaces
-**Open in** ends the track row, not the boundaries menu: a window is set rarely and
-asked of the other surfaces often, so the three targets stay one click away while the
-header keeps the window alone in its middle column. Board and Graph receive it
+**Open this period in**, under `⋯`, hands the window to Board, Graph or Map. Board and Graph receive it
as a **fact-time** filter and say so in a bar above the answer, with the way back to
Timeline and Map and a Clear. That filter is the question, so it narrows the page, the
totals and a saved view alike, and it never touches `since`/`until`, which ask when a
@@ -1259,12 +1499,30 @@ 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.
+Pieces come from **Frames**, the works of any file with the files last worked on
+first, or **Images**, any case image with the last added first. Each file shows its own
+thumbnail, one unfolds at a time, a search box beside the tabs narrows either list, and
+the list scrolls on its own so the controls below it stay in reach. 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 selected piece is named by its file and, for a video, the time
+it was cut at.
+
+**The export keeps full resolution without a setting.** It is a transparent PNG of the
+pieces trimmed to their bounds, enlarged until the sharpest piece is back at its own
+pixels, however small it sits on the canvas. It holds under 8192 px a side and 40
+megapixels in all, and the size it will have is written under Save to case.
+
+**The list shows what each collage holds.** The start page lays the collages out as
+cards and the Collages window as rows, each with a preview. The tool draws the preview
+itself once the pieces are in and the layout has settled, and files it beside the
+collage, so it follows a rename and the Trash and travels in a bundle. Entity pickers
+show the same picture. A collage with no preview yet shows its pieces'
+outlines. A small green check means the picture it exports is in the case as the
+layout stands. Once there are two, a search box narrows the list to the names holding
+every word typed, whatever their accents. **Close** in the header of an open collage waits
+for the last save and goes back to the list; a save that failed keeps it open.
**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
@@ -1328,15 +1586,20 @@ each one small from the tile proxy, priced before it is pressed and cached once
read, and a view that moved says so rather than refreshing on its own.
Difference opens no column: its strip joins the view's own controls in the footer
-under the stage, and its full settings open above that strip only from the gear.
-The strip keeps one width through a read, so the panel hanging from it stays put
-and the gear never moves. **Read** says what the reading is doing on the button
+under the stage, and its full settings open from the gear in a panel docked on
+the stage's right edge, under B's card. The panel lies over map B rather than
+narrowing the maps, since a narrower view would fetch Sentinel-2 bands again;
+it takes the glass of the map's floating panels (88% and a light blur), and the
+search, camera chip and legend step left of it. Read keeps one width through a
+read, so the gear never moves. **Read** says what the reading is doing on the button
itself: amber **Read** when pressing it is the next move, **Reading…**,
**Loading…** while map tiles are still coming in, and a disabled **Up to date**
when nothing moved since the last read. The map legend says the same in words
("out of date, press Read"). A reading waits for tiles to finish instead of
failing on them. The panel
-lies over the highlights and closes on Escape or a press anywhere outside it.
+lies over the highlights and stays open while the map pans or zooms, since
+tuning is watching them answer; the gear, its close button or Escape put it away,
+and it opens closed each time Difference comes on.
**Difference** checks that the sources can be compared before it runs.
Colour, structure and brightness methods read captured pixels in a worker.
@@ -1623,8 +1886,8 @@ which it is (`lib/map/tools.js`) rather than adding a button somewhere.
layer`. The line between the two is *who chose it*: the stack above is the
app's, this one is the analyst's. A row here carries four things a curated row
has no use for — where it came from, how fresh what is drawn actually is, a
- legend that filters, and Refresh and Remove. See
- **Added map layers** below.
+ legend that filters, and Refresh and Remove. Its rows are the map's stack,
+ top first. See **Added map layers** below.
- **The picture** — the provider, the Sentinel-2 layer and date, when the pixels
were taken, the eco and usage pills, and the compass — belongs to the
*surface*, in its own top-right corner. Which imagery is on screen is a
@@ -1795,7 +2058,19 @@ layer is labelled on the map; a feature's name is in the hover and in the card.
Far out, where the marks would be a solid mat, the map keeps only those that fit
and draws the rest as dots, so a dense layer never looks emptier than it is.
-**Refresh and Remove** sit under the row. A followed map is re-read
+**A row opens folded to one line**: the switch, the name, and Refresh and
+Remove as icons, Refresh only on a followed map. Unfolding it shows where it came
+from, how fresh it is, the counts, the time strip and the legend. A folded row
+still says when its copy is stale, with its name in the warning colour and a
+mark beside it. Every row starts folded on every visit, except the one just
+added. **The list is the stack**: the first row draws on top, and the grip left
+of the switch drags a row to another place, or moves it one place with the arrow
+keys. The order is kept on each layer, and a new layer lands on top. Added
+layers stay above the app's own overlays whatever their order. The section head
+carries one more Refresh, for every followed layer at once, read one after the
+other with a single toast at the end.
+
+A followed map is re-read
when it is added, when Refresh is pressed, and the first time it is switched on
after the app or the page opens — never on a timer, and never while it is
switched off. **Every added layer starts off** when the app or the page opens
@@ -2092,12 +2367,11 @@ 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
-row appears only inside a routine, a review, the wizard or the library, where it
-carries Back. **Analyzers** sits at the end of the tab row, then **Full screen**,
-which gives Detect the whole screen with its dock. Its toggle or the `]`
-key collapses the dock to an icon rail; pressing a tab reopens it and resizes the
+The right dock has a Detect heading with collapse, **Analyzers** and **Full screen**
+controls. Routines, Saved and Areas sit in a tab row below it, with New detection
+at the top of the content. A second heading appears inside a routine, review,
+wizard or library, where it carries Back. Full screen includes the dock. The
+collapse button or `]` reduces the dock to an icon rail; pressing a tab reopens it and resizes the
map. Detect's basemap, overlays, saved-work visibility and collapsed state are
viewer preferences carried by Settings → Backup. **Watched areas** is a row of the
map's own layer list, beside Saved work.
@@ -2119,6 +2393,21 @@ area at once, and deletes. Deleting an area used by a routine lists the routines
that must release it first. A routine and a one-off run can share an area.
Older routines migrate their embedded zones to shared areas on first read.
+Areas can be put in several named groups without copying their geometry. The
+Areas tab lists groups in a saved order, folds each one, searches through folded
+groups and keeps areas with no membership under **Ungrouped**. Dragging a group
+or an area changes its displayed order; dragging an area to another group moves
+that membership. The dragged row fades, a rule marks its insertion point, and
+the destination group lights up. Its menu can add the same area to another
+group, move it or change the order without dragging. Folding a group does not
+hide map outlines.
+Removing a group leaves its areas in the case. Older saved area sets become
+groups on first read: shared outlines are reused, while temporary drawings and
+outlines that have changed since the set was saved become shared areas with
+their saved shapes. If a shared area's current outline differs from the saved
+one, Areas asks which shape the group should use; Where holds that group until
+the choice is made. Both areas remain in the case after the choice.
+
The list holds two kinds, and **New detection** asks which before asking anything
else, because the answer changes every question after it:
@@ -2129,15 +2418,18 @@ else, because the answer changes every question after it:
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 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.
+ in that layer, so its date filter finds it in any period between them. A group
+ folds shut from its heading; its colour square changes the routine's colour
+ and its saved map overlays. A one pass has its own small colour square, which
+ changes that run's saved map overlay.
- a **routine** is a place you come back to. It keeps its areas, its analyzer and
what each pass compares against; it is run again whenever there is a new pass,
and it remembers what it found.
A routine's card carries what it is for, its analyzer, its areas, its rule and
where its last run stands: the day of the pass it swept and how many candidates
-are still to review, or how far a working one got. The play button opens the launch
-table, **Run all** queues idle routines with their saved rules, and the title
+are still to review, or how far a working one got. The play button opens dates
+in the dock, **Run all** queues idle routines with their saved rules, and the title
opens the routine's own page. **Analyzers** is where the things a detection looks
for are made.
@@ -2148,9 +2440,13 @@ Areas tab. Hovering a routine draws its areas heavier.
A routine's page leads with **Findings**: every candidate it has kept, as a pin or
just here, newest run first, each marked **Pinned** or **Kept here** and a press
away from the evidence it came from. **Runs** beside it lists its passes, each
-opening its own review. **Run routine** opens a floating table with a row for each
-area, its A and its B (the newest pass by default), each read and written as the
-app's own day-first date field. One button queues the run, naming what it covers.
+opening its own review. Opening any run shows only that run's saved overlay;
+Back restores the saved eye states from before the review. **Run routine** opens dates in the right dock, with A and B
+for every area. B is the newest eligible pass by default. **The pass before**
+takes A from that area's last completed pass; the first run uses its chosen A.
+Only areas with a newer eligible B are queued. If every area is current, no run
+is created. The dock resizes from its left edge between 300 and 720 pixels,
+while keeping room for the map.
The page also offers **Export as layer**, editing and deletion.
Either kind is built one step at a time: **Where**, **What**, **When**, then
@@ -2167,33 +2463,35 @@ the result before anything is fetched: ground area, native tiles, Copernicus
requests and roughly how long. Each date costs two requests a tile, the picture
reviewed and the bands measured. A radar vessel sweep adds one for the Sentinel-2 water
classification it is judged against. One-off drawings stay temporary unless **Save as area** is pressed;
-saving a routine promotes its drawings. Legacy area sets remain readable. An area is grabbed by its edge: dragging inside
+saving a routine promotes its drawings. In **Where**, the same groups select
+their current areas in one press, without duplicates, and ungrouped areas stay
+available on their own. A selection can be saved as a group; temporary drawings
+become shared areas first. A routine keeps the areas selected when it was saved,
+so later group edits do not change its scope. An area is grabbed by its edge: dragging inside
one pans the map as it would anywhere else, a click on the edge shows its corner
handles, and a press that does not travel selects without nudging the geometry.
Handles and outlines are projected from the ground, so they stay on it through a
pan, a zoom or a turn.
-**When** asks its questions in the order they are decided, in the step itself. A
-change names **A**, the picture before, and **B**, the one to look in; B is the
-newest pass under the cloud ceiling, and its button names the ceiling (**Newest
-pass under 30% cloud**), since it is not always the newest pass there is. Once
-the passes are found, the line under it names the day it takes and the newer ones
-it steps over, each with its cloud. The ceiling's slider, 30% to start, sits
-wherever the newest pass is taken: under that button, and under a routine's
-question. Above 30% it warns that the pass taken can be mostly cloud. **A day I
-choose** asks for one, and a chosen day is read whatever its cloud: the ceiling
-only picks the newest pass, and ground under cloud is left out pixel by pixel.
-The map shows a chosen day whole, as the run reads it, and its chip adds the
-tile's cloud when that is over 30%. Vessels and hotspots read one image and
-ask only that. A routine names no B: it asks what each run compares the newest pass with,
-**The pass before** (what changed since the last run; A serves the first run only)
-or **A fixed picture** (everything changed since that day), and a one-image routine
-asks nothing but its cloud ceiling, with its picture under **Picture**. The slot still missing is tinted,
-and the reason is written under the Next button. **Passes over the area** lists
-what exists right under the question, each row with its A and B buttons, and a
-typed day works too. One choice stands for every area; **Set them per area…**
-opens the per-area table for areas far enough apart to sit under different swaths,
-and the step then lists each area's days. When the two days see the sun at very
+**When** asks its questions in the step itself. A change names **A**, the picture
+before, and **B**, the one to look in. B is the newest pass under the cloud ceiling
+set in **What**, below target size. After a pass lookup, the step names the chosen
+day and any newer passes skipped for cloud, with their cloud percentage and limit.
+**Date A** and **Date B** each open a calendar of available passes for that area.
+Days without a pass or outside A-before-B order cannot be selected; optical pass
+days show cloud cover, and radar days with multiple passes offer their times. A
+chosen B is read whatever its cloud: the ceiling only picks the newest pass, and
+ground under cloud is left out pixel by pixel. **Use newest pass** returns B to
+automatic selection. Selecting A or B shows that image on the map at left,
+framed on its area. The map chip names the area and side. Vessels and hotspots
+read one image.
+A routine names no B: it asks what each
+run compares the newest pass with, **The pass before** (A serves the first run
+only) or **A fixed picture**. For multiple areas, each area has its own visible
+pass picker and dates; **Find passes** opens directly below that area's dates,
+and a lookup selects and previews passes for that area. The
+slot still missing is tinted, and the reason is written under the Next button.
+When the two days see the sun at very
different heights, the step says how long a 10 m building's shadow is on each: past
half a pixel of difference most buildings read as changed, as a January and a
September pass over an airbase showed. The last step reads the choice back in
@@ -2204,16 +2502,17 @@ a track, so the rows on the other track are closed to the pair. A day typed by
hand is pinned to the pass on the other side's track at launch, and an automatic
pass is looked for on the reference's track.
-**Find passes** explicitly asks Copernicus about the areas and counts one request
-a catalogue page against its quota, which is one for most windows. The picker
-shows coverage over all of them and the cloud of each pass's 110 km tile, so a
-small area can be clearer or cloudier than its row says. It looks 30 days, 90
-days or a year back, or under **Dates…** between two days picked in a calendar
-that starts at the satellite's launch. The catalogue answers newest first and a
+Typing a date remains available inside each open calendar. **Find passes**
+explicitly asks Copernicus about the areas
+and counts one request a catalogue page against its quota, which is one for
+most windows. The list shows coverage over all of them and the cloud of each
+pass's 110 km tile, so a small area can be clearer or cloudier than its row
+says. It looks 30 days, 90 days or a year back. The catalogue answers newest first and a
lookup reads up to five pages, so a list it still cut short offers **Older
passes**, one more lookup for the ones before the oldest listed. At launch, each area independently resolves its latest usable pass
under the cloud ceiling. Different tracks can therefore use different days.
-An unresolved area fails by name without stopping the rest. Opening Detect reads
+A cloudier newest pass is reported as skipped. An unresolved area fails by name
+without stopping the rest. Opening Detect reads
local state only; pass lookups happen only on request or during an explicit run.
**What** picks the analyzer from a list grouped by what it looks for — vessels,
@@ -2289,100 +2588,106 @@ the way, and tuning them there changes this detection only.
**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
+pass**, **1 fails**, **not tested**). **New analyzer** asks what the analyzer
+reads before anything else: **Sentinel-2 · optical** or **Sentinel-1 · radar**
+(which says what it needs while Settings has no radar layer), and **One date**
+or **Two dates**. That is fixed for good, so its rules and checks always fit it:
+the builder shows it as a locked chip, offers only the measures and dates that
+fit, and another satellite or number of dates is a new analyzer. A saved one
+that never declared it gets it from its rules, once. The same screen offers
+**Blank**, with one rule to begin with, and the ready examples that read the
+same thing: a fresh burn (Lahaina, August 2023), a forest cleared (Grünheide,
+2019 → 2020), water drained (the Kakhovka reservoir, June 2023) and a solar farm
+built (Dubai, 2019 → 2023) on two dates, ships at anchor (Fujairah, one pass) on
+one, each with its checks. A press copies an example into the library at once,
+checks and all, under a free name, and opens it with its first check on the
+map. A built-in opens read-only with **Copy to tune** (and **Open as rules**
+where it has them, which is burn scars, vegetation loss and new water): the copy
+keeps its calibrated method while its name, sizes, thresholds, candidate label
+and colour become yours. 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, the locked chip and the sentence the analyzer reads
+as at the top, and three tabs: **Rules**, **Checks** and **Settings** (sizes,
+shape, cleanup, smoothing, grouping, description, candidate label and colour).
+Over the rules a strip names the check on the map, says how it last came out and
+carries **Test**. A rule reads as the sentence it says (*NDVI dropped by 0.25 or
+more*); its dot carries its number and its map colour and hides or shows its
+pixels, and ★ ranks the candidates by it. A rule names a quantity, when it is
+read, and 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. On two
+dates it is read **Before**, **After** or as the **Change** (after minus before,
+so a loss is negative), and says which half of the split map it is painted on;
+one date has nothing to choose. The line is a direction and an amount: a change
+**Dropped**, **Rose** or moved **Either way**, a state **At least** or **At most**
+a value, and either **Between** two values, with a drop entered as its size.
+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 the ground around it** 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. **Rules** and
-**Detections** beside the count switch the map between that painting and the
-outlined candidates alone, as a run shows them; the dots keep their state for the
-way back, and one pressed from Detections returns to Rules. While a check is open
-the count is the check's own, since the map shows its frame only. 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 a check is open the
-preview and its candidates stay inside its frame and the ground outside is veiled,
-so what the map paints is what the check judges. 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.
+passes** all the rules or any rule. 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). 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 where checks are made and tried, and a console over it holds the
+controls. Its selector picks the check on the map, **Basemap only** to see the
+basemap alone, or **New check**. A check of two dates splits the map between its
+passes: the before pass on the left and the after pass on the right, each on its
+own map with the two cameras held together and a handle to drag the cut, and
+**Before**, **Split** and **After** switch between the whole map on one and the
+cut. A check of one date shows its pass on one map. An eye puts the basemap in
+the passes' place and back, and the layer menu picks the Copernicus layer they
+are shown in, with the one that reads rule ★ best marked.
+
+**Checks** are how an analyzer is proved, and one is needed to save it, with a
+pin where something should be found; the others may be traps, where nothing may
+be. A check is two passes (one, for one date) and the pins laid on them. It has
+no frame: it reads the ground under its pins, the tile under each and the tile
+across an edge when a pin is within 48 pixels of it, at most twelve tiles.
+**New check** opens a drawer over the console that takes its passes: a look-up
+for the ground at the middle of the map over 30 days, 90 days or a year, one
+Copernicus request, or **Dates**, which picks each side from a calendar of the
+month's passes, coloured by cloud and offering only days that keep the two in
+order, or from a typed day, as a routine does. The pins come next: **Should be
+found** and **Should stay empty** arm a pin, every click on the map drops it,
+on either half, and Esc puts it down. **Finish** keeps the check, which needs a
+pin; until then the column waits, dimmed, and **Cancel the check** gives it up.
+The Checks tab lists every check with how it came out, **Test all** with what it
+would cost at most, and for the one on the map its name, its passes and its pins
+to turn or take away.
+
+**Test** runs the rules on the ground under the pins and says, before it is
+pressed, how many Copernicus requests it will fetch (none once its frames are
+held), and nothing runs on its own: after a change to a rule or a pin the picture
+dims and the button reads **Test again**. A test paints each rule's pixels in its
+colour, what reads the before pass on the left half, the after pass on the right
+and a change on both, tints the ground it measured so that ground no rule kept
+still reads as tested and cloud stays clear, and outlines the candidates a run
+would return there, since it runs the engine's own evaluation, cleanup, sizes,
+shape and grouping. Each pin turns green or red as it comes out, and the row
+under the console says **2 of 2 found** or **1 of 1 flagged**, keeps a chip for
+every rule, to hide its pixels and see which ones help, and switches the map
+between **Rules** and **Detections**. Each rule's card gives the share of the
+measured ground it keeps, lays the pins along its slider where they were read
+(filled where they should be found, struck where none should), so the line can be
+set between them, and says what the pins would have come to without it (**Without
+it, 1 pin would come out wrong** means the rule keeps pins right, and one that
+would make pins come out right is losing them). 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, and the card can
+drop a pin there; a pin opens the same card to turn it the other way or take it
+away. 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
@@ -2557,7 +2862,10 @@ The **date** is when the material was taken, in the same profile a Claim's *When
uses — a day, a month, a year, a timestamp or a range, with `~` for approximate and
`?` for uncertain — typed into **one field** rather than assembled from a format, a
precision and a certainty. It reads `24/10/2025`, `Oct 2025`, `2025`, `~2025`,
-`24/10/2025 14:30 UTC` and two of those joined by *to*, keeps anything already
+`24/10/2025 14:30 UTC` and two of those joined by *to*. Month names are read in
+English and French everywhere, and in the languages the browser is set to as well,
+from `Intl` and in both the forms a language writes them (`март`, `12 марта 2026`,
+`12 de marzo de 2026`); the day still comes first. It keeps anything already
written in the stored syntax exactly as it is, and says underneath what it
understood. What it cannot read is handed on as typed, so the save refuses it with
a reason rather than filing a date nobody meant. The browser's own date field is
@@ -2570,6 +2878,15 @@ the field rather than over it, and it opens on the day the field holds — else
month a looser answer named. A month, a range or a mark of doubt is still typed:
those are not days, and a calendar has no way to offer them.
+**A date is read on a clock, and the field names it.** Under a set date, the shared
+**Clock** chip opens on *the point*: the first point's zone, looked up from the bundled
+boundaries, with its offset on that day. The date's reading names the zone rather than
+*local time*, so the 12th is Kyiv's 12th on the Timeline, from its midnight, and a typed
+`14:30` is placed on Kyiv's clock without being rewritten. **UTC** or any zone picked
+from the list overrides it. **Local at the point** goes back to following the point on
+every save; with no point yet the field says the day is read in UTC. The entity and the
+footage's Claim carry the zone as `when_zone`, which Details edits on the same chip.
+
**Nothing ever fills it in**, unlike the coordinates and the sources beside it. The
date a file carries is when it was uploaded, or what a camera clock said; neither is
when the thing happened, and a date offered is a date accepted without being read. So
@@ -2785,6 +3102,34 @@ deletes it, and one left behind goes when the next import opens. What Create
writes is a normal proof: it lists, travels in a bundle, and reopens in the
composer as a composition to annotate — one panel per picture taken.
+## Geo Report templates
+
+Settings → Templates lists the thread layouts, made there and nowhere else: the
+composer offers no "save as template". A layout is a body of tokens (`#place`,
+`#pluscode`, `#coordinates`, `#description`, `#mention`, `#source`, `#date`) and
+plain text. A token with no value drops its line. `#date` is the date the proof
+states, and the composer shows its Date field only when the layout uses it. It is
+filled from the proof as the case stores it (`2024-03-12`, `2024-03~`), the same in
+any language; a time says its clock as an offset on that day
+(`2024-07-12 14:30 UTC+3`). A proof with no date leaves it empty and says so, and the
+line drops. A token ends where its word does, so a `#dates` or `#placement` hashtag
+stays text.
+
+- **New** offers **Start from**: Classic, Coordinates only, Short, With date. Each
+ replaces the body and nothing else. A copy does not offer it.
+- **Duplicate** is on every template, proof or post, and opens an unsaved copy named
+ "… copy". Nothing is stored until Save; the 50-per-kind cap answers there.
+- **The preview** fills the layout with a sample or with **Open post**, the post in
+ the composer (off while it is empty). The template's own mention wins in both, and
+ no mention drops the line. Under it, one count per platform, X and Bluesky, red
+ past the limit.
+- **A word one edit from a token** (`#coordinate`) would go out as text, so it is
+ named under the layout with **Fix**, which mends every copy of it.
+- **Default** is the bookmark button on a post row. A blank composer opens on that
+ template without a toast, and its **Remove** goes back to the classic layout for
+ that draft only. Pressing the bookmark again clears it; deleting the template does
+ too. It is a setting, so the Settings backup carries it.
+
## Sheet
A table the analyst works in, which **is** a CSV in the case folder. Three uses no
@@ -3573,6 +3918,13 @@ instrument style of QGIS, Google Earth Pro, Resolve and Lightroom.
exception.
- **Copy**: no slogans or self-explanation in chrome. Empty states use one short
sentence. Visible UI strings use `·`, `:` or a period instead of em dashes.
+- **The analyst's words keep their direction**: the interface stays English, and a
+ label, a note or a statement in Arabic, Hebrew or Persian reads right to left
+ where it is shown or typed. HTML holding them carries `dir="auto"` (the Timeline's
+ captions, cards, list and inspector, the Board's names and fields, Details' name
+ and notes, the Claim editor). A canvas node name and an SVG plate label, which no
+ attribute reaches, are wrapped in a first-strong isolate (`lib/bidi.js`
+ `bidiIsolate`). Date fields stay left to right.
- **Brand**: north arrow (`Logo.svelte`) + drawn wordmark (`Wordmark.svelte`),
both defined in the components themselves. The arrow repeats in
`public/favicon.svg` and in the plated PNG/ICO icons that
diff --git a/frontend/e2e/app.fixture.js b/frontend/e2e/app.fixture.js
index 3c19467..67df3cb 100644
--- a/frontend/e2e/app.fixture.js
+++ b/frontend/e2e/app.fixture.js
@@ -110,6 +110,7 @@ const settings = {
home_view: { lat: 48.8584, lon: 2.2945, zoom: 16 },
post_mention: '@GeoConfirmed',
post_target: 'x',
+ post_template: '',
signature_handle: '',
signature: false,
export_dirs: { notes: '', media: '', proofs: '' },
@@ -919,8 +920,17 @@ export async function installAppFixture(page, options = {}) {
thumb: entity?.thumb ?? entity?.attrs?.thumb ?? null,
};
};
+ /** The server's file lanes: a source's picture or video, or what the app pictured
+ * from above (a capture, or a file whose `origin` is one of those routes). */
+ const fromAbove = (entry) => entry.type === 'capture'
+ || ['satellite', 'screenshot', 'compare'].includes(timelineEntity(entry.id)?.origin?.type);
+ const laneFile = (item, lane) => [...item.subject_entities, ...item.source_entities]
+ .find((entry) => ['media', 'capture'].includes(entry.type) && fromAbove(entry) === (lane === 'imagery'))
+ ?? null;
const timelineMatchesTrack = (item, track = {}) => {
if ((track.hidden ?? []).includes(item.id)) return false;
+ if (['sources', 'imagery'].includes(track.as_files)
+ && (item.category !== 'statement' || !laneFile(item, track.as_files))) return false;
const roles = Array.isArray(track.roles) ? track.roles : [];
if (roles.length && !roles.includes(item.time_role ?? 'unset')) return false;
const terms = track.terms && typeof track.terms === 'object' ? track.terms : {};
@@ -952,6 +962,8 @@ export async function installAppFixture(page, options = {}) {
&& (!entity || item.owner_id === entity || (item.subjects ?? []).includes(entity)
|| (item.places ?? []).includes(entity) || (item.sources ?? []).includes(entity))
&& timelineMatchesTrack(item, track)
+ // the server's `collected_only`: working files stay off, but the one in focus
+ && !(track.collected_only === true && item.produced_here === true && item.owner_id !== entity)
&& (item.earliest
? (!from || item.latest > (from.includes('T') ? from : `${from}T00:00:00Z`))
&& (!to || item.earliest < (to.includes('T') ? to : `${to}T23:59:59Z`))
@@ -1112,7 +1124,11 @@ export async function installAppFixture(page, options = {}) {
if (path === '/api/templates') return json(route, { proof: [], post: [] });
if (path === '/api/cases/relation-types') return json(route, relationTypes);
if (path === '/api/cases/confidence-levels') return json(route, confidenceLevels);
- if (path === '/api/cases/entity-types') return json(route, entityTypes);
+ if (path === '/api/cases/entity-types') return json(route, entityTypes.map((entry) => ({
+ ...entry,
+ retypable: entry.manual && ['actor', 'asset', 'class', 'identifier'].includes(entry.family),
+ mergeable: ['actor', 'asset', 'class', 'identifier', 'place'].includes(entry.family),
+ })));
if (path === '/api/cases/graph-lenses') return json(route, graphLenses);
if (path === '/api/cases/bundles/inspect' && request.method() === 'POST') {
bundleCalls.push({ kind: 'inspect' });
@@ -1293,6 +1309,11 @@ export async function installAppFixture(page, options = {}) {
const timelineClaimMatch = caseId && path.match(
new RegExp(`^/api/cases/${caseId}/timeline/claims(?:/([^/]+))?$`)
);
+ if (timelineClaimMatch?.[1] && request.method() === 'GET') {
+ const ownerId = decodeURIComponent(timelineClaimMatch[1]);
+ const held = timelineRows.map(enrichedTimelineItem).find((item) => item.owner_id === ownerId);
+ return held ? json(route, { item: held }) : json(route, { detail: 'not a claim' }, 404);
+ }
if (timelineClaimMatch && request.method() !== 'GET') {
const body = request.postDataJSON();
const ownerId = timelineClaimMatch[1] ?? `claim-browser-${timelineRows.length + 1}`;
@@ -1318,9 +1339,21 @@ export async function installAppFixture(page, options = {}) {
};
if (index >= 0) timelineRows[index] = temporal;
else timelineRows.push(temporal);
+ // New subjects named on the entry line are filed with the claim, as the route does.
+ const created = (body.create ?? []).map((entry, at) => ({
+ id: `${entry.type}-browser-${timelineRows.length}-${at + 1}`, ...entry,
+ }));
+ for (const entry of created) {
+ fixtureCatalog.push({
+ id: entry.id, type: entry.type, label: entry.label, attrs: {},
+ provenance: { by: 'user', at: '2026-08-12T10:00:00Z', status: 'confirmed' },
+ });
+ temporal[{ about: 'subjects', at: 'places', cites: 'sources' }[entry.slot]].push(entry.id);
+ }
return json(route, {
entity: { id: ownerId, type: 'claim', label: temporal.label, attrs: body, provenance: { by: 'user', at: '2026-08-12T10:00:00Z', status: 'confirmed' } },
links: [],
+ created,
temporal,
});
}
@@ -1381,8 +1414,14 @@ export async function installAppFixture(page, options = {}) {
held.categories[item.category] = (held.categories[item.category] ?? 0) + 1;
bucketCounts.set(key, held);
}
+ const lane = ['sources', 'imagery'].includes(track.as_files) ? track.as_files : null;
return json(route, {
- items: visible,
+ items: lane
+ ? visible.map((item) => {
+ const file = laneFile(item, lane);
+ return { ...item, file: { id: file.id, label: file.label, type: file.type } };
+ })
+ : visible,
next_cursor: null,
total: visible.length,
undated: base.filter((item) => !item.earliest && !item.raw).length,
@@ -1536,25 +1575,51 @@ export async function installAppFixture(page, options = {}) {
const descending = order.startsWith('-');
const column = descending ? order.slice(1) : order;
const direction = descending ? -1 : 1;
- const ordered = column
- ? [...matching].sort((left, right) => {
- const a = column === 'created' ? left.provenance?.at : left.label;
- const b = column === 'created' ? right.provenance?.at : right.label;
- return String(a ?? '').localeCompare(String(b ?? '')) * direction;
- })
- : matching;
+ // "Most noted": the Claims naming each row, newest first on a tie, as the store
+ // orders it.
+ const eventsOf = (id) => new Set(caseLinks
+ .filter((link) => link.to === id && ['about', 'at', 'cites'].includes(link.type)
+ && typeOf.get(link.from) === 'claim')
+ .map((link) => link.from)).size;
+ const ordered = column === 'events'
+ ? [...matching].map((entity, at) => ({ entity, at, n: eventsOf(entity.id) }))
+ .sort((left, right) => (left.n - right.n) * direction || (right.at - left.at))
+ .map((entry) => entry.entity)
+ : column
+ ? [...matching].sort((left, right) => {
+ const a = column === 'created' ? left.provenance?.at : left.label;
+ const b = column === 'created' ? right.provenance?.at : right.label;
+ return String(a ?? '').localeCompare(String(b ?? '')) * direction;
+ })
+ : matching;
catalogQueries.push(url.search);
// `catalogPage` makes the fixture answer in pages, which is the only way to
// reach the surface's server-search mode: a case that fits one page filters
// in the browser and never asks a second question.
const page = options.catalogPage ?? 0;
const items = page ? ordered.slice(0, page) : ordered;
+ const byType = {};
+ for (const entity of matching) byType[entity.type] = (byType[entity.type] ?? 0) + 1;
return json(route, {
items,
next_cursor: page && matching.length > page ? 'cursor-2' : null,
total: matching.length,
+ ...(url.searchParams.get('counts') === 'type' ? { by_type: byType } : {}),
});
}
+ // What the Claims say about a page of rows: the count naming each, from the edges
+ // this fixture holds. Dates stay empty, so no row draws a density it was not given.
+ if (caseId && path === `/api/cases/${caseId}/catalog/events` && request.method() === 'POST') {
+ const { ids = [] } = request.postDataJSON() ?? {};
+ const claims = new Set(catalogRows().filter((entity) => entity.type === 'claim').map((entity) => entity.id));
+ const rows = Object.fromEntries(ids.map((id) => [id, {
+ events: new Set(caseLinks
+ .filter((link) => link.to === id && claims.has(link.from) && ['about', 'at', 'cites'].includes(link.type))
+ .map((link) => link.from)).size,
+ first: null, last: null, sources: 0, places: 0, buckets: Array(12).fill(0),
+ }]));
+ return json(route, { range: null, rows });
+ }
const galleryMatch = caseId && path.match(
new RegExp(`^/api/cases/${caseId}/entities/([^/]+)/images(?:/([^/]+)(/primary)?)?$`)
);
@@ -1625,6 +1690,27 @@ export async function installAppFixture(page, options = {}) {
return json(route, { images: held });
}
}
+ // The identifier already in the case under this value, the way `identity_key`
+ // compares: case aside, and a handle with or without its sigil.
+ if (caseId && path === `/api/cases/${caseId}/entities/twin`) {
+ const type = url.searchParams.get('type');
+ const key = (value) => String(value ?? '').trim().toLowerCase().replace(/^@/, '');
+ const wanted = key(url.searchParams.get('label'));
+ const held = fixtureCatalog.find((entity) => entity.type === type && key(entity.label) === wanted);
+ return json(route, { entity: held ?? null });
+ }
+ // A grouped delete, one trash group: what the entry line's Undo sends.
+ if (caseId && path === `/api/cases/${caseId}/entities/delete` && request.method() === 'POST') {
+ const { ids } = request.postDataJSON();
+ entityWrites.push({ method: 'DELETE', ids });
+ for (const id of ids) {
+ const at = timelineRows.findIndex((item) => item.owner_id === id);
+ if (at >= 0) timelineRows.splice(at, 1);
+ const index = fixtureCatalog.findIndex((entity) => entity.id === id);
+ if (index >= 0) fixtureCatalog.splice(index, 1);
+ }
+ return json(route, { status: 'deleted', deleted: ids, tombstoned: [], trash: 'trash-1' });
+ }
const entityMatch = caseId && path.match(new RegExp(`^/api/cases/${caseId}/entities/([^/]+)$`));
if (entityMatch && request.method() !== 'GET') {
const body = request.method() === 'DELETE' ? null : request.postDataJSON();
@@ -1734,6 +1820,8 @@ export async function installAppFixture(page, options = {}) {
const row = options.tallies?.[tallyMatch[1]];
return row ? json(route, row) : route.fulfill({ status: 404, body: '{}' });
}
+ if (caseId && path === `/api/cases/${caseId}/entities/redirects`) return json(route, { redirects: {} });
+ if (caseId && path.match(new RegExp(`^/api/cases/${caseId}/entities/[^/]+/merges$`))) return json(route, { merges: [] });
const chainMatch = caseId && path.match(new RegExp(`^/api/cases/${caseId}/entities/(.+)/chain$`));
if (chainMatch) {
const chain = fixtureChains[chainMatch[1]];
@@ -1978,6 +2066,15 @@ export async function installAppFixture(page, options = {}) {
return json(route, { status: 'saved', ...sheetPayload(held) });
}
+ // The civil zone at a point, from the bundled boundaries: two zones are enough to
+ // tell a place's clock from another's.
+ if (path === '/api/geo/zone') {
+ geoQueries.zone = [...(geoQueries.zone ?? []), url.search];
+ const lon = Number(url.searchParams.get('lon'));
+ return json(route, {
+ name: lon > 20 ? 'Europe/Kyiv' : lon > 0 ? 'Europe/Paris' : lon > -30 ? 'Europe/Lisbon' : 'America/New_York',
+ });
+ }
// The search bar's two layers. The offline one answers coordinates and a
// handful of cities; the geocoder answers streets, and only ever late.
if (path === '/api/geo/suggest') {
diff --git a/frontend/e2e/board.spec.js b/frontend/e2e/board.spec.js
index 9cdc6d6..f4c1f75 100644
--- a/frontend/e2e/board.spec.js
+++ b/frontend/e2e/board.spec.js
@@ -50,8 +50,15 @@ const claimChain = {
empty: true,
};
-async function openBoard(page, options = {}) {
+/** Details docks beside the list on a wide Board and is a modal below that. */
+const details = (page) => page.locator('aside.fiche').or(page.getByRole('dialog', { name: 'Details', exact: true }));
+
+/** The flat table unless `grouped` is asked for: most of these read columns and headings. */
+async function openBoard(page, { grouped = false, ...options } = {}) {
const fixture = await installAppFixture(page, { catalog, ...options });
+ if (!grouped) {
+ await page.addInitScript((key) => localStorage.setItem(key, '{"group":"none"}'), `azimut:board-layout:${CASE_ID}`);
+ }
await page.goto('/#board');
await expect(page.getByRole('heading', { name: 'Board' })).toBeVisible();
return fixture;
@@ -99,17 +106,19 @@ function entityCell(page, name) {
.first();
}
-test('opens from the case it belongs to, not from the rail of stages', async ({ page }) => {
+test('opens from the rail, under the four stages', async ({ page }) => {
await installAppFixture(page, { catalog });
await page.goto('/#media');
- // the rail is the pipeline, and the case is not one of its steps
+ // the four stages, then the case a rule apart, then the theme
const rail = page.getByRole('navigation').first();
- await expect(rail.getByRole('button')).toHaveText(['Sources', 'Examine', 'Map', 'Compose', /Dark|Light/]);
+ await expect(rail.getByRole('button')).toHaveText(['Sources', 'Examine', 'Map', 'Compose', 'Case', /Dark|Light/]);
- await page.getByRole('button', { name: 'Board' }).click();
+ await rail.getByRole('button', { name: 'Case' }).click();
+ await expect(rail.getByRole('button', { name: 'Case' })).toHaveClass(/active/);
+ // the Case opens on its Timeline, and the Board is one tab away
+ await page.locator('.tabstrip').getByRole('button', { name: 'Board', exact: true }).click();
await expect(page.getByRole('heading', { name: 'Board' })).toBeVisible();
- await expect(page.getByTitle('Open the case board')).toHaveClass(/topbar-active/);
});
test('lists what the case holds, whatever the type', async ({ page }) => {
@@ -204,11 +213,11 @@ test('creates a claim, which nothing else in the app can do', async ({ page }) =
attrs: { method: 'spans counted against imagery' },
});
// and it lands on its own Details, because a claim exists to be pointed at things
- await expect(page.getByRole('heading', { name: 'Details' })).toBeVisible();
- await expect(page.getByRole('dialog').getByLabel('Claim', { exact: true })).toHaveValue('Where was this shot?');
+ await expect(details(page)).toBeVisible();
+ await expect(details(page).getByLabel('Claim', { exact: true })).toHaveValue('Where was this shot?');
});
-test('files a counted observation from a model’s row in one form', async ({ page }) => {
+test('files a counted observation about a model from its Details in one form', async ({ page }) => {
const model = {
id: 'model-1',
type: 'equipment-type',
@@ -216,18 +225,20 @@ test('files a counted observation from a model’s row in one form', async ({ pa
attrs: {},
provenance: { by: 'user', at: '2026-08-04T09:00:00Z', status: 'confirmed' },
};
- const fixture = await openBoard(page, { catalog: [...catalog, model] });
+ const fixture = await openBoard(page, {
+ catalog: [...catalog, model],
+ chains: { 'model-1': { entity: model, sources: [], lost: [], dependents: [], relations: [], empty: true } },
+ });
- const row = page.locator('tbody tr').filter({ has: page.locator('.name', { hasText: 'T-72B3' }) });
- await row.hover();
- await row.getByRole('button', { name: 'File a claim from T-72B3' }).click();
+ await entityCell(page, 'T-72B3').click();
+ await details(page).getByRole('button', { name: 'Add event', exact: true }).click();
- const form = page.getByRole('dialog').locator('.quick-claim');
- await expect(form.getByLabel('Claim', { exact: true })).toHaveValue('T-72B3 seen');
+ const form = details(page).locator('.entry-line');
+ await expect(form.getByLabel('What happened')).toHaveValue('T-72B3 seen');
await form.getByLabel('How many').fill('2');
await form.getByLabel('Condition').selectOption('destroyed');
- await expect(form.getByLabel('Claim', { exact: true })).toHaveValue('2 × T-72B3 destroyed');
- await form.getByRole('button', { name: 'Add claim' }).click();
+ await expect(form.getByLabel('What happened')).toHaveValue('2 × T-72B3 destroyed');
+ await form.getByRole('button', { name: 'Add', exact: true }).click();
await expect.poll(() => fixture.timelineWrites.length).toBe(1);
expect(fixture.timelineWrites[0].body).toMatchObject({
@@ -238,24 +249,24 @@ test('files a counted observation from a model’s row in one form', async ({ pa
at: [],
cites: [],
});
- await expect(page.locator('.quick-claim')).toHaveCount(0);
+ await expect(page.locator('.entry-line')).toHaveCount(0);
});
-test('files a claim from a place as where it was seen', async ({ page }) => {
- const fixture = await openBoard(page);
+test('files an event from a place as where it was seen', async ({ page }) => {
+ const fixture = await openBoard(page, {
+ chains: { 'place-1': { entity: catalog[1], sources: [], lost: [], dependents: [], relations: [], empty: true } },
+ });
- const row = page.locator('tbody tr').filter({ has: page.locator('.name', { hasText: 'checkpoint north' }) });
- await row.hover();
- const press = row.getByRole('button', { name: 'File a claim from checkpoint north' });
- await expect(press).toHaveAttribute('title', 'File a claim placed here');
- await press.click();
+ await entityCell(page, 'checkpoint north').click();
+ await details(page).getByRole('button', { name: 'Add event', exact: true }).click();
- const form = page.getByRole('dialog').locator('.quick-claim');
- await expect(form.getByLabel('Claim', { exact: true })).toHaveValue('Seen at checkpoint north');
+ const form = details(page).locator('.entry-line');
+ await expect(form.getByLabel('What happened')).toHaveValue('Seen at checkpoint north');
// a place is never counted and has no condition of its own to state
+ await form.getByRole('button', { name: 'More' }).click();
await expect(form.getByLabel('How many')).toHaveCount(0);
- await form.getByLabel('Claim', { exact: true }).fill('Convoy seen at checkpoint north');
- await form.getByRole('button', { name: 'Add claim' }).click();
+ await form.getByLabel('What happened').fill('Convoy seen at checkpoint north');
+ await form.getByLabel('What happened').press('Enter');
await expect.poll(() => fixture.timelineWrites.length).toBe(1);
expect(fixture.timelineWrites[0].body).toMatchObject({
@@ -288,7 +299,7 @@ test('shows an entity’s typed fields directly in Details', async ({ page }) =>
});
await entityCell(page, '203.0.113.42').click();
- const dialog = page.getByRole('dialog');
+ const dialog = details(page);
await expect(dialog.getByLabel('IP address')).toHaveValue('203.0.113.42');
await expect(dialog.getByText('Legacy network', { exact: true })).toBeVisible();
await expect(dialog.getByText('203.0.113.0/24', { exact: true })).toBeVisible();
@@ -350,7 +361,7 @@ test('opens a row in the same Details panel every other surface uses', async ({
await entityCell(page, 'harbour watch thread').click();
- await expect(page.getByRole('heading', { name: 'Details' })).toBeVisible();
+ await expect(details(page)).toBeVisible();
await expect(page.getByRole('link', { name: 'https://example.test/t' })).toBeVisible();
// the source's own grade is profile information, served by the entity registry
await expect(page.getByLabel('Source reliability')).toHaveValue('B');
@@ -377,7 +388,7 @@ test('keeps Add relation and Add mention as separate gestures', async ({ page })
});
await entityCell(page, 'Witness A').click();
- const dialog = page.getByRole('dialog');
+ const dialog = details(page);
await dialog.getByRole('tab', { name: 'Connections' }).click();
await expect(dialog.getByRole('button', { name: 'Add relation' })).toBeVisible();
await expect(dialog.getByRole('button', { name: 'Add mention' })).toBeVisible();
@@ -426,7 +437,7 @@ test('offers IP addresses and networks through Add relation', async ({ page }) =
});
await entityCell(page, '203.0.113.42').click();
- const dialog = page.getByRole('dialog');
+ const dialog = details(page);
await dialog.getByRole('tab', { name: 'Connections' }).click();
const add = dialog.getByRole('button', { name: 'Add relation' });
await expect(add).toHaveAttribute('title', /Network/);
@@ -461,7 +472,7 @@ test('keeps both readings when relation endpoints share a type', async ({ page }
});
await entityCell(page, '203.0.112.0/23').click();
- const dialog = page.getByRole('dialog');
+ const dialog = details(page);
await dialog.getByRole('tab', { name: 'Connections' }).click();
const composer = dialog.locator('.picker.composer');
await dialog.getByRole('button', { name: 'Add relation' }).click();
@@ -640,6 +651,12 @@ test('reads retained snapshot details in Board and leaves without a stale live d
},
};
await openBoard(page, { analysisViews: [snapshot] });
+ await page.route(`**/api/cases/${CASE_ID}/entities/redirects`, (route) => route.fulfill({
+ contentType: 'application/json', body: JSON.stringify({ redirects: { 'cap-person': { id: 'live-person' } } }),
+ }));
+ await page.route(`**/api/cases/${CASE_ID}/entities/cap-person/chain`, (route) => route.fulfill({
+ contentType: 'application/json', body: JSON.stringify({ entity: { id: 'live-person', type: 'person', label: 'Current witness', attrs: { role: 'Changed later' } } }),
+ }));
await page.getByRole('button', { name: /^Views/ }).click();
await page.locator('.views .menu .open', { hasText: 'Witness handover' }).click();
@@ -649,15 +666,17 @@ test('reads retained snapshot details in Board and leaves without a stale live d
await expect(page.getByRole('button', { name: /Show Archived witness in the graph/ })).toHaveCount(0);
await entityCell(page, 'Archived witness').click();
- const details = page.getByRole('dialog', { name: 'Snapshot details' });
- await expect(details).toContainText('observer');
- await expect(details.getByRole('img', { name: 'Witness portrait' })).toBeVisible();
- await expect(details).toContainText('Archived group');
- await details.getByRole('button', { name: 'Close' }).click();
+ const snap = page.locator('aside.fiche').or(page.getByRole('dialog', { name: 'Snapshot details' }));
+ await expect(snap.getByRole('status')).toContainText('Merged into Current witness');
+ await expect(snap).not.toContainText('Changed later');
+ await expect(snap).toContainText('observer');
+ await expect(snap.getByRole('img', { name: 'Witness portrait' })).toBeVisible();
+ await expect(snap).toContainText('Archived group');
+ await snap.getByRole('button', { name: /^Close/ }).click();
await page.getByRole('button', { name: 'Leave saved view' }).click();
await expect(page.getByRole('dialog', { name: 'Snapshot details' })).toHaveCount(0);
- await expect(page.getByRole('dialog', { name: 'Details', exact: true })).toHaveCount(0);
+ await expect(details(page)).toHaveCount(0);
});
test('settles a proposal from the row it is read on', async ({ page }) => {
@@ -712,8 +731,8 @@ test('takes a file into the case and opens what it filed', async ({ page }) => {
await expect.poll(() => fixture.uploads.length).toBe(1);
// one file opens where the analyst can say what it is
- await expect(page.getByRole('heading', { name: 'Details' })).toBeVisible();
- await expect(page.getByRole('dialog').getByLabel('Title')).toHaveValue('site plan');
+ await expect(details(page)).toBeVisible();
+ await expect(details(page).getByLabel('Title')).toHaveValue('site plan');
});
test('draws a document as a document, never as a photograph', async ({ page }) => {
@@ -751,7 +770,7 @@ test('hands a document back to the desktop instead of downloading a copy', async
});
await entityCell(page, 'harbour plan').click();
- const dialog = page.getByRole('dialog');
+ const dialog = details(page);
// no download link and no tool to send it to: neither exists for a document
await expect(dialog.getByRole('link', { name: 'Open file' })).toHaveCount(0);
@@ -761,3 +780,99 @@ test('hands a document back to the desktop instead of downloading a copy', async
await expect.poll(() => fixture.revealed).toEqual(['media/harbour plan.pdf']);
});
+
+// ── the index ────────────────────────────────────────────────────────────────
+
+const people = [
+ {
+ id: 'person-1',
+ type: 'person',
+ label: 'Harbour witness',
+ attrs: {},
+ provenance: { by: 'user', at: '2026-08-03T09:00:00Z', status: 'confirmed' },
+ },
+ {
+ id: 'person-2',
+ type: 'person',
+ label: 'Quay guard',
+ attrs: {},
+ provenance: { by: 'user', at: '2026-08-04T09:00:00Z', status: 'confirmed' },
+ },
+];
+const chainOf = (entity) => ({ entity, sources: [], lost: [], dependents: [], relations: [], empty: true });
+const groupTitles = (page) => page.locator('section.group .title');
+
+test('reads the case as who, what and where, the files folded under it', async ({ page }) => {
+ const fixture = await openBoard(page, { grouped: true, catalog: [...catalog, ...people] });
+
+ await expect(groupTitles(page)).toHaveText(['People & organizations', 'Places', 'Files', 'Work']);
+ const files = page.locator('section.group', { has: page.getByText('Files', { exact: true }) });
+ await expect(files.locator('button.fold')).toHaveAttribute('aria-expanded', 'false');
+ await expect(entityCell(page, 'roadside photo')).toHaveCount(0);
+ // folded, it says what is inside it, and asks for nothing
+ await expect(files.locator('.types')).toHaveText('Media');
+ expect(fixture.catalogQueries.some((query) => query.includes('type=media') && !query.includes('counts=type'))).toBe(false);
+
+ await files.locator('button.fold').click();
+ await expect(entityCell(page, 'roadside photo')).toBeVisible();
+ // the subjects are ordered by the events naming them, the files by when they came in
+ expect(fixture.catalogQueries.some((query) => query.includes('type=person') && query.includes('order=-events'))).toBe(true);
+ expect(fixture.catalogQueries.some((query) => query.includes('type=media') && query.includes('order=-created'))).toBe(true);
+});
+
+test('opens Details beside the list, and the arrow keys carry it along', async ({ page }) => {
+ await openBoard(page, {
+ grouped: true,
+ catalog: [...catalog, ...people],
+ chains: { 'person-1': chainOf(people[0]), 'person-2': chainOf(people[1]) },
+ });
+
+ await entityCell(page, 'Quay guard').click();
+ const fiche = page.locator('aside.fiche');
+ await expect(fiche.getByRole('heading', { name: 'Quay guard' })).toBeVisible();
+ await expect(page.getByRole('dialog', { name: 'Details', exact: true })).toHaveCount(0);
+
+ await page.locator('tbody tr', { hasText: 'Quay guard' }).focus();
+ await page.keyboard.press('ArrowDown');
+ await expect(fiche.getByRole('heading', { name: 'Harbour witness' })).toBeVisible();
+ await expect(page.locator('tbody tr.current')).toContainText('Harbour witness');
+
+ await page.keyboard.press('Escape');
+ await expect(fiche).toHaveCount(0);
+});
+
+test('keeps the one flat table under Group: None', async ({ page }) => {
+ await openBoard(page, { grouped: true, catalog: [...catalog, ...people] });
+
+ await page.locator('label.pick-one', { hasText: 'Group' }).locator('select').selectOption('none');
+ await expect(page.locator('section.group')).toHaveCount(0);
+ await expect(page.locator('.table tbody tr')).toHaveCount(catalog.length + people.length);
+ await expect(page.locator('.table thead').getByRole('button', { name: 'Type' })).toBeVisible();
+});
+
+test('says how a case of files only fills its index', async ({ page }) => {
+ await openBoard(page, { grouped: true, catalog: [catalog[0], catalog[2]] });
+
+ await expect(page.getByText('No people, places or things yet.')).toBeVisible();
+ await expect(groupTitles(page)).toHaveText(['Files', 'Work']);
+ await expect(entityCell(page, 'roadside photo')).toBeVisible();
+});
+
+test('adds an event about the open row from the topbar, with Alt+N', async ({ page }) => {
+ await openBoard(page, {
+ grouped: true,
+ catalog: [...catalog, ...people],
+ chains: { 'person-1': chainOf(people[0]) },
+ });
+
+ await entityCell(page, 'Harbour witness').click();
+ await page.locator('aside.fiche').getByRole('heading', { name: 'Harbour witness' }).click();
+ await page.keyboard.press('Alt+KeyN');
+
+ const bar = page.getByRole('dialog', { name: 'Add an event' });
+ await expect(bar).toContainText('about Harbour witness');
+ await expect(bar.getByLabel('What happened')).toHaveValue('Harbour witness seen');
+ await expect(bar.getByLabel('When')).toHaveValue('');
+ await page.keyboard.press('Escape');
+ await expect(bar).toHaveCount(0);
+});
diff --git a/frontend/e2e/collage-preview.spec.js b/frontend/e2e/collage-preview.spec.js
new file mode 100644
index 0000000..71eab58
--- /dev/null
+++ b/frontend/e2e/collage-preview.spec.js
@@ -0,0 +1,155 @@
+import { test, expect } from '@playwright/test';
+import { CASE_ID, PANEL_PATH, installAppFixture } from './app.fixture.js';
+
+// The collage list's preview is drawn by the browser from the open layout, warp
+// included, which only a real canvas can show.
+
+// A warped piece wider than a preview: its bounds are 1000×500, so it lands 480×240.
+const WARPED = [[0, 0], [1000, 40], [960, 500], [20, 460]];
+
+const strip = {
+ name: 'Strip',
+ title: 'Strip',
+ spec: {
+ width: 1200, height: 600, transparent: true,
+ nodes: [{
+ id: 'nd_1', frameId: null, save: { path: PANEL_PATH, time: null, ops: [] },
+ w: 640, h: 360, quad: WARPED, frameOps: [], crop: null,
+ }],
+ },
+};
+
+/** The PNG inside a multipart body. */
+function pngOf(body) {
+ const start = body.indexOf(Buffer.from([0x89, 0x50, 0x4e, 0x47]));
+ const end = body.indexOf(Buffer.from('IEND')) + 8;
+ return body.subarray(start, end);
+}
+
+test('draws a warped collage into the preview it files', async ({ page }) => {
+ await installAppFixture(page, {
+ collages: [{ name: 'Strip', title: 'Strip', pieces: 1, updated_at: '2026-09-20T10:00:00Z', outline: null }],
+ });
+ await page.route(`**/api/cases/${CASE_ID}/collages/Strip`, (route) => route.fulfill({ json: strip }));
+ const previews = [];
+ await page.route(`**/api/cases/${CASE_ID}/collages/Strip/thumb`, (route) => {
+ previews.push(pngOf(route.request().postDataBuffer()));
+ return route.fulfill({ json: { thumb: '.collages/Strip.webp' } });
+ });
+
+ await page.goto('/#collage');
+ await page.getByRole('button', { name: /^Strip/ }).click();
+ await expect.poll(() => previews.length, { timeout: 8000 }).toBe(1);
+
+ const read = await page.evaluate(async (b64) => {
+ const image = new Image();
+ image.src = `data:image/png;base64,${b64}`;
+ await image.decode();
+ const canvas = document.createElement('canvas');
+ canvas.width = image.width;
+ canvas.height = image.height;
+ const ctx = canvas.getContext('2d');
+ ctx.drawImage(image, 0, 0);
+ const alpha = (x, y) => ctx.getImageData(x, y, 1, 1).data[3];
+ return {
+ width: image.width,
+ height: image.height,
+ middle: alpha(240, 120),
+ // Above the top edge, which rises from (0,0) to (1000,40): outside the piece.
+ outside: alpha(470, 1),
+ };
+ }, previews[0].toString('base64'));
+
+ expect(read).toEqual({ width: 480, height: 240, middle: 255, outside: 0 });
+
+ // The list the Collages window reads back now carries it, and the row shows it.
+ await page.route(`**/api/cases/${CASE_ID}/collages`, (route) => route.fulfill({
+ json: [{ name: 'Strip', title: 'Strip', pieces: 1, updated_at: '2026-09-20T10:00:00Z', thumb: '.collages/Strip.webp', thumb_v: 1 }],
+ }));
+ await page.route(`**/files/${CASE_ID}/.collages/Strip.webp*`, (route) =>
+ route.fulfill({ contentType: 'image/png', body: previews[0] }));
+ await page.getByRole('button', { name: 'Collages' }).click();
+ const shown = page.locator('.row-preview img');
+ await expect(shown).toBeVisible();
+ await expect.poll(() => shown.evaluate((img) => img.naturalWidth)).toBe(480);
+ if (process.env.COLLAGE_SHOT) await page.screenshot({ path: process.env.COLLAGE_SHOT.replace('.png', '-rows.png') });
+});
+
+test('lays the collages out as cards, marking the one whose picture is in the case', async ({ page }) => {
+ const fixture = await installAppFixture(page, {
+ collages: [
+ {
+ name: 'Harbour strip', title: 'Harbour strip', pieces: 3, updated_at: '2026-09-21T10:00:00Z', filed: true,
+ outline: { width: 300, height: 100, quads: [
+ [[0, 0], [100, 0], [100, 100], [0, 100]],
+ [[100, 5], [200, 0], [200, 100], [100, 95]],
+ [[200, 0], [300, 0], [300, 100], [200, 100]],
+ ] },
+ },
+ {
+ name: 'Wall', title: 'Wall', pieces: 1, updated_at: '2026-09-20T10:00:00Z', filed: false,
+ outline: { width: 80, height: 120, quads: [[[0, 0], [80, 0], [80, 120], [0, 120]]] },
+ },
+ ],
+ });
+
+ await page.goto('/#collage');
+ const cards = page.locator('.card');
+ await expect(cards).toHaveCount(2);
+ await expect(cards.nth(0).locator('svg polygon')).toHaveCount(3);
+ await expect(cards.nth(0).locator('.filed')).toBeVisible();
+ await expect(cards.nth(1).locator('.filed')).toHaveCount(0);
+ const [a, b] = [await cards.nth(0).boundingBox(), await cards.nth(1).boundingBox()];
+ expect(Math.abs(a.y - b.y)).toBeLessThan(1); // side by side, a grid rather than rows
+ if (process.env.COLLAGE_SHOT) await page.screenshot({ path: process.env.COLLAGE_SHOT });
+
+ await page.getByRole('textbox', { name: 'Search collages…' }).fill('harbour');
+ await expect(cards).toHaveCount(1);
+ await expect(cards.first()).toContainText('Harbour strip');
+ fixture.expectNoUnexpectedRequests();
+});
+
+test('closes an open collage back to the list', async ({ page }) => {
+ await installAppFixture(page, {
+ collages: [{ name: 'Strip', title: 'Strip', pieces: 1, updated_at: '2026-09-20T10:00:00Z', outline: null }],
+ });
+ await page.route(`**/api/cases/${CASE_ID}/collages/Strip`, (route) => route.fulfill({ json: strip }));
+ await page.route(`**/api/cases/${CASE_ID}/collages/Strip/thumb`, (route) =>
+ route.fulfill({ json: { thumb: '.collages/Strip.webp' } }));
+
+ await page.goto('/#collage');
+ await page.getByRole('button', { name: /^Strip/ }).click();
+ await expect(page.getByRole('textbox', { name: 'Collage name' })).toHaveValue('Strip');
+ if (process.env.COLLAGE_SHOT) await page.screenshot({ path: process.env.COLLAGE_SHOT.replace('.png', '-open.png') });
+
+ await page.getByRole('button', { name: 'Close' }).click();
+ await expect(page.getByRole('heading', { name: 'Collages' })).toBeVisible();
+ await expect(page.locator('.card')).toHaveCount(1);
+});
+
+test('keeps the controls in reach over a case of many files', async ({ page }) => {
+ const works = Array.from({ length: 40 }, (_, i) => ({
+ name: `clip-${i}`, title: `clip_${String(i).padStart(2, '0')}_8f3a.mp4`, source: `media/clip-${i}.mp4`, frames: 3, kind: 'video',
+ }));
+ await installAppFixture(page, {
+ inspectWorks: works,
+ collages: [{ name: 'Strip', title: 'Strip', pieces: 1, updated_at: '2026-09-20T10:00:00Z', outline: null }],
+ });
+ await page.route(`**/api/cases/${CASE_ID}/collages/Strip`, (route) => route.fulfill({ json: strip }));
+ await page.route(`**/api/cases/${CASE_ID}/collages/Strip/thumb`, (route) =>
+ route.fulfill({ json: { thumb: '.collages/Strip.webp' } }));
+
+ await page.goto('/#collage');
+ await page.getByRole('button', { name: /^Strip/ }).click();
+ await page.locator('img.node').first().click();
+
+ await expect(page.locator('.identity .source')).toHaveText('panel.svg');
+ await expect(page.locator('.group-head')).toHaveCount(40);
+ // The files scroll on their own: the selected piece's controls stay on screen
+ // below forty of them.
+ await expect(page.getByRole('button', { name: 'Remove' })).toBeInViewport();
+ await page.getByRole('textbox', { name: 'Search…' }).fill('clip_07');
+ await expect(page.locator('.group-head')).toHaveCount(1);
+ await page.getByRole('textbox', { name: 'Search…' }).fill('');
+ if (process.env.COLLAGE_SHOT) await page.screenshot({ path: process.env.COLLAGE_SHOT.replace('.png', '-panel.png') });
+});
diff --git a/frontend/e2e/compare.spec.js b/frontend/e2e/compare.spec.js
index 433e8bc..395f0f7 100644
--- a/frontend/e2e/compare.spec.js
+++ b/frontend/e2e/compare.spec.js
@@ -236,8 +236,8 @@ test('spectral frames are requested only by Run, including after reopening and m
await page.mouse.down();
await page.mouse.move(box.x + 180, box.y + 130, { steps: 8 });
await page.mouse.up();
- // The press on the map put the settings away, and the pan spent nothing.
- await expect(page.locator('aside.settings')).toBeHidden();
+ // The settings stay up through a pan, and the pan spent nothing.
+ await expect(page.locator('aside.settings')).toBeVisible();
await expect(page.locator('.secondary .change-map')).not.toHaveCSS('transform', 'none');
// The reading followed on the frames it holds, and Read says there is nothing to do.
await expect(read).toHaveText('Up to date');
@@ -245,7 +245,6 @@ test('spectral frames are requested only by Run, including after reopening and m
expect(requests).toHaveLength(2);
// Choosing another index is asking for it: its bands come without a second
// press, and the follow-up the choice schedules does not throw them away.
- await page.getByRole('button', { name: 'Difference settings', exact: true }).click();
await page.locator('aside.settings select').nth(1).selectOption('nbr');
await expect.poll(() => requests.length).toBe(4);
expect(requests.slice(2).map((request) => request.product)).toEqual(['nbr', 'nbr']);
@@ -378,6 +377,40 @@ test('changes run in the worker and export a composed PNG', async ({ page }) =>
expect(errors).toEqual([]);
});
+test('a Difference GIF sends the visible palette and annotation colour to the encoder', async ({ page }) => {
+ const { errors } = await openCompare(page, 'Esri Wayback');
+ const canvas = page.getByLabel('Annotations on imagery A', { exact: true });
+ const box = await canvas.boundingBox();
+ await page.getByTitle('Numbered marker (N)', { exact: true }).click();
+ await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2);
+ await expect(canvas.locator('.numeral')).toHaveCount(1);
+
+ await page.getByRole('button', { name: 'Difference', exact: true }).click();
+ await expect(page.locator('.secondary .change-map')).toBeVisible({ timeout: 20000 });
+ await page.getByRole('button', { name: 'Difference settings', exact: true }).click();
+ await page.getByRole('tab', { name: 'Display' }).click();
+ await page.locator('aside.settings label').filter({ hasText: 'Palette' })
+ .locator('select').selectOption('colourblind');
+ await page.keyboard.press('Escape');
+
+ const requests = [];
+ await page.route('**/api/cases/*/compare/gif', async (route) => {
+ requests.push(route.request().postDataBuffer().toString('latin1'));
+ await route.fulfill({ json: { file: 'comparison.gif', path: '/tmp/exports' } });
+ });
+ await page.getByRole('button', { name: 'Export', exact: true }).click();
+ await page.getByRole('radio', { name: /GIF · Slide/ }).check();
+ await page.getByRole('button', { name: 'Export copy', exact: true }).click();
+
+ await expect.poll(() => requests.length).toBe(1);
+ const keep = requests[0].match(/name="keep"\r\n\r\n([^\r]+)/)?.[1].split(',');
+ expect(keep?.slice(0, 3)).toEqual(['#0072b2', '#e69f00', '#cc79a7']);
+ expect(keep).toContain('#f6a81a');
+ expect(requests[0]).toContain('name="image_a"');
+ expect(requests[0]).toContain('name="image_b"');
+ expect(errors).toEqual([]);
+});
+
/** Turn the shared camera to an exact bearing from the compass. */
async function turnTo(page, degrees) {
await page.getByTitle('Click to type an exact angle', { exact: true }).first().click();
@@ -517,14 +550,29 @@ test('the export frame keeps its shape when the camera turns, and still exports'
expect(errors).toEqual([]);
});
-test("Difference's settings stay put through a read, lie over the highlights, and close outside", async ({ page }) => {
+test("Difference's settings dock on the right over map B, stay put through a read and a pan", async ({ page }) => {
const { errors } = await openCompare(page, 'Esri Wayback');
await page.getByRole('button', { name: 'Difference', exact: true }).click();
await expect(page.locator('.secondary .change-map')).toBeVisible({ timeout: 20000 });
+ const stage = page.locator('.compare-stage');
+ const mapsBefore = await page.locator('.surface-shell.secondary').boundingBox();
await page.getByRole('button', { name: 'Difference settings', exact: true }).click();
const panel = page.locator('aside.settings');
await expect(panel).toBeVisible();
const before = await panel.boundingBox();
+ const box = await stage.boundingBox();
+ // Against the stage's right edge, from under B's card to the foot, over the
+ // maps rather than narrowing them.
+ const card = await page.locator('[aria-label="Imagery B"]').boundingBox();
+ expect(box.x + box.width - (before.x + before.width)).toBeCloseTo(8, 0);
+ expect(before.y).toBeGreaterThanOrEqual(card.y + card.height);
+ expect(box.y + box.height - (before.y + before.height)).toBeCloseTo(8, 0);
+ expect((await page.locator('.surface-shell.secondary').boundingBox()).width).toBeCloseTo(mapsBefore.width, 0);
+ // What rides that corner steps aside, so the search, the camera and the legend stay in reach.
+ for (const selector of ['.search-chip', '.camera-chip', '.change-legend']) {
+ const chip = await page.locator(selector).boundingBox();
+ expect(chip.x + chip.width, selector).toBeLessThanOrEqual(before.x);
+ }
// A read in flight used to widen the strip, and the panel hanging off it moved.
await page.getByLabel('Method', { exact: true }).selectOption('structure');
@@ -540,10 +588,14 @@ test("Difference's settings stay put through a read, lie over the highlights, an
{ x: after.x + 20, y: after.y + 20 });
expect(inside).toBe(true);
- // A press on the map beside it closes it.
- const stage = await page.locator('.compare-stage').boundingBox();
- await page.mouse.click(stage.x + 80, stage.y + 80);
+ // Tuning is watching the map answer: a press on the map leaves it up.
+ await page.mouse.click(box.x + 80, box.y + 80);
+ await expect(panel).toBeVisible();
+ await page.keyboard.press('Escape');
await expect(panel).toBeHidden();
+ // Put away, the corner is B's own again.
+ const search = await page.locator('.search-chip').boundingBox();
+ expect(search.x + search.width).toBeGreaterThan(before.x);
expect(errors).toEqual([]);
});
diff --git a/frontend/e2e/detect-design.spec.js b/frontend/e2e/detect-design.spec.js
new file mode 100644
index 0000000..d7b81ed
--- /dev/null
+++ b/frontend/e2e/detect-design.spec.js
@@ -0,0 +1,42 @@
+import { test, expect } from '@playwright/test';
+import { installAppFixture } from './app.fixture.js';
+
+test('Detect separates its tools, sections, and current task', async ({ page }) => {
+ await installAppFixture(page);
+ await page.route('**/api/compare/analyzers', (route) => route.fulfill({ json: {
+ builtins: [], custom: [], methods: [], grid: [13, 512], max_tiles: 4096, max_results: 2000,
+ } }));
+ await page.route('**/api/cases/*/analysis/**', (route) => route.fulfill({ json: [] }));
+ await page.goto('/#detect');
+
+ const dock = page.getByRole('complementary', { name: 'Detect' });
+ await expect(dock).toBeVisible({ timeout: 30_000 });
+ const heading = dock.locator('.dock-heading');
+ const tabs = dock.getByRole('navigation', { name: 'Detect sections' });
+ await expect(heading).toContainText('Detect');
+ await expect(tabs.getByRole('button', { name: 'Routines' })).toHaveAttribute('aria-pressed', 'true');
+ const headingBox = await heading.boundingBox();
+ const tabsBox = await tabs.boundingBox();
+ expect(headingBox.y + headingBox.height).toBeLessThanOrEqual(tabsBox.y + 1);
+ await expect(tabs.getByRole('button', { name: 'Routines' })).toHaveCSS('border-bottom-width', '2px');
+
+ await dock.getByRole('button', { name: 'New detection', exact: true }).click();
+ const menu = dock.getByRole('group', { name: 'New detection' });
+ await expect(menu.getByRole('button')).toHaveCount(2);
+ await expect(menu).not.toContainText('START WITH');
+ await menu.getByRole('button', { name: 'New one pass' }).click();
+ const stepper = dock.getByRole('navigation', { name: 'Steps' });
+ await expect(stepper.locator('button.current')).toContainText('Where');
+ const titleSize = await dock.getByRole('heading', { name: 'Where to look' }).evaluate(
+ (node) => parseFloat(getComputedStyle(node).fontSize)
+ );
+ const stepSize = await stepper.locator('button.current').evaluate(
+ (node) => parseFloat(getComputedStyle(node).fontSize)
+ );
+ expect(titleSize).toBeGreaterThan(stepSize);
+
+ await dock.getByRole('button', { name: 'Collapse Detect panel' }).click();
+ await expect(tabs).toHaveClass(/rail/);
+ await expect(dock.getByRole('button', { name: 'Analyzers' })).toBeVisible();
+ await expect(dock.getByRole('button', { name: 'Full screen' })).toBeVisible();
+});
diff --git a/frontend/e2e/detect-groups.spec.js b/frontend/e2e/detect-groups.spec.js
new file mode 100644
index 0000000..abb4793
--- /dev/null
+++ b/frontend/e2e/detect-groups.spec.js
@@ -0,0 +1,114 @@
+import { test, expect } from '@playwright/test';
+import { awaitMapReady, installAppFixture } from './app.fixture.js';
+
+const catalogue = {
+ builtins: [{ id: 'surface', name: 'Surface change', description: 'Surface change',
+ phenomenon: 'Surface change', method: 'surface', colour: '#38bdf8', style: 'both',
+ parameters: { sensitivity: 67, min_area: 2000, max_area: 0, cleanup: 1, smoothing: 0,
+ merge_metres: 30, index: 'ndvi', direction: 'both', ignore_clouds: true,
+ ignore_shadows: true, cloud_margin: 5 } }],
+ custom: [], methods: [{ id: 'surface', label: 'Surface change', single: false, clouds: true,
+ sizes: { medium: { min_area: 2000, max_area: 0, cleanup: 1, smoothing: 0, merge_metres: 30 } },
+ measure: 'Reflectance moved by {value}%' }],
+ max_tiles: 4096, max_results: 2000, grid: [13, 512], copernicus_key: true,
+};
+
+test('Areas groups fold and search, while Where keeps ungrouped areas available', async ({ page }) => {
+ await installAppFixture(page);
+ await page.route('**/api/compare/analyzers', (route) => route.fulfill({ json: catalogue }));
+ const ring = [[2.29, 48.855], [2.3, 48.855], [2.3, 48.862], [2.29, 48.862], [2.29, 48.855]];
+ const harbor = { id: 'aaaaaaaaaaaa', name: 'Harbor', colour: '#38bdf8',
+ geometry: { type: 'Polygon', coordinates: [ring] } };
+ const river = { ...harbor, id: 'bbbbbbbbbbbb', name: 'River' };
+ const groups = [
+ { id: '111111111111', title: 'Ports', area_ids: [harbor.id], position: 0 },
+ { id: '222222222222', title: 'Priority', area_ids: [harbor.id], position: 1 },
+ ];
+ await page.route('**/api/cases/*/analysis/**', (route) => {
+ const path = new URL(route.request().url()).pathname;
+ route.fulfill({ json: path.endsWith('/analysis/areas') ? [harbor, river]
+ : path.endsWith('/analysis/zones') ? groups : [] });
+ });
+ await page.goto('/#detect');
+ await awaitMapReady(page);
+ const dock = page.getByRole('complementary', { name: 'Detect' });
+ await dock.getByRole('button', { name: 'Areas', exact: true }).click();
+ const priority = dock.getByRole('region', { name: 'Priority' });
+ await expect(priority.getByRole('group', { name: 'Harbor' })).toHaveCount(0);
+ await dock.getByRole('textbox', { name: 'Search areas or groups' }).fill('Harbor');
+ await expect(priority.getByRole('group', { name: 'Harbor' })).toHaveCount(1);
+ await dock.getByRole('textbox', { name: 'Search areas or groups' }).fill('');
+
+ await dock.getByRole('button', { name: 'New detection' }).click();
+ await dock.getByRole('button', { name: 'New one pass' }).click();
+ const where = dock.getByRole('region', { name: 'Where to look' });
+ await expect(where).toContainText('Ungrouped');
+ await expect(where.getByRole('button', { name: 'River' })).toBeVisible();
+ await where.getByRole('button', { name: 'Use Ports' }).click();
+ await where.getByRole('button', { name: 'Use Priority' }).click();
+ await expect(where.locator('.area-row')).toHaveCount(1);
+ await where.getByRole('button', { name: 'River' }).click();
+ await expect(where.locator('.area-row')).toHaveCount(2);
+});
+
+test('dragging an area between groups and into Ungrouped moves its membership', async ({ page }) => {
+ await installAppFixture(page);
+ await page.route('**/api/compare/analyzers', (route) => route.fulfill({ json: catalogue }));
+ const harbor = { id: 'aaaaaaaaaaaa', name: 'Harbor', colour: '#38bdf8', geometry: {
+ type: 'Polygon', coordinates: [[[2.29, 48.855], [2.3, 48.855], [2.3, 48.862],
+ [2.29, 48.862], [2.29, 48.855]]],
+ } };
+ const groups = [
+ { id: '111111111111', title: 'Ports', area_ids: [harbor.id], position: 0 },
+ { id: '222222222222', title: 'Priority', area_ids: [], position: 1 },
+ ];
+ await page.route('**/api/cases/*/analysis/**', async (route) => {
+ const path = new URL(route.request().url()).pathname;
+ if (route.request().method() === 'PUT' && path.includes('/analysis/zones/')) {
+ const group = groups.find((row) => path.endsWith(`/${row.id}`));
+ Object.assign(group, route.request().postDataJSON());
+ await route.fulfill({ json: group });
+ return;
+ }
+ await route.fulfill({ json: path.endsWith('/analysis/areas') ? [harbor]
+ : path.endsWith('/analysis/zones') ? groups : [] });
+ });
+ await page.goto('/#detect');
+ await awaitMapReady(page);
+ const dock = page.getByRole('complementary', { name: 'Detect' });
+ await dock.getByRole('button', { name: 'Areas', exact: true }).click();
+ const ports = dock.getByRole('region', { name: 'Ports' });
+ const priority = dock.getByRole('region', { name: 'Priority' });
+ await expect(ports.locator('.group-head .group-icon svg')).toBeVisible();
+ // every group starts folded, the first one too
+ await expect(ports.locator('.fold')).toHaveAttribute('aria-expanded', 'false');
+ await ports.locator('.fold').click();
+ // a ⋯ menu shuts when the press lands anywhere else
+ const menu = ports.locator('details.item-menu').last();
+ await ports.getByLabel('More actions for Harbor').click();
+ await expect(menu).toHaveAttribute('open', '');
+ await dock.getByRole('textbox', { name: 'Search areas or groups' }).click();
+ await expect(menu).not.toHaveAttribute('open', '');
+ await priority.locator('.fold').click();
+ const handle = ports.getByRole('button', { name: 'Drag Harbor' });
+ const target = priority.locator('.group-head');
+ const sourceBox = await handle.boundingBox();
+ const targetBox = await target.boundingBox();
+ await page.mouse.move(sourceBox.x + sourceBox.width / 2, sourceBox.y + sourceBox.height / 2);
+ await page.mouse.down();
+ await page.mouse.move(sourceBox.x + sourceBox.width / 2 + 8, sourceBox.y + sourceBox.height / 2 + 8, { steps: 4 });
+ await page.mouse.move(targetBox.x + targetBox.width / 2, targetBox.y + targetBox.height / 2, { steps: 8 });
+ await expect(ports.getByRole('group', { name: 'Harbor' })).toHaveClass(/dragging/);
+ await expect(target).toHaveClass(/landing-area/);
+ await page.mouse.up();
+ await expect(target).not.toHaveClass(/landing-area/);
+ await expect(ports.getByRole('group', { name: 'Harbor' })).toHaveCount(0);
+ await expect(priority.getByRole('group', { name: 'Harbor' })).toHaveCount(1);
+ expect(groups.map((group) => group.area_ids)).toEqual([[], [harbor.id]]);
+
+ const ungrouped = dock.getByRole('region', { name: 'Ungrouped' });
+ await expect(ungrouped.locator('.ungrouped-head')).toBeVisible();
+ await priority.getByRole('button', { name: 'Drag Harbor' }).dragTo(ungrouped.locator('.ungrouped-head'));
+ await expect(ungrouped.getByRole('group', { name: 'Harbor' })).toHaveCount(1);
+ expect(groups.map((group) => group.area_ids)).toEqual([[], []]);
+});
diff --git a/frontend/e2e/detect.spec.js b/frontend/e2e/detect.spec.js
index f2803d7..8f8a188 100644
--- a/frontend/e2e/detect.spec.js
+++ b/frontend/e2e/detect.spec.js
@@ -6,13 +6,14 @@ const recipe = { id: 'change', name: 'Surface change', method: 'surface', phenom
cleanup: 0, smoothing: 0, merge_metres: 0, index: 'ndvi', direction: 'both' } };
const area = { id: 'aaaaaaaaaaaa', name: 'North site', colour: '#38bdf8',
geometry: { type: 'Polygon', coordinates: [[[2.29, 48.855], [2.3, 48.855], [2.3, 48.862], [2.29, 48.862], [2.29, 48.855]]] } };
+const secondArea = { ...area, id: 'eeeeeeeeeeee', name: 'Second site', colour: '#22d3ee' };
const zone = { id: area.id, name: area.name, kind: 'polygon', points: area.geometry.coordinates[0].slice(0, -1) };
const source = (date) => ({ provider: 'sentinel2', date, layer: 'TRUE_COLOR', maxcc: 30 });
const size = (min_area, max_area, cleanup, smoothing, merge_metres) => ({ min_area, max_area, cleanup, smoothing, merge_metres });
const SIZES = { small: size(300, 0, 0, 0, 0), medium: size(2000, 0, 1, 0, 30), large: size(20000, 0, 1, 1, 100),
all: size(0, 0, 0, 0, 0) };
-async function openDetect(page, withRun = false) {
+async function openDetect(page, withRun = false, withRoutine = false, twoRuns = false, twoAreas = false) {
await installAppFixture(page);
const errors = [], calls = [], prefs = [];
page.on('pageerror', (error) => errors.push(error.message));
@@ -22,11 +23,18 @@ async function openDetect(page, withRun = false) {
bbox: [2.29, 48.855, 2.3, 48.862], review: 'new', strength: 'clear', measure: {},
sources: { a, b }, area: 300 };
const run = { id: 'bbbbbbbbbbbb', title: 'North site pass', status: 'ready', progress: 1, total: 1,
+ colour: recipe.colour,
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' },
{ ...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' }] };
+ const secondRun = { ...run, id: 'cccccccccccc', title: 'Second site pass', colour: '#22d3ee',
+ input: { ...run.input, title: 'Second site pass', recipe: { ...recipe, colour: '#22d3ee' } },
+ results: [{ ...candidate, id: 'second-candidate' }] };
+ const routine = { ...run.input, id: 'dddddddddddd', title: 'North site routine',
+ date_rule: 'latest_previous' };
+ if (withRoutine) { run.input.followup_id = routine.id; run.followup_id = routine.id; }
await page.route('**/api/compare/analyzers', (route) => route.fulfill({ json: {
builtins: [recipe, { ...recipe, id: 'boats', name: 'Vessels', method: 'vessels' }], custom: [],
methods: [{ id: 'surface', single: false, sizes: SIZES }, { id: 'vessels', single: true, sizes: {} }],
@@ -47,6 +55,15 @@ async function openDetect(page, withRun = false) {
await page.route('**/api/cases/*/analysis/**', async (route) => {
const suffix = route.request().url().split('/analysis/')[1];
const method = route.request().method();
+ if (withRoutine && suffix === `followups/${routine.id}/colour` && method === 'PATCH') {
+ routine.recipe = { ...routine.recipe, ...route.request().postDataJSON() };
+ return route.fulfill({ json: routine });
+ }
+ if (suffix === `runs/${run.id}/colour` && method === 'PATCH') {
+ run.display_colour = route.request().postDataJSON().colour;
+ run.colour = run.display_colour;
+ return route.fulfill({ json: run });
+ }
if (suffix.endsWith('/preview')) return route.fulfill({ contentType: 'image/svg+xml',
body: `<svg xmlns="http://www.w3.org/2000/svg" width="${suffix.includes('candidate-2') ? 80 : 600}" height="160"><rect width="100%" height="100%" fill="#30352b"/></svg>` });
if (method === 'PATCH') {
@@ -62,8 +79,13 @@ async function openDetect(page, withRun = false) {
return route.fulfill({ json: manual });
}
if (method === 'GET') {
- const data = suffix === 'areas' ? [area] : suffix === 'runs' ? (withRun ? [run] : [])
- : suffix === `runs/${run.id}` ? run : [];
+ const data = suffix === 'areas' ? (twoAreas ? [area, secondArea] : [area])
+ : suffix === 'runs' ? (withRun ? twoRuns ? [run, secondRun] : [run] : [])
+ : suffix === 'followups' ? (withRoutine ? [{ id: routine.id, title: routine.title,
+ colour: routine.recipe.colour, method: 'surface', areas: 1, zones: [zone],
+ date_rule: routine.date_rule }] : [])
+ : suffix === `followups/${routine.id}` ? routine
+ : suffix === `runs/${run.id}` ? run : suffix === `runs/${secondRun.id}` ? secondRun : [];
return route.fulfill({ json: data });
}
return route.fulfill({ json: {} });
@@ -73,6 +95,118 @@ async function openDetect(page, withRun = false) {
return { errors, calls, prefs };
}
+async function typeWhenDay(page, button, field, value) {
+ await page.getByRole('button', { name: button, exact: true }).click();
+ const details = page.locator('.manual-date');
+ if (!await details.evaluate((node) => node.open)) await details.locator('summary').click();
+ await page.getByLabel(field).fill(value);
+}
+
+test('the Saved colour square recolours the routine and its map overlay', async ({ page }) => {
+ const { errors } = await openDetect(page, true, true);
+ await page.getByRole('button', { name: 'Saved', exact: true }).click();
+ const colour = page.getByLabel('Colour of North site routine');
+ await expect(colour).toHaveValue('#f6a81a');
+ await colour.fill('#eab308');
+ await expect(colour).toHaveValue('#eab308');
+ await expect(page.locator('.analysis-overlay > path').first()).toHaveAttribute('stroke', '#eab308');
+ await expect(page.locator('.fold[aria-expanded="true"]')).toBeVisible();
+ expect(errors).toEqual([]);
+});
+
+test('a one pass has a compact colour square that recolours its saved overlay', async ({ page }) => {
+ const { errors } = await openDetect(page, true);
+ await page.getByRole('button', { name: 'Saved', exact: true }).click();
+ const colour = page.getByLabel('Colour of North site pass');
+ const swatch = page.locator('.single .colour-control .swatch');
+ expect(Math.round((await swatch.boundingBox()).width)).toBe(8);
+ expect(Math.round((await swatch.boundingBox()).height)).toBe(8);
+ await page.screenshot({ path: test.info().outputPath('detect-saved-colour.png') });
+ await colour.fill('#eab308');
+ await expect(colour).toHaveValue('#eab308');
+ await expect(page.locator('.analysis-overlay > path').first()).toHaveAttribute('stroke', '#eab308');
+ expect(errors).toEqual([]);
+});
+
+test('review isolates one result layer and restores the saved eye states on Back', async ({ page }) => {
+ const { errors } = await openDetect(page, true, false, true);
+ await page.getByRole('button', { name: 'Saved', exact: true }).click();
+ const orange = page.locator('.analysis-overlay > path[stroke="#f6a81a"]');
+ const cyan = page.locator('.analysis-overlay > path[stroke="#22d3ee"]');
+ await expect(orange.first()).toBeVisible();
+ await expect(cyan.first()).toBeVisible();
+ await page.getByRole('button', { name: 'Hide Second site pass on the map' }).click();
+ await expect(cyan).toHaveCount(0);
+ await page.locator('.single .past').filter({ hasText: 'Second site pass' }).click();
+ await expect(cyan.first()).toBeVisible();
+ await expect(orange).toHaveCount(0);
+ await page.locator('.dock-content > header button[aria-label="Back"]').click();
+ await expect(orange.first()).toBeVisible();
+ await expect(cyan).toHaveCount(0);
+ await expect(page.getByRole('button', { name: 'Show Second site pass on the map' })).toBeVisible();
+ expect(errors).toEqual([]);
+});
+
+test('clicking a Detect date opens a calendar of passes and previews the chosen day', async ({ page }) => {
+ const { errors } = await openDetect(page);
+ const now = new Date();
+ const month = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() - 1, 1)).toISOString().slice(0, 7);
+ const day = `${month}-15`;
+ const requests = [];
+ await page.route('**/api/satellite/sentinel/acquisitions', (route) => {
+ requests.push(route.request().postDataJSON());
+ return route.fulfill({ json: {
+ dates: [{ date: day, cloud: 8, coverage: 1 }], truncated: false,
+ } });
+ });
+ await page.getByRole('button', { name: 'New detection', exact: true }).click();
+ await page.getByRole('button', { name: 'New one pass', exact: true }).click();
+ await page.getByRole('button', { name: 'North site', exact: true }).click();
+ await page.getByRole('button', { name: 'Next: What' }).click();
+ await page.getByRole('button', { name: 'Next: When' }).click();
+ await page.getByRole('button', { name: 'Date A', exact: true }).click();
+ const calendar = page.getByRole('group', { name: 'A pass calendar' });
+ await expect(calendar).toBeVisible();
+ await expect.poll(() => requests.length).toBeGreaterThan(0);
+ expect(requests[0].end <= new Date().toISOString().slice(0, 10)).toBe(true);
+ await calendar.getByRole('button', { name: 'Previous month' }).click();
+ await expect(calendar.getByRole('button', { name: `${month}-14: no pass` })).toBeDisabled();
+ await calendar.getByRole('button', { name: `${day}: 8% cloud` }).click();
+ await expect(page.getByRole('button', { name: 'Date A', exact: true })).toContainText(day);
+ await expect(page.getByRole('button', { name: 'Leave pass imagery' })).toContainText('North site · A');
+ await page.getByRole('button', { name: 'Date B', exact: true }).click();
+ const bCalendar = page.getByRole('group', { name: 'B pass calendar' });
+ await bCalendar.getByRole('button', { name: 'Previous month' }).click();
+ await expect(bCalendar.getByRole('button', { name: `${day}: outside date order` })).toBeDisabled();
+ expect(errors).toEqual([]);
+});
+
+test('each area opens its own A and B calendars with its pass list below', async ({ page }) => {
+ const { errors } = await openDetect(page, false, false, false, true);
+ await page.getByRole('button', { name: 'New detection', exact: true }).click();
+ await page.getByRole('button', { name: 'New one pass', exact: true }).click();
+ await page.getByRole('button', { name: 'North site', exact: true }).click();
+ await page.getByRole('button', { name: 'Second site', exact: true }).click();
+ await page.getByRole('button', { name: 'Next: What' }).click();
+ await page.getByRole('button', { name: 'Next: When' }).click();
+ const first = page.getByRole('region', { name: 'Dates for North site' });
+ const second = page.getByRole('region', { name: 'Dates for Second site' });
+ await second.getByRole('button', { name: 'Date A for Second site' }).click();
+ const calendar = second.getByRole('group', { name: 'Reference for Second site pass calendar' });
+ await expect(calendar).toBeVisible();
+ const month = await calendar.boundingBox();
+ const footer = await page.locator('.cmp-dock-foot').boundingBox();
+ expect(month.y + month.height).toBeLessThanOrEqual(footer.y + 1);
+ await expect(first.locator('.pass-calendar')).toHaveCount(0);
+ await page.screenshot({ path: test.info().outputPath('detect-area-calendar.png') });
+ await second.getByRole('button', { name: 'Find passes for Second site' }).click();
+ await expect(second.locator('.passes')).toBeVisible();
+ await expect(first.locator('.passes')).toHaveCount(0);
+ await expect(page.getByRole('button', { name: 'Dates…' })).toHaveCount(0);
+ await page.screenshot({ path: test.info().outputPath('detect-area-calendars.png') });
+ expect(errors).toEqual([]);
+});
+
test('landing, dock rail and the When step fit the existing map workspace', async ({ page }) => {
const { errors, calls, prefs } = await openDetect(page);
await expect(page.getByRole('button', { name: 'Imagery provider', exact: true })).toContainText('Esri World Imagery');
@@ -108,17 +242,64 @@ test('landing, dock rail and the When step fit the existing map workspace', asyn
await page.getByRole('button', { name: 'Next: When' }).click();
// A and B are asked in the step itself, B the newest pass until a day is chosen
await expect(page.getByRole('heading', { name: 'Which two images' })).toBeVisible();
- await expect(page.getByLabel('Day of A')).toBeVisible();
- await expect(page.getByRole('radio', { name: 'Newest pass' })).toHaveAttribute('aria-checked', 'true');
- await page.getByRole('radio', { name: 'A day I choose' }).click();
- await expect(page.getByLabel('Day of B')).toBeVisible();
+ await expect(page.getByRole('button', { name: 'Date A', exact: true })).toBeVisible();
+ await expect(page.getByRole('button', { name: 'Date B', exact: true })).toContainText('Newest pass');
+ await page.getByRole('button', { name: 'Date B', exact: true }).click();
+ await expect(page.getByRole('group', { name: 'B pass calendar' })).toBeVisible();
await expect(page.getByRole('button', { name: 'Find passes', exact: true })).toBeVisible();
expect((await map.boundingBox()).height).toBe(before.height);
- expect(calls).toEqual([]);
+ expect(calls.every((url) => url.includes('/api/satellite/sentinel/acquisitions'))).toBe(true);
await page.screenshot({ path: test.info().outputPath('detect-dates.png') });
expect(errors).toEqual([]);
});
+test('Detect menus fit the dock at its minimum and maximum widths', async ({ page }) => {
+ const { errors, prefs } = await openDetect(page, true);
+ const dock = page.locator('.detect-tool .cmp-dock');
+ const map = page.locator('.detect-tool .map');
+ const handle = page.getByRole('button', { name: 'Resize Detect panel' });
+ for (const [key, width] of [['Home', 300], ['End', 720]]) {
+ await handle.focus();
+ await page.keyboard.press(key);
+ await expect.poll(async () => Math.round((await dock.boundingBox()).width)).toBe(width);
+ expect((await map.boundingBox()).width).toBeGreaterThanOrEqual(320);
+ for (const tab of ['Routines', 'Saved', 'Areas']) {
+ await page.getByRole('button', { name: tab, exact: true }).click();
+ await expect.poll(() => dock.evaluate((node) => node.scrollWidth - node.clientWidth)).toBeLessThanOrEqual(2);
+ }
+ await page.getByRole('button', { name: 'Saved', exact: true }).click();
+ await page.getByRole('button', { name: /^North site pass/ }).click();
+ await expect.poll(() => dock.evaluate((node) => node.scrollWidth - node.clientWidth)).toBeLessThanOrEqual(2);
+ await dock.locator('.dock-content > header button[aria-label="Back"]').click();
+ await page.getByRole('button', { name: 'Analyzers', exact: true }).click();
+ await expect(dock.locator('.dock-content > header strong')).toHaveText('Analyzers');
+ await expect.poll(() => dock.evaluate((node) => node.scrollWidth - node.clientWidth)).toBeLessThanOrEqual(2);
+ await dock.locator('.dock-content > header button[aria-label="Back"]').click();
+ await page.getByRole('button', { name: 'New detection', exact: true }).click();
+ const menu = dock.getByRole('group', { name: 'New detection' });
+ await expect(menu.getByRole('button', { name: 'New one pass' })).toBeVisible();
+ await expect(menu.getByRole('button', { name: 'New routine' })).toBeVisible();
+ const [dockBox, menuBox] = await Promise.all([dock.boundingBox(), menu.boundingBox()]);
+ expect(menuBox.x).toBeGreaterThanOrEqual(dockBox.x);
+ expect(menuBox.x + menuBox.width).toBeLessThanOrEqual(dockBox.x + dockBox.width);
+ await page.screenshot({ path: test.info().outputPath(`detect-menu-${width}.png`) });
+ await page.getByRole('button', { name: 'New one pass', exact: true }).click();
+ await page.getByRole('button', { name: 'North site', exact: true }).click();
+ for (const next of ['Next: What', 'Next: When']) {
+ await expect.poll(() => dock.evaluate((node) => node.scrollWidth - node.clientWidth)).toBeLessThanOrEqual(2);
+ await page.getByRole('button', { name: next }).click();
+ }
+ await expect.poll(() => dock.evaluate((node) => node.scrollWidth - node.clientWidth)).toBeLessThanOrEqual(2);
+ await page.getByRole('button', { name: 'Date A', exact: true }).click();
+ await expect(page.getByRole('group', { name: 'A pass calendar' })).toBeVisible();
+ await expect.poll(() => dock.evaluate((node) => node.scrollWidth - node.clientWidth)).toBeLessThanOrEqual(2);
+ await page.getByRole('button', { name: 'Close calendar' }).click();
+ await dock.locator('.dock-content > header button[aria-label="Back"]').click();
+ }
+ await expect.poll(() => prefs.some((value) => value.detect_view?.width === 720)).toBe(true);
+ expect(errors).toEqual([]);
+});
+
test('the size is asked before the analyzers, and a pair months apart warns about shadows', async ({ page }) => {
const { errors, calls } = await openDetect(page);
await page.getByRole('button', { name: 'New detection', exact: true }).click();
@@ -131,17 +312,24 @@ test('the size is asked before the analyzers, and a pair months apart warns abou
await expect(sizes.getByRole('button', { name: 'All', exact: true })).toHaveAttribute('aria-pressed', 'true');
const [above, list] = [await sizes.boundingBox(), await step.getByRole('radiogroup', { name: 'Analyzer' }).boundingBox()];
expect(above.y + above.height).toBeLessThanOrEqual(list.y);
+ const cloud = step.getByLabel('Maximum cloud cover');
+ const cloudBox = await cloud.boundingBox();
+ expect(cloudBox.y).toBeGreaterThanOrEqual(above.y + above.height);
+ expect(cloudBox.y + cloudBox.height).toBeLessThanOrEqual(list.y);
await page.screenshot({ path: test.info().outputPath('detect-what.png') });
await page.getByRole('button', { name: 'Next: When' }).click();
- await page.getByLabel('Day of A').fill('21/01/2026');
+ await typeWhenDay(page, 'Date A', 'Day of A', '21/01/2026');
await expect(page.getByRole('note')).toHaveCount(0);
- await page.getByRole('radio', { name: 'A day I choose' }).click();
- await page.getByLabel('Day of B').fill('25/09/2026');
+ await typeWhenDay(page, 'Date B', 'Day of B', '25/09/2026');
await expect(page.getByRole('note')).toContainText('most buildings will read as changed');
await page.screenshot({ path: test.info().outputPath('detect-shadows.png') });
- await page.getByLabel('Day of B').fill('02/02/2026');
+ await typeWhenDay(page, 'Date B', 'Day of B', '02/02/2026');
await expect(page.getByRole('note')).toHaveCount(0);
- expect(calls).toEqual([]);
+ await typeWhenDay(page, 'Date B', 'Day of B', '20/01/2026');
+ await expect(page.locator('.step .warn[role="alert"]')).toContainText('Date A must be before date B.');
+ await expect(page.getByRole('button', { name: 'Next: Start' })).toBeDisabled();
+ expect(calls.every((url) => url.includes('/api/satellite/sentinel/acquisitions'))).toBe(true);
+ expect(calls.length).toBeGreaterThan(0);
expect(errors).toEqual([]);
});
@@ -183,151 +371,306 @@ test('review adds a manual point and uses the standard pin dialog', async ({ pag
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) => {
+const R = 6378137;
+const WORLD = 2 * Math.PI * R;
+const mercator = (lon, lat) => [R * (lon * Math.PI) / 180, R * Math.log(Math.tan(Math.PI / 4 + (lat * Math.PI) / 360))];
+/** The grid tile (level 13) a point is on, and where in it the point falls, 0 to 1. */
+function tileOf(lon, lat) {
+ const [mx, my] = mercator(lon, lat);
+ const count = 2 ** 13;
+ const gx = ((mx + WORLD / 2) / WORLD) * count;
+ const gy = ((WORLD / 2 - my) / WORLD) * count;
+ return { x: Math.floor(gx), y: Math.floor(gy), fx: gx - Math.floor(gx), fy: gy - Math.floor(gy) };
+}
+const tileBox = ({ x, y }) => {
+ const count = 2 ** 13;
+ return { west: (x / count) * WORLD - WORLD / 2, east: ((x + 1) / count) * WORLD - WORLD / 2,
+ north: WORLD / 2 - (y / count) * WORLD, south: WORLD / 2 - ((y + 1) / count) * WORLD };
+};
+const rulesCatalogue = {
+ builtins: [recipe], custom: [], grid: [13, 512], max_tiles: 4096, max_results: 2000, copernicus_key: true, radar_layer: '',
+ methods: [{ id: 'surface', single: false, sizes: {} }, { id: 'rules', single: false, clouds: true, sensor: 'sentinel2', frames: 4,
+ sizes: { all: size(0, 0, 0, 0, 0), medium: size(2000, 0, 1, 0, 30) }, 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, max_check_tiles: 12 },
+ examples: [],
+};
+
+/** The engine's side of a builder session: passes, what a test costs, what it finds, what a point reads. */
+async function answerBuilder(page) {
+ const log = { saved: [], plans: [], tests: [], probes: [], lookups: [], center: null, hole: null };
+ await page.route('**/api/compare/analyzers', (route) => {
if (route.request().method() === 'POST') {
- const body = route.request().postDataJSON();
- saved.push(body);
- return route.fulfill({ json: { ...body, id: 'custom-aaaaaaaaaaaa' } });
+ log.saved.push(route.request().postDataJSON());
+ return route.fulfill({ json: { ...route.request().postDataJSON(), 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: [] } });
+ return route.fulfill({ json: rulesCatalogue });
});
- 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/acquisitions', (route) => {
+ log.lookups.push(route.request().postDataJSON());
+ return 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/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) => {
+ await page.route('**/api/compare/analyzers/check/plan', (route) => {
+ log.plans.push(route.request().postDataJSON());
+ return route.fulfill({ json: { tiles: 1, missing: 4 } });
+ });
+ await page.route('**/api/compare/analyzers/check', async (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) } });
+ log.tests.push(body);
+ const [lon, lat] = body.check.marks[0].point;
+ const tile = tileOf(lon, lat);
+ log.center = { x: Math.round(tile.fx * 512), y: Math.round(tile.fy * 512) };
+ // the cloud sits in the corner of the tile farthest from the pin
+ log.hole = { x: log.center.x < 256 ? 412 : 0, y: log.center.y < 256 ? 432 : 0 };
+ // What the engine sends: one byte a pixel. 64 is measured ground, and the low bits are the rules that passed;
+ // rule 1 and 2 pass round the first pin, rule 2 alone further out, and a corner is cloud.
+ const mask = await page.evaluate(([cx, cy, hx, hy]) => {
+ const canvas = document.createElement('canvas');
+ canvas.width = 512; canvas.height = 512;
+ const context = canvas.getContext('2d');
+ const image = context.createImageData(512, 512);
+ for (let j = 0; j < 512; j++) {
+ for (let i = 0; i < 512; i++) {
+ let value = i >= hx && i < hx + 100 && j >= hy && j < hy + 80 ? 0 : 64;
+ const distance = Math.hypot(i - cx, j - cy);
+ if (value && distance < 150) value |= 2;
+ if (value && distance < 80) value |= 1 | 128;
+ const at = (j * 512 + i) * 4;
+ image.data[at] = image.data[at + 1] = image.data[at + 2] = value;
+ image.data[at + 3] = 255;
+ }
+ }
+ context.putImageData(image, 0, 0);
+ return canvas.toDataURL('image/png').split(',')[1];
+ }, [log.center.x, log.center.y, log.hole.x, log.hole.y]);
+ const marks = body.check.marks;
+ // the plot dropped by 0.6, so a line set at a drop of 0.5 or less takes it, and the empty pin is never taken
+ const covered = marks.map((mark) => mark.expect === 'found' && body.recipe.rules[0].value >= -0.5);
+ return route.fulfill({ json: { ready: true, missing: 0, count: covered.filter(Boolean).length, covered, size: 512, measured: 0.93,
+ tiles: [{ x: tile.x, y: tile.y, box: tileBox(tile), mask }],
+ rules: body.recipe.rules.map((_, i) => ({ share: 0.18 - i * 0.04, kept: 0.06 })), kept: 0.04,
+ candidates: [{ id: '0-1', coordinates: [lon, lat], bbox: [lon - 0.001, lat - 0.001, lon + 0.001, lat + 0.001], area: 12000,
+ margin: 3.4, strength: 'strong', measure: { before: 0.8, after: 0.2, signed: -0.6 }, geometry: null }],
+ readings: marks.map((mark) => ({ imaged: true, measured: true, kept: mark.expect === 'found',
+ rules: body.recipe.rules.map(() => ({ passes: true, value: mark.expect === 'found' ? -0.6 : -0.1, before: 0.8, after: 0.3 })) })) } });
});
+ await page.route('**/api/compare/analyzers/probe', (route) => {
+ log.probes.push(route.request().postDataJSON());
+ return 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 }] } });
+ });
+ return log;
+}
+
+/** A pixel of the canvas a part of the test layers painted, by the tile's own pixel. */
+const painted = (page, part, [x, y]) => page.locator(`.rule-layers .part.${part} canvas.rule-tile`).first().evaluate(
+ (canvas, at) => [...canvas.getContext('2d').getImageData(at[0], at[1], 1, 1).data], [x, y]);
+const near = (expected, tolerance = 6) => (read) => read.every((value, i) => Math.abs(value - expected[i]) <= tolerance);
+
+test('an analyzer of your own is proved on a check made on the map: two passes, pins, a test, the rules painted, then kept', async ({ page }) => {
+ const { errors } = await openDetect(page);
+ const log = await answerBuilder(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, attribution: 'Browser fixture' },
+ { id: 'sentinel2', label: 'Copernicus Sentinel-2', url: 'https://tiles.invalid/{z}/{x}/{y}.png', imagery: true, max_zoom: 19, tile_size: 256, attribution: 'Copernicus' },
+ ] }));
+ // what a new one reads is asked first, and stays
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: 'New analyzer' })).toBeVisible();
+ await expect(page.getByRole('group', { name: 'Satellite' }).getByRole('button', { name: /^Sentinel-2/ })).toHaveAttribute('aria-pressed', 'true');
+ await expect(page.getByRole('group', { name: 'Dates' }).getByRole('button', { name: 'Two dates' })).toHaveAttribute('aria-pressed', 'true');
+ await page.screenshot({ path: test.info().outputPath('detect-builder-new.png') });
+ await page.getByRole('button', { name: /^Blank/ }).click();
await expect(page.getByRole('heading', { name: 'Build an analyzer' })).toBeVisible();
+ await expect(page.locator('.reads')).toHaveText('Sentinel-2 · two dates');
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);
-
- // the detections alone, as a run would return them: no rule painted, the candidate still outlined
- const shows = page.getByRole('group', { name: 'What the map shows' });
- await shows.getByRole('button', { name: 'Detections', exact: true }).click();
- await expect.poll(tint([0, 0, 0, 0])).toBe(true);
- await expect(page.locator('svg.analysis-overlay [role="button"]')).toHaveCount(1);
- await shows.getByRole('button', { name: 'Rules', exact: true }).click();
- await expect.poll(tint([250, 204, 21, 110])).toBe(true);
+ await expect(page.getByLabel('Rule 2 says')).toHaveText('NDVI before is at least 0.40');
+ // nothing has been asked of Copernicus, and there is no check to test on
+ expect(log.lookups.length + log.plans.length + log.tests.length).toBe(0);
+ const deck = page.locator('.console');
+ await expect(deck.getByText('Pick a check to try the rules on it.')).toBeVisible();
+ await expect(page.locator('.strip').getByRole('button', { name: 'Test', exact: true })).toBeDisabled();
- const map = page.locator('.detect-tool .map');
+ // a check is made on the map: its passes first, in the drawer
+ await deck.getByRole('button', { name: 'New check' }).click();
+ await expect(page.getByRole('region', { name: 'Passes of the new check' })).toBeVisible();
+ await expect(page.locator('.panel')).toHaveClass(/locked/);
+ await expect(page.getByText('Making a check on the map')).toBeVisible();
+ await deck.getByRole('button', { name: 'Find passes', exact: true }).click();
+ expect(log.lookups).toHaveLength(1);
+ expect(log.lookups[0]).toMatchObject({ collection: 'sentinel2' });
+ await page.getByLabel('Use 2026-09-01').getByRole('button', { name: 'Before', exact: true }).click();
+ await page.getByLabel('Use 2026-09-10').getByRole('button', { name: 'After', exact: true }).click();
+ await page.screenshot({ path: test.info().outputPath('detect-builder-passes.png') });
+
+ // or from the calendar, as a routine picks its dates
+ await deck.getByRole('button', { name: 'Dates', exact: true }).click();
+ await deck.getByRole('button', { name: 'Before pass' }).click();
+ await expect(page.getByRole('group', { name: 'Before pass calendar' })).toBeVisible();
+ await expect(page.getByRole('button', { name: /^2026-09-01:/ })).toBeEnabled();
+ await expect(page.getByRole('button', { name: /^2026-09-10:/ })).toBeDisabled(); // not before the after pass
+ await page.getByRole('button', { name: /^2026-09-01:/ }).click();
+ await deck.getByRole('button', { name: 'Place the pins' }).click();
+
+ // the map is split between the two passes, one surface over the other
+ await expect(page.locator('.detect-tool .map')).toHaveCount(2);
+ const line = page.getByRole('slider', { name: 'Split between the before and after passes' });
+ await expect(line).toHaveAttribute('aria-valuenow', '50');
+ await line.focus();
+ await page.keyboard.press('ArrowRight');
+ await expect(line).toHaveAttribute('aria-valuenow', '52');
+ await deck.getByRole('button', { name: /^After/ }).click();
+ await expect(line).toHaveAttribute('aria-valuenow', '0');
+ await deck.getByRole('button', { name: 'Split', exact: true }).click();
+ await expect(line).toHaveAttribute('aria-valuenow', '50');
+
+ // pins: a click on the ground drops the armed one, on either half
+ const map = page.locator('.detect-tool .map').first();
const box = await map.boundingBox();
- await map.click({ position: { x: box.width / 2 - 40, y: box.height / 2 + 40 } });
+ await expect(deck.getByRole('button', { name: 'Should be found' })).toHaveAttribute('aria-pressed', 'true');
+ // dead centre, which is where the line of the split runs: with a pin armed it lets the click through
+ await page.mouse.click(box.x + box.width * 0.5, box.y + box.height * 0.4);
+ await expect(page.locator('.mark.pin-found')).toHaveCount(1);
+ await expect(line).toHaveAttribute('aria-valuenow', '50');
+ await deck.getByRole('button', { name: 'Should stay empty' }).click();
+ await expect(page.getByText('Click the ground where none should be')).toBeVisible();
+ await page.mouse.click(box.x + box.width * 0.7, box.y + box.height * 0.3);
+ await expect(page.locator('.mark.pin-found')).toHaveCount(1);
+ await expect(page.locator('.mark.pin-empty')).toHaveCount(1);
+ await page.keyboard.press('Escape');
+ await expect(page.getByText('Click the ground where none should be')).toHaveCount(0);
+ await page.screenshot({ path: test.info().outputPath('detect-builder-pins.png') });
+ await deck.getByRole('button', { name: 'Finish', exact: true }).click();
+ await expect(page.locator('.panel')).not.toHaveClass(/locked/);
+ await expect(page.getByRole('tab', { name: /^Checks/ })).toContainText('1');
+
+ // what testing costs is asked once the pins are down, and said before anything is read
+ const test_ = deck.getByRole('button', { name: 'Test · 4 requests' });
+ await expect(test_).toBeEnabled();
+ expect(log.plans.length).toBeGreaterThan(0);
+ expect(log.plans.at(-1).check.marks).toHaveLength(2);
+ expect(log.tests).toHaveLength(0);
+ await test_.click();
+ await expect(deck.getByText('1 of 1 found · stayed empty · 1 candidate')).toBeVisible();
+ await expect(deck.getByRole('button', { name: /Tested$/ })).toBeDisabled();
+ expect(log.tests[0]).toMatchObject({ read: true, detail: true });
+ await expect(page.locator('.mark.pass')).toHaveCount(2);
+ await page.screenshot({ path: test.info().outputPath('detect-builder-tested.png') });
+
+ // the rules are on the ground: a change across both halves, a before-state on the before half, the tested ground tinted
+ await expect(page.locator('.rule-layers .part')).toHaveCount(3);
+ await expect.poll(async () => near([250, 204, 21, 110])(await painted(page, 'shared', [log.center.x, log.center.y]))).toBe(true);
+ await expect.poll(async () => near([56, 189, 248, 110])(await painted(page, 'before', [log.center.x, log.center.y]))).toBe(true);
+ await expect.poll(async () => near([0, 0, 0, 0])(await painted(page, 'after', [log.center.x, log.center.y]))).toBe(true);
+ // further out only the before-state passes; ground no rule kept carries the tint, and a corner of cloud nothing
+ const far = [log.center.x + 200 < 512 ? log.center.x + 200 : log.center.x - 200, log.center.y];
+ await expect.poll(async () => near([56, 189, 248, 110])(await painted(page, 'before', far))).toBe(false);
+ await expect.poll(async () => near([120, 170, 255, 30], 8)(await painted(page, 'shared', far))).toBe(true);
+ await expect.poll(async () => near([0, 0, 0, 0])(await painted(page, 'shared', [log.hole.x + 10, log.hole.y + 10]))).toBe(true);
+
+ // a chip hides a rule's pixels, and its row in the column says the same
+ await deck.getByRole('group', { name: 'Rules on the map' }).getByRole('button', { name: /NDVI change/ }).click();
+ await expect.poll(async () => near([120, 170, 255, 30], 8)(await painted(page, 'shared', [log.center.x, log.center.y]))).toBe(true);
+ await expect(page.getByRole('button', { name: 'Show rule 1 on the map', exact: true })).toHaveAttribute('aria-pressed', 'false');
+ await deck.getByRole('group', { name: 'Rules on the map' }).getByRole('button', { name: /NDVI change/ }).click();
+ // the pointer is on its chip, which shows that rule alone and brighter
+ await expect.poll(async () => near([250, 204, 21, 190])(await painted(page, 'shared', [log.center.x, log.center.y]))).toBe(true);
+ await page.mouse.move(box.x + 5, box.y + box.height / 2);
+ await expect.poll(async () => near([250, 204, 21, 110])(await painted(page, 'shared', [log.center.x, log.center.y]))).toBe(true);
+
+ // a pin reads the rules under it, and can be turned or taken away
+ await page.getByRole('button', { name: /^Pin 1:/ }).click();
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).toContainText('Pin 1: should be found');
+ await page.screenshot({ path: test.info().outputPath('detect-builder-pin.png') });
+ await reading.getByRole('button', { name: 'Close the reading' }).click();
+ await page.mouse.click(box.x + box.width * 0.4, box.y + box.height * 0.6);
+ await expect(reading).toContainText('Drop a pin here');
+ // the card keeps clear of the console, whichever way it opens
+ const card = await reading.boundingBox();
+ const deckBox = await deck.boundingBox();
+ expect(card.y + card.height).toBeLessThanOrEqual(deckBox.y + 1);
+ await page.screenshot({ path: test.info().outputPath('detect-builder-point.png') });
+ await page.keyboard.press('Escape');
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();
+ // a stricter line moves nothing until Test is pressed again, and then the pin is lost
+ await page.getByLabel('Rule 1 value').fill('0.8');
+ await page.getByLabel('Rule 1 value').press('Tab');
+ await expect(deck.getByText('The rules or pins changed since this test.')).toBeVisible();
+ const before = log.tests.length;
+ await page.waitForTimeout(400);
+ expect(log.tests).toHaveLength(before);
+ await page.screenshot({ path: test.info().outputPath('detect-builder-stale.png') });
+ await deck.getByRole('button', { name: /^Test again/ }).click();
+ await expect.poll(() => log.tests.length).toBe(before + 1);
+ expect(log.tests.at(-1).recipe.rules[0].value).toBe(-0.8);
+ await expect(page.locator('.mark.fail')).toHaveCount(1);
+ await expect(deck.getByText('0 of 1 found · stayed empty · 0 candidates')).toBeVisible();
+ await page.screenshot({ path: test.info().outputPath('detect-builder-lost.png') });
+ // a looser one takes it back
+ await page.getByLabel('Rule 1 value').fill('0.3');
+ await page.getByLabel('Rule 1 value').press('Tab');
+ await deck.getByRole('button', { name: /^Test again/ }).click();
+ await expect(page.locator('.mark.pass')).toHaveCount(2);
+
+ // at its narrowest the dock still holds the rules and the checks without a sideways scroll
+ const dockBody = page.locator('.cmp-dock-body');
+ await page.getByRole('button', { name: 'Resize Detect panel' }).focus();
+ await page.keyboard.press('Home');
+ await expect.poll(async () => Math.round((await page.locator('.cmp-dock').boundingBox()).width)).toBe(300);
+ await expect.poll(() => dockBody.evaluate((node) => node.scrollWidth - node.clientWidth)).toBeLessThanOrEqual(1);
+ await page.getByRole('tab', { name: /^Checks/ }).click();
+ await expect.poll(() => dockBody.evaluate((node) => node.scrollWidth - node.clientWidth)).toBeLessThanOrEqual(1);
+ await page.getByRole('tab', { name: /^Rules/ }).click();
+ await page.screenshot({ path: test.info().outputPath('detect-builder-narrow.png') });
+
+ // kept for every case, with the check that proves it
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',
+ await expect.poll(() => log.saved.length).toBe(1);
+ expect(log.saved[0]).toMatchObject({ method: 'rules', name: 'Cleared ground', match: 'all', sensor: 'sentinel2', dates: 'two' });
+ expect(log.saved[0].rules).toHaveLength(2);
+ expect(log.saved[0].checks).toEqual([expect.objectContaining({ name: 'Check 1',
+ a: expect.objectContaining({ date: '2026-09-01' }), b: expect.objectContaining({ date: '2026-09-10' }),
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);
+ result: expect.objectContaining({ covered: [true, false] }) })]);
+ expect(log.saved[0].rules[0]).toMatchObject({ op: 'le', value: -0.3 });
+ expect(log.saved[0].checks[0]).not.toHaveProperty('bounds');
+ await expect(page.locator('.console')).toHaveCount(0);
+ await expect(page.locator('.rule-layers')).toHaveCount(0);
+ await expect(page.locator('.detect-tool .map')).toHaveCount(1);
+ expect(errors).toEqual([]);
+});
+
+test('an analyzer of one date is tried on one map, with no split and no before or after to choose', async ({ page }) => {
+ const { errors } = await openDetect(page);
+ const log = await answerBuilder(page);
+ await page.getByRole('button', { name: 'Analyzers', exact: true }).click();
+ await page.getByRole('button', { name: 'New analyzer', exact: true }).click();
+ await page.getByRole('group', { name: 'Dates' }).getByRole('button', { name: 'One date' }).click();
+ await page.getByRole('button', { name: /^Blank/ }).click();
+ await expect(page.locator('.reads')).toHaveText('Sentinel-2 · one date');
+ await expect(page.getByLabel('Rule 1 says')).toHaveText('NDVI is at least 0.40');
+ await expect(page.getByLabel('Rule 1 reads')).toHaveCount(0);
+
+ const deck = page.locator('.console');
+ await deck.getByRole('button', { name: 'New check' }).click();
+ await deck.getByRole('button', { name: 'Find passes', exact: true }).click();
+ await page.getByLabel('Use 2026-09-10').getByRole('button', { name: 'Use', exact: true }).click();
+ await expect(page.getByRole('button', { name: 'Place the pins' })).toBeEnabled();
+ await page.getByRole('button', { name: 'Place the pins' }).click();
+ await expect(page.locator('.detect-tool .map')).toHaveCount(1);
+ await expect(page.getByRole('slider', { name: 'Split between the before and after passes' })).toHaveCount(0);
+ await expect(deck.getByRole('group', { name: 'Which pass to look at' })).toHaveCount(0);
+ expect(log.lookups).toHaveLength(1);
expect(errors).toEqual([]);
});
diff --git a/frontend/e2e/entity-photos.spec.js b/frontend/e2e/entity-photos.spec.js
index b73a867..13a03b5 100644
--- a/frontend/e2e/entity-photos.spec.js
+++ b/frontend/e2e/entity-photos.spec.js
@@ -18,6 +18,11 @@ const chain = {
empty: true,
};
+
+/** Details opens beside a wide Board, and over it below that. */
+const boardDetails = (page) =>
+ page.locator('aside.fiche').or(page.getByRole('dialog', { name: 'Details', exact: true }));
+
async function openDetails(page, options = {}) {
const fixture = await installAppFixture(page, {
catalog: [person],
@@ -26,7 +31,7 @@ async function openDetails(page, options = {}) {
});
await page.goto('/#board');
await page.getByRole('cell', { name: 'Unknown subject', exact: true }).click();
- await expect(page.getByRole('dialog', { name: 'Details' })).toBeVisible();
+ await expect(boardDetails(page)).toBeVisible();
return fixture;
}
@@ -38,7 +43,7 @@ test('imports a photo from the computer and keeps the main image bounded', async
title: 'portrait',
},
});
- const details = page.getByRole('dialog', { name: 'Details' });
+ const details = boardDetails(page);
await expect(details.locator('.main-photo')).toHaveCount(0);
await details.locator('input[type=file]').setInputFiles({
@@ -72,7 +77,7 @@ test('chooses an existing Media Library image without creating a relation', asyn
thumbnail: null,
}],
});
- const details = page.getByRole('dialog', { name: 'Details' });
+ const details = boardDetails(page);
await details.getByRole('button', { name: 'Choose from media' }).click();
const picker = page.getByRole('dialog', { name: 'Choose photos' });
@@ -128,7 +133,7 @@ test('adds private photos while creating an entity and chooses the primary one',
await dialog.getByRole('button', { name: 'Use portrait two as primary photo' }).click();
await dialog.getByRole('button', { name: 'Create', exact: true }).click();
- await expect(page.getByRole('dialog', { name: 'Details' })).toBeVisible();
+ await expect(boardDetails(page)).toBeVisible();
await expect(page.getByText('Primary', { exact: true })).toBeVisible();
expect(fixture.galleryWrites).toEqual([
{ method: 'UPLOAD', entityId: 'e_new', imageId: 'photo-direct-1' },
diff --git a/frontend/e2e/graph.spec.js b/frontend/e2e/graph.spec.js
index 4b5ceee..632a332 100644
--- a/frontend/e2e/graph.spec.js
+++ b/frontend/e2e/graph.spec.js
@@ -342,7 +342,8 @@ test('rereads while mounted when the Board files an entity', async ({ page }) =>
await page.getByLabel('Type').selectOption('person');
await page.getByLabel('Full name').fill('Second witness');
await page.getByRole('button', { name: 'Create', exact: true }).click();
- await page.getByRole('dialog').getByRole('button', { name: 'Close' }).click();
+ // what it creates opens beside the list
+ await page.getByRole('button', { name: 'Close Details' }).click();
await page.locator('.tabstrip').getByRole('button', { name: 'Graph', exact: true }).click();
await expect(page.getByText('2 of 2')).toBeVisible();
diff --git a/frontend/e2e/paste.spec.js b/frontend/e2e/paste.spec.js
index b175c0e..078115c 100644
--- a/frontend/e2e/paste.spec.js
+++ b/frontend/e2e/paste.spec.js
@@ -74,8 +74,9 @@ test('files a screenshot that exists nowhere but the clipboard', async ({ page }
title: 'Front gate',
source_url: 'https://example.test/thread',
});
- // filed, then opened: the next gesture is relating it to whatever prompted it
- await expect(page.getByRole('dialog', { name: 'Details' })).toBeVisible();
+ // filed, then opened beside the list: the next gesture is relating it to whatever
+ // prompted it
+ await expect(page.locator('aside.fiche')).toBeVisible();
fixture.expectNoUnexpectedRequests();
});
@@ -137,7 +138,8 @@ test('one Ctrl+V opens one dialog, however many tabs have been visited', async (
// the point here is to leave three tools mounted at the same time
await page.getByRole('button', { name: 'Files', exact: true }).click();
await expect(page.getByRole('heading', { name: 'Files' })).toBeVisible();
- await page.getByRole('button', { name: 'Board', exact: true }).click();
+ await page.getByRole('navigation').first().getByRole('button', { name: 'Case' }).click();
+ await page.locator('.tabstrip').getByRole('button', { name: 'Board', exact: true }).click();
await expect(page.getByRole('heading', { name: 'Board' })).toBeVisible();
await paste(page, { image: PNG_1PX });
@@ -176,7 +178,8 @@ test('a paste in Proof stays the composer\'s own', async ({ page }) => {
const fixture = await installAppFixture(page, { catalog });
await page.goto('/#media');
await expect(page.getByRole('heading', { name: 'Media Library' })).toBeVisible();
- await page.getByRole('button', { name: 'Board', exact: true }).click();
+ await page.getByRole('navigation').first().getByRole('button', { name: 'Case' }).click();
+ await page.locator('.tabstrip').getByRole('button', { name: 'Board', exact: true }).click();
await expect(page.getByRole('heading', { name: 'Board' })).toBeVisible();
await page.getByRole('button', { name: 'Compose', exact: true }).click();
diff --git a/frontend/e2e/proof-date-clock.spec.js b/frontend/e2e/proof-date-clock.spec.js
new file mode 100644
index 0000000..f93b4bd
--- /dev/null
+++ b/frontend/e2e/proof-date-clock.spec.js
@@ -0,0 +1,57 @@
+import { test, expect } from '@playwright/test';
+import { PANEL_PATH, installAppFixture, openProofWithPanel } from './app.fixture.js';
+
+/**
+ * The clock a proof's date is read on. A day is the day of the place the footage
+ * shows, so the composer reads it on the first point's zone, and a save sends the
+ * analyst's pick only when they made one.
+ */
+
+const framed = {
+ path: PANEL_PATH,
+ provider_label: 'Esri',
+ lat: 48.8584,
+ lon: 2.2945,
+ center_lat: 48.8584,
+ center_lon: 2.2945,
+ zoom: 17,
+ fetched_at: '2026-09-01T10:00:00Z',
+};
+
+test('reads the date on the point’s clock, and sends another only once picked', async ({ page }) => {
+ const fixture = await installAppFixture(page, { satCaptures: [framed] });
+ await openProofWithPanel(page);
+
+ const clock = page.locator('.when-zone .clock-trigger');
+ await expect(clock).toHaveCount(0);
+ const when = page.locator('#proof-when');
+ await when.fill('12/03/2024');
+ await when.blur();
+ await expect(clock).toHaveAttribute('aria-label', 'Clock: the point UTC+01:00');
+ await expect(page.getByText('12 Mar 2024 (Europe/Paris)')).toBeVisible();
+
+ await clock.click();
+ const menu = page.locator('.clock-menu');
+ await expect(menu.getByRole('button', { name: /^Local at the point/ })).toBeVisible();
+ await menu.getByRole('button', { name: /^UTC/ }).click();
+ await expect(clock).toHaveAttribute('aria-label', 'Clock: UTC');
+ await page.getByRole('button', { name: 'Save proof', exact: true }).click();
+ await page.getByRole('dialog', { name: 'Check the point' }).getByRole('button', { name: 'Use this point' }).click();
+ await expect.poll(() => fixture.proofSaves.length).toBe(1);
+ expect(fixture.proofSaves[0].spec).toMatchObject({ when: '2024-03-12', whenZone: 'UTC' });
+
+ // Any zone in the world, by search.
+ await clock.click();
+ await menu.getByRole('textbox').fill('tokyo');
+ await menu.getByRole('button', { name: /^Tokyo/ }).click();
+ await page.getByRole('button', { name: 'Save proof', exact: true }).click();
+ await expect.poll(() => fixture.proofSaves.length).toBe(2);
+ expect(fixture.proofSaves[1].spec.whenZone).toBe('Asia/Tokyo');
+
+ // Back to the point: the save leaves the zone to it.
+ await clock.click();
+ await menu.getByRole('button', { name: /^Local at the point/ }).click();
+ await page.getByRole('button', { name: 'Save proof', exact: true }).click();
+ await expect.poll(() => fixture.proofSaves.length).toBe(3);
+ expect(fixture.proofSaves[2].spec.whenZone).toBe(null);
+});
diff --git a/frontend/e2e/report-buttons.spec.js b/frontend/e2e/report-buttons.spec.js
new file mode 100644
index 0000000..89ff641
--- /dev/null
+++ b/frontend/e2e/report-buttons.spec.js
@@ -0,0 +1,74 @@
+import { test, expect } from '@playwright/test';
+import { installAppFixture, openProofWithPanel } from './app.fixture.js';
+
+async function buttonStyle(button) {
+ return button.evaluate((element) => {
+ const style = getComputedStyle(element);
+ const properties = [
+ 'backgroundColor', 'color', 'borderColor', 'borderWidth', 'borderStyle',
+ 'borderRadius', 'padding', 'fontSize', 'fontWeight', 'gap', 'opacity', 'height',
+ ];
+ return Object.fromEntries(properties.map((property) => [property, style[property]]));
+ });
+}
+
+for (const theme of ['dark', 'light']) {
+ test(`Report actions match Proof buttons in the ${theme} theme`, async ({ page }) => {
+ await page.setViewportSize({ width: 1600, height: 1000 });
+ const fixture = await installAppFixture(page);
+ await page.addInitScript((value) => localStorage.setItem('azimut:theme', value), theme);
+ await page.goto('/#proof');
+ await expect(page.getByRole('heading', { name: 'Geo Proof' })).toBeVisible({ timeout: 15_000 });
+
+ const header = page.locator('.tool-header');
+ const saveProof = header.getByRole('button', { name: 'Save proof', exact: true });
+ const toPost = header.getByRole('button', { name: 'To Post', exact: true });
+ await expect(saveProof).toBeDisabled();
+ const disabledSave = await buttonStyle(saveProof);
+ const disabledPublish = await buttonStyle(toPost);
+ const neutral = await buttonStyle(header.getByRole('button', { name: 'Open proof', exact: true }));
+ const spacing = await header.evaluate((element) => getComputedStyle(element).gap);
+
+ await openProofWithPanel(page);
+ await expect(saveProof).toBeEnabled();
+ const save = await buttonStyle(saveProof);
+ const publish = await buttonStyle(toPost);
+
+ // Read the hover treatment too, after the shared colour transition settles.
+ await saveProof.hover();
+ await page.waitForTimeout(200);
+ const saveHover = await buttonStyle(saveProof);
+ await toPost.hover();
+ await page.waitForTimeout(200);
+ const publishHover = await buttonStyle(toPost);
+
+ await page.getByRole('button', { name: 'Geo Report', exact: true }).click();
+ await expect(page.getByRole('heading', { name: 'Geo Report' })).toBeVisible();
+ await page.mouse.move(0, 0);
+ const actions = header.locator('.head-actions');
+ const draft = actions.getByRole('button', { name: 'Save as draft', exact: true });
+ const report = actions.getByRole('button', { name: 'Save report', exact: true });
+ const publishReport = actions.getByRole('button', { name: 'Publish on X', exact: true });
+ await expect(draft).toBeEnabled();
+ await expect(report).toBeDisabled();
+ await expect(publishReport).toBeDisabled();
+ expect(await buttonStyle(actions.getByRole('button', { name: 'Open', exact: true }))).toEqual(neutral);
+ expect(await buttonStyle(draft)).toEqual(neutral);
+ expect(await buttonStyle(report)).toEqual(disabledSave);
+ expect(await buttonStyle(publishReport)).toEqual(disabledPublish);
+ expect(await actions.evaluate((element) => getComputedStyle(element).gap)).toBe(spacing);
+
+ await page.locator('.post-text').first().fill('A verified location.');
+ await expect(report).toBeEnabled();
+ await expect(publishReport).toBeEnabled();
+ expect(await buttonStyle(actions.getByRole('button', { name: 'Discard', exact: true }))).toEqual(neutral);
+ expect(await buttonStyle(report)).toEqual(save);
+ expect(await buttonStyle(publishReport)).toEqual(publish);
+ await report.hover();
+ await expect.poll(() => buttonStyle(report)).toEqual(saveHover);
+ await publishReport.hover();
+ await expect.poll(() => buttonStyle(publishReport)).toEqual(publishHover);
+
+ fixture.expectNoUnexpectedRequests();
+ });
+}
diff --git a/frontend/e2e/satellite-added-layers.spec.js b/frontend/e2e/satellite-added-layers.spec.js
index 12bf67c..fc38c34 100644
--- a/frontend/e2e/satellite-added-layers.spec.js
+++ b/frontend/e2e/satellite-added-layers.spec.js
@@ -110,3 +110,46 @@ test("the pin's card states its point and copies it", async ({ page, context, br
await expect(page.getByText('Coordinates copied')).toBeVisible();
expect(await page.evaluate(() => navigator.clipboard.readText())).toBe('48.850000, 2.350000');
});
+
+test('the rows open folded and a dragged row is stored in its new place', async ({ page }) => {
+ const second = { ...LAYER, name: 'depots', title: 'Depots map' };
+ let order = null;
+ await installAppFixture(page);
+ await page.route(`**/api/cases/${CASE_ID}/map-layers`, (route) =>
+ route.request().method() === 'GET' ? route.fulfill({ json: [LAYER, second] }) : route.fallback()
+ );
+ await page.route(`**/api/cases/${CASE_ID}/map-layers/order`, (route) => {
+ order = route.request().postDataJSON().names;
+ route.fulfill({ json: [second, LAYER] });
+ });
+ await page.goto('/#satellite?ll=48.85,2.35&z=16');
+
+ const details = page.getByRole('button', { name: `${LAYER.title}, details` });
+ await expect(details).toHaveAttribute('aria-expanded', 'false');
+ await expect(page.getByText('checkpoints.geojson')).toHaveCount(0);
+
+ // dragged by hand, drifting off the rows to the left on the way, as a hand
+ // moving down a grip on the row's edge does: the drop still takes
+ // measured once the panel above has stopped moving the list down
+ const list = page.locator('ul.layers:has(.fold)');
+ let settled = null;
+ await expect
+ .poll(async () => {
+ const top = (await list.boundingBox())?.y;
+ const same = top === settled;
+ settled = top;
+ return same;
+ })
+ .toBe(true);
+ const grip = await page.getByRole('button', { name: `Move ${second.title}`, exact: true }).boundingBox();
+ const target = await page.locator('ul.layers:has(.fold) > li').first().boundingBox();
+ await page.mouse.move(grip.x + grip.width / 2, grip.y + grip.height / 2);
+ await page.mouse.down();
+ for (let step = 1; step <= 8; step += 1) {
+ await page.mouse.move(grip.x - 14, grip.y + (target.y + 4 - grip.y) * (step / 8));
+ }
+ await page.mouse.up();
+
+ await expect.poll(() => order).toEqual([second.name, LAYER.name]);
+ await expect(page.locator('.layers > li .fold .name')).toHaveText([second.title, LAYER.title]);
+});
diff --git a/frontend/e2e/settings.spec.js b/frontend/e2e/settings.spec.js
index b7c76d9..810504a 100644
--- a/frontend/e2e/settings.spec.js
+++ b/frontend/e2e/settings.spec.js
@@ -158,3 +158,38 @@ test('a signature resize whose release the window never sees still lands, and st
await page.mouse.up();
fixture.expectNoUnexpectedRequests();
});
+
+test('a new post template starts from a layout, counts each platform and mends a misspelled token', async ({ page }) => {
+ const fixture = await installAppFixture(page);
+ await page.goto('/#settings');
+ await page.getByRole('navigation', { name: 'Settings sections' })
+ .getByRole('button', { name: 'Templates' }).click();
+ await page.getByRole('button', { name: 'New post template' }).click();
+
+ const editor = page.locator('.tpl-modal');
+ const body = editor.locator('textarea.body');
+ const preview = editor.locator('.pe-preview pre');
+
+ await editor.getByRole('group', { name: 'Start from' }).getByRole('button', { name: 'With date' }).click();
+ await expect(body).toHaveValue(/Filmed: #date/);
+ await expect(preview).toContainText('Filmed: 2025-10-24 14:30 UTC+3');
+ await expect(editor.locator('.counters')).toContainText(/X \d+\/280 · Bluesky \d+\/300/);
+
+ // no post is open in the composer, so only the sample can be previewed
+ const open = editor.getByRole('button', { name: 'Open post' });
+ await expect(open).toBeDisabled();
+ await expect(open).toHaveAttribute('title', 'No post is open in the composer');
+
+ await body.fill('#place\n#coordinate\n#coordinate');
+ await expect(editor.locator('.misspelled'))
+ .toContainText('#coordinate is not a token. Did you mean #coordinates?');
+ await editor.locator('.misspelled').getByRole('button', { name: 'Fix' }).click();
+ await expect(body).toHaveValue('#place\n#coordinates\n#coordinates');
+ await expect(editor.locator('.misspelled')).toHaveCount(0);
+
+ await body.fill('a'.repeat(290));
+ await expect(editor.locator('.counter').first()).toHaveClass(/over/);
+ await expect(editor.locator('.counter').nth(1)).not.toHaveClass(/over/);
+
+ fixture.expectNoUnexpectedRequests();
+});
diff --git a/frontend/e2e/subject-corrections.spec.js b/frontend/e2e/subject-corrections.spec.js
new file mode 100644
index 0000000..b835f69
--- /dev/null
+++ b/frontend/e2e/subject-corrections.spec.js
@@ -0,0 +1,92 @@
+import { test, expect } from '@playwright/test';
+import { CASE_ID, installAppFixture } from './app.fixture.js';
+
+const subject = (id, label, at) => ({ id, type: 'vehicle', label, attrs: { plate: 'AA1234' }, provenance: { by: 'user', at, status: 'confirmed' } });
+const newer = subject('newer', 'Convoy vehicle', '2026-09-02T12:00:00Z');
+const older = subject('older', 'Earlier vehicle', '2026-09-01T12:00:00Z');
+const chain = (entity) => ({ entity, sources: [], lost: [], dependents: [], relations: [], empty: true });
+
+
+/** Details docks beside a wide Board and is a modal below that, as when the window is
+ * narrowed to a phone's width. */
+const boardDetails = (page) =>
+ page.locator('aside.fiche').or(page.getByRole('dialog', { name: 'Details', exact: true }));
+
+async function setup(page) {
+ const fixture = await installAppFixture(page, { catalog: [newer, older] });
+ let current = structuredClone(newer);
+ let merged = false;
+ let restored = false;
+ const writes = [];
+ await page.route(`**/api/cases/${CASE_ID}/entities/**`, async (route) => {
+ const request = route.request();
+ const url = new URL(request.url());
+ const send = (body, status = 200) => route.fulfill({ status, contentType: 'application/json', body: JSON.stringify(body) });
+ if (url.pathname.endsWith('/chain')) {
+ const id = url.pathname.split('/').at(-2);
+ return send(chain(id === 'older' ? older : current));
+ }
+ if (url.pathname.endsWith('/merges')) return send({ merges: merged ? [{ id: 'merge-1', merged_label: newer.label }] : [] });
+ if (url.pathname.endsWith('/merge-preview')) return send({
+ fields: { kept: { plate: 'AA1234' }, added: {}, conflicts: [] },
+ links: { moved: 2, twins: 0, loops: 0 }, refused: [], images: {}, pins: {}, views: [], sheets: 0, notes: 1,
+ });
+ if (url.pathname.endsWith('/merge')) {
+ writes.push({ path: url.pathname, body: request.postDataJSON() }); merged = true;
+ return send({ merge: 'merge-1', survivor: older, warnings: [] });
+ }
+ if (request.method() === 'PATCH') {
+ const body = request.postDataJSON(); writes.push(body);
+ if (body.type) {
+ current = { ...current, type: body.type, attrs: { plate: 'AA1234', _retained_fields: { plate: 'vehicle' } } };
+ } else if (body.attrs?.plate === null) current.attrs = {};
+ return send(current);
+ }
+ return route.fallback();
+ });
+ await page.route(`**/api/cases/${CASE_ID}/merges/merge-1/undo`, async (route) => {
+ merged = false; restored = true;
+ await route.fulfill({ contentType: 'application/json', body: JSON.stringify({ restored: newer, survivor: older.id, lost: [] }) });
+ });
+ await page.goto('/#board');
+ await page.locator('tbody tr').filter({ has: page.locator('.name', { hasText: newer.label }) }).locator('td:not(.pick)').first().click();
+ await expect(boardDetails(page)).toBeVisible();
+ return { fixture, writes, restored: () => restored };
+}
+
+test('changes a subject type and explicitly removes a retained field', async ({ page }) => {
+ const state = await setup(page);
+ const details = boardDetails(page);
+ await details.getByRole('button', { name: 'Change type…', exact: true }).click();
+ await details.getByLabel('New type').selectOption('organization');
+ await details.getByRole('button', { name: 'Change type', exact: true }).click();
+ await expect(details.getByText('Kept from Vehicle', { exact: true })).toBeVisible();
+ await expect(details.getByRole('button', { name: 'Remove Plate' })).toBeVisible();
+ await details.getByRole('button', { name: 'Remove Plate' }).click();
+ await expect(details.getByText('Kept from Vehicle', { exact: true })).toHaveCount(0);
+ expect(state.writes).toEqual([{ type: 'organization' }, { attrs: { plate: null } }]);
+ state.fixture.expectNoUnexpectedRequests();
+});
+
+test('previews the older survivor, merges, and undoes from Details', async ({ page }) => {
+ const state = await setup(page);
+ await page.getByRole('button', { name: 'Merge…', exact: true }).click();
+ const dialog = page.getByRole('dialog', { name: 'Merge subjects', exact: true });
+ await dialog.getByRole('option', { name: /Earlier vehicle/ }).click();
+ await expect(dialog.getByRole('button', { name: /Keep Earlier vehicle/ })).toHaveAttribute('aria-pressed', 'true');
+ await expect(dialog.getByRole('table', { name: 'Fields after merging' })).toBeVisible();
+ await page.screenshot({ path: test.info().outputPath('merge-desktop.png') });
+ await page.setViewportSize({ width: 390, height: 844 });
+ await expect(dialog).toBeVisible();
+ expect(await dialog.evaluate((node) => node.scrollWidth <= node.clientWidth)).toBe(true);
+ await page.screenshot({ path: test.info().outputPath('merge-mobile.png') });
+ await dialog.getByRole('button', { name: 'Merge subjects', exact: true }).click();
+ await expect(dialog).toHaveCount(0);
+ expect(state.writes[0]).toEqual({ path: `/api/cases/${CASE_ID}/entities/older/merge`, body: { other: 'newer' } });
+ const details = boardDetails(page);
+ await expect(details.getByText('Merged from')).toBeVisible();
+ await details.getByRole('button', { name: 'Undo', exact: true }).click();
+ await expect.poll(state.restored).toBe(true);
+ await expect(details.getByRole('button', { name: 'Undo', exact: true })).toHaveCount(0);
+ state.fixture.expectNoUnexpectedRequests();
+});
diff --git a/frontend/e2e/timeline.spec.js b/frontend/e2e/timeline.spec.js
index d8431c7..ae6e301 100644
--- a/frontend/e2e/timeline.spec.js
+++ b/frontend/e2e/timeline.spec.js
@@ -1,6 +1,15 @@
import { test, expect } from '@playwright/test';
import { awaitMapReady, CASE_ID, installAppFixture } from './app.fixture.js';
+/** Details docks beside a wide Board and is a modal below that. */
+const boardDetails = (page) =>
+ page.locator('aside.fiche').or(page.getByRole('dialog', { name: 'Details', exact: true }));
+
+/** The Board's flat table, where a file or a claim is a row on screen rather than one
+ * in a folded group. */
+const flatBoard = (page) =>
+ page.addInitScript((key) => localStorage.setItem(key, '{"group":"none"}'), `azimut:board-layout:${CASE_ID}`);
+
const person = {
id: 'person-1',
type: 'person',
@@ -75,7 +84,16 @@ const timelineItems = [
earliest: '2026-06-23T18:42:11Z', latest: '2026-06-23T18:42:12Z', precision: 'second',
shape: 'instant', time_role: null, uncertain: false, approximate: false,
zone: 'utc', sortable: true, status: null, confidence: null, parse_error: null,
- subjects: [], places: [], sources: [],
+ subjects: [], places: [], sources: [], produced_here: false,
+ },
+ {
+ // a frame the case extracted itself: a working file, held back by the Media track
+ id: 'temporal:media:frame-1:captured', owner_id: 'frame-1', category: 'media', kind: 'captured',
+ label: 'Extracted frame 00:12', raw: '2026-06-23T19:10:00Z',
+ earliest: '2026-06-23T19:10:00Z', latest: '2026-06-23T19:10:01Z', precision: 'second',
+ shape: 'instant', time_role: null, uncertain: false, approximate: false,
+ zone: 'utc', sortable: true, status: null, confidence: null, parse_error: null,
+ subjects: [], places: [], sources: [], produced_here: true,
},
{
id: 'temporal:claim:claim-3', owner_id: 'claim-3', category: 'statement', kind: 'claim',
@@ -142,11 +160,54 @@ async function setWindow(page, from, to) {
await expect(menu).toHaveCount(0);
}
-/** The window the axis says it is drawing, as `<start> to <end>` on the display zone.
- * It is what stays on screen while the ruler and the overview are being dragged. */
-const axisWindowText = (page) => page.locator('.axis-label small').innerText();
+/** The window the axis says it is drawing, as `<start> to <end>` on the display zone:
+ * the exact boundaries the window's reading carries on hover. */
+const axisWindowText = async (page) =>
+ (await page.locator('.range-face').getAttribute('title')).split(' · ')[0];
+
+/** A preset put on the axis from `⋯`, where tracks are added. */
+async function addTrack(page, name) {
+ await page.locator('.timeline-bar').getByRole('button', { name: 'More', exact: true }).click();
+ await page.locator('.more-menu section').getByRole('button').filter({ hasText: name }).click();
+ await expect(page.locator('.more-menu')).toHaveCount(0);
+}
+
+/** The two lanes a fresh reading opens on: the files where the analyst dated them,
+ * then the events. */
+const mediaLane = (page) => page.locator('.track-canvas').first();
+const eventsLane = (page) => page.locator('.track-canvas').nth(1);
+
+/** What each file says about itself, a track added on purpose from `⋯`. */
+const fileDatesRow = (page) => page.locator('.track-row')
+ .filter({ has: page.locator('.track-label strong', { hasText: /^File dates$/ }) });
+const fileDatesLane = (page) => fileDatesRow(page).locator('.track-canvas');
+const showFileDates = (page) => addTrack(page, /^File dates/);
+
+/** `⋯`, opened, for what waits under it. */
+async function more(page) {
+ await page.locator('.timeline-bar').getByRole('button', { name: 'More', exact: true }).click();
+ return page.locator('.more-menu');
+}
+
+/** Group the lanes from `⋯`, and close it again. */
+async function groupLanes(page, by) {
+ await (await more(page)).getByLabel('Group by').selectOption(by);
+ await page.keyboard.press('Escape');
+ await expect(page.locator('.more-menu')).toHaveCount(0);
+}
+
+/** Narrow the window so the whole-case strip under the axis has something to show. */
+async function zoomIn(page) {
+ await page.locator('.axis-ruler').focus();
+ await page.keyboard.press('+');
+ await expect(page.locator('.overview-card')).toBeVisible();
+}
-async function openTimeline(page, options = {}) {
+async function openTimeline(page, { clock, ...options } = {}) {
+ // A clock the analyst picked for the case, kept in this browser like the real one.
+ if (clock) {
+ await page.addInitScript(([key, value]) => localStorage.setItem(key, value), [`azimut:timeline-clock:${CASE_ID}`, clock]);
+ }
const fixture = await installAppFixture(page, {
catalog: [person, source, mediaEntity],
timelineItems,
@@ -167,7 +228,7 @@ async function openTimeline(page, options = {}) {
});
await page.setViewportSize({ width: 1440, height: 900 });
await page.goto('/#timeline');
- await expect(page.getByRole('heading', { name: 'Timeline', exact: true })).toBeVisible();
+ await expect(page.locator('.timeline-bar')).toBeVisible();
await expect(page.locator('.loading-line')).toHaveCount(0);
return fixture;
}
@@ -175,11 +236,20 @@ async function openTimeline(page, options = {}) {
test('draws a clear chronology with density, uncertainty and an inspector', async ({ page }, testInfo) => {
const fixture = await openTimeline(page);
- await expect(page.locator('.tabstrip').getByRole('button')).toHaveText(['Board', 'Graph', 'Timeline', 'Sheet']);
- await expect(page.locator('.track-label strong')).toHaveText(['Events', 'Media']);
+ await expect(page.locator('.tabstrip').getByRole('button')).toHaveText(['Timeline', 'Board', 'Graph', 'Sheet']);
+ // the files where the analyst dated them, over what the analyst dated
+ await expect(page.locator('.track-label strong')).toHaveText(['Media', 'Events']);
+ // no inspector before a pick, and no whole-case strip while the window is the case
+ await expect(page.locator('.inspector')).toHaveCount(0);
+ await expect(page.locator('.overview-card')).toHaveCount(0);
+ // what a file says about itself is a clue, drawn when asked for
+ await expect(page.getByRole('button', { name: /Roadside camera frame/ })).toHaveCount(0);
+ await showFileDates(page);
+ // the files the case collected, not its own frames
+ await expect(page.getByRole('button', { name: /Roadside camera frame/ })).toBeVisible();
+ await expect(page.getByRole('button', { name: /Extracted frame/ })).toHaveCount(0);
await expect(page.getByRole('button', { name: /Witness arrived/ })).toBeVisible();
await expect(page.getByRole('button', { name: /Vehicle remained/ }).locator('..')).toHaveClass(/period.*approximate.*uncertain/);
- await expect(page.locator('.density-bucket')).toHaveCount(4);
await expect(page.getByText('Undated', { exact: true })).toBeVisible();
await expect(page.getByText('Not on UTC axis', { exact: true })).toBeVisible();
await expect(page.getByText('2021-04-24T14:52:29', { exact: false })).toBeVisible();
@@ -202,17 +272,25 @@ test('draws a clear chronology with density, uncertainty and an inspector', asyn
}
await page.getByRole('button', { name: /Witness arrived/ }).click();
- expect((await page.locator('.axis-ruler').boundingBox()).width).toBeCloseTo(axis.width, 0);
+ // the inspector takes its column from the axis, which keeps a readable width
+ expect((await page.locator('.axis-ruler').boundingBox()).width).toBeGreaterThan(600);
const inspector = page.locator('.inspector');
+ await expect(inspector.locator('header')).toContainText('Event');
await expect(inspector.getByRole('heading', { name: timelineItem('claim-1').label })).toBeVisible();
- await expect(inspector.getByText('2026-06-18', { exact: true })).toBeVisible();
await expect(inspector.getByText('Confidence: probable')).toBeVisible();
await expect(inspector.getByText('Compared the checkpoint log with the interview notes.')).toBeVisible();
await expect(inspector.getByRole('button', { name: /Interview notes/ })).toBeVisible();
+ // how the date is held is folded under the reading
+ await expect(inspector.getByText('2026-06-18', { exact: true })).toBeHidden();
+ await inspector.getByText('About this date').click();
+ await expect(inspector.getByText('2026-06-18', { exact: true })).toBeVisible();
- await page.getByRole('button', { name: 'Track', exact: true }).click();
- await page.locator('.track-menu').getByRole('button').filter({ hasText: 'Case activity' }).click();
- await expect(page.locator('.track-label strong')).toHaveText(['Events', 'Media', 'Case activity']);
+ // narrowed, the window leaves part of the case out, and the strip under the axis says where
+ await zoomIn(page);
+ await expect(page.locator('.density-bucket')).toHaveCount(4);
+
+ await addTrack(page, 'Case activity');
+ await expect(page.locator('.track-label strong')).toHaveText(['Media', 'Events', 'File dates', 'Case activity']);
if (process.env.AZIMUT_TIMELINE_SCREENSHOT && testInfo.project.name === 'chromium') {
await page.screenshot({ path: process.env.AZIMUT_TIMELINE_SCREENSHOT, fullPage: true });
@@ -223,13 +301,12 @@ test('draws a clear chronology with density, uncertainty and an inspector', asyn
test('builds, reorders and curates tracks without leaving the chronology', async ({ page }) => {
const fixture = await openTimeline(page);
- await page.getByRole('button', { name: 'Track', exact: true }).click();
- await page.locator('.track-menu').getByRole('button').filter({ hasText: /^Person/ }).click();
- await expect(page.locator('.track-label strong')).toHaveText(['Events', 'Media', 'Person']);
+ await addTrack(page, /^Person/);
+ await expect(page.locator('.track-label strong')).toHaveText(['Media', 'Events', 'Person']);
const movePerson = page.getByRole('button', { name: 'Move Person track' });
await movePerson.press('Alt+ArrowUp');
- await expect(page.locator('.track-label strong')).toHaveText(['Events', 'Person', 'Media']);
+ await expect(page.locator('.track-label strong')).toHaveText(['Media', 'Person', 'Events']);
await page.getByRole('button', { name: 'Fold Person' }).click();
await expect(page.locator('.track-row').filter({ hasText: 'Person' })).toHaveClass(/folded/);
@@ -245,8 +322,7 @@ test('builds, reorders and curates tracks without leaving the chronology', async
await personTrack.getByRole('button', { name: 'Show hidden' }).click();
await expect(personTrack.getByRole('button', { name: /Witness arrived/ })).toBeVisible();
- await page.getByRole('button', { name: 'Track', exact: true }).click();
- await page.locator('.track-menu').getByRole('button').filter({ hasText: /^Custom/ }).click();
+ await addTrack(page, /^Custom/);
const editor = page.getByRole('dialog', { name: 'Add track' });
await expect(editor.getByText('Search+', { exact: true })).toBeVisible();
await editor.getByLabel('Name').fill('Evidence review');
@@ -254,7 +330,7 @@ test('builds, reorders and curates tracks without leaving the chronology', async
await editor.getByRole('button', { name: 'Add track' }).click();
await expect(page.locator('.track-label strong').filter({ hasText: 'Evidence review' })).toHaveCount(1);
- await page.getByLabel('Group by').selectOption('subject');
+ await groupLanes(page, 'subject');
await expect(page.locator('.track-label strong').filter({ hasText: 'Harbour witness' })).toHaveCount(3);
fixture.expectNoUnexpectedRequests();
});
@@ -304,8 +380,7 @@ test('asks an entry what can be done with it, without choosing it', async ({ pag
test('autosaves a live Timeline view and restores its track reading', async ({ page }) => {
const fixture = await openTimeline(page);
- await page.getByRole('button', { name: 'Track', exact: true }).click();
- await page.locator('.track-menu').getByRole('button').filter({ hasText: /^Person/ }).click();
+ await addTrack(page, /^Person/);
await page.getByRole('button', { name: /^Views/ }).click();
await page.getByRole('button', { name: 'Save view' }).click();
@@ -314,7 +389,7 @@ test('autosaves a live Timeline view and restores its track reading', async ({ p
await dialog.getByRole('button', { name: 'Save', exact: true }).click();
await expect(page.locator('.views .active')).toContainText('live · saved');
- await page.getByLabel('Group by').selectOption('role');
+ await groupLanes(page, 'role');
await expect.poll(() => fixture.analysisWrites.at(-1)?.body?.spec?.timeline?.group_by)
.toBe('role');
await expect(page.locator('.views .active')).toContainText('saved');
@@ -323,7 +398,8 @@ test('autosaves a live Timeline view and restores its track reading', async ({ p
await page.getByRole('button', { name: /^Views/ }).click();
// the surface is not printed on this list: every view in it is a Timeline reading
await page.getByRole('button', { name: 'Witness chronology live' }).click();
- await expect(page.getByLabel('Group by')).toHaveValue('role');
+ await expect((await more(page)).getByLabel('Group by')).toHaveValue('role');
+ await page.keyboard.press('Escape');
await expect(page.locator('.track-name em').filter({ hasText: 'Person' })).toHaveCount(2);
fixture.expectNoUnexpectedRequests();
});
@@ -342,7 +418,7 @@ test('files a pending live edit before switching cases', async ({ page }) => {
await dialog.getByRole('button', { name: 'Save', exact: true }).click();
await expect(page.locator('.views .active')).toContainText('live · saved');
- await page.getByLabel('Group by').selectOption('role');
+ await groupLanes(page, 'role');
await page.getByTitle('Switch case').click();
await page.locator('.switcher .menu .item').filter({ hasText: 'Second Case' }).click();
@@ -366,8 +442,10 @@ test('keeps a Timeline snapshot frozen and read-only', async ({ page }) => {
await expect(page.locator('.views .active')).toContainText('snapshot');
await expect(page.getByText('Frozen view', { exact: true })).toBeVisible();
- await expect(page.getByRole('button', { name: 'Track', exact: true })).toBeDisabled();
- await expect(page.getByLabel('Group by')).toBeDisabled();
+ const menu = await more(page);
+ await expect(menu.locator('section').getByRole('button').first()).toBeDisabled();
+ await expect(menu.getByLabel('Group by')).toBeDisabled();
+ await page.keyboard.press('Escape');
await expect(page.getByTitle('Which clock the axis is labelled with')).toBeDisabled();
await expect(page.getByRole('button', { name: /Witness arrived/ }).first()).toBeVisible();
expect(fixture.analysisWrites.at(-1)).toMatchObject({
@@ -379,22 +457,135 @@ test('keeps a Timeline snapshot frozen and read-only', async ({ page }) => {
test('creates a dated statement from a point on the axis', async ({ page }) => {
const fixture = await openTimeline(page);
- const canvas = page.locator('.track-canvas').first();
+ const canvas = eventsLane(page);
const box = await canvas.boundingBox();
await page.mouse.click(box.x + box.width * 0.72, box.y + box.height - 8);
- const dialog = page.getByRole('dialog', { name: 'Add claim' });
- await expect(dialog).toBeVisible();
- await expect(dialog.getByLabel('When')).not.toHaveValue('');
- await dialog.getByLabel('Claim', { exact: true }).fill('A second witness reached the checkpoint');
- await dialog.getByRole('button', { name: 'Add claim' }).click();
+ // The click dates the line under the axis and hands it the sentence.
+ const line = page.getByRole('region', { name: 'Add an event' });
+ await expect(line.getByLabel('When')).not.toHaveValue('');
+ await expect(line.getByLabel('What happened')).toBeFocused();
+ await expect(page.getByRole('dialog')).toHaveCount(0);
+ await page.keyboard.type('A second witness reached the checkpoint');
+ await page.keyboard.press('Enter');
await expect.poll(() => fixture.timelineWrites.length).toBe(1);
expect(fixture.timelineWrites[0]).toMatchObject({
method: 'POST',
- body: { statement: 'A second witness reached the checkpoint' },
+ body: { statement: 'A second witness reached the checkpoint', create: [] },
});
+ expect(fixture.timelineWrites[0].body.when).toMatch(/^2026-06-/);
await expect(page.getByRole('button', { name: /A second witness/ })).toBeVisible();
+ // Emptied for the next one, and the way back is offered.
+ await expect(line.getByLabel('What happened')).toHaveValue('');
+ await expect(line.getByLabel('When')).toHaveValue('');
+ await page.locator('.toast').getByRole('button', { name: 'Undo' }).click();
+ await expect.poll(() => fixture.entityWrites.at(-1)?.ids).toEqual([fixture.timelineWrites[0].ownerId]);
+ fixture.expectNoUnexpectedRequests();
+});
+
+test('notes an entry with a new subject and a place, on that place’s clock', async ({ page }) => {
+ const fixture = await openTimeline(page, { catalog: [person, source, mediaEntity, quay] });
+ const line = page.getByRole('region', { name: 'Add an event' });
+ const say = line.getByLabel('What happened');
+
+ await say.pressSequentially('Crane seen at @South');
+ const mentions = page.getByRole('listbox', { name: 'Mentions' });
+ await expect(mentions.getByRole('option').first()).toContainText('South quay');
+ await say.press('Enter');
+ await say.pressSequentially('with @4th brigade');
+ await expect(mentions.getByRole('option').last()).toContainText('New · 4th brigade');
+ await say.press('ArrowUp');
+ await say.press('Enter');
+ await expect(line.locator('.chip.new')).toContainText('4th brigade');
+
+ await line.getByLabel('When').fill('23/06/2026 17:05');
+ await expect(line).toContainText('Reads: 23 Jun 2026, 17:05:00 Europe/Paris (UTC+02:00)');
+ // the chip names the place whose clock it is
+ await expect(line.getByRole('button', { name: 'Clock: South quay UTC+02:00' })).toBeVisible();
+ await say.press('Enter');
+
+ await expect.poll(() => fixture.timelineWrites.length).toBe(1);
+ const { body } = fixture.timelineWrites[0];
+ expect(body).toMatchObject({
+ statement: 'Crane seen at South quay with 4th brigade',
+ at: ['place-1'],
+ when: '2026-06-23T17:05:00+02:00',
+ when_zone: 'Europe/Paris',
+ create: [{ slot: 'about', type: 'person', label: '4th brigade' }],
+ });
+ fixture.expectNoUnexpectedRequests();
+});
+
+test('files a day at a place as that place’s day, and names the zone', async ({ page }) => {
+ const fixture = await openTimeline(page, { catalog: [quay] });
+ const line = page.getByRole('region', { name: 'Add an event' });
+ const say = line.getByLabel('What happened');
+
+ await say.pressSequentially('Crane seen at @South');
+ await expect(page.getByRole('listbox', { name: 'Mentions' }).getByRole('option').first()).toContainText('South quay');
+ await say.press('Enter');
+ await line.getByLabel('When').fill('23/06/2026');
+ await expect(line).toContainText('Reads: 23 Jun 2026 (Europe/Paris)');
+ await expect(line.getByRole('button', { name: 'Clock: South quay UTC+02:00' })).toBeVisible();
+ await say.press('Enter');
+
+ await expect.poll(() => fixture.timelineWrites.length).toBe(1);
+ expect(fixture.timelineWrites[0].body).toMatchObject({
+ at: ['place-1'], when: '2026-06-23', when_zone: 'Europe/Paris',
+ });
+ fixture.expectNoUnexpectedRequests();
+});
+
+test('says what the line takes, and cites a source picked by its kind', async ({ page }) => {
+ const fixture = await openTimeline(page);
+ const line = page.getByRole('region', { name: 'Add an event' });
+
+ await line.getByLabel('When').focus();
+ await expect(line.locator('.help')).toContainText('a month March 2026');
+ await line.getByLabel('What happened').focus();
+ await expect(line.locator('.help')).toContainText('mentions a person, a place or a file');
+
+ await line.getByRole('button', { name: 'Cite a source' }).click();
+ const finder = line.locator('.sources-panel');
+ await expect(finder.getByRole('group', { name: 'Kinds' })).toBeVisible();
+ await finder.getByRole('button', { name: /^Media/ }).click();
+ await expect(finder.getByRole('option')).toHaveCount(1);
+ await finder.getByRole('option', { name: /Roadside camera frame/ }).click();
+ await expect(line.locator('.chip')).toContainText('Roadside camera frame');
+ await expect(line.getByLabel('What happened')).toHaveValue('Seen in Roadside camera frame');
+ await line.getByLabel('What happened').press('Enter');
+
+ await expect.poll(() => fixture.timelineWrites.length).toBe(1);
+ expect(fixture.timelineWrites[0].body).toMatchObject({ statement: 'Seen in Roadside camera frame', cites: ['media-1'] });
+ fixture.expectNoUnexpectedRequests();
+});
+
+test('keeps the source picker in the viewport and separates images from videos', async ({ page }) => {
+ const video = { ...mediaEntity, id: 'clip-2', label: 'Convoy clip', attrs: { kind: 'video', path: 'media/clip.mp4' } };
+ const fixture = await openTimeline(page, { catalog: [person, source, mediaEntity, video] });
+ await page.setViewportSize({ width: 1024, height: 600 });
+ const line = page.getByRole('region', { name: 'Add an event' });
+ // Put the line near the bottom inside its existing clipped tool container.
+ await line.evaluate((node) => { node.style.position = 'fixed'; node.style.bottom = '20px'; node.style.left = '240px'; node.style.width = '740px'; node.style.zIndex = '100'; });
+ await line.getByRole('button', { name: 'Cite a source' }).click();
+ const picker = line.locator('.sources-panel');
+ await expect(picker.getByRole('button', { name: 'Videos', exact: true })).toBeVisible();
+ await picker.getByRole('button', { name: 'Videos', exact: true }).click();
+ await expect(picker.getByRole('option')).toHaveCount(1);
+ await expect(picker.getByRole('option')).toContainText('Convoy clip');
+ const box = await picker.boundingBox();
+ expect(box.y).toBeGreaterThanOrEqual(0);
+ expect(box.y + box.height).toBeLessThanOrEqual(600);
+ expect(box.y + box.height).toBeLessThan((await line.locator('.row').boundingBox()).y);
+ await picker.getByRole('button', { name: 'Images', exact: true }).click();
+ await expect(picker.getByRole('option')).toHaveCount(1);
+ await expect(picker.getByRole('option')).toContainText('Roadside camera frame');
+ const heights = await line.locator('.row').evaluate((node) => [...node.querySelectorAll('input, button')].map((field) => field.getBoundingClientRect().height));
+ expect(Math.max(...heights) - Math.min(...heights)).toBeLessThanOrEqual(1);
+ await page.screenshot({ path: test.info().outputPath('source-picker.png') });
+ await page.keyboard.press('Escape');
+ await expect(picker).toHaveCount(0);
fixture.expectNoUnexpectedRequests();
});
@@ -420,16 +611,17 @@ test('pans from the ruler and zooms with the wheel', async ({ page }) => {
await expect.poll(days).toBeLessThan(beforeDays);
});
-test('closes the legend outside and can use the whole screen', async ({ page }) => {
+test('keeps the legend and the whole screen under ⋯, and closes it outside', async ({ page }) => {
await openTimeline(page);
- await page.getByText('Legend', { exact: true }).click();
+ await (await more(page)).getByText('Legend', { exact: true }).click();
await expect(page.getByText('Confidence and date quality are independent.')).toBeVisible();
- await page.locator('.title-block').click();
+ await page.locator('.axis-label').click();
await expect(page.getByText('Confidence and date quality are independent.')).toBeHidden();
- await page.getByRole('button', { name: 'Full screen' }).click();
+ await (await more(page)).getByRole('button', { name: 'Full screen' }).click();
await expect.poll(() => page.evaluate(() => Boolean(document.fullscreenElement))).toBe(true);
- await expect(page.getByRole('button', { name: 'Exit full screen' })).toBeVisible();
+ // left from the bar, where it can be seen while it is on
+ await expect(page.locator('.timeline-bar').getByRole('button', { name: 'Exit full screen' })).toBeVisible();
await page.getByRole('button', { name: 'Exit full screen' }).click();
await expect.poll(() => page.evaluate(() => Boolean(document.fullscreenElement))).toBe(false);
});
@@ -439,18 +631,193 @@ test('shows day precision across the full day without drawing a period', async (
await setWindow(page, '2026-06-18T00:00', '2026-06-19T00:00');
await expect(page.getByRole('button', { name: /Witness arrived/ })).toBeVisible();
- const canvas = page.locator('.track-canvas').first();
- const span = page.locator('.precision-span.statement').first();
- const [canvasBox, spanBox] = await Promise.all([canvas.boundingBox(), span.boundingBox()]);
+ // A bracket across the day it covers: two stops and a hairline, never a period's bar.
+ const canvas = eventsLane(page);
+ const mark = page.getByRole('button', { name: /Witness arrived/ }).locator('..');
+ await expect(mark).toHaveClass(/bracket/);
+ await expect(mark).not.toHaveClass(/\bbar\b|period/);
+ const [canvasBox, spanBox] = await Promise.all([canvas.boundingBox(), mark.boundingBox()]);
expect(spanBox.width).toBeGreaterThan(canvasBox.width * .95);
- expect(spanBox.height).toBeLessThan(12);
+ expect(spanBox.height).toBeLessThan(20);
+});
+
+test('puts an exact instant on its pixel, and never nudges it sideways', async ({ page }) => {
+ await openTimeline(page);
+ await showFileDates(page);
+ await setWindow(page, '2026-06-23T18:00', '2026-06-23T19:00');
+ const canvas = await fileDatesLane(page).boundingBox();
+ const dot = await page.getByRole('button', { name: /Roadside camera frame/ })
+ .locator('..').locator('.event-shape').boundingBox();
+ // 18:42:11 on a one-hour axis, the middle of the second it was stamped to
+ const expected = canvas.x + canvas.width * ((42 * 60 + 11.5) / 3600);
+ expect(Math.abs(dot.x + dot.width / 2 - expected)).toBeLessThan(1);
+});
+
+test('reads a mark on the ruler, and walks the track with Alt and an arrow', async ({ page }) => {
+ await openTimeline(page);
+ const witness = page.getByRole('button', { name: /Witness arrived/ });
+ await witness.hover();
+ const reading = page.locator('.guide-reading');
+ await expect(reading).toHaveText('18 Jun 2026');
+ // a reduced date is read at both ends of what it covers
+ await expect(page.locator('.guide-line')).toHaveCount(2);
+ const [line, ruler] = await Promise.all([
+ page.locator('.guide-line').first().boundingBox(),
+ page.locator('.axis-ruler').boundingBox(),
+ ]);
+ expect(Math.abs(line.y - (ruler.y + ruler.height))).toBeLessThan(2);
+
+ await page.getByRole('button', { name: /Vehicle remained/ }).focus();
+ await page.keyboard.press('Alt+ArrowRight');
+ await expect(eventsLane(page).locator(':focus')).toHaveAttribute('data-mark', /claim-1|claim-4|dense/);
+ await expect(page.getByRole('dialog', { name: 'Add event' })).toHaveCount(0);
+});
+
+test('hangs a card from each mark when the track has the room', async ({ page }) => {
+ await openTimeline(page);
+ await showFileDates(page);
+ const media = fileDatesLane(page);
+ const card = media.locator('.event-card');
+ await expect(card).toHaveCount(1);
+ await expect(card).toContainText('Roadside camera frame');
+ await expect(card).toContainText('23 Jun 2026, 18:42:11 UTC');
+ await card.click();
+ await expect(page.locator('.inspector').getByRole('heading', { name: 'Roadside camera frame' })).toBeVisible();
+ // the crowded Events track stays on its marks and their captions
+ await expect(eventsLane(page).locator('.event-card')).toHaveCount(0);
+});
+
+test('says how many dates the files carry when nothing is dated yet', async ({ page }) => {
+ await installAppFixture(page, {
+ timelineItems: timelineItems.filter((item) => item.produced_here === true),
+ });
+ await page.setViewportSize({ width: 1440, height: 900 });
+ await page.goto('/#timeline');
+ await expect(page.getByRole('heading', { name: 'Nothing dated yet' })).toBeVisible();
+ await expect(page.getByText('1 date read from files')).toBeVisible();
+ await page.getByRole('button', { name: 'Show them' }).click();
+ // on a File dates track that holds every file, since that is what was counted
+ await expect(page.locator('.track-label strong')).toHaveText(['Media', 'Events', 'File dates']);
+ await expect(page.getByRole('button', { name: /Extracted frame/ })).toBeVisible();
+});
+
+test("lets a track's working files in from its editor, and out again", async ({ page }) => {
+ await openTimeline(page);
+ await showFileDates(page);
+ await setWindow(page, '2026-06-23T18:00', '2026-06-23T20:00');
+ const media = fileDatesLane(page);
+ const name = fileDatesRow(page).locator('.track-name');
+ await expect(media.getByRole('button', { name: /Extracted frame/ })).toHaveCount(0);
+ await expect(name).toHaveAttribute('title', /working files held back/);
+
+ await page.getByRole('button', { name: 'Edit File dates' }).click();
+ const editor = page.getByRole('region', { name: 'Edit timeline track' });
+ await editor.getByLabel('Include working files').check();
+ await editor.getByRole('button', { name: 'Update track' }).click();
+ await expect(media.getByRole('button', { name: /Extracted frame/ })).toBeVisible();
+ await expect(name).not.toHaveAttribute('title', /held back/);
+
+ await page.getByRole('button', { name: 'Edit File dates' }).click();
+ await editor.getByLabel('Include working files').uncheck();
+ await editor.getByRole('button', { name: 'Update track' }).click();
+ await expect(media.getByRole('button', { name: /Extracted frame/ })).toHaveCount(0);
+});
+
+test('reads the axis and the list as one', async ({ page }) => {
+ await openTimeline(page);
+ const list = page.getByRole('region', { name: 'Timeline list' });
+ await expect(list).toBeVisible();
+ const row = list.getByRole('row', { name: /Witness arrived/ });
+ await expect(row).toContainText('Harbour witness');
+ await expect(row).toContainText('Interview notes');
+ // a Claim still waiting for its reasoning says so, in words
+ await expect(list.getByRole('row', { name: /Vehicle remained/ })).toContainText('no source');
+
+ const mark = page.getByRole('button', { name: /Witness arrived/ });
+ await row.hover();
+ await expect(mark.locator('..')).toHaveClass(/\blit\b/);
+ await expect(page.locator('.guide-reading')).toHaveText('18 Jun 2026');
+ await mark.hover();
+ await expect(row).toHaveClass(/\blit\b/);
+
+ const axisBefore = await page.locator('.axis-card').boundingBox();
+ await page.getByRole('button', { name: /Second convoy cleared/ }).click();
+ const third = list.getByRole('row', { name: /Second convoy cleared/ });
+ await expect(third).toHaveAttribute('aria-selected', 'true');
+ await expect(third).toBeInViewport();
+ // the list scrolled on its own; the axis did not move
+ expect((await page.locator('.axis-card').boundingBox()).y).toBeCloseTo(axisBefore.y, 0);
+
+ await row.focus();
+ await page.keyboard.press('Enter');
+ await expect(page.locator('.inspector').getByRole('heading', { name: timelineItem('claim-1').label })).toBeVisible();
+});
+
+test('gives the axis or the list the room, as a saved mode or a drag', async ({ page }) => {
+ await openTimeline(page);
+ const axis = page.locator('.axis-card');
+ // measured once the column has its height, which is what the share is a share of
+ await expect.poll(async () => (await axis.boundingBox()).height).toBeGreaterThan(160);
+ const plot = (await axis.boundingBox()).height;
+ await page.getByRole('button', { name: 'List' }).click();
+ await expect.poll(async () => (await axis.boundingBox()).height).toBeLessThan(plot);
+ const listed = (await axis.boundingBox()).height;
+
+ const split = page.getByRole('separator', { name: /axis and the list/ });
+ const box = await split.boundingBox();
+ await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2);
+ await page.mouse.down();
+ await page.mouse.move(box.x + box.width / 2, box.y + 120, { steps: 4 });
+ await page.mouse.up();
+ await expect.poll(async () => (await axis.boundingBox()).height).toBeGreaterThan(listed);
+ // the ruler stays over the tracks it measures while they scroll
+ await axis.evaluate((element) => { element.scrollTop = element.scrollHeight; });
+ const [ruler, card] = await Promise.all([page.locator('.axis-row').boundingBox(), axis.boundingBox()]);
+ expect(Math.abs(ruler.y - card.y)).toBeLessThan(2);
+});
+
+test('copies the window as a table for a report or a block for a spreadsheet', async ({ page }) => {
+ await page.addInitScript(() => {
+ window.__copied = [];
+ Object.defineProperty(navigator, 'clipboard', {
+ configurable: true,
+ value: { writeText: async (text) => { window.__copied.push(text); } },
+ });
+ });
+ await openTimeline(page);
+ const list = page.getByRole('region', { name: 'Timeline list' });
+ await list.getByRole('button', { name: 'Copy' }).click();
+ await page.getByRole('menuitem', { name: 'As a Markdown table' }).click();
+ await expect.poll(() => page.evaluate(() => window.__copied.length)).toBe(1);
+ const markdown = await page.evaluate(() => window.__copied[0]);
+ expect(markdown).toContain('| Date | Statement | Subjects | Places | Sources | Confidence |');
+ expect(markdown).toContain('| 18 Jun 2026 | Witness arrived at the north checkpoint | Harbour witness | | Interview notes | probable |');
+ expect(markdown).toMatch(/^> .*Timeline/);
+
+ await list.getByRole('button', { name: 'Copy' }).click();
+ await page.getByRole('menuitem', { name: 'For a spreadsheet' }).click();
+ await expect.poll(() => page.evaluate(() => window.__copied.length)).toBe(2);
+ const block = await page.evaluate(() => window.__copied[1]);
+ expect(block.split('\n')[0]).toBe('date_as_written\ttime_zone\tearliest_utc\tlatest_utc\tstatement\tsubjects\tplaces\tsources\tconfidence\tstatus');
+ expect(block).toContain('2026-06-18\t\t2026-06-18T00:00:00Z\t2026-06-19T00:00:00Z\tWitness arrived at the north checkpoint');
+});
+
+test('lands on what the Overview counted as waiting for a date', async ({ page }) => {
+ await installAppFixture(page, { catalog: [person, source, mediaEntity], timelineItems });
+ await page.setViewportSize({ width: 1440, height: 900 });
+ await page.goto('/#overview');
+ await page.getByRole('button', { name: /No date yet/ }).click();
+ const queue = page.locator('.undated-card');
+ await expect(queue).toHaveAttribute('open', '');
+ await expect(queue).toBeInViewport();
+ await expect(queue.getByRole('button', { name: /Resolve the timezone/ })).toBeFocused();
});
test('creates and resizes an hourly period on a day view', async ({ page }) => {
const fixture = await openTimeline(page);
await setWindow(page, '2026-06-23T00:00', '2026-06-24T00:00');
- const canvas = page.locator('.track-canvas').first();
+ const canvas = eventsLane(page);
await expect(canvas).toHaveClass(/createable/);
await canvas.evaluate((element) => new Promise((resolve) => {
requestAnimationFrame(() => requestAnimationFrame(resolve));
@@ -462,13 +829,10 @@ test('creates and resizes an hourly period on a day view', async ({ page }) => {
await page.mouse.move(box.x + box.width * .5, y, { steps: 5 });
await page.mouse.up();
- const dialog = page.getByRole('dialog', { name: 'Add claim' });
- await expect(dialog).toBeVisible();
- await expect(dialog.getByLabel('Date format')).toHaveValue('time-range');
- await expect(dialog.getByLabel('Start time')).toHaveValue(/2026-06-23T\d{2}:\d{2}(?::\d{2})?/);
- await expect(dialog.getByLabel('End time')).toHaveValue(/2026-06-23T\d{2}:\d{2}(?::\d{2})?/);
- await dialog.getByLabel('Claim', { exact: true }).fill('Traffic peaked around the checkpoint');
- await dialog.getByRole('button', { name: 'Add claim' }).click();
+ const line = page.getByRole('region', { name: 'Add an event' });
+ await expect(line.getByLabel('When')).toHaveValue(/^23\/06\/2026 \d{2}:\d{2}.* 23\/06\/2026 \d{2}:\d{2}/);
+ await page.keyboard.type('Traffic peaked around the checkpoint');
+ await page.keyboard.press('Enter');
await expect.poll(() => fixture.timelineWrites.length).toBe(1);
expect(fixture.timelineWrites[0].body.when).toMatch(
@@ -494,29 +858,34 @@ test('creates and resizes an hourly period on a day view', async ({ page }) => {
test('keeps creation on the Claims track and offers the list view', async ({ page }) => {
await openTimeline(page);
- const mediaCanvas = page.locator('.track-canvas').nth(1);
- const box = await mediaCanvas.boundingBox();
+ // a file is dated from its proof or an event about it, not by a click on its lane
+ await expect(mediaLane(page)).toContainText('A proof’s date or an event about a file puts it here.');
+ const box = await mediaLane(page).boundingBox();
await page.mouse.click(box.x + box.width * .7, box.y + box.height - 8);
- await expect(page.getByRole('dialog', { name: 'Add claim' })).toHaveCount(0);
+ await expect(page.getByRole('region', { name: 'Add an event' }).getByLabel('When')).toHaveValue('');
await page.getByRole('button', { name: 'List' }).click();
await expect(page.getByRole('region', { name: 'Timeline list' })).toBeVisible();
- await expect(page.getByRole('button', { name: /Second convoy cleared/ })).toBeVisible();
+ await expect(page.getByRole('row', { name: /Second convoy cleared/ })).toBeVisible();
});
test('starts a media correction from the captured date', async ({ page }) => {
const fixture = await openTimeline(page);
+ await showFileDates(page);
await page.getByRole('button', { name: /Roadside camera frame/ }).click();
const inspector = page.locator('.inspector');
- const correction = inspector.getByRole('button', { name: 'Add correction' });
+ await expect(inspector.locator('header')).toContainText('File date');
+ // once, under the date: the footer no longer offers it a second time
+ await expect(inspector.getByRole('button', { name: 'Add correction' })).toHaveCount(0);
+ const correction = inspector.getByRole('button', { name: 'Correct this date' });
await expect(correction).toBeEnabled();
await correction.click();
- const dialog = page.getByRole('dialog', { name: 'Add claim' });
+ const dialog = page.getByRole('dialog', { name: 'Add event' });
await expect(dialog.getByLabel('Date format')).toHaveValue('timestamp');
await expect(dialog.getByLabel('Date and time')).toHaveValue('2026-06-23T18:42:11');
- await expect(dialog.getByLabel('Timezone')).toHaveValue('utc');
- await dialog.getByRole('button', { name: 'Add claim' }).click();
+ await expect(dialog.getByRole('button', { name: 'Clock: UTC' })).toBeVisible();
+ await dialog.getByRole('button', { name: 'Add event' }).click();
await expect.poll(() => fixture.timelineWrites.length).toBe(1);
expect(fixture.timelineWrites[0]).toMatchObject({
@@ -545,6 +914,7 @@ test('expands dense events in place and can collapse them again', async ({ page
test('moves and resizes the overview window', async ({ page }) => {
await openTimeline(page);
+ await zoomIn(page);
const before = await axisWindowText(page);
const start = page.getByRole('button', { name: 'Change range start' });
const startBox = await start.boundingBox();
@@ -568,7 +938,8 @@ test('moves and shortens a selected claim on the axis', async ({ page }) => {
const fixture = await openTimeline(page);
const period = page.getByRole('button', { name: /Vehicle remained/ });
await period.click();
- await expect(page.getByText('Drag to move. Use either edge to resize.')).toBeVisible();
+ await page.locator('.inspector').getByText('About this date').click();
+ await expect(page.getByText('Drag it on the axis to move it, or either edge to resize.')).toBeVisible();
const end = period.locator('..').locator('.resize.end');
const endBox = await end.boundingBox();
@@ -596,13 +967,16 @@ test('moves and shortens a selected claim on the axis', async ({ page }) => {
test('validates advanced syntax before saving', async ({ page }) => {
await openTimeline(page);
- await page.getByRole('button', { name: 'Add claim' }).click();
- const dialog = page.getByRole('dialog', { name: 'Add claim' });
- await dialog.getByLabel('Claim', { exact: true }).fill('A dated observation');
+ const line = page.getByRole('region', { name: 'Add an event' });
+ await line.getByLabel('What happened').fill('A dated observation');
+ await line.getByRole('button', { name: 'More' }).click();
+ await line.getByRole('button', { name: 'Full editor' }).click();
+ const dialog = page.getByRole('dialog', { name: 'Add event' });
+ await expect(dialog.getByLabel('Claim', { exact: true })).toHaveValue('A dated observation');
await dialog.getByLabel('Date format').selectOption('advanced');
await dialog.getByLabel('When').fill('late summer');
await expect(dialog.getByText('Use a supported date or timestamp.')).toBeVisible();
- await expect(dialog.getByRole('button', { name: 'Add claim' })).toBeDisabled();
+ await expect(dialog.getByRole('button', { name: 'Add event' })).toBeDisabled();
await dialog.getByText('Syntax guide').click();
await expect(dialog.getByRole('region', { name: 'Supported date syntax' })).toBeVisible();
});
@@ -619,9 +993,10 @@ test('keeps entity history in the same three-tab Details model', async ({ page }
'claim-3': claimChain('claim-3', timelineItem('claim-3').label, { time_role: 'observed' }),
},
});
+ await flatBoard(page);
await page.goto('/#board');
await page.locator('tbody tr').filter({ hasText: person.label }).locator('td:not(.pick)').first().click();
- const details = page.getByRole('dialog', { name: 'Details' });
+ const details = boardDetails(page);
await expect(details.getByRole('tab')).toHaveText(['Info', 'Connections', 'Time']);
await details.getByRole('tab', { name: 'Time' }).click();
@@ -640,9 +1015,10 @@ test('opens the row handed over from the Time tab', async ({ page }) => {
'media-1': { entity: mediaEntity, sources: [], lost: [], dependents: [], relations: [], empty: true },
},
});
+ await flatBoard(page);
await page.goto('/#board');
await page.locator('tbody tr').filter({ hasText: mediaEntity.label }).locator('td:not(.pick)').first().click();
- const details = page.getByRole('dialog', { name: 'Details' });
+ const details = boardDetails(page);
await details.getByRole('tab', { name: 'Time' }).click();
await details.getByRole('button', { name: `Open ${mediaEntity.label} in Timeline` }).click();
@@ -651,7 +1027,9 @@ test('opens the row handed over from the Time tab', async ({ page }) => {
await expect(page.locator('.scope-chip')).toContainText(mediaEntity.label);
const inspector = page.locator('.inspector');
await expect(inspector.getByRole('heading', { name: mediaEntity.label })).toBeVisible();
- await expect(inspector.getByText('2026-06-23T18:42:11Z')).toBeVisible();
+ await expect(inspector.getByText('23 Jun 2026, 18:42:11 UTC')).toBeVisible();
+ // the track that holds a file's own date is put on the axis to show it
+ await expect(page.locator('.track-label strong')).toHaveText(['Media', 'Events', 'File dates']);
});
test('edits an existing claim from the Time tab', async ({ page }) => {
@@ -666,9 +1044,10 @@ test('edits an existing claim from the Time tab', async ({ page }) => {
'claim-3': claimChain('claim-3', timelineItem('claim-3').label, { time_role: 'observed' }),
},
});
+ await flatBoard(page);
await page.goto('/#board');
await page.locator('tbody tr').filter({ hasText: person.label }).locator('td:not(.pick)').first().click();
- const details = page.getByRole('dialog', { name: 'Details' });
+ const details = boardDetails(page);
await details.getByRole('tab', { name: 'Time' }).click();
await details.getByRole('button', { name: `Edit ${timelineItem('claim-1').label}` }).click();
@@ -697,9 +1076,10 @@ test('starts a new claim from an empty form after editing one', async ({ page })
'claim-3': claimChain('claim-3', timelineItem('claim-3').label, { time_role: 'observed' }),
},
});
+ await flatBoard(page);
await page.goto('/#board');
await page.locator('tbody tr').filter({ hasText: person.label }).locator('td:not(.pick)').first().click();
- const details = page.getByRole('dialog', { name: 'Details' });
+ const details = boardDetails(page);
await details.getByRole('tab', { name: 'Time' }).click();
await details.getByRole('button', { name: `Edit ${timelineItem('claim-1').label}` }).click();
@@ -720,9 +1100,10 @@ test('shows an undated Claim as a missing claim date, not an existing one', asyn
'claim-3': claimChain('claim-3', undatedClaim.label, undatedClaim.attrs),
},
});
+ await flatBoard(page);
await page.goto('/#board');
await page.locator('tbody tr').filter({ hasText: undatedClaim.label }).locator('td:not(.pick)').first().click();
- const details = page.getByRole('dialog', { name: 'Details' });
+ const details = boardDetails(page);
await details.getByRole('tab', { name: 'Time' }).click();
await expect(details.getByText('This claim has no date yet.')).toBeVisible();
@@ -765,9 +1146,12 @@ const placedItem = {
};
async function openTimelineOverJune(page, options = {}) {
+ // Read on UTC, so the window handed on is the one typed: the quay would otherwise put
+ // the axis on Paris time, and 1 June there starts on 31 May in UTC.
const fixture = await openTimeline(page, {
catalog: [person, source, mediaEntity, quay],
timelineItems: [...timelineItems, placedItem],
+ clock: 'utc',
...options,
});
await setWindow(page, '2026-06-01T00:00', '2026-06-21T00:00');
@@ -783,7 +1167,7 @@ function timelineMapLayer(page) {
test('hands one window from the Timeline to the Map, the Board and back', async ({ page }) => {
const fixture = await openTimelineOverJune(page);
- await page.getByRole('group', { name: 'Open range' }).getByRole('button', { name: 'Map' }).click();
+ await (await more(page)).getByRole('group', { name: 'Open range' }).getByRole('button', { name: 'Map' }).click();
await awaitMapReady(page); // the marks are drawn on it, so it has to be up
const layer = timelineMapLayer(page);
@@ -800,20 +1184,21 @@ test('hands one window from the Timeline to the Map, the Board and back', async
// and says which window it is answering.
await expect(page.getByLabel('Fact-time range')).toContainText('1 Jun – 21 Jun 2026');
await expect.poll(() => fixture.catalogQueries.at(-1)).toContain('temporal_from=2026-06-01');
+ // Grouped by kind, and every group holding part of the window open.
await expect(page.locator('tbody tr')).toHaveText([
- /Harbour witness/, /Interview notes/, /South quay/,
+ /Harbour witness/, /South quay/, /Interview notes/,
]);
await page.getByLabel('Fact-time range').getByRole('button', { name: 'Timeline' }).click();
- await expect(page.getByRole('heading', { name: 'Timeline', exact: true })).toBeVisible();
+ await expect(page.locator('.timeline-bar')).toBeVisible();
await expect(page.getByRole('button', { name: '1 Jun – 21 Jun 2026' })).toBeVisible();
fixture.expectNoUnexpectedRequests();
});
test('opens a statement in the Timeline from its mark on the map', async ({ page }) => {
const fixture = await openTimelineOverJune(page);
- await page.getByRole('group', { name: 'Open range' }).getByRole('button', { name: 'Map' }).click();
+ await (await more(page)).getByRole('group', { name: 'Open range' }).getByRole('button', { name: 'Map' }).click();
await awaitMapReady(page); // the marks are drawn on it, so it has to be up
await page.locator('.temporal-mark').click();
@@ -838,7 +1223,7 @@ test('draws the window and nothing else, framed on what it holds', async ({ page
],
},
});
- await page.getByRole('group', { name: 'Open range' }).getByRole('button', { name: 'Map' }).click();
+ await (await more(page)).getByRole('group', { name: 'Open range' }).getByRole('button', { name: 'Map' }).click();
await awaitMapReady(page); // the marks are drawn on it, so it has to be up
await expect(page.locator('.temporal-mark')).toHaveCount(1);
@@ -869,7 +1254,7 @@ test('says a window holds nothing placed instead of pulling the map out to say i
},
});
await setWindow(page, '2026-06-18T00:00', '2026-06-19T00:00');
- await page.getByRole('group', { name: 'Open range' }).getByRole('button', { name: 'Map' }).click();
+ await (await more(page)).getByRole('group', { name: 'Open range' }).getByRole('button', { name: 'Map' }).click();
await awaitMapReady(page); // the marks are drawn on it, so it has to be up
const layer = timelineMapLayer(page);
@@ -880,3 +1265,154 @@ test('says a window holds nothing placed instead of pulling the map out to say i
await expect(page.locator('.saved-mark-place')).toHaveCount(0);
fixture.expectNoUnexpectedRequests();
});
+
+test('shows the file a picked entry is about, one press from full screen', async ({ page }) => {
+ await openTimeline(page);
+ await showFileDates(page);
+
+ await page.getByRole('button', { name: /Roadside camera frame/ }).first().click();
+ const preview = page.locator('.inspector figure.preview');
+ await expect(preview.locator('img')).toHaveAttribute('src', /media\/panel\.svg/);
+
+ await preview.getByRole('button', { name: 'Open Roadside camera frame full screen' }).click();
+ await expect(page.locator('.stage img')).toBeVisible();
+ await page.keyboard.press('Escape');
+ await expect(page.locator('.stage')).toHaveCount(0);
+ // the inspector stays on the entry
+ await expect(preview).toBeVisible();
+});
+
+test('changes a picked entry’s date from the inspector, asked like a drag', async ({ page }) => {
+ const fixture = await openTimeline(page);
+
+ await page.getByRole('button', { name: /Witness arrived/ }).first().click();
+ const inspector = page.locator('.inspector');
+ await inspector.getByRole('button', { name: 'Change the date' }).click();
+ const field = inspector.getByLabel('When');
+ await field.fill('20/06/2026 15:10');
+ await expect(inspector.getByText(/20 Jun 2026/)).toBeVisible();
+ await inspector.getByRole('button', { name: 'Save date' }).click();
+
+ const ask = page.getByRole('alertdialog');
+ await expect(ask).toContainText('→ 20 Jun 2026');
+ await ask.getByRole('button', { name: 'Update date' }).click();
+ // the entry's day was UTC's, so the time it becomes is read on UTC too; the new day
+ // stays inside the window, so the picked entry is still there to read after the reload
+ await expect.poll(() => fixture.timelineWrites.at(-1)?.body?.when).toBe('2026-06-20T15:10:00Z');
+ await expect(inspector.getByRole('button', { name: 'Change the date' })).toBeVisible();
+});
+
+test('gives a picked entry’s day any zone in the world from the inspector', async ({ page }) => {
+ const fixture = await openTimeline(page);
+
+ await page.getByRole('button', { name: /Witness arrived/ }).first().click();
+ const inspector = page.locator('.inspector');
+ await inspector.getByRole('button', { name: 'Change the date' }).click();
+ await expect(inspector.getByRole('button', { name: 'Clock: UTC' })).toBeVisible();
+ // the same day on another clock is a change worth saving
+ await inspector.getByRole('button', { name: 'Clock: UTC' }).click();
+ const menu = page.locator('.clock-menu');
+ await menu.getByRole('textbox').fill('tokyo');
+ await menu.getByRole('button', { name: /^Tokyo/ }).click();
+ await expect(inspector.getByRole('button', { name: 'Clock: Tokyo UTC+09:00' })).toBeVisible();
+ await inspector.getByRole('button', { name: 'Save date' }).click();
+
+ const ask = page.getByRole('alertdialog');
+ await expect(ask).toContainText('→ 18 Jun 2026 (Asia/Tokyo)');
+ await ask.getByRole('button', { name: 'Update date' }).click();
+ await expect.poll(() => fixture.timelineWrites.at(-1)?.body).toMatchObject({ when: '2026-06-18', when_zone: 'Asia/Tokyo' });
+});
+
+test('offers a file’s date as a correction rather than a rewrite', async ({ page }) => {
+ await openTimeline(page);
+ await showFileDates(page);
+ await page.getByRole('button', { name: /Roadside camera frame/ }).first().click();
+ await expect(page.locator('.inspector').getByRole('button', { name: 'Correct this date' })).toBeVisible();
+ await expect(page.locator('.inspector').getByRole('button', { name: 'Change the date' })).toHaveCount(0);
+});
+
+test('draws a file where the analyst dated it, and imagery on a lane of its own', async ({ page }) => {
+ // A proof's date is stated for the footage, and an event cites a Compare render.
+ const render = {
+ id: 'render-1', type: 'media', label: 'Compare render of the bridge',
+ attrs: { path: 'media/render.png', kind: 'image' }, origin: { type: 'compare' },
+ provenance: { by: 'compare', at: '2026-08-01T09:00:00Z', status: 'confirmed' },
+ };
+ const dated = (id, label, raw, connectors) => ({
+ ...timelineItem('claim-4'), id: `temporal:claim:${id}`, owner_id: id, label, raw,
+ earliest: `${raw}T00:00:00Z`, latest: `${raw}T23:59:59Z`, subjects: [], sources: [], ...connectors,
+ });
+ await openTimeline(page, {
+ catalog: [person, source, mediaEntity, render],
+ timelineItems: [
+ ...timelineItems,
+ dated('claim-footage', 'Material of Bridge proof was taken', '2026-06-20', { subjects: ['media-1'] }),
+ dated('claim-render', 'A crater on the approach road', '2026-06-21', { sources: ['render-1'] }),
+ ],
+ });
+
+ // the footage is drawn as itself, at the proof's date, and the render is not
+ const media = mediaLane(page);
+ await expect(media.getByRole('button', { name: /Roadside camera frame/ })).toHaveCount(1);
+ await expect(media.getByRole('button', { name: /Compare render/ })).toHaveCount(0);
+ await expect(eventsLane(page).getByRole('button', { name: /Material of Bridge proof/ })).toBeVisible();
+ // picked, it is the event that dates it
+ await media.getByRole('button', { name: /Roadside camera frame/ }).click();
+ const inspector = page.locator('.inspector');
+ await expect(inspector.locator('header')).toContainText('Event');
+ await expect(inspector.getByRole('heading', { name: 'Material of Bridge proof was taken' })).toBeVisible();
+
+ // what the app pictured from above is a lane added on purpose
+ await addTrack(page, /^Imagery/);
+ await expect(page.locator('.track-label strong')).toHaveText(['Media', 'Events', 'Imagery']);
+ const imagery = page.locator('.track-canvas').nth(2);
+ await expect(imagery.getByRole('button', { name: /Compare render of the bridge/ })).toHaveCount(1);
+ await expect(imagery.getByRole('button', { name: /Roadside camera frame/ })).toHaveCount(0);
+});
+
+test('reads the case on the clock of its places, and keeps the one picked', async ({ page }) => {
+ // The quay is at Marseille: the axis opens on Paris time and says so, and the list
+ // reads its instants there too.
+ await openTimeline(page, { catalog: [person, source, mediaEntity, quay] });
+ await showFileDates(page);
+ const clock = page.locator('.zone-picker .trigger');
+ await expect(clock).toContainText('Paris');
+ await expect(clock).toHaveAttribute('title', "The clock of the case's places");
+ await expect(page.locator('.axis-label')).toContainText('Paris time');
+ const list = page.getByRole('region', { name: 'Timeline list' });
+ await expect(list.getByRole('columnheader').first()).toHaveText('Date · Paris time');
+ // 18:42:11 UTC on 23 June is 20:42:11 in Paris
+ await expect(list.getByRole('row', { name: /Roadside camera frame/ })).toContainText('23 Jun 2026, 20:42:11');
+
+ await clock.click();
+ await page.locator('.zone-picker .menu').getByRole('button', { name: /^UTC/ }).click();
+ await expect(clock).toHaveText(/^\s*UTC\s*$/);
+ await expect(page.locator('.axis-label small')).toHaveCount(0);
+
+ // the pick is the case's from now on, in this browser
+ await page.reload();
+ await expect(page.locator('.timeline-bar')).toBeVisible();
+ await expect(page.locator('.zone-picker .trigger')).toHaveText(/^\s*UTC\s*$/);
+});
+
+test('opens with no inspector and no whole-case strip, one bar over the axis', async ({ page }) => {
+ await openTimeline(page);
+ const bar = page.locator('.timeline-bar');
+ // the period, its clock and the split are out; the rest waits under ⋯
+ await expect(bar.locator('.range-face')).toBeVisible();
+ await expect(bar.locator('.zone-picker')).toBeVisible();
+ await expect(bar.getByRole('button', { name: 'Plot' })).toBeVisible();
+ await expect(page.getByRole('button', { name: 'Full screen' })).toHaveCount(0);
+ await expect(page.getByLabel('Group by')).toHaveCount(0);
+ // adding is the line under the axis, not a second button over it
+ await expect(bar.getByRole('button', { name: 'Add', exact: true })).toHaveCount(0);
+ await expect(page.locator('.inspector')).toHaveCount(0);
+ await expect(page.locator('.overview-card')).toHaveCount(0);
+ // the first lane starts right under the bar and the ruler
+ const events = await page.locator('.track-row').first().boundingBox();
+ expect(events.y).toBeLessThan(260);
+ // Escape lets go of ⋯
+ await more(page);
+ await page.keyboard.press('Escape');
+ await expect(page.locator('.more-menu')).toHaveCount(0);
+});
diff --git a/frontend/src/App.svelte b/frontend/src/App.svelte
index 22fe15b..afb37f1 100644
--- a/frontend/src/App.svelte
+++ b/frontend/src/App.svelte
@@ -37,6 +37,8 @@
import UpdateModal from './components/UpdateModal.svelte';
import DetectActivity from './components/DetectActivity.svelte';
import WorkspaceStopped from './components/WorkspaceStopped.svelte';
+ import NoteBar from './components/NoteBar.svelte';
+ import { isNoteKey } from './lib/noteHere.svelte.js';
import { readStatus, stoppedBecause } from './lib/workspace.js';
import { analysisSearch, leaveAnalysisView } from './lib/analysisSearch.svelte.js';
@@ -154,6 +156,32 @@
function openWorkspace(ws) {
uiState.tool = lastTool[ws.id] ?? ws.tools[0];
}
+
+ // ── Add event, from wherever the analyst is ──────────────────────────────────
+ /** A frozen reading takes no new event, and says so rather than hiding the pencil:
+ * a control that is visible and unusable teaches something. */
+ const noteFrozen = $derived(
+ (['board', 'graph'].includes(uiState.tool) && Boolean(analysisSearch.catalog.snapshotId)) ||
+ (uiState.tool === 'timeline' && Boolean(analysisSearch.timeline.snapshotId))
+ );
+ const noteTitle = $derived(
+ noteFrozen ? 'A frozen snapshot takes no new event. Leave it to add one.' : 'Add an event about what is on screen (Alt+N)'
+ );
+ function toggleNote() {
+ if (!caseState.current || noteFrozen) return;
+ // The Timeline already has its line under the axis: the pencil goes there.
+ if (uiState.tool === 'timeline') {
+ uiState.noting = false;
+ uiState.timelineLineFocus += 1;
+ return;
+ }
+ uiState.noting = !uiState.noting;
+ }
+ function onGlobalKey(event) {
+ if (!isNoteKey(event)) return;
+ event.preventDefault();
+ toggleNote();
+ }
function toggleSidebar() {
const open = !uiState.sidebarOpen;
const ws = workspaceOf(uiState.tool);
@@ -255,15 +283,6 @@
</button>
<div class="case-group">
<CaseSwitcher />
- <button
- class="btn btn-ghost case-btn"
- class:topbar-active={activeWs?.id === CASE_WORKSPACE.id}
- title="Open the case board"
- onclick={() => openWorkspace(CASE_WORKSPACE)}
- >
- <Icon name={CASE_WORKSPACE.icon} size={16} />
- <span>{TOOL_LABELS.board}</span>
- </button>
</div>
<div class="spacer"></div>
<DetectActivity />
@@ -271,6 +290,23 @@
the gear rather than in each toolbar so there is one of it, and it opens the
Guide on the section written about the current tool. Silent on the Guide
itself, which is the answer. -->
+ <!-- The one way into Add event from every tool: quiet like the marks beside it,
+ since amber is kept for the main action and the selection. -->
+ {#if caseState.current && !solo}
+ <button
+ class="note-btn"
+ class:on={uiState.noting}
+ title={noteTitle}
+ aria-label="Add an event"
+ aria-pressed={uiState.noting}
+ disabled={noteFrozen}
+ onclick={toggleNote}
+ >
+ <Icon name="eventAdd" size={15} />
+ <span class="note-label">Add event</span>
+ <kbd>Alt N</kbd>
+ </button>
+ {/if}
{#if uiState.tool !== 'guide'}
<button
class="btn btn-ghost btn-sm"
@@ -316,6 +352,19 @@
<span>{ws.label}</span>
</button>
{/each}
+ <!-- The case, under the four stages and apart from them: it is what every stage
+ files into rather than one of them, and one press from any of them opens its
+ Timeline, Board, Graph and Sheet. -->
+ <span class="rail-rule" role="presentation"></span>
+ <button
+ class="rail-btn case-rail"
+ class:active={activeWs?.id === CASE_WORKSPACE.id}
+ onclick={() => openWorkspace(CASE_WORKSPACE)}
+ title="The case: its Timeline, Board, Graph and Sheet"
+ >
+ <Icon name={CASE_WORKSPACE.icon} size={19} />
+ <span>{CASE_WORKSPACE.label}</span>
+ </button>
<button
class="rail-btn theme-toggle"
onclick={toggleTheme}
@@ -368,6 +417,9 @@
</div>
</div>
+<svelte:window onkeydown={onGlobalKey} />
+
+<NoteBar />
<Toasts />
{#if workspaceStopped}
@@ -417,33 +469,71 @@
.spacer {
flex: 1;
}
- /* the switcher and the board button are one control — which case, then open
- it. Both carry the same weight, and the hairline is what says they belong
- together: their own padding leaves too much air for proximity alone to. */
+ /* which case: the switcher alone, since the case itself opens from the rail */
.case-group {
display: flex;
align-items: center;
}
- .case-btn {
- position: relative;
- margin-left: 13px;
- gap: 8px;
- padding: 6px 12px;
- font-size: var(--fs-sm);
- font-weight: 600;
+ .topbar-active {
+ color: var(--text-1);
+ background: var(--bg-2);
}
- .case-btn::before {
- content: '';
- position: absolute;
- left: -7px;
- top: 5px;
- bottom: 5px;
- width: 1px;
- background: var(--border);
+ /* Add event: one outlined pill among the icon marks, since it is the one of them
+ that makes something; amber only while its bar is open. */
+ .note-btn {
+ display: inline-flex;
+ align-items: center;
+ gap: 7px;
+ height: 28px;
+ padding: 0 6px 0 9px;
+ border: 1px solid var(--border-strong);
+ border-radius: 999px;
+ background: transparent;
+ color: var(--text-2);
+ font-size: var(--fs-xs);
+ font-weight: 600;
+ cursor: pointer;
+ transition: color 0.15s var(--ease), background 0.15s var(--ease), border-color 0.15s var(--ease);
}
- .topbar-active {
+ .note-btn:hover:not(:disabled) {
+ border-color: color-mix(in srgb, var(--text-1) 35%, transparent);
+ background: var(--bg-2);
color: var(--text-1);
+ }
+ .note-btn.on {
+ border-color: color-mix(in srgb, var(--accent) 60%, transparent);
+ background: var(--accent-soft);
+ color: var(--accent);
+ }
+ .note-btn:disabled {
+ opacity: 0.45;
+ cursor: default;
+ }
+ .note-btn kbd {
+ padding: 1px 5px;
+ border: 1px solid var(--border);
+ border-radius: 999px;
background: var(--bg-2);
+ color: var(--text-3);
+ font-family: var(--font-mono);
+ font-size: 10px;
+ font-weight: 500;
+ line-height: 1.4;
+ }
+ .note-btn.on kbd {
+ border-color: transparent;
+ background: color-mix(in srgb, var(--accent) 18%, transparent);
+ color: var(--accent);
+ }
+ /* A narrow window keeps the mark and drops the words, which the tooltip says. */
+ @media (max-width: 1100px) {
+ .note-btn {
+ padding: 0 7px;
+ }
+ .note-label,
+ .note-btn kbd {
+ display: none;
+ }
}
.main {
flex: 1;
@@ -479,6 +569,13 @@
color: var(--text-1);
border-left-color: var(--accent);
}
+ /* The case under the four stages, a rule and some air between them. */
+ .rail-rule {
+ flex-shrink: 0;
+ height: 1px;
+ margin: 14px 14px 10px;
+ background: var(--border-strong);
+ }
/* pinned to the foot of the rail, away from the workspace switches */
.theme-toggle {
margin-top: auto;
diff --git a/frontend/src/App.test.js b/frontend/src/App.test.js
new file mode 100644
index 0000000..9df0be3
--- /dev/null
+++ b/frontend/src/App.test.js
@@ -0,0 +1,54 @@
+import { readFileSync } from 'node:fs';
+import { describe, expect, it } from 'vitest';
+
+/** The shell's wiring for the two doors into the case: the Case button, and Add event
+ * from wherever the analyst is. */
+const source = readFileSync(new URL('./App.svelte', import.meta.url), 'utf8');
+const markup = source.slice(source.indexOf('</script>'));
+
+describe('the case on the rail', () => {
+ it('sits under the four stages, a rule between them, with the theme at the foot', () => {
+ const stages = markup.indexOf('{/each}', markup.indexOf('{#each WORKSPACES as ws (ws.id)}'));
+ const rule = markup.indexOf('<span class="rail-rule"');
+ const caseButton = markup.indexOf('onclick={() => openWorkspace(CASE_WORKSPACE)}');
+ const theme = markup.indexOf('class="rail-btn theme-toggle"');
+ expect(stages).toBeGreaterThan(-1);
+ expect(rule).toBeGreaterThan(stages);
+ expect(caseButton).toBeGreaterThan(rule);
+ expect(theme).toBeGreaterThan(caseButton);
+ expect(markup).toContain('title="The case: its Timeline, Board, Graph and Sheet"');
+ });
+
+ it('leaves the topbar to the case switcher', () => {
+ expect(markup).not.toContain('case-btn');
+ });
+});
+
+describe('Add event, from every tool', () => {
+ it('is one labelled button in the topbar, just before the guide mark', () => {
+ const button = markup.indexOf('aria-label="Add an event"');
+ const guide = markup.indexOf('onclick={() => openGuide(uiState.tool)}');
+ expect(button).toBeGreaterThan(-1);
+ expect(button).toBeLessThan(guide);
+ expect(markup).toContain('<Icon name="eventAdd" size={15} />');
+ expect(markup).toContain('<kbd>Alt N</kbd>');
+ // shown only with a case, since there is nowhere to add an event without one
+ expect(markup).toMatch(/\{#if caseState\.current && !solo\}\s*<button[\s\S]{0,200}class:on=\{uiState\.noting\}/);
+ });
+
+ it('says why it is off on a frozen snapshot rather than hiding', () => {
+ expect(source).toContain("'A frozen snapshot takes no new event. Leave it to add one.'");
+ expect(markup).toContain('disabled={noteFrozen}');
+ });
+
+ it('answers Alt+N outside any field, and sends the Timeline to its own line', () => {
+ expect(source).toContain("import { isNoteKey } from './lib/noteHere.svelte.js';");
+ expect(markup).toContain('<svelte:window onkeydown={onGlobalKey} />');
+ expect(source).toContain("if (uiState.tool === 'timeline') {");
+ expect(source).toContain('uiState.timelineLineFocus += 1;');
+ });
+
+ it('mounts the one bar every tool shares', () => {
+ expect(markup).toContain('<NoteBar />');
+ });
+});
diff --git a/frontend/src/components/AttrFields.render.test.js b/frontend/src/components/AttrFields.render.test.js
index 4e3e6b4..1217597 100644
--- a/frontend/src/components/AttrFields.render.test.js
+++ b/frontend/src/components/AttrFields.render.test.js
@@ -67,6 +67,10 @@ const BY_TYPE = {
traced: [FIELDS[1]],
claim: COUNTED,
bookmark: [{ key: 'archive_url', label: 'Archived copy', kind: 'url', rungs: [] }, RELIABILITY],
+ proof: [
+ { key: 'when', label: 'Taken', kind: 'temporal', rungs: [] },
+ { key: 'when_zone', label: 'Time zone', kind: 'timezone', rungs: [] },
+ ],
ip: [
{ key: 'network', label: 'Legacy network', kind: 'text', editable: false, rungs: [] },
{ key: 'provider', label: 'Provider', kind: 'text', rungs: [] },
@@ -379,7 +383,8 @@ describe('a temporal Claim field', () => {
choose(root, 'Date format', 'timestamp');
type(field(root, 'when'), '2026-08-11T18:40');
- choose(root, 'Timezone', 'utc');
+ // with no place tied to it, a time typed into an empty field reads on UTC
+ expect(root.querySelector('.clock-trigger').getAttribute('aria-label')).toBe('Clock: UTC');
choose(root, 'Date format', 'advanced');
expect(field(root, 'when').value).toBe('2026-08-11T18:40:00Z');
@@ -417,3 +422,38 @@ describe('a temporal Claim field', () => {
]);
});
});
+
+describe('the clock a date is read on', () => {
+ const trigger = (root) => root.querySelector('.clock-trigger');
+ function pick(root, words) {
+ trigger(root).click();
+ flushSync();
+ // the world's zones are searched, not scrolled through
+ type(document.querySelector('.clock-menu .search-input'), words);
+ const row = [...document.querySelectorAll('.clock-menu .rows > button')]
+ .find((button) => button.querySelector('span').textContent === words);
+ row.click();
+ flushSync();
+ }
+
+ it('is the date’s own Clock row rather than a second field', () => {
+ const root = open({ when: '2024-03-12' }, 'proof');
+
+ expect(field(root, 'when_zone')).toBeNull();
+ expect(trigger(root).getAttribute('aria-label')).toBe('Clock: UTC');
+ });
+
+ it('shows the zone the entity holds, with its offset on that day', () => {
+ const root = open({ when: '2024-03-12', when_zone: 'Asia/Tokyo' }, 'proof');
+ expect(trigger(root).getAttribute('aria-label')).toBe('Clock: Tokyo UTC+09:00');
+ });
+
+ it('takes any zone in the world by search, and UTC back as none', () => {
+ const root = open({ when: '2024-03-12' }, 'proof');
+
+ pick(root, 'Tokyo');
+ expect(trigger(root).getAttribute('aria-label')).toBe('Clock: Tokyo UTC+09:00');
+ pick(root, 'UTC');
+ expect(trigger(root).getAttribute('aria-label')).toBe('Clock: UTC');
+ });
+});
diff --git a/frontend/src/components/AttrFields.svelte b/frontend/src/components/AttrFields.svelte
index c3e3450..e1020bd 100644
--- a/frontend/src/components/AttrFields.svelte
+++ b/frontend/src/components/AttrFields.svelte
@@ -12,11 +12,19 @@
* nothing is flagged for being absent.
*/
import { entityFields, withHeadings } from '../lib/entityTypes.svelte.js';
+ import { UTC } from '../lib/clock.js';
+ import ClockField from './ClockField.svelte';
import TemporalInput from './TemporalInput.svelte';
let { type, values = $bindable({}), exclude = [] } = $props();
const fields = $derived(entityFields(type));
+ /** The clock a date is read on is the `<key>_zone` field beside it, edited on the
+ * date's own Clock row rather than as a second field. */
+ const zoneFor = (key) => fields.find((field) => field.kind === 'timezone' && field.key === `${key}_zone`);
+ const paired = (field) =>
+ field.kind === 'timezone' &&
+ fields.some((other) => other.kind === 'temporal' && `${other.key}_zone` === field.key && !exclude.includes(other.key));
/**
* A shape is traced on the map, never typed here. So an empty footprint shows
@@ -25,7 +33,7 @@
* the summary and the Clear that drops it.
*/
const shown = $derived(withHeadings(fields.filter((field) => {
- if (exclude.includes(field.key)) return false;
+ if (exclude.includes(field.key) || paired(field)) return false;
if (field.editable === false) return values?.[field.key] != null && values[field.key] !== '';
return field.kind !== 'geojson' || values?.[field.key];
})));
@@ -119,13 +127,21 @@
{/each}
</select>
{:else if field.kind === 'temporal'}
+ {@const clock = zoneFor(field.key)}
<div class="temporal-field">
<TemporalInput
id={`attr-${field.key}`}
value={values?.[field.key] ?? ''}
+ zone={clock ? values?.[clock.key] ?? null : null}
+ onzonechange={clock ? (zone) => set(clock.key, zone) : null}
onchange={(value) => set(field.key, value)}
/>
</div>
+ {:else if field.kind === 'timezone'}
+ <ClockField
+ clock={{ zone: values?.[field.key] || UTC, fixed: '' }}
+ onpick={(zone) => set(field.key, zone && zone !== UTC ? zone : null)}
+ />
{:else if field.kind === 'longtext'}
<!-- A quoted source and the reasoning behind a claim run to paragraphs.
Held in a one-line box they scroll sideways past eighty characters,
diff --git a/frontend/src/components/AttrFields.test.js b/frontend/src/components/AttrFields.test.js
index 28faae8..d1d8603 100644
--- a/frontend/src/components/AttrFields.test.js
+++ b/frontend/src/components/AttrFields.test.js
@@ -30,7 +30,12 @@ describe('generated fields', () => {
it('can leave fields to a dedicated Details tab without changing the registry', () => {
expect(source).toContain('exclude = []');
- expect(source).toContain('if (exclude.includes(field.key)) return false;');
+ expect(source).toContain('if (exclude.includes(field.key) || paired(field)) return false;');
+ });
+
+ it('edits a date’s zone on the date’s own Clock row rather than as a second field', () => {
+ expect(source).toContain('`${other.key}_zone` === field.key');
+ expect(source).toContain('onzonechange={clock ? (zone) => set(clock.key, zone) : null}');
});
});
diff --git a/frontend/src/components/ClockField.render.test.js b/frontend/src/components/ClockField.render.test.js
new file mode 100644
index 0000000..1b1f6da
--- /dev/null
+++ b/frontend/src/components/ClockField.render.test.js
@@ -0,0 +1,141 @@
+// @vitest-environment happy-dom
+/**
+ * The one control every date field uses to say which clock it is read on, mounted
+ * and pressed: what it offers, in what order, and what a pick hands back.
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { flushSync, mount, unmount } from 'svelte';
+
+vi.mock('../lib/state.svelte.js', () => ({ caseState: { current: { id: 'case-a' } } }));
+
+const { default: ClockField } = await import('./ClockField.svelte');
+const { machineZone } = await import('../lib/timeline.js');
+const { forgetAxisZone, noteAxisZone } = await import('../lib/caseAxis.svelte.js');
+
+let live = null;
+let target = null;
+let picks = [];
+
+function open(props = {}) {
+ target = document.createElement('div');
+ document.body.append(target);
+ picks = [];
+ live = mount(ClockField, {
+ target,
+ props: { value: '2026-08-11', onpick: (zone, how) => picks.push([zone, how.here]), ...props },
+ });
+ flushSync();
+}
+
+const trigger = () => target.querySelector('.clock-trigger');
+const menu = () => document.querySelector('.clock-menu');
+const rows = () => [...document.querySelectorAll('.clock-menu .rows > button')];
+const names = () => rows().map((row) => row.querySelector('span').textContent);
+
+function press(element) {
+ element.click();
+ flushSync();
+}
+
+function search(text) {
+ const input = document.querySelector('.clock-menu .search-input');
+ input.value = text;
+ input.dispatchEvent(new Event('input', { bubbles: true }));
+ flushSync();
+}
+
+beforeEach(() => localStorage.clear());
+
+afterEach(() => {
+ if (live) unmount(live);
+ live = null;
+ target?.remove();
+ document.body.innerHTML = '';
+});
+
+describe('the clock a date is read on', () => {
+ it('says the clock and its offset on that day, a place by its own name', () => {
+ open({ clock: { zone: 'Europe/Kyiv', fixed: '' } });
+ expect(trigger().getAttribute('aria-label')).toBe('Clock: Kyiv UTC+03:00');
+
+ unmount(live);
+ open({ value: '2026-01-11', clock: { zone: 'Europe/Kyiv', fixed: '' }, here: [{ zone: 'Europe/Kyiv', place: 'Kharkiv' }] });
+ expect(trigger().getAttribute('aria-label')).toBe('Clock: Kharkiv UTC+02:00');
+ });
+
+ it('says an offset written with no zone, and a clock nobody knows', () => {
+ open({ clock: { zone: null, fixed: '+04:30' } });
+ expect(trigger().getAttribute('aria-label')).toBe('Clock: UTC+04:30');
+ unmount(live);
+ open({ clock: { zone: null, fixed: '' } });
+ expect(trigger().getAttribute('aria-label')).toBe('Clock: Clock unknown');
+ });
+
+ it('offers the entry’s places first, then UTC and this computer, then the world', () => {
+ open({ clock: { zone: 'UTC', fixed: '' }, here: [{ zone: 'Europe/Kyiv', place: 'Kharkiv' }] });
+ press(trigger());
+
+ const offered = names();
+ expect(offered[0]).toBe('Local at Kharkiv');
+ expect(offered[1]).toBe('UTC');
+ if (machineZone() !== 'UTC') expect(offered[2]).toBe(machineZone().split('/').at(-1).replace(/_/g, ' '));
+ expect(menu().textContent).toContain('Anywhere in the world');
+ // a date has no clock to leave unknown
+ expect(offered).not.toContain('Clock unknown');
+ });
+
+ it('offers the case’s clock, the one its axis reads on', () => {
+ noteAxisZone('case-a', 'America/Los_Angeles');
+ try {
+ open({ clock: { zone: 'UTC', fixed: '' }, here: [{ zone: 'Europe/Kyiv', place: 'Kharkiv' }] });
+ press(trigger());
+ expect(names().slice(0, 2)).toEqual(['Local at Kharkiv', 'Los Angeles']);
+ expect(rows()[1].textContent).toContain("the case's clock");
+ press(rows()[1]);
+ expect(picks).toEqual([['America/Los_Angeles', false]]);
+ } finally {
+ forgetAxisZone();
+ }
+ });
+
+ it('offers an unknown clock for a time only', () => {
+ open({ value: '2026-08-11T14:30:00', timed: true, clock: { zone: 'UTC', fixed: '' } });
+ press(trigger());
+ press(rows().find((row) => row.textContent.includes('Clock unknown')));
+ expect(picks).toEqual([[null, false]]);
+ });
+
+ it('finds any zone by search, and says whether a pick was one of the places', () => {
+ open({ clock: { zone: 'UTC', fixed: '' }, here: [{ zone: 'Europe/Kyiv', place: 'Kharkiv' }] });
+ press(trigger());
+ search('tokyo');
+ expect(names()).toEqual(['Tokyo']);
+ press(rows()[0]);
+ expect(picks.at(-1)).toEqual(['Asia/Tokyo', false]);
+ expect(menu()).toBeNull();
+
+ press(trigger());
+ press(rows().find((row) => row.textContent.includes('Local at Kharkiv')));
+ expect(picks.at(-1)).toEqual(['Europe/Kyiv', true]);
+ });
+
+ it('brings back the zones picked lately in this case', () => {
+ open({ clock: { zone: 'UTC', fixed: '' } });
+ press(trigger());
+ search('aden');
+ press(rows()[0]);
+
+ press(trigger());
+ expect(names()[0]).toBe('Aden');
+ expect(rows()[0].textContent).toContain('used lately');
+ });
+
+ it('closes on Escape without picking', () => {
+ open({ clock: { zone: 'UTC', fixed: '' } });
+ press(trigger());
+ menu().dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }));
+ flushSync();
+ expect(menu()).toBeNull();
+ expect(picks).toEqual([]);
+ });
+});
diff --git a/frontend/src/components/ClockField.svelte b/frontend/src/components/ClockField.svelte
new file mode 100644
index 0000000..88023b3
--- /dev/null
+++ b/frontend/src/components/ClockField.svelte
@@ -0,0 +1,216 @@
+<script>
+ /**
+ * Which clock a stated date was read on: the one control every date field uses.
+ *
+ * A day in Kharkiv is not UTC's day, and a 14:30 read off a caption is nobody's
+ * instant until its clock is known. So the field says the clock it reads on, and one
+ * press opens every answer in a single searchable list:
+ *
+ * - **Here**, the zones of the places the entry is tied to;
+ * - **The case's clock**, the one its Timeline axis reads on (`lib/caseAxis.svelte.js`);
+ * - **Lately**, the zones picked in this case, since a case is argued on a few clocks;
+ * - **UTC**, and **this computer**;
+ * - **Clock unknown**, for a time only: it stays off the axis until one is known;
+ * - **Anywhere in the world**, by search.
+ *
+ * The pick goes to the parent, which stores it through `lib/clock.js`.
+ */
+ import { caseState } from '../lib/state.svelte.js';
+ import { UTC, clockInstant, recentClocks, rememberClockPick } from '../lib/clock.js';
+ import { axisZone } from '../lib/caseAxis.svelte.js';
+ import { machineZone, offsetLabel, worldZones, zoneMatches, zoneWords } from '../lib/timeline.js';
+ import { anchoredPanel } from '../lib/anchoredPanel.js';
+ import Icon from './Icon.svelte';
+ import SearchInput from './SearchInput.svelte';
+
+ let {
+ /** The value the clock is for, which sets the day the offsets are shown on. */
+ value = '',
+ /** What it reads on now, `{ zone, fixed }` (see `clockOf`). */
+ clock = { zone: UTC, fixed: '' },
+ /** The zones of the places the entry is tied to, `{ zone, place }`. */
+ here = [],
+ /** Whether the value has a time of day, so its clock can be left unknown. */
+ timed = false,
+ disabled = false,
+ /** Told the pick: a zone name, `UTC`, or null for an unknown clock. The second
+ * argument says whether it was one of the entry's own places. */
+ onpick,
+ } = $props();
+
+ const uid = $props.id();
+ /** How many zones the list shows before it asks for a narrower term. */
+ const ROWS = 40;
+
+ let open = $state(false);
+ let query = $state('');
+ let trigger = $state();
+ let menu = $state();
+
+ const at = $derived(clockInstant(value));
+ const local = machineZone();
+ const zones = worldZones();
+ const axis = $derived(axisZone(caseState.current?.id));
+ const caseRow = $derived(axis !== UTC && !here.some((entry) => entry.zone === axis));
+ const recent = $derived(
+ open
+ ? recentClocks(caseState.current?.id).filter((zone) => zone !== axis && !here.some((entry) => entry.zone === zone))
+ : [],
+ );
+ const matching = $derived(zones.filter((zone) => zoneMatches(zone, query, at)));
+ const shown = $derived(matching.slice(0, ROWS));
+ const term = $derived(query.trim().toLowerCase());
+ const hereShown = $derived(
+ here.filter((entry) => zoneMatches(entry.zone, query, at) || entry.place.toLowerCase().includes(term)),
+ );
+
+ const place = $derived(here.find((entry) => entry.zone === clock.zone)?.place ?? '');
+ /** What the button says: the place's name, the zone's, or the offset the value carries. */
+ const label = $derived(
+ clock.fixed ? `UTC${clock.fixed}`
+ : !clock.zone ? 'Clock unknown'
+ : clock.zone === UTC ? UTC
+ : place || zoneWords(clock.zone).place,
+ );
+ const offset = $derived(clock.zone && clock.zone !== UTC && !clock.fixed ? offsetLabel(clock.zone, at) : '');
+ const title = $derived(
+ clock.fixed ? 'An offset written in the date, with no zone named'
+ : !clock.zone ? 'No clock yet, so the time stays off the axis'
+ : place ? `Local time at ${place} (${clock.zone})`
+ : clock.zone === UTC ? 'Read on UTC' : `Read on ${clock.zone}`,
+ );
+
+ $effect(() => {
+ if (!open || typeof document === 'undefined') return;
+ const closeOutside = (event) => {
+ if (!trigger?.contains(event.target) && !menu?.contains(event.target)) open = false;
+ };
+ document.addEventListener('pointerdown', closeOutside);
+ return () => document.removeEventListener('pointerdown', closeOutside);
+ });
+
+ function pick(zone, { isHere = false } = {}) {
+ open = false;
+ query = '';
+ rememberClockPick(caseState.current?.id, zone);
+ onpick?.(zone, { here: isHere });
+ }
+
+ function onKey(event) {
+ if (event.key === 'Escape') {
+ event.stopPropagation();
+ open = false;
+ trigger?.focus();
+ }
+ }
+</script>
+
+<button
+ bind:this={trigger}
+ type="button"
+ class="clock-trigger"
+ {disabled}
+ aria-expanded={open}
+ aria-controls="{uid}-clock"
+ aria-label="Clock: {label}{offset ? ` ${offset}` : ''}"
+ {title}
+ onclick={() => (open = !open)}
+>
+ <Icon name="clock" size={12} />
+ <span>{label}</span>
+ {#if offset}<small>{offset}</small>{/if}
+</button>
+
+{#if open}
+ <!-- svelte-ignore a11y_no_static_element_interactions -->
+ <div
+ bind:this={menu}
+ id="{uid}-clock"
+ class="clock-menu"
+ popover="manual"
+ use:anchoredPanel={{ anchor: () => trigger, width: 280 }}
+ onkeydown={onKey}
+ >
+ <SearchInput bind:value={query} placeholder="Search a zone or a city…" width="100%" />
+ <div class="rows">
+ {#each hereShown as entry (entry.zone)}
+ <button class:on={clock.zone === entry.zone && !clock.fixed} onclick={() => pick(entry.zone, { isHere: true })}>
+ <span>Local at {entry.place}</span><small>{entry.zone} · {offsetLabel(entry.zone, at)}</small>
+ </button>
+ {/each}
+ {#if caseRow && (zoneMatches(axis, query, at) || "the case's clock".includes(term))}
+ <button class:on={clock.zone === axis && !clock.fixed && !place} onclick={() => pick(axis)}>
+ <span>{zoneWords(axis).place}</span><small>the case's clock · {offsetLabel(axis, at)}</small>
+ </button>
+ {/if}
+ {#each recent.filter((zone) => zoneMatches(zone, query, at)) as zone (zone)}
+ <button class:on={clock.zone === zone && !clock.fixed} onclick={() => pick(zone)}>
+ <span>{zoneWords(zone).place}</span><small>used lately · {offsetLabel(zone, at)}</small>
+ </button>
+ {/each}
+ {#if zoneMatches(UTC, query, at)}
+ <button class:on={clock.zone === UTC} onclick={() => pick(UTC)}>
+ <span>UTC</span><small>the same everywhere</small>
+ </button>
+ {/if}
+ {#if local !== UTC && local !== axis && zoneMatches(local, query, at)}
+ <button class:on={clock.zone === local && !place} onclick={() => pick(local)}>
+ <span>{zoneWords(local).place}</span><small>this computer · {offsetLabel(local, at)}</small>
+ </button>
+ {/if}
+ {#if timed && (!term || 'clock unknown'.includes(term))}
+ <button class:on={!clock.zone && !clock.fixed} onclick={() => pick(null)}>
+ <span>Clock unknown</span><small>stays off the axis</small>
+ </button>
+ {/if}
+
+ {#if zones.length}
+ <p class="heading">Anywhere in the world</p>
+ {#each shown as zone (zone)}
+ {@const words = zoneWords(zone)}
+ <button class:on={clock.zone === zone && !clock.fixed && !place} onclick={() => pick(zone)}>
+ <span>{words.place}</span><small>{words.region} · {offsetLabel(zone, at)}</small>
+ </button>
+ {/each}
+ {#if matching.length > shown.length}
+ <p class="more">{matching.length - shown.length} more. Keep typing.</p>
+ {:else if !matching.length && !hereShown.length}
+ <p class="more">No zone matches that.</p>
+ {/if}
+ {:else}
+ <p class="more">This browser cannot list world zones. UTC and this computer still work.</p>
+ {/if}
+ </div>
+ </div>
+{/if}
+
+<style>
+ .clock-trigger {
+ display: inline-flex; align-items: center; justify-self: start; gap: 5px; height: 24px; max-width: 100%;
+ padding: 0 7px; border: 1px solid var(--border); border-radius: var(--r-sm);
+ background: var(--bg-2); color: var(--text-2); font-size: var(--fs-xs); cursor: pointer;
+ }
+ .clock-trigger:hover:not(:disabled) { border-color: var(--border-strong); color: var(--text-1); }
+ .clock-trigger:disabled { opacity: .5; cursor: default; }
+ .clock-trigger span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+ .clock-trigger small { color: var(--text-3); font-variant-numeric: tabular-nums; white-space: nowrap; }
+ .clock-menu {
+ position: fixed; inset: auto; margin: 0; z-index: 60;
+ display: grid; grid-template-rows: auto minmax(0, 1fr); gap: 5px; padding: 7px;
+ border: 1px solid var(--border-strong); border-radius: var(--r-md);
+ background: var(--bg-1); color: var(--text-1); box-shadow: var(--shadow-2);
+ }
+ .rows { max-height: 260px; overflow: auto; }
+ .rows > button {
+ width: 100%; display: grid; grid-template-columns: minmax(0, 1fr) auto;
+ align-items: baseline; gap: 8px; padding: 5px 6px; border: 0; border-radius: var(--r-sm);
+ background: none; color: var(--text-2); font-size: var(--fs-xs); text-align: left;
+ cursor: pointer;
+ }
+ .rows > button:hover { background: var(--bg-2); color: var(--text-1); }
+ .rows > button.on { background: var(--accent-soft); color: var(--text-1); }
+ .rows > button span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+ .rows > button small { color: var(--text-3); font-size: 10px; white-space: nowrap; }
+ .heading { margin: 7px 0 3px; padding: 0 6px; color: var(--text-3); font-size: 10px; }
+ .more { margin: 5px 0 2px; padding: 0 6px; color: var(--text-3); font-size: 10px; }
+</style>
diff --git a/frontend/src/components/DateField.svelte b/frontend/src/components/DateField.svelte
index 934f92d..c5c76a9 100644
--- a/frontend/src/components/DateField.svelte
+++ b/frontend/src/components/DateField.svelte
@@ -36,6 +36,9 @@
* would rather build than spell. Off by default: most of these fields sit in
* a row where a second control would crowd what is already a small box. */
calendar = false,
+ /** The zone the value is read in, when the field's owner knows it, so the
+ * reading names that clock instead of saying `local time`. */
+ zone = null,
onchange,
} = $props();
@@ -62,7 +65,7 @@
const said = $derived.by(() => {
if (!text.trim()) return '';
if (parsed.error) return parsed.error;
- const format = formatTemporalValue(parsed.value);
+ const format = formatTemporalValue(parsed.value, zone);
return [format.label, ...format.qualifiers].join(' · ');
});
diff --git a/frontend/src/components/EntityDetails.render.test.js b/frontend/src/components/EntityDetails.render.test.js
index 84cb6af..06a3dcd 100644
--- a/frontend/src/components/EntityDetails.render.test.js
+++ b/frontend/src/components/EntityDetails.render.test.js
@@ -65,6 +65,7 @@ vi.mock('../lib/state.svelte.js', async () => await import('./details.fixture.sv
vi.mock('../lib/relations.svelte.js', () => ({
loadRelationTypes: () => Promise.resolve(),
relatableTypes: () => [],
+ relationOptions: () => [],
relationAction: () => 'relation',
saveRelation: vi.fn(),
}));
diff --git a/frontend/src/components/EntityDetails.svelte b/frontend/src/components/EntityDetails.svelte
index 4344625..52a853b 100644
--- a/frontend/src/components/EntityDetails.svelte
+++ b/frontend/src/components/EntityDetails.svelte
@@ -44,6 +44,7 @@
import { canStateSource, sourceProblem } from '../lib/statedSource.js';
import { deletedToast, FILE_BACKED, RESTORABLE } from '../lib/trash.js';
import Icon from './Icon.svelte';
+ import SubjectActions from './SubjectActions.svelte';
import ConfirmDialog from './ConfirmDialog.svelte';
import FolderSelect from './FolderSelect.svelte';
import AttrFields from './AttrFields.svelte';
@@ -53,8 +54,7 @@
import RelationPicker from './RelationPicker.svelte';
import EntityImages from './EntityImages.svelte';
import EntityTime from './EntityTime.svelte';
- import QuickClaim, { claimSeat } from './QuickClaim.svelte';
- import { claimActionTitle } from '../lib/quickClaim.js';
+ import EntitySummary from './EntitySummary.svelte';
let {
entityId,
@@ -284,7 +284,7 @@
// Connections have their own explicit composer. They are graph statements, not
// unsaved text fields, so waiting on the panel-wide Save made the Add action feel
// broken and let a mention masquerade as a relation.
- let connectionComposer = $state(null); // 'relation' | 'mention' | 'claim' | null
+ let connectionComposer = $state(null); // 'relation' | 'mention' | null
let connectionSaving = $state(false);
loadRelationTypes();
loadEntityTypes();
@@ -296,8 +296,6 @@
);
const canRelate = $derived(relationTargetTypes.length > 0);
const canMention = $derived(mentionTargetTypes.length > 0);
- // Where this entity would sit on a claim filed from here, or null for none.
- const claimSeatHere = $derived(claimSeat(entity));
const relationTargetHint = $derived(
`Relate this to: ${relationTargetTypes.map(entityLabel).join(', ')}.`
);
@@ -647,6 +645,8 @@
<div class="info-loading">Loading…</div>
{/if}
+ <EntitySummary caseId={caseState.current.id} {entity} {onclose} />
+
<div class="ed-tabs" role="tablist" aria-label="Details sections">
<button
class="ed-tab" class:on={tab === 'info'} role="tab" aria-selected={tab === 'info'}
@@ -665,7 +665,15 @@
>Time</button>
</div>
+ {#if chainData?.merged_from}
+ <p class="merged-notice" role="status"><bdi>{chainData.merged_from.label}</bdi> · Merged into <bdi>{entity.label}</bdi></p>
+ {/if}
{#if tab === 'info'}
+ <SubjectActions caseId={caseState.current.id} {entity} {twin} disabled={dirty || infoSaving} onchanged={(saved) => {
+ seededId = null;
+ chainData = { ...chainData, entity: saved };
+ if (saved.id !== currentId) walkedId = saved.id;
+ }} />
{#if infoData?.kind === 'image' && infoData.thumbnail}
<div class="info-preview">
<img src={fileUrl(caseState.current.id, infoData.path)} alt={entity.label} />
@@ -708,6 +716,7 @@
<input
id="ed-title"
class="input"
+ dir="auto"
bind:value={infoTitle}
placeholder={coordText || identityPlaceholder}
/>
@@ -804,7 +813,7 @@
<AttrFields
type={entity.type}
bind:values={infoAttrs}
- exclude={entity.type === 'claim' ? ['when', 'time_role', 'confidence', 'method', 'verbatim'] : []}
+ exclude={entity.type === 'claim' ? ['when', 'when_zone', 'time_role', 'confidence', 'method', 'verbatim'] : []}
/>
{/if}
@@ -854,7 +863,7 @@
{/if}
<label class="modal-label" for="ed-notes">Notes</label>
- <textarea id="ed-notes" class="textarea" rows="3" bind:value={infoNotes} placeholder="Add observations, links, context…"></textarea>
+ <textarea id="ed-notes" class="textarea" rows="3" dir="auto" bind:value={infoNotes} placeholder="Add observations, links, context…"></textarea>
<span class="modal-label">Folder (My work)</span>
<FolderSelect bind:value={infoFolder} folders={allFolders} emptyLabel="None" />
@@ -862,7 +871,7 @@
{#if tab === 'connections'}
<div class="case-layout">
- {#if canRelate || canMention || claimSeatHere || hasRelations || lineageCount || placedPoints.length}
+ {#if canRelate || canMention || claimRelations.length || hasRelations || lineageCount || placedPoints.length}
<section class="connections">
<div class="card-head connections-head"><h3>Connections</h3></div>
@@ -988,29 +997,13 @@
onchanged={reloadCase}
/>
</div>
- {:else if claimSeatHere || claimRelations.length}
+ {:else if claimRelations.length}
+ <!-- The events that name it. Adding one is the summary's, above the tabs,
+ where it can be reached from whichever tab is open. -->
<div class="connection-group">
<div class="connection-head">
- <h4>Claims</h4>
- {#if claimSeatHere}
- <button
- class="btn btn-ghost btn-sm"
- class:on={connectionComposer === 'claim'}
- title={claimActionTitle(claimSeatHere.slot)}
- onclick={() => (connectionComposer = connectionComposer === 'claim' ? null : 'claim')}
- >Add claim</button>
- {/if}
+ <h4>Events</h4>
</div>
- {#if connectionComposer === 'claim'}
- <div class="quick-claim-host">
- <QuickClaim
- caseId={caseState.current.id}
- {entity}
- onsaved={() => (connectionComposer = null)}
- oncancel={() => (connectionComposer = null)}
- />
- </div>
- {/if}
<!-- What those statements come to, above the statements themselves.
The rows were always here; adding them up by reading four of them
was the arithmetic this line does. Only where a statement is
@@ -1098,7 +1091,7 @@
</section>
{/if}
- {#if !canRelate && !canMention && !claimSeatHere && !hasRelations && !lineageCount && !placedPoints.length}
+ {#if !canRelate && !canMention && !claimRelations.length && !hasRelations && !lineageCount && !placedPoints.length}
<div class="case-card empty-card">
<Icon name="link" size={16} />
<p>No connections yet.</p>
@@ -1469,13 +1462,6 @@
padding: 7px 0;
border-top: 1px solid var(--border);
}
- .quick-claim-host {
- margin: 6px 0 4px;
- padding: 10px;
- border: 1px solid var(--border);
- border-radius: var(--r-sm);
- background: var(--bg-1);
- }
.connection-head {
display: flex;
align-items: center;
diff --git a/frontend/src/components/EntityDetails.test.js b/frontend/src/components/EntityDetails.test.js
index c235cd2..d32ab60 100644
--- a/frontend/src/components/EntityDetails.test.js
+++ b/frontend/src/components/EntityDetails.test.js
@@ -68,21 +68,22 @@ describe('import enrichment details', () => {
// a relation says something about the world; the chain says how a file was
// made and decides what a delete destroys
expect(source).toContain(
- '{#if canRelate || canMention || claimSeatHere || hasRelations || lineageCount || placedPoints.length}'
+ '{#if canRelate || canMention || claimRelations.length || hasRelations || lineageCount || placedPoints.length}'
);
expect(source).toContain('{#if lineageCount}');
expect(source).toContain('<details class="lineage-card">');
});
- it('files a claim from the Claims group of anything that can sit on one', () => {
- // The group is there before the first claim exists, since that is when it is
- // needed; the seat comes from the verb registry, not from a list of types.
- expect(source).toContain('const claimSeatHere = $derived(claimSeat(entity));');
- expect(source).toContain('{:else if claimSeatHere || claimRelations.length}');
- expect(source).toContain('title={claimActionTitle(claimSeatHere.slot)}');
- expect(source).toContain(">Add claim</button>");
- expect(source).toContain("{#if connectionComposer === 'claim'}");
- expect(source).toContain('onsaved={() => (connectionComposer = null)}');
+ it('adds an event from the summary above the tabs, and lists events in Connections', () => {
+ // One place to add an event, reachable from whichever tab is open; Connections
+ // keeps the list of the events that name it.
+ const summary = source.indexOf('<EntitySummary caseId={caseState.current.id} {entity} {onclose} />');
+ expect(summary).toBeGreaterThan(-1);
+ expect(summary).toBeLessThan(source.indexOf('class="ed-tabs"'));
+ expect(source).toContain('{:else if claimRelations.length}');
+ expect(source).toContain('<h4>Events</h4>');
+ expect(source).not.toContain("connectionComposer === 'claim'");
+ expect(source).not.toContain('quick-claim-host');
});
it('files a connection from its own Add action rather than the panel Save', () => {
@@ -258,7 +259,7 @@ describe('the declared fields', () => {
expect(source).toContain('type={entity.type}');
expect(source).toContain('bind:values={infoAttrs}');
expect(source).toContain("exclude={entity.type === 'claim'");
- expect(source).toContain("['when', 'time_role', 'confidence', 'method', 'verbatim']");
+ expect(source).toContain("['when', 'when_zone', 'time_role', 'confidence', 'method', 'verbatim']");
expect(source).toContain('{#if declaredFields.length}');
});
@@ -381,7 +382,7 @@ describe('a file the app has no viewer for', () => {
describe('Claim details tabs', () => {
it('keeps assessment fields in Time instead of duplicating them in Info', () => {
expect(source).toContain(
- "exclude={entity.type === 'claim' ? ['when', 'time_role', 'confidence', 'method', 'verbatim'] : []}"
+ "exclude={entity.type === 'claim' ? ['when', 'when_zone', 'time_role', 'confidence', 'method', 'verbatim'] : []}"
);
expect(source).toContain('<EntityTime');
});
diff --git a/frontend/src/components/EntityFinder.svelte b/frontend/src/components/EntityFinder.svelte
new file mode 100644
index 0000000..a5d1851
--- /dev/null
+++ b/frontend/src/components/EntityFinder.svelte
@@ -0,0 +1,243 @@
+<script>
+ /**
+ * Find one thing in the case to attach, among the types a connector accepts.
+ *
+ * A source can be a file, a map capture, a proof, a web page, a note or another
+ * claim, and one list of all of them read as everything the case holds. So the
+ * kinds the case actually has are chips above the list, each with its count, and
+ * every row says what it is: its picture when it has one, its type, the kind of
+ * file, its folder and the day it came in. The newest come first when asked, which
+ * is where the source being cited usually is.
+ */
+ import { api } from '../lib/api.js';
+ import { buildCatalogQuery } from '../lib/catalog.js';
+ import { entityIcon } from '../lib/entityIcon.js';
+ import { entitySearchMatches } from '../lib/entitySearch.js';
+ import { entityLabel } from '../lib/entityTypes.svelte.js';
+ import { fileUrl } from '../lib/fileUrl.js';
+ import { folderOf } from '../lib/folderTree.js';
+ import Icon from './Icon.svelte';
+
+ let {
+ caseId,
+ /** The types the connector accepts. */
+ types = [],
+ /** Ids already attached, left out of the list. */
+ exclude = [],
+ /** `-created` for newest first, or '' for the catalog's own order. */
+ order = '',
+ placeholder = 'Search the case…',
+ label = 'Search the case',
+ onpick,
+ onclose,
+ } = $props();
+
+ const PAGE = 30;
+ let query = $state('');
+ let kind = $state('');
+ let mediaKind = $state('');
+ let rows = $state([]);
+ let more = $state(false);
+ let loading = $state(false);
+ let active = $state(0);
+ let summary = $state(null);
+ let input = $state();
+ let seq = 0;
+
+ $effect(() => {
+ if (!caseId) return;
+ let live = true;
+ api.get(`/api/cases/${caseId}/catalog/summary`)
+ .then((body) => { if (live) summary = body; })
+ .catch(() => {});
+ return () => { live = false; };
+ });
+
+ /** The kinds worth a chip: the accepted types this case holds any of. */
+ const kinds = $derived(
+ types
+ .map((type) => ({ type, label: entityLabel(type), count: Number(summary?.by_type?.[type] ?? 0) }))
+ .filter((entry) => entry.count > 0)
+ );
+
+ const hidden = $derived(new Set(exclude));
+ const shown = $derived(rows.filter((entity) => !hidden.has(entity.id)));
+
+ $effect(() => {
+ const term = query.trim();
+ const wanted = kind ? [kind] : types;
+ if (!caseId || !wanted.length) return;
+ const mine = ++seq;
+ loading = true;
+ api
+ .get(buildCatalogQuery(caseId, { types: wanted, query: term || undefined, limit: PAGE, order, previews: true,
+ ...(kind === 'media' && mediaKind ? { attr: 'kind', value: mediaKind } : {}),
+ }))
+ .then((page) => {
+ if (mine !== seq) return;
+ rows = page.items ?? [];
+ more = Boolean(page.next_cursor);
+ active = 0;
+ })
+ .catch(() => {
+ if (mine === seq) rows = [];
+ })
+ .finally(() => {
+ if (mine === seq) loading = false;
+ });
+ });
+
+ $effect(() => {
+ input?.focus();
+ });
+
+ const day = (at) => {
+ const date = new Date(at ?? '');
+ return Number.isNaN(date.getTime())
+ ? ''
+ : date.toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' });
+ };
+
+ /** What a row is, in a few words: its type, the kind of file, where it is filed
+ * and when it came in. */
+ function describe(entity) {
+ const kindOfFile = entity.type === 'media' ? entity.attrs?.kind : '';
+ const folder = folderOf(entity);
+ return [
+ entityLabel(entity.type),
+ kindOfFile && kindOfFile !== 'file' ? kindOfFile : '',
+ folder ? `in ${folder}` : '',
+ day(entity.provenance?.at) ? `added ${day(entity.provenance?.at)}` : '',
+ ].filter(Boolean).join(' · ');
+ }
+
+ function reason(entity) {
+ if (!query.trim()) return null;
+ const match = entitySearchMatches(entity, query)[0];
+ return match && match.field !== 'label' ? match : null;
+ }
+
+ function pick(entity) {
+ if (entity) onpick?.(entity);
+ }
+
+ function onkeydown(event) {
+ if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
+ event.preventDefault();
+ if (!shown.length) return;
+ const step = event.key === 'ArrowDown' ? 1 : -1;
+ active = (active + step + shown.length) % shown.length;
+ input?.closest('.finder')?.querySelectorAll('[role="option"]')[active]?.scrollIntoView?.({ block: 'nearest' });
+ } else if (event.key === 'Enter') {
+ event.preventDefault();
+ event.stopPropagation();
+ pick(shown[active]);
+ } else if (event.key === 'Escape' && onclose) {
+ event.preventDefault();
+ event.stopPropagation();
+ onclose();
+ }
+ }
+</script>
+
+<div class="finder">
+ <div class="search">
+ <Icon name="search" size={13} />
+ <input
+ bind:this={input}
+ type="search"
+ dir="auto"
+ autocomplete="off"
+ aria-label={label}
+ {placeholder}
+ bind:value={query}
+ {onkeydown}
+ />
+ </div>
+
+ {#if kinds.length > 1}
+ <div class="kinds" role="group" aria-label="Kinds">
+ <button class:on={!kind} aria-pressed={!kind} onclick={() => { kind = ''; mediaKind = ''; }}>All</button>
+ {#each kinds as entry (entry.type)}
+ <button class:on={kind === entry.type} aria-pressed={kind === entry.type} onclick={() => { kind = kind === entry.type ? '' : entry.type; mediaKind = ''; }}>
+ {entry.label}<em>{entry.count}</em>
+ </button>
+ {/each}
+ </div>
+ {/if}
+
+ {#if types.includes('media') && (!kind || kind === 'media')}
+ <div class="kinds formats" role="group" aria-label="Media format">
+ {#each [['image', 'Images'], ['video', 'Videos'], ['audio', 'Audio'], ['file', 'Other files']] as [value, name]}
+ <button class:on={mediaKind === value} aria-pressed={mediaKind === value} onclick={() => { kind = 'media'; mediaKind = mediaKind === value ? '' : value; }}>{name}</button>
+ {/each}
+ </div>
+ {/if}
+
+ <ul class="rows" role="listbox" aria-label={label}>
+ {#each shown as entity, index (entity.id)}
+ {@const why = reason(entity)}
+ <li
+ role="option"
+ aria-selected={index === active}
+ class:active={index === active}
+ onpointerenter={() => (active = index)}
+ onpointerdown={(event) => { event.preventDefault(); pick(entity); }}
+ >
+ <span class="picture">
+ {#if entity.thumb}
+ <img src={entity.thumb.startsWith('data:') ? entity.thumb : fileUrl(caseId, entity.thumb)} alt="" loading="lazy" />
+ {:else}
+ <Icon name={entityIcon(entity)} size={14} />
+ {/if}
+ </span>
+ <span class="text">
+ <span class="name" dir="auto">{entity.label}</span>
+ <small>{describe(entity)}{#if why} · <span dir="auto">{why.label}: {why.value}</span>{/if}</small>
+ </span>
+ </li>
+ {:else}
+ <li class="none">
+ {#if loading}Searching…
+ {:else if query.trim()}Nothing here by that name{kind ? ` among the ${entityLabel(kind).toLowerCase()} kind` : ''}
+ {:else}Nothing of this kind in the case yet{/if}
+ </li>
+ {/each}
+ {#if more && shown.length}
+ <li class="none">More below these {shown.length}: type a few letters to narrow</li>
+ {/if}
+ </ul>
+</div>
+
+<style>
+ .finder { display: flex; flex-direction: column; gap: 8px; min-width: 0; min-height: 0; max-height: inherit; }
+ .search {
+ display: flex; flex: 0 0 auto; align-items: center; gap: 8px; padding: 8px 10px; min-height: 36px; box-sizing: border-box;
+ border: 1px solid var(--border); border-radius: var(--r-sm); background: var(--bg-2); color: var(--text-3);
+ }
+ .search:focus-within { border-color: var(--accent); }
+ .search input { flex: 1; min-width: 0; border: 0; background: none; color: var(--text-1); font: inherit; font-size: var(--fs-sm); outline: none; }
+ .kinds { display: flex; flex: 0 0 auto; flex-wrap: wrap; gap: 6px; }
+ .kinds button {
+ display: inline-flex; align-items: center; gap: 5px; padding: 4px 9px; min-height: 28px;
+ border: 1px solid var(--border); border-radius: 999px; background: none;
+ color: var(--text-2); font-size: var(--fs-xs); cursor: pointer;
+ }
+ .kinds button.on { border-color: var(--accent); color: var(--text-1); background: var(--accent-soft); }
+ .kinds em { color: var(--text-3); font-style: normal; font-size: 10px; }
+ .rows { max-height: 300px; min-height: 0; overflow: auto; overscroll-behavior: contain; margin: 0; padding: 0; list-style: none; }
+ .rows li {
+ display: grid; grid-template-columns: 48px minmax(0, 1fr); align-items: center; gap: 10px;
+ padding: 7px 6px; border-radius: var(--r-sm); cursor: pointer; color: var(--text-2);
+ }
+ .rows li.active { background: var(--bg-3); color: var(--text-1); }
+ .rows li.none { display: block; padding: 10px; color: var(--text-3); font-size: var(--fs-xs); text-align: center; cursor: default; }
+ .picture {
+ width: 48px; height: 36px; display: grid; place-items: center; overflow: hidden;
+ border-radius: 3px; background: var(--bg-2); color: var(--text-3);
+ }
+ .picture img { width: 100%; height: 100%; object-fit: cover; }
+ .text { display: grid; min-width: 0; }
+ .name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: var(--fs-sm); }
+ .text small { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--text-3); font-size: var(--fs-xs); }
+</style>
diff --git a/frontend/src/components/EntitySummary.render.test.js b/frontend/src/components/EntitySummary.render.test.js
new file mode 100644
index 0000000..f5313dc
--- /dev/null
+++ b/frontend/src/components/EntitySummary.render.test.js
@@ -0,0 +1,101 @@
+// @vitest-environment happy-dom
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { flushSync, mount, unmount } from 'svelte';
+
+/** The top of Details: what an entity is, and what the case's events say about it. */
+
+const rows = {
+ o1: {
+ events: 5, first: '2026-03-11T00:00:00.000000Z', last: '2026-03-20T00:00:00.000000Z',
+ sources: 2, places: 1, buckets: [0, 0, 0, 0, 2, 1, 1, 0, 0, 1, 0, 0],
+ },
+ p1: { events: 0, first: null, last: null, sources: 0, places: 0, buckets: Array(12).fill(0) },
+};
+const post = vi.fn(async (_url, body) => ({ range: null, rows: { [body.ids[0]]: rows[body.ids[0]] } }));
+vi.mock('../lib/api.js', () => ({ api: { post, get: vi.fn(async () => []) } }));
+
+const uiState = { tool: 'board', timelineFocus: null };
+vi.mock('../lib/state.svelte.js', () => ({ caseState: { rev: 0, current: { id: 'case-a' } }, uiState }));
+vi.mock('../lib/entityTypes.svelte.js', () => ({
+ entityFamily: (type) => ({ organization: 'actor', person: 'actor', claim: 'claim' })[type] ?? null,
+ entityLabel: (type) => type.charAt(0).toUpperCase() + type.slice(1),
+}));
+vi.mock('../lib/entityIcon.js', () => ({ entityIcon: () => 'user' }));
+vi.mock('./EntryLine.svelte', async () => ({
+ default: (await import('./Modal.svelte')).default,
+ claimSeat: (entity) => (entity?.type === 'claim' ? null : { slot: 'about' }),
+}));
+
+const { default: EntitySummary } = await import('./EntitySummary.svelte');
+
+let live = null;
+let target = null;
+
+async function settle() {
+ for (let index = 0; index < 8; index += 1) await Promise.resolve();
+ flushSync();
+}
+
+async function show(entity) {
+ target = document.createElement('div');
+ document.body.append(target);
+ live = mount(EntitySummary, { target, props: { caseId: 'case-a', entity, onclose: vi.fn() } });
+ flushSync();
+ await settle();
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ uiState.tool = 'board';
+ uiState.timelineFocus = null;
+});
+
+afterEach(() => {
+ if (live) unmount(live);
+ live = null;
+ target?.remove();
+ document.querySelectorAll('[role="dialog"]').forEach((node) => node.remove());
+});
+
+describe('the summary above Details', () => {
+ it('names the entity, its type and its other names', async () => {
+ await show({ id: 'o1', type: 'organization', label: '4th brigade', attrs: { aliases: '4 Bde; 4th Mech' } });
+ expect(target.querySelector('h3').textContent).toBe('4th brigade');
+ expect(target.querySelector('.kind').textContent).toContain('Organization');
+ expect(target.querySelector('.also').textContent).toContain('4 Bde, 4th Mech');
+ });
+
+ it('says how many events name it, what they reach and when they fall', async () => {
+ await show({ id: 'o1', type: 'organization', label: '4th brigade', attrs: {} });
+ expect(target.querySelector('.facts').textContent).toBe('5 events · 2 sources · 1 place');
+ expect(target.querySelector('.span').textContent).toBe('11–19 Mar 2026');
+ expect(target.querySelector('svg.sparkline')).not.toBeNull();
+ expect(post).toHaveBeenCalledWith('/api/cases/case-a/catalog/events', { ids: ['o1'] });
+ });
+
+ it('opens the Timeline on the entity', async () => {
+ await show({ id: 'o1', type: 'organization', label: '4th brigade', attrs: {} });
+ [...target.querySelectorAll('button')].find((b) => b.textContent.includes('Timeline')).click();
+ expect(uiState.tool).toBe('timeline');
+ expect(uiState.timelineFocus).toMatchObject({ entityId: 'o1', entityLabel: '4th brigade' });
+ });
+
+ it('says when nothing names it yet, and offers the first event', async () => {
+ await show({ id: 'p1', type: 'person', label: 'Witness', attrs: {} });
+ expect(target.querySelector('.facts').textContent).toBe('No events yet');
+ const add = [...target.querySelectorAll('button')].find((b) => b.textContent.includes('Add event'));
+ expect(add.getAttribute('aria-expanded')).toBe('false');
+ add.click();
+ flushSync();
+ await settle();
+ expect(add.getAttribute('aria-expanded')).toBe('true');
+ expect(target.querySelector('.compose')).not.toBeNull();
+ });
+
+ it('adds nothing about a Claim, which is itself an event', async () => {
+ await show({ id: 'k1', type: 'claim', label: 'Column seen', attrs: {} });
+ expect(target.querySelector('.strip')).toBeNull();
+ expect([...target.querySelectorAll('button')].some((b) => b.textContent.includes('Add event'))).toBe(false);
+ expect(post).not.toHaveBeenCalled();
+ });
+});
diff --git a/frontend/src/components/EntitySummary.svelte b/frontend/src/components/EntitySummary.svelte
new file mode 100644
index 0000000..ebdfbf2
--- /dev/null
+++ b/frontend/src/components/EntitySummary.svelte
@@ -0,0 +1,277 @@
+<script>
+ /**
+ * The top of Details: what this is, and what the case's events say about it.
+ *
+ * The tabs below hold everything, and reading a subject used to mean opening
+ * Connections to count its Claims, then Time to see when they fell. This says it in
+ * one line above the tabs: how many events name it, the sources and places they
+ * reach, and when they fall across the case's own span. It is also where the next
+ * event is added, already about this entity, because that is the question an
+ * entity's page most often raises.
+ *
+ * One read per entity shown (`/catalog/events`), refreshed with the case.
+ */
+ import { tick } from 'svelte';
+ import { caseState, uiState } from '../lib/state.svelte.js';
+ import { fetchEventRows } from '../lib/catalog.js';
+ import { entityFamily, entityLabel } from '../lib/entityTypes.svelte.js';
+ import { entityIcon } from '../lib/entityIcon.js';
+ import { eventWords, spanWords } from '../lib/boardGroups.js';
+ import { claimActionTitle } from '../lib/quickClaim.js';
+ import EntryLine, { claimSeat } from './EntryLine.svelte';
+ import Icon from './Icon.svelte';
+ import Sparkline from './Sparkline.svelte';
+
+ let { caseId, entity, onclose } = $props();
+
+ let events = $state(null);
+ let composing = $state(false);
+ let line = $state(null);
+ let seq = 0;
+
+ /** Open the line on the sentence, since that is what the press was for. */
+ async function compose() {
+ composing = !composing;
+ if (!composing) return;
+ await tick();
+ line?.focus?.();
+ }
+
+ const seat = $derived(claimSeat(entity));
+ const isClaim = $derived(entity?.type === 'claim');
+ const family = $derived(entityFamily(entity?.type) ?? 'other');
+ /** Other names, as the analyst wrote them: the field is one text, split on the
+ * separators people use for a list. Two at most, the rest is in Info. */
+ const aliases = $derived(
+ String(entity?.attrs?.aliases ?? '')
+ .split(/[;,\n]/)
+ .map((name) => name.trim())
+ .filter(Boolean)
+ );
+
+ $effect(() => {
+ const id = entity?.id;
+ caseState.rev; // an event added, moved or deleted changes every number here
+ const mine = ++seq;
+ if (!id || !caseId || isClaim) {
+ events = null;
+ return;
+ }
+ fetchEventRows(caseId, [id])
+ .then((body) => {
+ if (mine === seq) events = body?.rows?.[id] ?? null;
+ })
+ .catch(() => {
+ if (mine === seq) events = null;
+ });
+ });
+
+ // A composer belongs to the entity it was opened on.
+ let composedFor = null;
+ $effect(() => {
+ if (entity?.id !== composedFor) {
+ composedFor = entity?.id ?? null;
+ composing = false;
+ }
+ });
+
+ const span = $derived(events ? spanWords(events.first, events.last) : '');
+ const facts = $derived.by(() => {
+ if (!events) return [];
+ const out = [eventWords(events.events)];
+ if (events.sources) out.push(`${events.sources} source${events.sources === 1 ? '' : 's'}`);
+ if (events.places) out.push(`${events.places} place${events.places === 1 ? '' : 's'}`);
+ return out;
+ });
+
+ function openTimeline() {
+ uiState.timelineFocus = {
+ entityId: entity.id,
+ entityLabel: entity.label,
+ entityType: entity.type,
+ entityAttrs: entity.attrs ?? {},
+ itemId: null,
+ producedHere: false,
+ };
+ uiState.tool = 'timeline';
+ onclose?.();
+ }
+</script>
+
+{#if entity}
+ <header class="summary" style="--tone: var(--graph-{family}, var(--text-3))">
+ <div class="who">
+ <span class="badge" aria-hidden="true"><Icon name={entityIcon(entity)} size={15} /></span>
+ <div class="names">
+ <h3 dir="auto" title={entity.label}>{entity.label}</h3>
+ <p class="kind">
+ <span>{entityLabel(entity.type)}</span>
+ {#if aliases.length}
+ <span class="also" title={aliases.join(' · ')}>
+ also <bdi>{aliases.slice(0, 2).join(', ')}</bdi>{aliases.length > 2 ? '…' : ''}
+ </span>
+ {/if}
+ {#if entity.provenance?.status === 'suggested'}<span class="tag">suggested</span>{/if}
+ </p>
+ </div>
+ {#if seat}
+ <button
+ class="btn btn-sm add"
+ class:on={composing}
+ aria-expanded={composing}
+ title={claimActionTitle(seat.slot)}
+ onclick={compose}
+ >
+ <Icon name="plus" size={12} /> Add event
+ </button>
+ {/if}
+ </div>
+
+ {#if events && (events.events || seat)}
+ <div class="strip">
+ {#if events.events}
+ <span class="facts">{facts.join(' · ')}</span>
+ {#if span}
+ <Sparkline buckets={events.buckets} label="When its events fall across the case" />
+ <span class="span">{span}</span>
+ {/if}
+ <button class="as-link" title="Read its events in the Timeline" onclick={openTimeline}>
+ Timeline <Icon name="chevronRight" size={11} />
+ </button>
+ {:else}
+ <span class="facts none">No events yet</span>
+ {/if}
+ </div>
+ {/if}
+
+ {#if composing && seat}
+ <div class="compose">
+ <EntryLine
+ bind:this={line}
+ {caseId}
+ {entity}
+ draftKey={`details:${entity.id}`}
+ onsaved={() => (composing = false)}
+ oncancel={() => (composing = false)}
+ />
+ </div>
+ {/if}
+ </header>
+{/if}
+
+<style>
+ .summary {
+ display: grid;
+ gap: 8px;
+ padding: 2px 0 10px;
+ margin-bottom: 6px;
+ border-bottom: 1px solid var(--border);
+ }
+ .who {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ min-width: 0;
+ }
+ /* The family's own colour, the one its nodes wear in the Graph, so the same thing
+ reads as the same thing on both screens. */
+ .badge {
+ display: grid;
+ place-items: center;
+ width: 32px;
+ height: 32px;
+ flex-shrink: 0;
+ border-radius: 50%;
+ background: color-mix(in srgb, var(--tone) 22%, transparent);
+ color: var(--tone);
+ }
+ .names {
+ flex: 1;
+ min-width: 0;
+ }
+ h3 {
+ margin: 0;
+ overflow: hidden;
+ color: var(--text-1);
+ font-size: var(--fs-lg);
+ font-weight: 600;
+ line-height: 1.25;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ .kind {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: 6px;
+ margin: 2px 0 0;
+ color: var(--text-3);
+ font-size: var(--fs-xs);
+ }
+ .also {
+ overflow: hidden;
+ max-width: 260px;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ .also::before {
+ content: '·';
+ margin-right: 6px;
+ }
+ .tag {
+ padding: 1px 6px;
+ border-radius: 999px;
+ background: var(--accent-soft);
+ color: var(--accent);
+ font-size: 10px;
+ }
+ .add {
+ flex-shrink: 0;
+ }
+ .add.on {
+ border-color: var(--accent);
+ color: var(--accent);
+ }
+ .strip {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ min-height: 22px;
+ padding: 5px 10px;
+ border-radius: var(--r-md);
+ background: var(--bg-2);
+ color: var(--text-2);
+ font-size: var(--fs-xs);
+ }
+ .facts {
+ margin-right: auto;
+ color: var(--text-1);
+ white-space: nowrap;
+ }
+ .facts.none {
+ color: var(--text-3);
+ }
+ .span {
+ color: var(--text-3);
+ font-variant-numeric: tabular-nums;
+ white-space: nowrap;
+ }
+ .as-link {
+ display: inline-flex;
+ align-items: center;
+ gap: 2px;
+ padding: 0;
+ border: 0;
+ background: none;
+ color: var(--accent);
+ font: inherit;
+ cursor: pointer;
+ white-space: nowrap;
+ }
+ .as-link:hover {
+ text-decoration: underline;
+ }
+ .compose {
+ padding-top: 2px;
+ }
+</style>
diff --git a/frontend/src/components/EntityTime.svelte b/frontend/src/components/EntityTime.svelte
index 82ab3ba..f0a2935 100644
--- a/frontend/src/components/EntityTime.svelte
+++ b/frontend/src/components/EntityTime.svelte
@@ -100,13 +100,20 @@
}
function openTimeline(item = null) {
- uiState.timelineFocus = { entityId: entity.id, entityLabel: entity.label, itemId: item?.id ?? null };
+ uiState.timelineFocus = {
+ entityId: entity.id,
+ entityLabel: entity.label,
+ entityType: entity.type,
+ entityAttrs: entity.attrs ?? {},
+ itemId: item?.id ?? null,
+ producedHere: item?.produced_here === true,
+ };
uiState.tool = 'timeline';
onclose?.();
}
function timeLabel(item) {
- return formatTemporalValue(item.raw ?? '').label;
+ return formatTemporalValue(item.raw ?? '', item.tz).label;
}
</script>
diff --git a/frontend/src/components/EntityTime.test.js b/frontend/src/components/EntityTime.test.js
index 3c29841..ef5d55c 100644
--- a/frontend/src/components/EntityTime.test.js
+++ b/frontend/src/components/EntityTime.test.js
@@ -37,7 +37,9 @@ describe('entity Time tab', () => {
});
it('hands the visible entity scope to the global Timeline', () => {
- expect(source).toContain('uiState.timelineFocus = { entityId: entity.id, entityLabel: entity.label');
+ expect(source).toContain('uiState.timelineFocus = {\n entityId: entity.id,\n entityLabel: entity.label,');
+ // a working file says so, or a Media track holding them back would hide the row
+ expect(source).toContain('producedHere: item?.produced_here === true,');
expect(source).toContain("uiState.tool = 'timeline'");
});
@@ -49,7 +51,7 @@ describe('entity Time tab', () => {
});
it('uses the Timeline visual language and separates unresolved dates', () => {
- expect(source).toContain('formatTemporalValue(item.raw ?? \'\').label');
+ expect(source).toContain('formatTemporalValue(item.raw ?? \'\', item.tz).label');
expect(source).toContain('var(--timeline-statement)');
expect(source).toContain('Not on UTC axis');
expect(source).toContain('Undated <span>{visibleUndated.length}</span>');
diff --git a/frontend/src/components/EntryLine.render.test.js b/frontend/src/components/EntryLine.render.test.js
new file mode 100644
index 0000000..ea6d60c
--- /dev/null
+++ b/frontend/src/components/EntryLine.render.test.js
@@ -0,0 +1,707 @@
+// @vitest-environment happy-dom
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { flushSync, mount, unmount } from 'svelte';
+
+/**
+ * The entry line, filled the way an analyst fills it: one thing to say is enough, the
+ * entity it was opened from already in its seat, `@` for the rest, a date only when
+ * one is given, and one request that files the whole entry.
+ */
+
+const CONDITIONS = [
+ { value: 'intact', label: 'Intact' },
+ { value: 'damaged', label: 'Damaged' },
+ { value: 'destroyed', label: 'Destroyed' },
+ { value: 'abandoned', label: 'Abandoned' },
+];
+const TYPES = [
+ { type: 'person', family: 'actor', label: 'Person', attrs: [{ key: 'aliases', label: 'Other names', kind: 'text' }], manual: true },
+ { type: 'organization', family: 'actor', label: 'Organization', attrs: [], manual: true },
+ { type: 'vehicle', family: 'asset', label: 'Vehicle', attrs: [{ key: 'plate', label: 'Plate', kind: 'text' }], manual: true },
+ { type: 'equipment-type', family: 'class', label: 'Equipment type', attrs: [], manual: true },
+ { type: 'account', family: 'identifier', label: 'Account', attrs: [], manual: true },
+ { type: 'email', family: 'identifier', label: 'Email', attrs: [], manual: true },
+ { type: 'place', family: 'place', label: 'Place', attrs: [{ key: 'aliases', label: 'Other names', kind: 'text' }] },
+ { type: 'media', family: 'collected', label: 'Media', attrs: [] },
+ {
+ type: 'claim',
+ family: 'claim',
+ label: 'Claim',
+ manual: true,
+ attrs: [
+ { key: 'count', label: 'How many', kind: 'number', minimum: 1, maximum: 100000 },
+ { key: 'condition', label: 'Condition', kind: 'choice', options: CONDITIONS },
+ {
+ key: 'confidence',
+ label: 'Confidence',
+ kind: 'choice',
+ options: [
+ { value: 'certain', label: 'Certain' },
+ { value: 'probable', label: 'Probable' },
+ ],
+ },
+ ],
+ },
+];
+const SUBJECTS = ['equipment-type', 'vehicle', 'person', 'organization', 'account', 'email', 'place', 'media'];
+const verb = (type, to) => ({ type, label: type, action: 'claim', manual: true, from_types: ['claim'], to_types: to });
+const RELATIONS = [
+ verb('about', SUBJECTS),
+ verb('at', ['place']),
+ verb('cites', ['media', 'claim']),
+];
+
+const KHARKIV = { id: 'place-k', type: 'place', label: 'Kharkiv', attrs: { lat: 49.99, lon: 36.23 } };
+const LVIV = { id: 'place-l', type: 'place', label: 'Lviv', attrs: { lat: 49.84, lon: 24.03 } };
+const LISBON = { id: 'place-p', type: 'place', label: 'Lisbon', attrs: { lat: 38.72, lon: -9.14 } };
+const CROSSROADS = { id: 'place-1', type: 'place', label: 'Crossroads North', attrs: { aliases: 'Perekhrestia; X-roads' } };
+const TRUCK = { id: 'v-1', type: 'vehicle', label: 'Bridge truck', attrs: { plate: 'AA1234' } };
+
+let catalog = [];
+let twin = null;
+const get = vi.fn(async (url) => {
+ if (url.includes('/entity-types')) return TYPES;
+ if (url.includes('/relation-types')) return RELATIONS;
+ if (url.includes('/confidence-levels')) return [];
+ if (url.includes('/catalog/summary')) return { total: 6, by_type: { organization: 3, person: 1, media: 1, claim: 1 } };
+ if (url.includes('/entities/twin')) return { entity: twin };
+ if (url.includes('/api/geo/zone')) {
+ const lon = Number(new URL(url, 'http://x').searchParams.get('lon'));
+ return { name: lon > 30 ? 'Europe/Kyiv' : lon > 20 ? 'Europe/Kyiv' : 'Europe/Lisbon' };
+ }
+ if (url.includes('/catalog/entities')) return { items: catalog };
+ return { items: [] };
+});
+const post = vi.fn(async () => ({ entity: { id: 'claim-1' }, created: [], links: [] }));
+vi.mock('../lib/api.js', () => ({ api: { get, post } }));
+
+const reloadCase = vi.fn(async () => {});
+const toast = vi.fn();
+vi.mock('../lib/state.svelte.js', () => ({ reloadCase, toast, caseState: { current: { id: 'case-a' } } }));
+
+const { default: EntryLine, claimSeat } = await import('./EntryLine.svelte');
+const { forgetZones } = await import('../lib/localZone.js');
+const { forgetAxisZone, noteAxisZone } = await import('../lib/caseAxis.svelte.js');
+
+let live = null;
+let target = null;
+
+async function settle() {
+ for (let index = 0; index < 16; index += 1) await Promise.resolve();
+ flushSync();
+}
+
+async function open(entity = null, props = {}) {
+ target = document.createElement('div');
+ document.body.append(target);
+ live = mount(EntryLine, { target, props: { caseId: 'case-a', entity, ...props } });
+ await settle();
+ return live;
+}
+
+function close() {
+ if (live) unmount(live);
+ live = null;
+ target?.remove();
+}
+
+const sentence = () => target.querySelector('input[aria-label="What happened"]');
+const dateField = () => target.querySelector('input[aria-label="When"]');
+const count = () => target.querySelector('input[type="number"]');
+const conditionSelect = () =>
+ [...target.querySelectorAll('select')].find((s) => [...s.options].some((o) => o.value === 'destroyed'));
+const button = (name) => [...document.querySelectorAll('button')].find((b) => b.textContent.trim() === name);
+const addButton = () => button('Add');
+const options = () => [...target.querySelectorAll('[role="option"]')];
+const chips = () => [...target.querySelectorAll('.chip')].map((chip) => chip.textContent.replace(/\s+/g, ' ').trim());
+
+function type(element, value) {
+ element.value = value;
+ if (element.type === 'text') element.setSelectionRange(value.length, value.length);
+ element.dispatchEvent(new Event('input', { bubbles: true }));
+ flushSync();
+}
+
+function choose(element, value) {
+ element.value = value;
+ element.dispatchEvent(new Event('change', { bubbles: true }));
+ flushSync();
+}
+
+function key(element, name, extra = {}) {
+ element.dispatchEvent(new KeyboardEvent('keydown', { key: name, bubbles: true, cancelable: true, ...extra }));
+ flushSync();
+}
+
+const MODEL = { id: 'model-1', type: 'equipment-type', label: 'T-72B3' };
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ catalog = [];
+ twin = null;
+ forgetZones();
+});
+
+afterEach(close);
+
+describe('filed from a model', () => {
+ it('opens on how many and in what state, and writes the sentence from them', async () => {
+ await open(MODEL);
+
+ expect(count()).not.toBeNull();
+ expect(conditionSelect()).not.toBeUndefined();
+ expect(sentence().value).toBe('T-72B3 seen');
+
+ type(count(), '2');
+ choose(conditionSelect(), 'destroyed');
+ expect(sentence().value).toBe('2 × T-72B3 destroyed');
+ });
+
+ it('files the observation about the model in one request, then refreshes the case', async () => {
+ const onsaved = vi.fn();
+ await open(MODEL, { onsaved });
+ type(count(), '2');
+ choose(conditionSelect(), 'destroyed');
+
+ addButton().click();
+ await settle();
+
+ expect(post).toHaveBeenCalledWith('/api/cases/case-a/timeline/claims', {
+ statement: '2 × T-72B3 destroyed',
+ when: null,
+ time_role: null,
+ confidence: null,
+ count: 2,
+ condition: 'destroyed',
+ about: ['model-1'],
+ at: [],
+ cites: [],
+ create: [],
+ });
+ expect(reloadCase).toHaveBeenCalled();
+ expect(onsaved).toHaveBeenCalled();
+ });
+
+ it('keeps a sentence the analyst wrote when a field changes under it', async () => {
+ await open(MODEL);
+ type(sentence(), 'Two tanks burning near the bridge');
+ type(count(), '3');
+
+ expect(sentence().value).toBe('Two tanks burning near the bridge');
+ button('Rewrite from the mentions').click();
+ flushSync();
+ expect(sentence().value).toBe('3 × T-72B3 seen');
+ });
+});
+
+describe('filed from something else', () => {
+ it('asks a named object for its state and never for a count', async () => {
+ await open(TRUCK);
+ expect(count()).toBeNull();
+ expect(conditionSelect()).not.toBeUndefined();
+ });
+
+ it('asks a person for neither, and keeps them folded away', async () => {
+ await open({ id: 'p-1', type: 'person', label: 'Ivan' });
+ expect(count()).toBeNull();
+ expect(conditionSelect()).toBeUndefined();
+ expect(sentence().value).toBe('Ivan seen');
+ });
+
+ it('seats a place where it was seen', async () => {
+ await open({ id: 'place-1', type: 'place', label: 'Crossroads' });
+ expect(sentence().value).toBe('Seen at Crossroads');
+
+ type(sentence(), 'Convoy seen at Crossroads');
+ addButton().click();
+ await settle();
+ expect(post.mock.calls[0][1]).toMatchObject({ about: [], at: ['place-1'], cites: [] });
+ });
+
+ it('seats a video as the source and says it was seen in it', async () => {
+ await open({ id: 'm-1', type: 'media', label: 'clip.mp4', attrs: { kind: 'video' } });
+ expect(sentence().value).toBe('Seen in clip.mp4');
+ // A date is never offered from the file: the line opens with none.
+ expect(dateField().value).toBe('');
+
+ addButton().click();
+ await settle();
+ expect(post.mock.calls[0][1]).toMatchObject({ statement: 'Seen in clip.mp4', when: null, about: [], at: [], cites: ['m-1'] });
+ });
+});
+
+describe('what the line asks for', () => {
+ it('needs one thing to say, and says so on the button', async () => {
+ await open();
+ expect(addButton().disabled).toBe(true);
+ expect(addButton().title).toBe('Write what happened, mention a subject or cite a source');
+
+ type(sentence(), 'Explosions heard');
+ expect(addButton().disabled).toBe(false);
+ });
+
+ it('holds back a date it cannot read, and not an empty one', async () => {
+ await open();
+ type(sentence(), 'Explosions heard');
+ type(dateField(), '12/03/26');
+ expect(addButton().disabled).toBe(true);
+ expect(addButton().title).toBe('Correct the date or clear it');
+
+ type(dateField(), '');
+ expect(addButton().disabled).toBe(false);
+
+ type(dateField(), 'mars 2026');
+ expect(target.textContent).toContain('Reads: Mar 2026');
+ key(sentence(), 'Enter');
+ await settle();
+ expect(post.mock.calls[0][1]).toMatchObject({ statement: 'Explosions heard', when: '2026-03', time_role: 'observed' });
+ });
+
+ it('empties after adding and keeps the sentence for the next one, with an Undo', async () => {
+ post.mockResolvedValueOnce({ entity: { id: 'claim-9' }, created: [{ id: 'org-1' }], links: [] });
+ await open();
+ type(sentence(), 'Explosions heard');
+ key(sentence(), 'Enter');
+ await settle();
+
+ expect(sentence().value).toBe('');
+ expect(document.activeElement).toBe(sentence());
+ const [message, kind, , action] = toast.mock.calls.at(-1);
+ expect([message, kind, action.label]).toEqual(['Added', 'ok', 'Undo']);
+
+ await action.onClick();
+ expect(post).toHaveBeenLastCalledWith('/api/cases/case-a/entities/delete', { ids: ['claim-9', 'org-1'] });
+ });
+
+ it('keeps everything and says why when the case refuses', async () => {
+ post.mockRejectedValueOnce(new Error("entity 'place-1' not found"));
+ await open({ id: 'place-1', type: 'place', label: 'Crossroads' });
+ addButton().click();
+ await settle();
+
+ expect(sentence().value).toBe('Seen at Crossroads');
+ expect(target.querySelector('[role="alert"]').textContent).toContain('not found');
+ });
+
+ it('files from any field with Ctrl+Enter', async () => {
+ await open();
+ type(sentence(), 'Explosions heard');
+ key(dateField(), 'Enter', { ctrlKey: true });
+ await settle();
+ expect(post).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe('mentions', () => {
+ it('offers an exact other name first and says which field matched', async () => {
+ catalog = [TRUCK, { id: 'place-2', type: 'place', label: 'X-roads market' }, CROSSROADS];
+ await open();
+ type(sentence(), 'Convoy at @X-roads');
+ await settle();
+
+ const names = options().map((option) => option.querySelector('.name').textContent);
+ expect(names[0]).toBe('Crossroads North');
+ expect(options()[0].textContent).toContain('Also known as: X-roads');
+ expect(names.at(-1)).toBe('New · X-roads');
+ expect(get.mock.calls.some(([url]) => url.includes('/catalog/entities') && url.includes('q=X-roads'))).toBe(true);
+ });
+
+ it('puts the chosen name in the sentence and the subject in its seat', async () => {
+ catalog = [CROSSROADS, TRUCK];
+ await open();
+ type(sentence(), 'Convoy at @Cross');
+ await settle();
+ key(sentence(), 'Enter');
+ await settle();
+
+ expect(sentence().value).toBe('Convoy at Crossroads North ');
+ expect(chips()).toEqual([expect.stringContaining('Crossroads North at')]);
+
+ type(sentence(), 'Convoy at Crossroads North with @AA12');
+ await settle();
+ key(sentence(), 'ArrowDown');
+ key(sentence(), 'ArrowUp');
+ key(sentence(), 'Tab');
+ await settle();
+ expect(chips()[1]).toContain('Bridge truck about');
+
+ addButton().click();
+ await settle();
+ expect(post.mock.calls[0][1]).toMatchObject({ at: ['place-1'], about: ['v-1'], create: [] });
+ });
+
+ it('shows the field that matched when it is not the name', async () => {
+ catalog = [TRUCK];
+ await open();
+ type(sentence(), '@AA12');
+ await settle();
+ expect(options()[0].textContent).toContain('Plate: AA1234');
+ });
+
+ it('keeps a literal @ as text on Escape', async () => {
+ catalog = [TRUCK];
+ await open();
+ type(sentence(), 'Mail @ops');
+ await settle();
+ expect(options().length).toBeGreaterThan(0);
+ key(sentence(), 'Escape');
+ expect(target.querySelector('[role="listbox"]')).toBeNull();
+ expect(sentence().value).toBe('Mail @ops');
+ expect(chips()).toEqual([]);
+ });
+
+ it('never opens a mention inside an address', async () => {
+ await open();
+ type(sentence(), 'Wrote to [email protected]');
+ await settle();
+ expect(target.querySelector('[role="listbox"]')).toBeNull();
+ });
+
+ it('removes a mention with a click on its chip, and moves it with Alt+↓', async () => {
+ catalog = [TRUCK];
+ await open();
+ type(sentence(), '@Bridge');
+ await settle();
+ key(sentence(), 'Enter');
+ await settle();
+ const chip = target.querySelector('.chip-name');
+ chip.click();
+ flushSync();
+ expect(chips()).toEqual([]);
+
+ catalog = [CROSSROADS];
+ type(sentence(), '@Cross');
+ await settle();
+ key(sentence(), 'Enter');
+ await settle();
+ expect(chips()[0]).toContain('Crossroads North at');
+ // A place can also be what the entry is about.
+ key(target.querySelector('.chip-name'), 'ArrowDown', { altKey: true });
+ expect(chips()[0]).toContain('Crossroads North about');
+ addButton().click();
+ await settle();
+ expect(post.mock.calls[0][1]).toMatchObject({ about: ['place-1'], at: [] });
+ });
+});
+
+describe('a new subject', () => {
+ it('is guessed from its shape, says its rule, and is created only with the line', async () => {
+ await open();
+ type(sentence(), 'Mail from @[email protected]');
+ await settle();
+ const created = options().at(-1);
+ expect(created.textContent).toContain('New · [email protected]');
+ expect(created.textContent).toContain('Email · looks like an email');
+ key(sentence(), 'Enter');
+ await settle();
+
+ expect(chips()[0]).toContain('new · looks like an email');
+ expect(post).not.toHaveBeenCalled();
+
+ addButton().click();
+ await settle();
+ expect(post.mock.calls[0][1]).toMatchObject({
+ statement: 'Mail from [email protected]',
+ about: [],
+ create: [{ slot: 'about', type: 'email', label: '[email protected]' }],
+ });
+ });
+
+ it('takes the type the case uses most when its shape says nothing', async () => {
+ await open();
+ type(sentence(), '@4th brigade');
+ await settle();
+ expect(options().at(-1).textContent).toContain('Organization · the type this case uses most');
+ });
+
+ it('can be retyped from its chip', async () => {
+ await open();
+ type(sentence(), '@Ivan');
+ await settle();
+ key(sentence(), 'Enter');
+ await settle();
+ const retype = target.querySelector('select.retype');
+ expect([...retype.options].map((option) => option.value)).not.toContain('place');
+ choose(retype, 'person');
+ await settle();
+ addButton().click();
+ await settle();
+ expect(post.mock.calls[0][1].create).toEqual([{ slot: 'about', type: 'person', label: 'Ivan' }]);
+ });
+
+ it('offers the identifier the case already holds, without refusing the new one', async () => {
+ twin = { id: 'mail-1', type: 'email', label: '[email protected]' };
+ await open();
+ type(sentence(), '@[email protected]');
+ await settle();
+ key(sentence(), 'Enter');
+ await settle();
+
+ expect(addButton().disabled).toBe(false);
+ button('Use the one in the case').click();
+ flushSync();
+ addButton().click();
+ await settle();
+ expect(post.mock.calls[0][1]).toMatchObject({ about: ['mail-1'], create: [] });
+ });
+});
+
+describe('the time at the place', () => {
+ const clockSays = () => target.querySelector('.clock-trigger')?.getAttribute('aria-label');
+ /** Open the Clock and press the row named `words`, searching for it first. */
+ function pickClock(words, search = '') {
+ target.querySelector('.clock-trigger').click();
+ flushSync();
+ if (search) type(document.querySelector('.clock-menu .search-input'), search);
+ const row = [...document.querySelectorAll('.clock-menu .rows > button')]
+ .find((entry) => entry.querySelector('span').textContent === words);
+ row.click();
+ flushSync();
+ }
+
+ it('reads an hour as the local time at the one place, summer or winter', async () => {
+ await open(KHARKIV);
+ type(sentence(), 'Strike reported');
+ type(dateField(), '11/08/2026 17:05');
+ await settle();
+ expect(target.textContent).toContain('Reads: 11 Aug 2026, 17:05:00 Europe/Kyiv (UTC+03:00)');
+ expect(clockSays()).toBe('Clock: Kharkiv UTC+03:00');
+
+ addButton().click();
+ await settle();
+ expect(post.mock.calls[0][1]).toMatchObject({ when: '2026-08-11T17:05:00+03:00', when_zone: 'Europe/Kyiv' });
+
+ type(sentence(), 'Second strike');
+ type(dateField(), '11/01/2026 17:05');
+ await settle();
+ addButton().click();
+ await settle();
+ expect(post.mock.calls[1][1].when).toBe('2026-01-11T17:05:00+02:00');
+ // One zone read per point, however many times the hour changes.
+ expect(get.mock.calls.filter(([url]) => url.includes('/api/geo/zone'))).toHaveLength(1);
+ });
+
+ it('never replaces a clock the analyst typed, and can leave it unknown', async () => {
+ await open(KHARKIV);
+ type(sentence(), 'Strike reported');
+ type(dateField(), '11/08/2026 17:05 UTC');
+ await settle();
+ expect(clockSays()).toBe('Clock: UTC');
+ addButton().click();
+ await settle();
+ expect(post.mock.calls[0][1].when).toBe('2026-08-11T17:05:00Z');
+ expect(post.mock.calls[0][1]).not.toHaveProperty('when_zone');
+
+ type(sentence(), 'Strike reported');
+ type(dateField(), '11/08/2026 17:05');
+ await settle();
+ pickClock('Clock unknown');
+ addButton().click();
+ await settle();
+ expect(post.mock.calls[1][1].when).toBe('2026-08-11T17:05:00');
+ });
+
+ it('reads on UTC when two places disagree, and offers each', async () => {
+ catalog = [LISBON];
+ await open(KHARKIV);
+ type(sentence(), 'Seen at Kharkiv and @Lisbon');
+ await settle();
+ key(sentence(), 'Enter');
+ await settle();
+ type(dateField(), '11/08/2026 17:05');
+ await settle();
+
+ expect(clockSays()).toBe('Clock: UTC');
+ pickClock('Local at Lisbon');
+ addButton().click();
+ await settle();
+ expect(post.mock.calls[0][1]).toMatchObject({ when: '2026-08-11T17:05:00+01:00', when_zone: 'Europe/Lisbon' });
+ });
+
+ it('reads a day as the day at the place, and as a UTC day once picked', async () => {
+ await open(KHARKIV);
+ type(sentence(), 'Strike reported');
+ type(dateField(), '12/03/2024');
+ await settle();
+ expect(target.textContent).toContain('Reads: 12 Mar 2024 (Europe/Kyiv)');
+ addButton().click();
+ await settle();
+ expect(post.mock.calls[0][1]).toMatchObject({ when: '2024-03-12', when_zone: 'Europe/Kyiv' });
+
+ type(sentence(), 'Strike reported');
+ type(dateField(), '12/03/2024');
+ await settle();
+ pickClock('UTC');
+ addButton().click();
+ await settle();
+ expect(post.mock.calls[1][1].when).toBe('2024-03-12');
+ expect(post.mock.calls[1][1]).not.toHaveProperty('when_zone');
+ });
+
+ it('opens a date with no place on the case’s clock, the one its axis reads on', async () => {
+ noteAxisZone('case-a', 'America/Los_Angeles');
+ try {
+ await open(null);
+ type(sentence(), 'Convoy seen');
+ type(dateField(), '10/09/2026');
+ await settle();
+ expect(clockSays()).toBe('Clock: Los Angeles UTC-07:00');
+ addButton().click();
+ await settle();
+ expect(post.mock.calls[0][1]).toMatchObject({ when: '2026-09-10', when_zone: 'America/Los_Angeles' });
+ } finally {
+ forgetAxisZone();
+ }
+ });
+
+ it('gives a day any zone in the world, with no place on the line', async () => {
+ await open(null);
+ type(sentence(), 'Convoy seen');
+ type(dateField(), '10/09/2026');
+ await settle();
+ expect(clockSays()).toBe('Clock: UTC');
+
+ pickClock('Tokyo', 'tokyo');
+ // the pick holds while the day is corrected
+ type(dateField(), '11/09/2026');
+ await settle();
+ expect(target.textContent).toContain('Reads: 11 Sep 2026 (Asia/Tokyo)');
+ addButton().click();
+ await settle();
+ expect(post.mock.calls[0][1]).toMatchObject({ when: '2026-09-11', when_zone: 'Asia/Tokyo' });
+ });
+
+ it('counts two places in one zone as one choice', async () => {
+ catalog = [LVIV];
+ await open(KHARKIV);
+ type(sentence(), 'Seen in @Lviv');
+ await settle();
+ key(sentence(), 'Enter');
+ await settle();
+ type(dateField(), '11/08/2026 17:05');
+ await settle();
+ expect(clockSays()).toBe('Clock: Kharkiv UTC+03:00');
+ });
+});
+
+describe('help where it is needed', () => {
+ it('says what a date can be while its field is empty and focused', async () => {
+ await open();
+ dateField().dispatchEvent(new FocusEvent('focusin', { bubbles: true }));
+ flushSync();
+ const help = target.querySelector('.help').textContent;
+ for (const example of ['12/03/2026', '12/03/2026 14:30', 'March 2026', '~2026', '2026?', '12/03/2026 to 15/03/2026']) {
+ expect(help).toContain(example);
+ }
+ expect(help).toContain('Or leave it empty: the entry waits in Undated.');
+
+ type(dateField(), 'mars 2026');
+ expect(target.querySelector('.help')).toBeNull();
+ expect(target.textContent).toContain('Reads: Mar 2026');
+ });
+
+ it('says how the sentence works while it is empty and focused', async () => {
+ await open();
+ sentence().dispatchEvent(new FocusEvent('focusin', { bubbles: true }));
+ flushSync();
+ expect(target.querySelector('.help').textContent).toContain('mentions a person, a place or a file');
+ type(sentence(), 'Explosions heard');
+ expect(target.querySelector('.help')).toBeNull();
+ });
+
+ it('builds a date from the calendar for someone who would rather point at it', async () => {
+ await open();
+ target.querySelector('button[aria-label="Build the date"]').click();
+ flushSync();
+ expect(target.querySelector('.calendar-panel')).not.toBeNull();
+ button('Today').click();
+ flushSync();
+ expect(dateField().value).toMatch(/^\d{2}\/\d{2}\/\d{4}$/);
+
+ document.body.dispatchEvent(new Event('pointerdown', { bubbles: true }));
+ flushSync();
+ expect(target.querySelector('.calendar-panel')).toBeNull();
+ });
+
+ it('cites a source picked by its kind from the paperclip', async () => {
+ catalog = [
+ { id: 'm-1', type: 'media', label: 'clip.mp4', attrs: { kind: 'video' } },
+ { id: 'c-9', type: 'claim', label: 'Earlier finding' },
+ ];
+ await open();
+ target.querySelector('button[aria-label="Cite a source"]').click();
+ await settle();
+
+ const kinds = [...target.querySelectorAll('[aria-label="Kinds"] button')].map((chip) => chip.textContent.trim());
+ expect(kinds).toEqual(['All', 'Media1', 'Claim1']);
+ const finder = get.mock.calls.map(([url]) => url).filter((url) => url.includes('/catalog/entities')).at(-1);
+ expect(finder).toContain('order=-created');
+ expect(finder).toContain('previews=true');
+
+ target.querySelector('.sources-panel [role="option"]').dispatchEvent(new Event('pointerdown', { bubbles: true, cancelable: true }));
+ flushSync();
+ expect(target.querySelector('.sources-panel')).toBeNull();
+ expect(chips()[0]).toContain('clip.mp4 source');
+ expect(sentence().value).toBe('Seen in clip.mp4');
+
+ addButton().click();
+ await settle();
+ expect(post.mock.calls[0][1]).toMatchObject({ statement: 'Seen in clip.mp4', cites: ['m-1'] });
+ });
+});
+
+describe('more, and the full editor', () => {
+ it('asks a confidence and hands the whole draft to the full editor', async () => {
+ catalog = [TRUCK];
+ await open();
+ type(sentence(), 'Truck at the bridge @Bridge');
+ await settle();
+ key(sentence(), 'Enter');
+ await settle();
+ type(dateField(), 'mars 2026');
+ button('More').click();
+ flushSync();
+ const confidence = [...target.querySelectorAll('select')].find((s) => [...s.options].some((o) => o.value === 'probable'));
+ choose(confidence, 'probable');
+
+ button('Full editor').click();
+ await settle();
+ const dialog = document.querySelector('[role="dialog"]');
+ expect(dialog.querySelector('#temporal-statement').value).toBe('Truck at the bridge Bridge truck');
+ expect(dialog.textContent).toContain('Bridge truck');
+ expect([...dialog.querySelectorAll('select')].some((s) => s.value === 'probable')).toBe(true);
+ });
+});
+
+describe('a draft', () => {
+ it('is kept for the session under its key, and dropped once added', async () => {
+ await open(null, { draftKey: 'timeline:' });
+ type(sentence(), 'Half written');
+ close();
+
+ await open(null, { draftKey: 'timeline:' });
+ expect(sentence().value).toBe('Half written');
+ addButton().click();
+ await settle();
+ close();
+
+ await open(null, { draftKey: 'timeline:' });
+ expect(sentence().value).toBe('');
+ });
+
+ it('takes a date offered from the axis and goes to the sentence', async () => {
+ const line = await open();
+ line.offer('2026-03-12');
+ await settle();
+ expect(dateField().value).toBe('12/03/2026');
+ expect(document.activeElement).toBe(sentence());
+ });
+});
+
+describe('claimSeat', () => {
+ it('offers no seat on a claim itself, which has its own editor', async () => {
+ await open(MODEL); // lands both registries
+ expect(claimSeat({ id: 'c', type: 'claim', label: 'x' })).toBeNull();
+ expect(claimSeat(MODEL)).toEqual({ slot: 'about', count: true, condition: true });
+ });
+});
diff --git a/frontend/src/components/EntryLine.svelte b/frontend/src/components/EntryLine.svelte
new file mode 100644
index 0000000..f0f3879
--- /dev/null
+++ b/frontend/src/components/EntryLine.svelte
@@ -0,0 +1,971 @@
+<script module>
+ import { entityFamily } from '../lib/entityTypes.svelte.js';
+ import { relationOptions } from '../lib/relations.svelte.js';
+ import { SEAT_ORDER, quickClaimSeat } from '../lib/quickClaim.js';
+
+ /**
+ * Where this entity sits on a Claim filed from it, or null when it has no seat.
+ * Read off the relation registry, so a host shows its button exactly where this
+ * line can file something. Null until both registries have landed.
+ */
+ export function claimSeat(entity) {
+ if (!entity || entity.type === 'claim') return null;
+ return quickClaimSeat(entityFamily(entity.type), (verb) =>
+ relationOptions('claim', entity, 'claim').some((o) => o.type === verb && o.direction === 'out')
+ );
+ }
+
+ /** Every seat the vocabulary gives an entity on a Claim, most specific first. A
+ * Claim is only ever cited: `about` a Claim is a second date for the same event. */
+ export function seatsFor(entity) {
+ if (!entity) return [];
+ if (entity.type === 'claim') return ['cites'];
+ return SEAT_ORDER.filter((verb) =>
+ relationOptions('claim', entity, 'claim').some((o) => o.type === verb && o.direction === 'out'));
+ }
+
+ /** Unsaved lines, per case and per host, for this session only. Never on disk. */
+ const DRAFTS = new Map();
+</script>
+
+<script>
+ /**
+ * One line to note what happened: a date, a sentence with `@` mentions, sources.
+ *
+ * Nothing is required but one thing to say (D1): a sentence, a mention or a source.
+ * The sentence is kept as typed (D2) and, left empty, is written from the mentions.
+ * The date is empty until the analyst gives one (D3); a date the line cannot read
+ * holds the line back, and an empty one does not (D4). A name the case has never
+ * held becomes a new subject with a guessed type, created only when the line is
+ * added (D16). Each mention takes its seat from its family (D17).
+ *
+ * Used by the Timeline under its axis, and by Board, Graph and Details with their
+ * entity already seated.
+ */
+ import { onDestroy, untrack } from 'svelte';
+ import { api } from '../lib/api.js';
+ import { reloadCase, toast } from '../lib/state.svelte.js';
+ import {
+ creatableTypes,
+ entityFields,
+ entityTypes,
+ entityLabel as typeLabel,
+ loadEntityTypes,
+ } from '../lib/entityTypes.svelte.js';
+ import { loadRelationTypes } from '../lib/relations.svelte.js';
+ import { buildCatalogQuery } from '../lib/catalog.js';
+ import { entityIcon } from '../lib/entityIcon.js';
+ import { composeClaimStatement, quickClaimBody } from '../lib/quickClaim.js';
+ import {
+ guessSubjectType,
+ insertMention,
+ mentionAt,
+ mostUsedType,
+ rankMentions,
+ typeMenu,
+ } from '../lib/entryLine.js';
+ import { zonesOf } from '../lib/localZone.js';
+ import { isTimed, settleClock, writesOwnClock } from '../lib/clock.js';
+ import { axisZone, learnAxisZone } from '../lib/caseAxis.svelte.js';
+ import { FILE_TYPES, fetchFileDates } from '../lib/fileDates.js';
+ import { formatTemporalValue } from '../lib/timeline.js';
+ import DateBuilder from './DateBuilder.svelte';
+ import { anchoredPanel } from '../lib/anchoredPanel.js';
+ import DateField from './DateField.svelte';
+ import EntityFinder from './EntityFinder.svelte';
+ import ClockField from './ClockField.svelte';
+ import Icon from './Icon.svelte';
+ import Modal from './Modal.svelte';
+ import TemporalClaimEditor from './TemporalClaimEditor.svelte';
+
+ let {
+ caseId,
+ /** The entity the line was opened from, already in its seat. */
+ entity = null,
+ /** What else the place it was opened from already knows, seated too: a file's
+ * one confirmed place. `{ id, label, type, attrs, slot }`, locked like the entity. */
+ also = [],
+ /** Dates the place it was opened from can offer, one press each: a pair's
+ * "between A and B". `{ kind, value, words, hint }`, like a file's own. */
+ dates = [],
+ /** Where an unsaved line is kept for the session, or '' to keep nothing. */
+ draftKey = '',
+ /** Whether the line says `Added · Undo` itself. A host with more to say turns
+ * it off and uses the `undo` handed to `onsaved`. */
+ announce = true,
+ onsaved,
+ oncancel,
+ } = $props();
+
+ const uid = $props.id();
+ loadEntityTypes();
+ loadRelationTypes();
+
+ const seat = $derived(entity ? claimSeat(entity) : null);
+ const seated = $derived([
+ ...(entity && seat
+ ? [{ key: `seat:${entity.id}`, id: entity.id, label: entity.label, type: entity.type,
+ attrs: entity.attrs, slot: seat.slot, locked: true }]
+ : []),
+ ...also
+ .filter((item) => item?.id && item.id !== entity?.id && item.slot)
+ .map((item) => ({ key: `seat:${item.id}`, id: item.id, label: item.label, type: item.type,
+ attrs: item.attrs ?? {}, slot: item.slot, locked: true })),
+ ]);
+
+ // -- the dates the file and the place offer, one press each ------------------
+ /** A date the file carries is offered, never put in: filled by itself it would be
+ * accepted without being read, the argument Geo Proof settled. A press fills the
+ * field, which stays the analyst's to correct, and the reading says where it came
+ * from until it is changed. */
+ let fileOffers = $state([]);
+ let usedOffer = $state(null);
+ const offers = $derived([...dates, ...fileOffers]);
+ $effect(() => {
+ const id = entity?.id;
+ fileOffers = [];
+ if (!caseId || !id || !FILE_TYPES.has(entity.type)) return;
+ let live = true;
+ fetchFileDates(caseId, id)
+ .then((found) => { if (live) fileOffers = found; })
+ .catch(() => {});
+ return () => { live = false; };
+ });
+ function useOffer(offer) {
+ when = offer.value;
+ clockPick = undefined;
+ usedOffer = offer;
+ queueMicrotask(() => sentence?.focus());
+ }
+ const fromOffer = $derived(usedOffer && usedOffer.value === when ? usedOffer : null);
+
+ let when = $state('');
+ let text = $state('');
+ let edited = $state(false);
+ let mentions = $state([]);
+ let count = $state(null);
+ let condition = $state('');
+ let confidence = $state('');
+ let more = $state(false);
+ let saving = $state(false);
+ let error = $state('');
+ let refused = $state({});
+ /** The clock the analyst picked, `undefined` until they pick one (see `settleClock`). */
+ let clockPick = $state(undefined);
+ let zones = $state({ zones: [], only: null });
+ let full = $state(null);
+ let dragging = $state(false);
+
+ let sentence = $state();
+ let lineElement = $state();
+
+ // A host whose entity calls for a count or a state opens on them: a model is
+ // filed to say how many were seen and in what condition.
+ $effect(() => {
+ if (seat?.count || seat?.condition) untrack(() => (more = true));
+ });
+
+ // -- the session draft ------------------------------------------------------
+
+ const storeKey = $derived(caseId && draftKey ? `${caseId}:${draftKey}` : '');
+ $effect(() => {
+ const key = storeKey;
+ if (!key) return;
+ untrack(() => {
+ const held = DRAFTS.get(key);
+ if (!held) return;
+ ({ when, clockPick, text, edited, mentions, count, condition, confidence } = held);
+ });
+ });
+ const blank = $derived(!when && !text.trim() && !mentions.length && count == null && !condition && !confidence);
+ function keepDraft() {
+ if (!storeKey) return;
+ if (blank) DRAFTS.delete(storeKey);
+ else DRAFTS.set(storeKey, $state.snapshot({ when, clockPick, text, edited, mentions, count, condition, confidence }));
+ }
+ onDestroy(keepDraft);
+
+ // -- what the line adds up to -----------------------------------------------
+
+ const all = $derived([...seated, ...mentions]);
+ const inSeat = (slot) => all.filter((item) => item.slot === slot);
+ const claimFields = $derived(entityFields('claim'));
+ const countField = $derived(claimFields.find((field) => field.key === 'count'));
+ const conditions = $derived(claimFields.find((field) => field.key === 'condition')?.options ?? []);
+ const confidences = $derived(claimFields.find((field) => field.key === 'confidence')?.options ?? []);
+ /** A count is of a model, and a state is of a model or a named object: asked when
+ * something `about` the line is one. */
+ const facts = $derived.by(() => {
+ const families = inSeat('about').map((item) => entityFamily(item.type));
+ return {
+ count: families.includes('class'),
+ condition: families.some((family) => family === 'class' || family === 'asset'),
+ };
+ });
+
+ const composed = $derived(
+ composeClaimStatement({
+ count: facts.count && Number.isInteger(count) ? count : null,
+ condition: facts.condition ? conditions.find((option) => option.value === condition)?.label ?? '' : '',
+ subjects: inSeat('about').map((item) => item.label),
+ places: inSeat('at').map((item) => item.label),
+ sources: inSeat('cites').map((item) => item.label),
+ })
+ );
+ // The fields write the sentence until the analyst writes one; a sentence of their
+ // own is never overwritten by a field changing under it.
+ $effect(() => {
+ if (!edited) text = composed;
+ });
+ const statement = $derived(text.trim() || composed);
+
+ // -- the date, and the clock of the place it happened at --------------------
+
+ const points = $derived([...inSeat('at'), ...inSeat('cites')].filter((item) => item.type === 'place' || item.type === 'proof'));
+ $effect(() => {
+ const placed = points.map((item) => ({ type: item.type, label: item.label, attrs: item.attrs }));
+ let live = true;
+ zonesOf(placed).then((found) => { if (live) zones = found; });
+ return () => { live = false; };
+ });
+ // The clock the date is read on: the analyst's pick, else the one the value writes
+ // itself, else the zone the line's places agree on, else the clock the case's axis
+ // reads on. A day is that zone's day and a time its local time, said on the chip.
+ $effect(() => { learnAxisZone(caseId); });
+ const settled = $derived(settleClock(when, { picked: clockPick, fallback: zones.only?.zone ?? axisZone(caseId) }));
+ /** A typed date keeps the clock picked, unless it writes its own (`14:30 UTC`). */
+ function typeWhen(value) {
+ when = value;
+ if (writesOwnClock(value)) clockPick = undefined;
+ }
+ const whenValid = $derived(!when || formatTemporalValue(when).valid);
+
+ // -- sending ---------------------------------------------------------------
+
+ const ready = $derived(Boolean(statement) && whenValid && !saving);
+ const refusal = $derived(
+ !whenValid ? 'Correct the date or clear it'
+ : !statement ? 'Write what happened, mention a subject or cite a source'
+ : ''
+ );
+
+ function body() {
+ const ids = (slot) => inSeat(slot).filter((item) => !item.isNew).map((item) => item.id);
+ return quickClaimBody({
+ statement,
+ when: settled.raw,
+ whenZone: settled.zone,
+ confidence,
+ count,
+ condition,
+ seat: facts,
+ about: ids('about'),
+ at: ids('at'),
+ cites: ids('cites'),
+ create: mentions.filter((item) => item.isNew).map((item) => ({ slot: item.slot, type: item.type, label: item.label })),
+ });
+ }
+
+ function clear() {
+ when = '';
+ text = '';
+ edited = false;
+ mentions = [];
+ count = null;
+ condition = '';
+ confidence = '';
+ clockPick = undefined;
+ error = '';
+ refused = {};
+ if (storeKey) DRAFTS.delete(storeKey);
+ }
+
+ async function undo(saved) {
+ const ids = [saved.entity.id, ...(saved.created ?? []).map((entry) => entry.id)];
+ try {
+ await api.post(`/api/cases/${caseId}/entities/delete`, { ids });
+ toast('Removed. It is in the Trash', 'ok', 2400);
+ await reloadCase();
+ } catch (failure) {
+ toast(failure.message, 'danger');
+ }
+ }
+
+ async function save() {
+ if (!ready) return;
+ saving = true;
+ error = '';
+ refused = {};
+ try {
+ const saved = await api.post(`/api/cases/${caseId}/timeline/claims`, body());
+ clear();
+ if (announce) toast('Added', 'ok', 8000, { label: 'Undo', onClick: () => undo(saved) });
+ sentence?.focus();
+ await reloadCase();
+ onsaved?.(saved, { undo: () => undo(saved) });
+ } catch (failure) {
+ error = failure.message;
+ // A mention the case lost since it was picked is marked where it sits.
+ const gone = /entity '([^']+)' not found/.exec(failure.message)?.[1];
+ if (gone) refused = { [gone]: 'no longer in the case' };
+ } finally {
+ saving = false;
+ }
+ }
+
+ /** Put a date on the line, as a click on the axis does, and go to the sentence. */
+ export function offer(value) {
+ when = value ?? '';
+ clockPick = undefined;
+ queueMicrotask(() => sentence?.focus());
+ }
+
+ /** Go to the sentence. A sentence the fields wrote is selected, so typing replaces
+ * it; one the analyst wrote keeps its caret at the end. */
+ export function focus() {
+ sentence?.focus();
+ if (!edited && text) sentence?.select();
+ }
+
+ // -- mentions ---------------------------------------------------------------
+
+ const seatableTypes = $derived(entityTypes().filter((entry) => seatsFor(entry).length).map((entry) => entry.type));
+ const sourceTypes = $derived(entityTypes().filter((entry) => seatsFor(entry).includes('cites')).map((entry) => entry.type));
+
+ /** The list under the sentence while an `@` is typed. */
+ let suggest = $state(null); // { mention, term, rows, active, loading }
+ /** Which panel is open under the line: the sources, or the date builder. */
+ let panel = $state('');
+ /** Which field has the focus, for the help it gets under the line. */
+ let focused = $state('');
+ let seq = 0;
+ let summary = null;
+
+ async function caseSummary() {
+ summary ??= api.get(`/api/cases/${caseId}/catalog/summary`).catch(() => null);
+ return summary;
+ }
+
+ function search(term, mention) {
+ const types = seatableTypes;
+ const mine = ++seq;
+ suggest = { ...(suggest ?? { active: 0, rows: [] }), term, mention, loading: true };
+ if (!types.length) return;
+ api
+ .get(buildCatalogQuery(caseId, { types, query: term.trim() || undefined, limit: 20 }))
+ .then((page) => {
+ if (mine !== seq || !suggest) return;
+ const mentioned = new Set(all.map((item) => item.id));
+ const rows = rankMentions(page.items ?? [], term, mentioned)
+ .filter((row) => !mentioned.has(row.entity.id) && seatsFor(row.entity).length);
+ suggest = { ...suggest, rows, active: 0, loading: false };
+ })
+ .catch(() => {
+ if (mine === seq && suggest) suggest = { ...suggest, rows: [], loading: false };
+ });
+ }
+
+ /** What `New · <name>` would create, guessed, or null when there is no name. */
+ let guess = $state(null);
+ /** The subject type this case holds most of, once the summary has been read. */
+ let favourite = $state('');
+ $effect(() => {
+ const name = suggest ? suggest.term.trim() : '';
+ if (!name) {
+ guess = null;
+ return;
+ }
+ let live = true;
+ caseSummary().then((held) => {
+ if (!live) return;
+ favourite = mostUsedType(held, creatableTypes());
+ guess = { label: name, ...guessSubjectType(name, { mostUsed: favourite }) };
+ });
+ return () => { live = false; };
+ });
+ const options = $derived([
+ ...(suggest?.rows ?? []).map((row) => ({ kind: 'entity', ...row })),
+ ...(guess && suggest ? [{ kind: 'new', ...guess }] : []),
+ ]);
+
+ function readCaret() {
+ if (!sentence) return;
+ const mention = mentionAt(text, sentence.selectionStart ?? text.length);
+ if (mention) search(mention.term, mention);
+ else if (suggest) suggest = null;
+ }
+
+ function onSentenceInput(event) {
+ text = event.currentTarget.value;
+ edited = true;
+ readCaret();
+ }
+
+ function seatOf(item) {
+ return seatsFor(item)[0] ?? 'about';
+ }
+
+ function pick(option) {
+ if (!option) return;
+ const label = option.kind === 'new' ? option.label : option.entity.label;
+ if (suggest?.mention) {
+ const next = insertMention(text, suggest.mention, label);
+ text = next.text;
+ edited = true;
+ queueMicrotask(() => sentence?.setSelectionRange(next.caret, next.caret));
+ }
+ if (option.kind === 'new') {
+ const item = {
+ key: `new:${Date.now()}:${label}`, label, type: option.type, rule: option.rule,
+ isNew: true, slot: seatOf({ type: option.type }),
+ };
+ mentions = [...mentions, item];
+ checkTwin(item);
+ } else {
+ const { entity: found } = option;
+ mentions = [...mentions, {
+ key: found.id, id: found.id, label: found.label, type: found.type,
+ attrs: found.attrs, slot: seatOf(found),
+ }];
+ }
+ suggest = null;
+ sentence?.focus();
+ }
+
+ function remove(item) {
+ if (item.locked) return;
+ mentions = mentions.filter((entry) => entry.key !== item.key);
+ }
+
+ /** `Alt+↓` on a chip moves it to its next seat, when the vocabulary gives it one. */
+ function chipKey(event, item) {
+ if (event.key === 'ArrowDown' && event.altKey && !item.locked) {
+ event.preventDefault();
+ const seats = seatsFor(item);
+ const next = seats[(seats.indexOf(item.slot) + 1) % seats.length];
+ if (next && next !== item.slot) {
+ mentions = mentions.map((entry) => (entry.key === item.key ? { ...entry, slot: next } : entry));
+ }
+ }
+ }
+
+ function retype(item, type) {
+ const next = { ...item, type, rule: 'chosen', twin: null, slot: seatOf({ type }) };
+ mentions = mentions.map((entry) => (entry.key === item.key ? next : entry));
+ checkTwin(next);
+ }
+
+ /** An identifier the case already holds is offered in place of the new one. It
+ * warns and never refuses: the analyst can still keep the new subject. */
+ async function checkTwin(item) {
+ const params = new URLSearchParams({ type: item.type, label: item.label });
+ try {
+ const { entity: twin } = await api.get(`/api/cases/${caseId}/entities/twin?${params}`);
+ mentions = mentions.map((entry) => (entry.key === item.key && entry.type === item.type ? { ...entry, twin } : entry));
+ } catch {
+ /* the warning is a courtesy; its absence blocks nothing */
+ }
+ }
+
+ function useTwin(item) {
+ const twin = item.twin;
+ mentions = mentions.map((entry) => (entry.key === item.key
+ ? { key: twin.id, id: twin.id, label: twin.label, type: twin.type, attrs: twin.attrs, slot: seatOf(twin) }
+ : entry));
+ }
+
+ /** A source picked from the paperclip's finder, cited at once. */
+ function cite(found) {
+ if (!all.some((entry) => entry.id === found.id)) {
+ mentions = [...mentions, {
+ key: found.id, id: found.id, label: found.label, type: found.type, attrs: found.attrs, slot: 'cites',
+ }];
+ }
+ panel = '';
+ sentence?.focus();
+ }
+
+ function togglePanel(name) {
+ panel = panel === name ? '' : name;
+ suggest = null;
+ }
+
+ /** A press outside the open panel closes it, as a menu does. */
+ function onWindowPointerDown(event) {
+ if (!panel || !lineElement) return;
+ if (event.target.closest?.('.panel, .panel-toggle')) return;
+ panel = '';
+ }
+
+ function onSentenceKey(event) {
+ if (suggest && options.length) {
+ if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
+ event.preventDefault();
+ const step = event.key === 'ArrowDown' ? 1 : -1;
+ suggest = { ...suggest, active: (suggest.active + step + options.length) % options.length };
+ return;
+ }
+ if ((event.key === 'Enter' && !event.ctrlKey && !event.metaKey) || event.key === 'Tab') {
+ event.preventDefault();
+ pick(options[suggest.active]);
+ return;
+ }
+ }
+ if (event.key === 'Escape') {
+ if (suggest) {
+ // The `@` stays as typed: an address or a handle is text.
+ event.stopPropagation();
+ suggest = null;
+ return;
+ }
+ if (!oncancel) sentence?.blur();
+ return;
+ }
+ if (event.key === 'Enter' && !event.shiftKey) {
+ event.preventDefault();
+ save();
+ }
+ }
+
+ function onLineKey(event) {
+ if (event.key === 'Escape' && panel) {
+ event.preventDefault();
+ event.stopPropagation();
+ panel = '';
+ sentence?.focus();
+ }
+ if (event.key === 'Enter' && (event.ctrlKey || event.metaKey)) {
+ event.preventDefault();
+ save();
+ }
+ }
+
+ // -- files dropped from the system ------------------------------------------
+
+ function onDragOver(event) {
+ if (![...(event.dataTransfer?.types ?? [])].includes('Files')) return;
+ event.preventDefault();
+ event.stopPropagation();
+ dragging = true;
+ }
+
+ /** A file dropped on the line is imported the way the Media Library imports it,
+ * then cited. The import stands even if the line is abandoned. */
+ async function onDrop(event) {
+ const files = [...(event.dataTransfer?.files ?? [])];
+ dragging = false;
+ if (!files.length) return;
+ event.preventDefault();
+ event.stopPropagation();
+ for (const file of files) {
+ const form = new FormData();
+ form.append('file', file);
+ try {
+ const result = await api.post(`/api/cases/${caseId}/media/upload`, form);
+ const item = result.entity;
+ if (item && !all.some((entry) => entry.id === item.id)) {
+ mentions = [...mentions, { key: item.id, id: item.id, label: item.label, type: item.type, attrs: item.attrs, slot: 'cites' }];
+ }
+ } catch (failure) {
+ toast(`${file.name}: ${failure.message}`, 'danger');
+ }
+ }
+ }
+
+ // -- the full editor --------------------------------------------------------
+
+ function openFull() {
+ const pick = (slot) => inSeat(slot).filter((item) => !item.isNew)
+ .map(({ id, label, type, attrs }) => ({ id, label, type, attrs }));
+ full = {
+ statement,
+ when: settled.raw,
+ whenZone: settled.zone,
+ confidence,
+ about: pick('about').filter((item) => item.id !== entity?.id || seat?.slot !== 'about'),
+ at: pick('at'),
+ cites: pick('cites'),
+ facts: {
+ count: facts.count && Number.isInteger(count) ? count : null,
+ condition: facts.condition && condition ? condition : null,
+ },
+ create: mentions.filter((item) => item.isNew).map(({ slot, type, label }) => ({ slot, type, label })),
+ subject: seat?.slot === 'about' ? { id: entity.id, label: entity.label, type: entity.type } : null,
+ };
+ }
+
+ async function fullSaved(saved) {
+ full = null;
+ clear();
+ if (announce) toast('Added', 'ok', 8000, { label: 'Undo', onClick: () => undo(saved) });
+ await reloadCase();
+ onsaved?.(saved, { undo: () => undo(saved) });
+ }
+
+ const SEAT_WORDS = { about: 'about', at: 'at', cites: 'source' };
+ const counter = $derived(text.length >= 250 ? `${text.length}/300` : '');
+</script>
+
+<svelte:window onpointerdown={onWindowPointerDown} />
+
+<!-- svelte-ignore a11y_no_static_element_interactions -->
+<div
+ class="entry-line"
+ class:dragging
+ bind:this={lineElement}
+ onkeydown={onLineKey}
+ ondragover={onDragOver}
+ ondragleave={() => (dragging = false)}
+ ondrop={onDrop}
+>
+ <div class="row">
+ <div class="when" onfocusin={() => (focused = 'when')} onfocusout={() => (focused = '')}>
+ <DateField
+ id="{uid}-when"
+ label="When"
+ placeholder="Date · optional"
+ value={when}
+ reading={false}
+ onchange={typeWhen}
+ />
+ <button
+ class="panel-toggle calendar"
+ class:on={panel === 'calendar'}
+ aria-expanded={panel === 'calendar'}
+ aria-label="Build the date"
+ title="Build the date: a day, a month or a year, and how sure"
+ onclick={() => togglePanel('calendar')}
+ >
+ <Icon name="calendar" size={13} />
+ </button>
+ </div>
+ <div class="say" onfocusin={() => (focused = 'say')} onfocusout={() => (focused = '')}>
+ <input
+ bind:this={sentence}
+ id="{uid}-say"
+ class="input sentence"
+ type="text"
+ dir="auto"
+ maxlength="300"
+ autocomplete="off"
+ placeholder="What happened? Type @ to mention"
+ aria-label="What happened"
+ role="combobox"
+ aria-expanded={Boolean(suggest)}
+ aria-controls="{uid}-options"
+ aria-autocomplete="list"
+ aria-activedescendant={suggest && options.length ? `${uid}-option-${suggest.active}` : undefined}
+ value={text}
+ oninput={onSentenceInput}
+ onkeydown={onSentenceKey}
+ onclick={readCaret}
+ />
+ {#if counter}<small class="counter" class:full={text.length >= 300}>{counter}</small>{/if}
+ {#if suggest}
+ <ul class="options" popover="manual" use:anchoredPanel={{ anchor: () => sentence }} id="{uid}-options" role="listbox" aria-label="Mentions">
+ {#each options as option, index (option.kind === 'new' ? 'new' : option.entity.id)}
+ <li
+ id="{uid}-option-{index}"
+ role="option"
+ aria-selected={index === suggest.active}
+ class:active={index === suggest.active}
+ onpointerdown={(event) => { event.preventDefault(); pick(option); }}
+ >
+ {#if option.kind === 'new'}
+ <Icon name="plus" size={12} />
+ <span class="name" dir="auto">New · {option.label}</span>
+ <small>{typeLabel(option.type)} · {option.rule}</small>
+ {:else}
+ <Icon name={entityIcon(option.entity)} size={12} />
+ <span class="name" dir="auto">{option.entity.label}</span>
+ <small>
+ {#if option.reason}<span dir="auto">{option.reason.label}: {option.reason.value}</span> · {/if}{typeLabel(option.entity.type)}
+ </small>
+ {/if}
+ </li>
+ {:else}
+ <li class="none">{suggest.loading ? 'Searching…' : 'Type a name: the case has nothing to offer yet'}</li>
+ {/each}
+ <li class="keys" aria-hidden="true">↑ ↓ to choose · Enter or Tab to pick · Esc keeps the @ as text</li>
+ </ul>
+ {/if}
+ </div>
+ <button
+ class="btn btn-ghost panel-toggle attach"
+ class:on={panel === 'sources'}
+ aria-expanded={panel === 'sources'}
+ aria-label="Cite a source"
+ title="Cite a source: a file, a capture, a proof, a page, a note. Or drop a file on the line"
+ onclick={() => togglePanel('sources')}
+ >
+ <Icon name="paperclip" size={16} /><span class="attach-label">Source</span>
+ </button>
+ {#if oncancel}<button class="btn btn-ghost" onclick={oncancel}>Cancel</button>{/if}
+ <button class="btn btn-primary" disabled={!ready} title={refusal || 'Enter · Ctrl+Enter from any field'} onclick={save}>
+ {saving ? 'Adding…' : 'Add'}
+ </button>
+ </div>
+
+ {#if panel === 'calendar'}
+ <div class="panel calendar-panel" popover="manual" use:anchoredPanel={{ anchor: () => lineElement?.querySelector('.when'), width: 320 }}>
+ <DateBuilder value={formatTemporalValue(when).valid ? when : ''} label="When" onbuild={typeWhen} />
+ </div>
+ {:else if panel === 'sources'}
+ <div class="panel sources-panel" popover="manual" use:anchoredPanel={{ anchor: () => lineElement?.querySelector('.row') }}>
+ <EntityFinder
+ {caseId}
+ types={sourceTypes}
+ exclude={all.map((item) => item.id).filter(Boolean)}
+ order="-created"
+ label="Find a source"
+ placeholder="Find a source by name, folder or notes…"
+ onpick={cite}
+ onclose={() => { panel = ''; sentence?.focus(); }}
+ />
+ </div>
+ {/if}
+
+ {#if all.length}
+ <div class="chips" aria-label="Mentioned">
+ {#each all as item (item.key)}
+ <span class="chip" class:locked={item.locked} class:new={item.isNew} class:refused={refused[item.id]}>
+ <button
+ class="chip-name"
+ title={item.locked ? `${item.label} · where this line was opened` : refused[item.id] ? `${item.label} is ${refused[item.id]}` : `Remove ${item.label} · Alt+↓ changes its seat`}
+ disabled={item.locked}
+ onclick={() => remove(item)}
+ onkeydown={(event) => chipKey(event, item)}
+ >
+ <Icon name={entityIcon(item)} size={11} />
+ <span dir="auto">{item.label}</span>
+ <small>{SEAT_WORDS[item.slot]}</small>
+ {#if !item.locked}<Icon name="x" size={10} />{/if}
+ </button>
+ {#if item.isNew}
+ {@const menu = typeMenu(creatableTypes(), favourite)}
+ <select
+ class="retype"
+ aria-label={`What ${item.label} is`}
+ value={item.type}
+ onchange={(event) => retype(item, event.currentTarget.value)}
+ >
+ {#each menu.quick as type (type)}<option value={type}>{typeLabel(type)}</option>{/each}
+ {#if !menu.quick.includes(item.type)}<option value={item.type}>{typeLabel(item.type)}</option>{/if}
+ <optgroup label="Other">
+ {#each menu.other.filter((type) => type !== item.type) as type (type)}<option value={type}>{typeLabel(type)}</option>{/each}
+ </optgroup>
+ </select>
+ <small class="rule">{item.rule === 'chosen' ? 'new' : `new · ${item.rule}`}</small>
+ {#if item.twin}
+ <button class="btn btn-ghost btn-sm twin" title="The case already holds this value" onclick={() => useTwin(item)}>
+ Use the one in the case
+ </button>
+ {/if}
+ {/if}
+ </span>
+ {/each}
+ </div>
+ {/if}
+
+ {#if offers.length && !when}
+ <p class="file-says">
+ <span class="lead"><Icon name="calendar" size={11} /> Use</span>
+ {#each offers as offer (offer.value + offer.kind)}
+ <button class="date-offer" title={offer.hint} onclick={() => useOffer(offer)}>{offer.words}</button>
+ {/each}
+ </p>
+ {/if}
+
+ <div class="under">
+ {#if when && whenValid}
+ {@const reading = formatTemporalValue(settled.raw, settled.zone)}
+ <!-- A date it cannot read is said under the field itself, by DateField. -->
+ <span class="said" aria-live="polite">
+ Reads: {[reading.label, ...reading.qualifiers].join(' · ')}
+ {#if fromOffer} · from the {fromOffer.kind} date, yours to correct{/if}
+ </span>
+ <ClockField
+ value={when}
+ clock={settled.clock}
+ here={zones.zones}
+ timed={isTimed(when)}
+ onpick={(zone) => (clockPick = zone)}
+ />
+ {:else if focused === 'when' && !when}
+ <p class="help">
+ <span>A day <code>12/03/2026</code></span>
+ <span>a time <code>12/03/2026 14:30</code></span>
+ <span>a month <code>March 2026</code></span>
+ <span>a year <code>2026</code></span>
+ <span>about <code>~2026</code></span>
+ <span>unsure <code>2026?</code></span>
+ <span>a span <code>12/03/2026 to 15/03/2026</code></span>
+ <span class="aside">Or leave it empty: the entry waits in Undated.</span>
+ </p>
+ {:else if focused === 'say' && !suggest && !text.trim()}
+ <p class="help">
+ <span>In your own words, as short as you like.</span>
+ <span><code>@</code> mentions a person, a place or a file, and a name the case lacks becomes a new subject.</span>
+ <span><Icon name="paperclip" size={11} /> cites a source.</span>
+ <span><code>Enter</code> adds.</span>
+ </p>
+ {/if}
+ {#if error}<span class="error" role="alert">{error}</span>{/if}
+ <button class="btn btn-ghost btn-sm more" aria-expanded={more} onclick={() => (more = !more)}>
+ <Icon name={more ? 'minus' : 'plus'} size={10} /> More
+ </button>
+ </div>
+
+ {#if more}
+ <div class="details">
+ {#if facts.count}
+ <label>
+ <span class="field-name">How many</span>
+ <input class="input input-sm" type="number" min={countField?.minimum ?? 1} max={countField?.maximum} step="1" placeholder="Not counted" bind:value={count} />
+ </label>
+ {/if}
+ {#if facts.condition}
+ <label>
+ <span class="field-name">Condition</span>
+ <select class="select input-sm" value={condition} onchange={(event) => (condition = event.currentTarget.value)}>
+ <option value="">Not stated</option>
+ {#each conditions as option (option.value)}<option value={option.value}>{option.label}</option>{/each}
+ </select>
+ </label>
+ {/if}
+ <label>
+ <span class="field-name">Confidence</span>
+ <select class="select input-sm" value={confidence} onchange={(event) => (confidence = event.currentTarget.value)}>
+ <option value="">Not assessed</option>
+ {#each confidences as option (option.value)}<option value={option.value}>{option.label}</option>{/each}
+ </select>
+ </label>
+ <span class="gap"></span>
+ {#if edited && text.trim() !== composed && composed}
+ <button class="btn btn-ghost btn-sm" title="Write the sentence from the mentions again" onclick={() => (edited = false)}>
+ Rewrite from the mentions
+ </button>
+ {/if}
+ <button class="btn btn-ghost btn-sm" title="The role of the date, how it was worked out, and the source's own wording" onclick={openFull}>
+ <Icon name="edit" size={11} /> Full editor
+ </button>
+ </div>
+ {/if}
+</div>
+
+{#if full}
+ <Modal title="Add event" onclose={() => (full = null)} width="660px">
+ <TemporalClaimEditor
+ {caseId}
+ subject={full.subject}
+ initialWhen={full.when}
+ initialWhenZone={full.whenZone}
+ initialStatement={full.statement}
+ initialRole={full.when ? 'observed' : ''}
+ initialConfidence={full.confidence}
+ initialAbout={full.about}
+ initialAt={full.at}
+ initialCites={full.cites}
+ initialFacts={full.facts}
+ initialCreate={full.create}
+ announce={false}
+ onsaved={fullSaved}
+ oncancel={() => (full = null)}
+ />
+ </Modal>
+{/if}
+
+<style>
+ /* Sized by where it sits rather than by the window: the same line runs the width of
+ the Timeline and fits Details beside the Board. */
+ .entry-line { position: relative; display: grid; gap: 6px; min-width: 0; container: entry-line / inline-size; }
+ .entry-line.dragging { outline: 1px dashed var(--accent); outline-offset: 3px; border-radius: var(--r-sm); }
+ .row { display: flex; align-items: start; gap: 8px; min-width: 0; }
+ .row > .btn, .sentence, .when :global(.date-field input) { min-height: 36px; height: 36px; box-sizing: border-box; font-size: var(--fs-sm); }
+ .row > .btn { flex: 0 0 auto; padding: 0 12px; }
+ .when { position: relative; flex: 0 0 224px; min-width: 0; display: flex; align-items: start; }
+ .when :global(.date-field) { flex: 1; }
+ .when :global(.date-field input) { border-top-right-radius: 0; border-bottom-right-radius: 0; }
+ .calendar {
+ flex: 0 0 auto; height: 36px; width: 36px; box-sizing: border-box; display: grid; place-items: center;
+ border: 1px solid var(--border); border-left: 0; border-radius: 0 var(--r-sm) var(--r-sm) 0;
+ background: var(--bg-3); color: var(--text-3); cursor: pointer;
+ }
+ .calendar:hover, .calendar.on { color: var(--accent); }
+ .say { position: relative; flex: 1; min-width: 0; }
+ .sentence { width: 100%; }
+ .counter { position: absolute; right: 8px; top: 8px; color: var(--text-3); font-size: 10px; pointer-events: none; }
+ .counter.full { color: var(--warn); }
+ .options {
+ position: fixed; z-index: 1000; inset: auto; box-sizing: border-box;
+ max-height: 260px; overflow: auto; margin: 0; padding: 3px; list-style: none;
+ border: 1px solid var(--border-strong); border-radius: var(--r-sm);
+ background: var(--bg-1); box-shadow: var(--shadow-2);
+ }
+ .options li {
+ display: grid; grid-template-columns: auto minmax(0, 1fr) auto; align-items: center; gap: 7px;
+ padding: 6px 8px; border-radius: var(--r-sm); color: var(--text-2); cursor: pointer;
+ }
+ .options li.active, .options li:hover { background: var(--bg-3); color: var(--text-1); }
+ .options li.none, .options li.keys { display: block; cursor: default; color: var(--text-3); font-size: var(--fs-xs); }
+ .options li.keys { padding: 5px 8px 3px; border-top: 1px solid var(--border); font-size: 10px; }
+ .options li.none:hover, .options li.keys:hover { background: none; }
+ .options .name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+ .options small { color: var(--text-3); font-size: 10px; white-space: nowrap; }
+ .attach.on { color: var(--accent); background: var(--accent-soft); }
+ .panel {
+ position: fixed; z-index: 1000; inset: auto; margin: 0; box-sizing: border-box; overflow: auto; color: var(--text-1);
+ padding: 10px; border: 1px solid var(--border-strong); border-radius: var(--r-md);
+ background: var(--bg-1); box-shadow: var(--shadow-2);
+ }
+ .sources-panel { display: flex; flex-direction: column; }
+ .chips { display: flex; flex-wrap: wrap; gap: 5px; }
+ .chip {
+ display: inline-flex; align-items: center; gap: 4px; min-width: 0;
+ padding: 1px 3px 1px 1px; border: 1px solid var(--border); border-radius: 999px;
+ background: var(--bg-2); color: var(--text-2); font-size: var(--fs-xs);
+ }
+ .chip.locked { border-style: dashed; }
+ .chip.new { border-color: var(--accent); }
+ .chip.refused { border-color: var(--danger); color: var(--danger); }
+ .chip-name {
+ display: inline-flex; align-items: center; gap: 5px; min-width: 0; padding: 3px 6px;
+ border: 0; border-radius: 999px; background: none; color: inherit; font: inherit; cursor: pointer;
+ }
+ .chip-name:disabled { cursor: default; }
+ .chip-name small, .rule { color: var(--text-3); font-size: 10px; }
+ .retype { padding: 1px 4px; border: 1px solid var(--border); border-radius: var(--r-sm); background: var(--bg-1); color: var(--text-2); font-size: 10px; }
+ .twin { color: var(--warn); }
+ .under { display: flex; flex-wrap: wrap; align-items: center; gap: 4px 10px; min-height: 22px; }
+ .said { color: var(--text-2); font-size: var(--fs-xs); }
+ .file-says { display: flex; flex-wrap: wrap; align-items: center; gap: 5px; margin: 0; color: var(--text-3); font-size: var(--fs-xs); }
+ .file-says .lead { display: inline-flex; align-items: center; gap: 4px; }
+ .file-says :global(svg) { flex-shrink: 0; }
+ .date-offer {
+ padding: 2px 8px; border: 1px dashed var(--border-strong); border-radius: 999px;
+ background: none; color: var(--text-2); font: inherit; font-size: var(--fs-xs); cursor: pointer;
+ }
+ .date-offer:hover, .date-offer:focus-visible { border-style: solid; border-color: var(--accent); color: var(--text-1); }
+ .help { display: flex; flex-wrap: wrap; gap: 3px 12px; margin: 0; flex: 1; color: var(--text-3); font-size: var(--fs-xs); line-height: 1.6; }
+ .help code { padding: 0 4px; border-radius: 3px; background: var(--bg-2); color: var(--text-2); font-family: var(--font-mono); font-size: 10.5px; }
+ .help .aside { color: var(--text-3); font-style: italic; }
+ .help :global(svg) { vertical-align: -1px; }
+ .more { margin-left: auto; }
+ .error { color: var(--warn); font-size: var(--fs-xs); }
+ .details { display: flex; flex-wrap: wrap; align-items: end; gap: 8px 12px; padding-top: 8px; border-top: 1px solid var(--border); }
+ .details label { display: grid; gap: 3px; min-width: 130px; }
+ .field-name { color: var(--text-3); font-size: var(--fs-xs); }
+ .gap { flex: 1; }
+ .input-sm { padding: 4px 7px; font-size: var(--fs-xs); }
+ /* Too narrow for one row: the date and the buttons share the first, and the
+ sentence takes the whole of the second, where it has room to be typed. */
+ @container entry-line (max-width: 700px) {
+ .row { flex-wrap: wrap; }
+ .when { flex: 1 1 180px; }
+ .say { flex-basis: 100%; order: 2; }
+ .row > .btn { padding: 0 10px; }
+ }
+ @container entry-line (max-width: 420px) {
+ .attach-label { display: none; }
+ }
+</style>
diff --git a/frontend/src/components/FilterBar.svelte b/frontend/src/components/FilterBar.svelte
index 7d3ec44..1fd5926 100644
--- a/frontend/src/components/FilterBar.svelte
+++ b/frontend/src/components/FilterBar.svelte
@@ -24,13 +24,16 @@
import {
ADDED,
AXES,
+ LACKS,
QUESTIONS,
STATUSES,
+ askQuestion,
chipsOf,
clearAxis,
emptyFilter,
hasTerm,
isFiltering,
+ toggleLack,
toggleValue,
} from '../lib/entityFilter.js';
import Icon from './Icon.svelte';
@@ -168,6 +171,9 @@
const loose = summary?.unlinked ?? 0;
return loose ? { off: false, note: String(loose) } : { off: true, note: 'all connected' };
}
+ if (axis in LACKS) {
+ return summary?.by_type?.claim ? { off: false, note: '' } : { off: true, note: 'no claims yet' };
+ }
if (axis === 'folder') {
return folders.length || unfiledCount
? { off: false, note: folders.length ? `${folders.length} folders` : '' }
@@ -204,6 +210,11 @@
open = '';
return;
}
+ if (axis in LACKS) {
+ filter = toggleLack(filter, axis);
+ open = '';
+ return;
+ }
if (axis === 'field') onfields();
open = axis;
}
@@ -227,8 +238,7 @@
}
function ask(id) {
- const question = QUESTIONS.find((entry) => entry.id === id);
- filter = { ...filter, ...question.terms };
+ filter = askQuestion(filter, id);
open = '';
}
diff --git a/frontend/src/components/Icon.svelte b/frontend/src/components/Icon.svelte
index 095d750..67487c3 100644
--- a/frontend/src/components/Icon.svelte
+++ b/frontend/src/components/Icon.svelte
@@ -30,6 +30,8 @@
download: 'M12 3v12m0 0 4-4m-4 4-4-4M4 17v2a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-2',
upload: 'M12 15V3m0 0 4 4m-4-4-4 4M4 17v2a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-2',
link: 'M10 14a5 5 0 0 0 7.5.5l3-3a5 5 0 0 0-7-7l-1.7 1.7M14 10a5 5 0 0 0-7.5-.5l-3 3a5 5 0 0 0 7 7l1.7-1.7',
+ // a source attached to what is being written: the entry line's evidence press
+ paperclip: 'M20 11.5 12.4 19a5 5 0 0 1-7.1-7.1l8-8a3.3 3.3 0 0 1 4.7 4.7l-8 8a1.7 1.7 0 0 1-2.4-2.4l7.3-7.3',
copy: 'M8 8h11a1 1 0 0 1 1 1v11a1 1 0 0 1-1 1H8a1 1 0 0 1-1-1V9a1 1 0 0 1 1-1Zm-4 8V4a1 1 0 0 1 1-1h12',
save: 'M5 3h11l3 3v14a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1Zm3 0v5h7V3M7 21v-7h10v7',
check: 'm4.5 12.5 5 5 10-11',
@@ -72,6 +74,8 @@
compass: 'M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18Zm3.5 5.5-2 5-5 2 2-5 5-2Z',
arrowRight: 'M4 12h16m0 0-6-6m6 6-6 6',
edit: 'M14 5.5 18.5 10M4 20l1-4.5L16.5 4a2.1 2.1 0 0 1 3 3L8 18.5 4 20Z',
+ // Add event: a point on the Timeline's own line, with the plus above it
+ eventAdd: 'M3 18h6.5m5 0H21M12 15.5a2.5 2.5 0 1 1 0 5 2.5 2.5 0 0 1 0-5ZM12 3.5v7M8.5 7h7',
external: 'M14 4h6v6m0-6L10 14M9 5H6a2 2 0 0 0-2 2v11a2 2 0 0 0 2 2h11a2 2 0 0 0 2-2v-3',
grip: 'M9 6h.01M9 12h.01M9 18h.01M15 6h.01M15 12h.01M15 18h.01',
// One column of `grip`'s dots: the settings of the thing beside it, rather than
@@ -110,6 +114,7 @@
eye: 'M2.5 12S6 5.5 12 5.5 21.5 12 21.5 12 18 18.5 12 18.5 2.5 12 2.5 12Zm9.5-3a3 3 0 1 1 0 6 3 3 0 0 1 0-6Z',
eyeOff: 'M9.9 9.9a3 3 0 1 0 4.2 4.2M10.7 5.7A9.8 9.8 0 0 1 12 5.5c6 0 9.5 6.5 9.5 6.5a17.8 17.8 0 0 1-2.2 3M6.6 6.6C4 8.4 2.5 12 2.5 12S6 18.5 12 18.5c1.5 0 2.9-.4 4.1-1.1M3 3l18 18',
key: 'm21 2-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777Zm0 0L15.5 7.5m0 0 3 3L22 7l-3-3m-3.5 3.5L19 4',
+ lock: 'M7 11V7a5 5 0 0 1 10 0v4M5 11h14a1 1 0 0 1 1 1v8a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1v-8a1 1 0 0 1 1-1Z',
shield: 'M12 21.5s7.5-3.7 7.5-9.3V5.4L12 2.5 4.5 5.4v6.8c0 5.6 7.5 9.3 7.5 9.3Z',
chart: 'M3.5 3.5v17h17m-4-5v-6m-5 6V8m-5 8.5v-3',
square: 'M5 5h14a1 1 0 0 1 1 1v12a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V6a1 1 0 0 1 1-1Z',
diff --git a/frontend/src/components/MediaPreview.render.test.js b/frontend/src/components/MediaPreview.render.test.js
new file mode 100644
index 0000000..1df0220
--- /dev/null
+++ b/frontend/src/components/MediaPreview.render.test.js
@@ -0,0 +1,61 @@
+// @vitest-environment happy-dom
+import { afterEach, describe, expect, it } from 'vitest';
+import { flushSync, mount, unmount } from 'svelte';
+import MediaPreview from './MediaPreview.svelte';
+
+/** A file shown where it is read, one press from full screen. */
+
+let live = null;
+let target = null;
+
+function show(props) {
+ target = document.createElement('div');
+ document.body.append(target);
+ live = mount(MediaPreview, { target, props: { caseId: 'case-a', ...props } });
+ flushSync();
+}
+
+afterEach(() => {
+ if (live) unmount(live);
+ live = null;
+ target?.remove();
+ document.querySelectorAll('.stage').forEach((node) => node.remove());
+});
+
+const media = (kind, path) => ({ id: 'm1', type: 'media', label: 'VID_0312', attrs: { kind, path } });
+
+describe('the preview', () => {
+ it('draws a picture from the path the entity carries', () => {
+ show({ entity: media('image', 'media/frame.jpg') });
+ expect(target.querySelector('img').getAttribute('src')).toContain('media/frame.jpg');
+ });
+
+ it('gives a video its controls, with the list’s picture as the first frame', () => {
+ show({ entity: media('video', 'media/clip.mp4'), thumb: '.thumbs/clip.jpg' });
+ const video = target.querySelector('video');
+ expect(video.getAttribute('src')).toContain('media/clip.mp4');
+ expect(video.hasAttribute('controls')).toBe(true);
+ expect(video.getAttribute('poster')).toContain('.thumbs/clip.jpg');
+ });
+
+ it('shows the picture the row had while the file is not known yet', () => {
+ show({ entity: null, thumb: '.thumbs/clip.jpg', label: 'VID_0312' });
+ expect(target.querySelector('img').getAttribute('src')).toContain('.thumbs/clip.jpg');
+ expect(target.querySelector('.enlarge')).toBeNull();
+ });
+
+ it('says what a file with no picture is, rather than drawing nothing', () => {
+ show({ entity: media('file', 'media/plan.pdf') });
+ expect(target.querySelector('.plain').textContent).toContain('VID_0312');
+ });
+
+ it('opens full screen on a press, and Escape closes it', () => {
+ show({ entity: media('image', 'media/frame.jpg') });
+ target.querySelector('.enlarge').click();
+ flushSync();
+ expect(document.querySelector('.stage img')).not.toBeNull();
+ window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', cancelable: true }));
+ flushSync();
+ expect(document.querySelector('.stage')).toBeNull();
+ });
+});
diff --git a/frontend/src/components/MediaPreview.svelte b/frontend/src/components/MediaPreview.svelte
new file mode 100644
index 0000000..fb2e5fb
--- /dev/null
+++ b/frontend/src/components/MediaPreview.svelte
@@ -0,0 +1,177 @@
+<script>
+ /**
+ * A file shown where it is read: the picture, the video ready to play, the sound.
+ *
+ * What an analyst most often wants from a dated file is to see it, and reaching it
+ * used to cost Details, then Info, then the file. This draws it in place from the
+ * path the entity already carries, with the thumbnail the list already had as the
+ * first frame, and one press opens it full screen. Nothing is made: a file with no
+ * picture says what it is and where it lives instead.
+ */
+ import { fileUrl } from '../lib/fileUrl.js';
+ import { mediaKindOf } from '../lib/entityIcon.js';
+ import { portal } from '../lib/fullscreen.js';
+ import { isTopOverlay, joinOverlays } from '../lib/overlayStack.js';
+ import Icon from './Icon.svelte';
+
+ let {
+ caseId,
+ /** The file, as the case holds it: `attrs.path` is what is drawn. */
+ entity = null,
+ /** A picture the row already had, shown until the file itself is known. */
+ thumb = '',
+ /** What the preview is of, for the reader of a screen reader and the tooltip. */
+ label = '',
+ } = $props();
+
+ const kind = $derived(entity ? (entity.type === 'capture' ? 'image' : mediaKindOf(entity)) : '');
+ const path = $derived(entity?.attrs?.path ?? '');
+ const source = $derived(caseId && path ? fileUrl(caseId, path) : '');
+ const still = $derived(caseId && thumb ? (thumb.startsWith('data:') ? thumb : fileUrl(caseId, thumb)) : '');
+ const name = $derived(label || entity?.label || 'File');
+
+ let large = $state(false);
+ const self = {};
+ $effect(() => (large ? joinOverlays(self) : undefined));
+ function onkeydown(event) {
+ if (large && event.key === 'Escape' && isTopOverlay(self)) {
+ event.preventDefault();
+ large = false;
+ }
+ }
+</script>
+
+<svelte:window {onkeydown} />
+
+{#if source || still}
+ <figure class="preview">
+ {#if source && kind === 'image'}
+ <button class="frame" title="Open it full screen" onclick={() => (large = true)}>
+ <img src={source} alt={name} loading="lazy" decoding="async" />
+ </button>
+ {:else if source && kind === 'video'}
+ <div class="frame">
+ <!-- svelte-ignore a11y_media_has_caption -->
+ <video src={source} poster={still || undefined} controls preload="metadata"></video>
+ </div>
+ {:else if source && kind === 'audio'}
+ <audio src={source} controls preload="metadata"></audio>
+ {:else if still}
+ <div class="frame"><img src={still} alt={name} /></div>
+ {:else}
+ <div class="plain"><Icon name="file" size={16} /><span>{name}</span></div>
+ {/if}
+ {#if source && (kind === 'image' || kind === 'video')}
+ <button class="enlarge" title="Open it full screen" aria-label="Open {name} full screen" onclick={() => (large = true)}>
+ <Icon name="maximize" size={13} />
+ </button>
+ {/if}
+ </figure>
+{/if}
+
+{#if large}
+ <!-- svelte-ignore a11y_click_events_have_key_events -->
+ <!-- svelte-ignore a11y_no_static_element_interactions -->
+ <div class="stage" use:portal onclick={(event) => event.target === event.currentTarget && (large = false)}>
+ <button class="close btn btn-ghost" aria-label="Close" title="Close (Esc)" onclick={() => (large = false)}>
+ <Icon name="x" size={20} />
+ </button>
+ {#if kind === 'video'}
+ <!-- svelte-ignore a11y_media_has_caption -->
+ <video src={source} controls autoplay></video>
+ {:else}
+ <img src={source} alt={name} />
+ {/if}
+ <p class="caption" dir="auto">{name}</p>
+ </div>
+{/if}
+
+<style>
+ .preview {
+ position: relative;
+ margin: 0 0 14px;
+ }
+ .frame {
+ display: grid;
+ place-items: center;
+ width: 100%;
+ max-height: 260px;
+ padding: 0;
+ overflow: hidden;
+ border: 1px solid var(--border);
+ border-radius: var(--r-md);
+ background: #0b0b0b;
+ }
+ button.frame {
+ cursor: zoom-in;
+ }
+ .frame img,
+ .frame video {
+ display: block;
+ width: 100%;
+ max-height: 258px;
+ object-fit: contain;
+ }
+ audio {
+ width: 100%;
+ }
+ .plain {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 12px;
+ border: 1px dashed var(--border-strong);
+ border-radius: var(--r-md);
+ color: var(--text-3);
+ font-size: var(--fs-xs);
+ }
+ .enlarge {
+ position: absolute;
+ top: 6px;
+ right: 6px;
+ display: grid;
+ place-items: center;
+ width: 26px;
+ height: 26px;
+ border: 0;
+ border-radius: var(--r-sm);
+ background: rgba(0, 0, 0, 0.55);
+ color: #fff;
+ opacity: 0;
+ cursor: pointer;
+ transition: opacity 120ms var(--ease);
+ }
+ .preview:hover .enlarge,
+ .enlarge:focus-visible {
+ opacity: 1;
+ }
+ .stage {
+ position: fixed;
+ inset: 0;
+ z-index: 980;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ gap: 10px;
+ padding: 40px;
+ background: rgba(4, 7, 12, 0.94);
+ }
+ .stage img,
+ .stage video {
+ max-width: 100%;
+ max-height: calc(100vh - 120px);
+ object-fit: contain;
+ }
+ .stage .close {
+ position: absolute;
+ top: 14px;
+ right: 14px;
+ color: #fff;
+ }
+ .caption {
+ margin: 0;
+ color: #cfcfcf;
+ font-size: var(--fs-sm);
+ }
+</style>
diff --git a/frontend/src/components/MergeSubjects.svelte b/frontend/src/components/MergeSubjects.svelte
new file mode 100644
index 0000000..3784613
--- /dev/null
+++ b/frontend/src/components/MergeSubjects.svelte
@@ -0,0 +1,125 @@
+<script>
+ import { onMount } from 'svelte';
+ import { api } from '../lib/api.js';
+ import { entityFields, entityLabel } from '../lib/entityTypes.svelte.js';
+ import EntityFinder from './EntityFinder.svelte';
+ import Modal from './Modal.svelte';
+
+ let { caseId, entity, initialOther = null, onclose, onmerged } = $props();
+ let other = $state(null);
+ let keepId = $state('');
+ let preview = $state(null);
+ let error = $state('');
+ let loading = $state(false);
+ let saving = $state(false);
+ let seq = 0;
+ const survivor = $derived(keepId === other?.id ? other : entity);
+ const absorbed = $derived(keepId === other?.id ? entity : other);
+ const display = (value) => typeof value === 'object' ? JSON.stringify(value) : String(value ?? '');
+ const fieldName = (key) => entityFields(entity.type).find((field) => field.key === key)?.label ?? ({ notes: 'Notes', folder: 'Folder' }[key] ?? key);
+ const visible = (fields) => Object.entries(fields ?? {}).filter(([key]) => !key.startsWith('_'));
+
+ function choose(candidate) {
+ other = candidate;
+ keepId = (candidate.provenance?.at ?? '') < (entity.provenance?.at ?? '') ? candidate.id : entity.id;
+ }
+ onMount(() => { if (initialOther) choose(initialOther); });
+ $effect(() => {
+ const keep = survivor?.id;
+ const lose = absorbed?.id;
+ const mine = ++seq;
+ preview = null;
+ error = '';
+ if (!lose) return;
+ loading = true;
+ let live = true;
+ api.get(`/api/cases/${caseId}/entities/${keep}/merge-preview?other=${encodeURIComponent(lose)}`)
+ .then((result) => { if (live && mine === seq) preview = result; })
+ .catch((cause) => { if (live && mine === seq) error = cause.message; })
+ .finally(() => { if (live && mine === seq) loading = false; });
+ return () => { live = false; };
+ });
+ async function save() {
+ if (!preview || preview.refused?.length || saving || loading) return;
+ saving = true;
+ error = '';
+ try {
+ const result = await api.post(`/api/cases/${caseId}/entities/${survivor.id}/merge`, { other: absorbed.id });
+ onmerged?.(result);
+ } catch (cause) {
+ error = cause.message;
+ } finally {
+ saving = false;
+ }
+ }
+</script>
+
+<Modal title="Merge subjects" width="720px" onclose={() => { if (!saving) onclose?.(); }}>
+ <div class="merge-body">
+ <p>Choose another {entityLabel(entity.type).toLowerCase()} that represents the same subject.</p>
+ {#if !other}
+ <EntityFinder {caseId} types={[entity.type]} exclude={[entity.id]} label="Find the duplicate" placeholder="Search by name or identifier…" onpick={choose} />
+ {:else}
+ <div class="survivors" role="group" aria-label="Subject to keep">
+ {#each [entity, other] as candidate (candidate.id)}
+ <button class="choice" class:chosen={survivor.id === candidate.id} aria-pressed={survivor.id === candidate.id} disabled={saving} onclick={() => (keepId = candidate.id)}>
+ <small>{survivor.id === candidate.id ? 'Keep' : 'Merge into the other'}</small>
+ <strong dir="auto">{candidate.label}</strong>
+ <span>Created {candidate.provenance?.at?.slice(0, 10) ?? 'date unknown'}</span>
+ </button>
+ {/each}
+ </div>
+ <button class="btn btn-ghost btn-sm another" disabled={saving} onclick={() => { other = null; keepId = ''; }}>Choose another subject</button>
+ {#if loading}<p role="status">Checking what will move…</p>{/if}
+ {#if preview}
+ <div class="table-wrap">
+ <table aria-label="Fields after merging">
+ <thead><tr><th>Kept</th><th>Added from <bdi>{absorbed.label}</bdi></th><th>Conflicts</th></tr></thead>
+ <tbody><tr>
+ <td>{#each visible(preview.fields.kept) as [key, value]}<p><strong>{fieldName(key)}</strong><span dir="auto">{display(value)}</span></p>{:else}No filled fields{/each}</td>
+ <td>{#each visible(preview.fields.added) as [key, value]}<p><strong>{fieldName(key)}</strong><span dir="auto">{display(value)}</span></p>{:else}None{/each}</td>
+ <td>{#each preview.fields.conflicts as conflict}<p><strong>{conflict.label}</strong><span dir="auto">{display(conflict.kept)} stays; {display(conflict.other)} goes into Notes.</span></p>{:else}None{/each}</td>
+ </tr></tbody>
+ </table>
+ </div>
+ <ul class="effects">
+ <li>{preview.links.moved} relations move; {preview.links.twins} identical relations combine; {preview.links.loops} links between these subjects are removed.</li>
+ <li>{preview.images.moved ?? 0} photos move; {preview.images.twins ?? 0} duplicate photos combine.</li>
+ <li>{preview.pins.moved ?? 0} graph positions move; {preview.pins.kept ?? 0} existing positions stay.</li>
+ <li>{preview.views.length} saved views and {preview.sheets} sheets follow the kept subject.</li>
+ <li>{preview.notes} notes keep their text and open the kept subject.</li>
+ </ul>
+ {#if preview.refused?.length}
+ <div class="error" role="alert">These relations prevent the merge:
+ <ul>{#each preview.refused as link}<li>{link.type}: {link.reason}</li>{/each}</ul>
+ </div>
+ {/if}
+ <p class="hint">Undo remains available in Details until this case is exported and imported as a bundle.</p>
+ {/if}
+ {/if}
+ {#if error}<p class="error" role="alert">{error}</p>{/if}
+ <div class="actions">
+ <button class="btn" disabled={saving} onclick={onclose}>Cancel</button>
+ <button class="btn btn-primary" disabled={!preview || loading || saving || Boolean(preview?.refused?.length)} onclick={save}>{saving ? 'Merging…' : 'Merge subjects'}</button>
+ </div>
+ </div>
+</Modal>
+
+<style>
+ .merge-body { display: grid; gap: 12px; font-size: var(--fs-sm); }
+ p { margin: 0; }
+ .survivors { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 8px; }
+ .choice { display: grid; gap: 5px; padding: 10px; text-align: left; border: 1px solid var(--border); border-radius: var(--r-md); background: var(--bg-2); color: var(--text-2); cursor: pointer; overflow-wrap: anywhere; }
+ .choice.chosen { border-color: var(--accent); background: var(--accent-soft); }
+ .choice small { color: var(--accent); }
+ .choice span, .hint { color: var(--text-3); font-size: var(--fs-xs); }
+ .another { justify-self: start; }
+ .table-wrap { overflow: auto; }
+ table { width: 100%; border-collapse: collapse; table-layout: fixed; }
+ th, td { width: 33%; padding: 8px; border: 1px solid var(--border); text-align: left; vertical-align: top; overflow-wrap: anywhere; }
+ th { background: var(--bg-2); font-size: var(--fs-xs); }
+ td p { display: grid; gap: 2px; margin-bottom: 7px; }
+ .effects { margin: 0; padding-left: 18px; display: grid; gap: 5px; color: var(--text-2); }
+ .actions { display: flex; justify-content: end; gap: 8px; }
+ .error { color: var(--danger); }
+</style>
diff --git a/frontend/src/components/NoteBar.render.test.js b/frontend/src/components/NoteBar.render.test.js
new file mode 100644
index 0000000..c03a956
--- /dev/null
+++ b/frontend/src/components/NoteBar.render.test.js
@@ -0,0 +1,109 @@
+// @vitest-environment happy-dom
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { flushSync, mount, unmount } from 'svelte';
+
+/** Add an event from wherever the analyst is, with what the tool is looking at. */
+
+const chains = {};
+const get = vi.fn(async (url) => chains[url.split('/entities/')[1]?.split('/')[0]] ?? { relations: [] });
+vi.mock('../lib/api.js', () => ({ api: { get, post: vi.fn() } }));
+
+const seatedWith = [];
+vi.mock('./EntryLine.svelte', async () => {
+ const { default: Stub } = await import('./NoteBarLine.fixture.svelte');
+ return {
+ default: Stub,
+ claimSeat: (entity) =>
+ entity ? { slot: { media: 'cites', place: 'at' }[entity.type] ?? 'about' } : null,
+ };
+});
+
+const { caseState, uiState } = await import('../lib/state.svelte.js');
+const { offerNote, withdrawNote } = await import('../lib/noteHere.svelte.js');
+const { default: NoteBar } = await import('./NoteBar.svelte');
+
+let live = null;
+
+async function settle() {
+ for (let index = 0; index < 8; index += 1) await Promise.resolve();
+ flushSync();
+}
+
+async function show() {
+ live = mount(NoteBar, { target: document.body });
+ flushSync();
+ await settle();
+}
+
+const bar = () => document.querySelector('.note-bar');
+
+beforeEach(() => {
+ caseState.current = { id: 'case-a', name: 'Case', entities: [], links: [], folders: [] };
+ uiState.tool = 'media';
+ uiState.noting = false;
+ seatedWith.length = 0;
+ globalThis.__noteBarLine = seatedWith;
+ withdrawNote('media');
+ withdrawNote('satellite');
+});
+
+afterEach(() => {
+ if (live) unmount(live);
+ live = null;
+});
+
+describe('the Add event bar', () => {
+ it('shows nothing until it is asked for', async () => {
+ await show();
+ expect(bar()).toBeNull();
+ });
+
+ it('opens on the tool’s own selection, with the date left to the analyst', async () => {
+ offerNote('media', { id: 'm1', label: 'VID_0312', type: 'media', attrs: {} });
+ uiState.noting = true;
+ await show();
+ expect(bar().querySelector('header').textContent).toContain('seen in VID_0312');
+ expect(seatedWith.at(-1)).toMatchObject({ entity: { id: 'm1' }, also: [] });
+ });
+
+ it('seats a file’s one confirmed place beside it', async () => {
+ chains.m1 = {
+ relations: [{
+ direction: 'out',
+ link: { type: 'located-at', provenance: { status: 'confirmed' } },
+ entity: { id: 'p1', type: 'place', label: 'Crossroads', attrs: {}, provenance: { status: 'confirmed' } },
+ }],
+ };
+ offerNote('media', { id: 'm1', label: 'VID_0312', type: 'media', attrs: {} });
+ uiState.noting = true;
+ await show();
+ await settle();
+ expect(seatedWith.at(-1).also).toEqual([
+ { id: 'p1', label: 'Crossroads', type: 'place', attrs: {}, slot: 'at' },
+ ]);
+ delete chains.m1;
+ });
+
+ it('never seats what another tool holds', async () => {
+ offerNote('satellite', { id: 'p1', label: 'Crossroads', type: 'place', attrs: {} });
+ uiState.noting = true;
+ await show();
+ expect(bar().querySelector('header .about')).toBeNull();
+ expect(seatedWith.at(-1).entity).toBeNull();
+ });
+
+ it('closes on Escape, and when the analyst moves to another tool', async () => {
+ uiState.noting = true;
+ await show();
+ bar().dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true, cancelable: true }));
+ flushSync();
+ expect(uiState.noting).toBe(false);
+
+ uiState.noting = true;
+ flushSync();
+ uiState.tool = 'satellite';
+ flushSync();
+ await settle();
+ expect(uiState.noting).toBe(false);
+ });
+});
diff --git a/frontend/src/components/NoteBar.svelte b/frontend/src/components/NoteBar.svelte
new file mode 100644
index 0000000..7b9850e
--- /dev/null
+++ b/frontend/src/components/NoteBar.svelte
@@ -0,0 +1,163 @@
+<script>
+ /**
+ * Add an event from wherever the analyst is: one line, anchored over the bottom of
+ * the tool on screen.
+ *
+ * Nothing is visible until it is asked for, by Add event in the topbar or Alt+N;
+ * no tool gains a button of its own (D19). What the tool is looking at is already
+ * seated (`lib/noteHere.svelte.js`): the video playing cites itself, and its one
+ * confirmed place is where it happened. The date stays empty (D3), with the file's
+ * own dates said beside it. It closes after Add, on Escape, and when the analyst
+ * moves to another tool, since what it seated belonged to this one.
+ */
+ import { tick } from 'svelte';
+ import { api } from '../lib/api.js';
+ import { caseState, uiState } from '../lib/state.svelte.js';
+ import { noteDatesFor, noteEntityFor, placeOf } from '../lib/noteHere.svelte.js';
+ import { portal } from '../lib/fullscreen.js';
+ import { isTopOverlay, joinOverlays } from '../lib/overlayStack.js';
+ import { claimActionTitle } from '../lib/quickClaim.js';
+ import EntryLine, { claimSeat } from './EntryLine.svelte';
+ import Icon from './Icon.svelte';
+
+ let line = $state(null);
+ let also = $state([]);
+
+ const caseId = $derived(caseState.current?.id ?? '');
+ const entity = $derived(uiState.noting ? noteEntityFor(uiState.tool) : null);
+ const dates = $derived(uiState.noting ? noteDatesFor(uiState.tool) : []);
+ const seat = $derived(entity ? claimSeat(entity) : null);
+ /** How the thing on screen sits on the event, in the heading's words. */
+ const SEAT_WORDS = { about: 'about', at: 'at', cites: 'seen in' };
+ const about = $derived(seat ? SEAT_WORDS[seat.slot] ?? '' : '');
+
+ function close() {
+ uiState.noting = false;
+ }
+
+ // What was seated belonged to the tool it was opened over.
+ let openedOn = null;
+ $effect(() => {
+ const tool = uiState.tool;
+ if (!uiState.noting) {
+ openedOn = null;
+ return;
+ }
+ if (openedOn && openedOn !== tool) close();
+ else openedOn = tool;
+ });
+
+ // A file's one confirmed place is seated beside it, read off its chain.
+ $effect(() => {
+ const id = entity?.id;
+ also = [];
+ if (!id || !caseId || !['media', 'capture', 'proof'].includes(entity.type)) return;
+ let live = true;
+ api.get(`/api/cases/${caseId}/entities/${id}/chain`)
+ .then((chain) => {
+ const place = placeOf(chain);
+ if (live && place) also = [place];
+ })
+ .catch(() => {});
+ return () => { live = false; };
+ });
+
+ // Straight to the sentence, which is what the press was for.
+ $effect(() => {
+ if (!uiState.noting) return;
+ entity?.id;
+ void tick().then(() => line?.focus?.());
+ });
+
+ // Over the tool's own overlays too (a file's Details, the lightbox), since that is
+ // where a file is watched; so it takes its turn in the Escape order like a modal.
+ const self = {};
+ $effect(() => (uiState.noting ? joinOverlays(self) : undefined));
+
+ function onkeydown(event) {
+ if (event.key !== 'Escape' || event.defaultPrevented || !isTopOverlay(self)) return;
+ event.preventDefault();
+ close();
+ }
+</script>
+
+{#if uiState.noting && caseId}
+ <!-- svelte-ignore a11y_no_noninteractive_element_interactions -->
+ <div class="note-bar" use:portal role="dialog" aria-modal="false" aria-label="Add an event" tabindex="-1" {onkeydown}>
+ <header>
+ <Icon name="edit" size={13} />
+ <strong>Add an event</strong>
+ {#if entity && seat}
+ <span class="about" title={claimActionTitle(seat.slot)}>
+ {about} <bdi>{entity.label}</bdi>
+ </span>
+ {/if}
+ <span class="keys">Enter adds · Esc closes</span>
+ <button class="btn btn-ghost btn-sm" aria-label="Close" title="Close (Esc)" onclick={close}>
+ <Icon name="x" size={13} />
+ </button>
+ </header>
+ {#key `${uiState.tool}:${entity?.id ?? ''}`}
+ <EntryLine
+ bind:this={line}
+ {caseId}
+ {entity}
+ {also}
+ {dates}
+ draftKey={`note:${uiState.tool}:${entity?.id ?? ''}`}
+ onsaved={close}
+ oncancel={close}
+ />
+ {/key}
+ </div>
+{/if}
+
+<style>
+ /* Over the bottom of the screen, above the tool's own overlays (a modal is 900, the
+ lightbox 950) and under the topbar and the toasts, and wide enough for the line to
+ sit on one row where it can. */
+ .note-bar {
+ position: fixed;
+ left: calc(50% + var(--rail-w) / 2);
+ bottom: 20px;
+ z-index: 960;
+ width: min(920px, calc(100vw - var(--rail-w) - 48px));
+ transform: translateX(-50%);
+ display: grid;
+ gap: 8px;
+ padding: 10px 12px 12px;
+ border: 1px solid var(--border-strong);
+ border-radius: var(--r-lg);
+ background: var(--bg-1);
+ box-shadow: var(--shadow-2);
+ animation: rise 140ms var(--ease);
+ }
+ @keyframes rise {
+ from {
+ opacity: 0;
+ transform: translate(-50%, 8px);
+ }
+ }
+ header {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ min-width: 0;
+ color: var(--text-3);
+ font-size: var(--fs-xs);
+ }
+ header strong {
+ color: var(--text-1);
+ font-weight: 600;
+ }
+ .about {
+ overflow: hidden;
+ color: var(--text-2);
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ .keys {
+ margin-left: auto;
+ white-space: nowrap;
+ }
+</style>
diff --git a/frontend/src/components/NoteBarLine.fixture.svelte b/frontend/src/components/NoteBarLine.fixture.svelte
new file mode 100644
index 0000000..a3154e8
--- /dev/null
+++ b/frontend/src/components/NoteBarLine.fixture.svelte
@@ -0,0 +1,10 @@
+<script>
+ // A stand-in for EntryLine in the NoteBar tests: records what it was seated with.
+ let { entity = null, also = [] } = $props();
+ $effect(() => {
+ globalThis.__noteBarLine?.push({ entity, also });
+ });
+ export function focus() {}
+</script>
+
+<div class="entry-line-stub"></div>
diff --git a/frontend/src/components/PostTemplateEditor.render.svelte.test.js b/frontend/src/components/PostTemplateEditor.render.svelte.test.js
new file mode 100644
index 0000000..780c1eb
--- /dev/null
+++ b/frontend/src/components/PostTemplateEditor.render.svelte.test.js
@@ -0,0 +1,221 @@
+// @vitest-environment happy-dom
+/**
+ * The post-template editor, actually mounted.
+ *
+ * What it promises is only visible in a DOM: a preview that follows the layout as
+ * it is typed, a count that turns red at a platform's limit, a warning that mends
+ * itself in one click, and starting layouts that appear for a new template only.
+ */
+import { afterEach, describe, expect, it } from 'vitest';
+import { flushSync, mount, unmount } from 'svelte';
+import PostTemplateEditor from './PostTemplateEditor.svelte';
+import { postDraftState } from '../lib/state.svelte.js';
+import { DEFAULT_TWEET_BODY, POST_TEMPLATE_STARTERS, TWEET_TOKENS } from '../lib/post.js';
+
+const sample = (tag) => TWEET_TOKENS.find((t) => t.tag === tag).sample;
+
+let target;
+let app;
+
+function open({ fresh = false, ...blob } = {}) {
+ target = document.createElement('div');
+ document.body.append(target);
+ const data = $state({
+ mention: '@GeoConfirmed',
+ body: DEFAULT_TWEET_BODY,
+ mediaEnabled: true,
+ extraTweets: [],
+ ...blob,
+ });
+ app = mount(PostTemplateEditor, {
+ target,
+ props: {
+ get data() {
+ return data;
+ },
+ fresh,
+ },
+ });
+ flushSync();
+ return data;
+}
+
+afterEach(() => {
+ if (app) unmount(app);
+ target?.remove();
+ app = null;
+ postDraftState.fields = null;
+});
+
+const preview = () => target.querySelector('.pe-preview pre').textContent;
+const counters = () => [...target.querySelectorAll('.counter')];
+const optionButton = (label) =>
+ [...target.querySelectorAll('.pv-opt')].find((b) => b.textContent.trim() === label);
+const warnings = () => [...target.querySelectorAll('.misspelled')];
+const click = (el) => {
+ el.click();
+ flushSync();
+};
+
+describe('the preview', () => {
+ it('opens on the sample facts, with the template own mention', () => {
+ open({ body: '#place\n#mention', mention: '@House' });
+ expect(preview()).toBe(`${sample('#place')}\n@House`);
+ });
+
+ it('shows the date line the sample carries', () => {
+ open({ body: 'Filmed: #date' });
+ expect(preview()).toBe(`Filmed: ${sample('#date')}`);
+ });
+
+ it('drops the mention line when the template has none, as a post would', () => {
+ open({ body: '#place\n#mention', mention: '' });
+ expect(preview()).toBe(sample('#place'));
+ });
+
+ it('follows the layout as it is typed', () => {
+ const data = open({ body: '#place' });
+ data.body = '#mention\n#place';
+ flushSync();
+ expect(preview()).toBe(`@GeoConfirmed\n${sample('#place')}`);
+ });
+
+ it('says so when the layout would print nothing', () => {
+ open({ body: '#description', mention: '' });
+ postDraftState.fields = { description: '' };
+ flushSync();
+ click(optionButton('Open post'));
+ expect(preview()).toBe('(empty post)');
+ });
+});
+
+describe('the open post', () => {
+ const draft = {
+ place: 'Kyiv', plusCode: '', description: '', lat: 50.45, lon: 30.52,
+ coordsText: '', mention: '@FromTheDraft', source: '', date: '',
+ };
+
+ it('is not offered while the composer holds nothing, and says why', () => {
+ open();
+ const button = optionButton('Open post');
+ expect(button.disabled).toBe(true);
+ expect(button.getAttribute('title')).toBe('No post is open in the composer');
+ expect(optionButton('Sample').getAttribute('aria-pressed')).toBe('true');
+ });
+
+ it('fills the layout with the draft, under the template own mention', () => {
+ open({ body: '#place\n#mention', mention: '@House' });
+ postDraftState.fields = draft;
+ flushSync();
+
+ expect(optionButton('Open post').disabled).toBe(false);
+ expect(preview()).toBe(`${sample('#place')}\n@House`); // still the sample until asked
+
+ click(optionButton('Open post'));
+ expect(preview()).toBe('Kyiv\n@House');
+ expect(optionButton('Open post').getAttribute('aria-pressed')).toBe('true');
+
+ click(optionButton('Sample'));
+ expect(preview()).toBe(`${sample('#place')}\n@House`);
+ });
+
+ it('follows the draft while it is edited, and lets go when the composer is emptied', () => {
+ open({ body: '#place' });
+ postDraftState.fields = draft;
+ flushSync();
+ click(optionButton('Open post'));
+
+ postDraftState.fields = { ...draft, place: 'Bucha' };
+ flushSync();
+ expect(preview()).toBe('Bucha');
+
+ postDraftState.fields = null;
+ flushSync();
+ expect(preview()).toBe(sample('#place'));
+ expect(optionButton('Open post').disabled).toBe(true);
+ expect(optionButton('Sample').getAttribute('aria-pressed')).toBe('true');
+ });
+});
+
+describe('the character counters', () => {
+ it('counts the first post for each platform', () => {
+ open({ body: 'hello', mention: '' });
+ expect(counters().map((c) => c.textContent)).toEqual(['X 5/280', 'Bluesky 5/300']);
+ expect(target.querySelector('.counters').textContent).toBe('X 5/280 · Bluesky 5/300');
+ });
+
+ it('reddens only the platform whose limit the post is past', () => {
+ open({ body: 'a'.repeat(290), mention: '' });
+ const [x, bluesky] = counters();
+ expect(x.textContent).toBe('X 290/280');
+ expect(x.classList.contains('over')).toBe(true);
+ expect(bluesky.textContent).toBe('Bluesky 290/300');
+ expect(bluesky.classList.contains('over')).toBe(false);
+ });
+
+ it('counts a link as X does, whatever its length', () => {
+ open({ body: `https://example.org/${'a'.repeat(200)}`, mention: '' });
+ expect(counters()[0].textContent).toBe('X 23/280');
+ });
+});
+
+describe('a word that looks like a token and is not one', () => {
+ it('is named with the token it meant', () => {
+ open({ body: '#place\n#coordinate' });
+ expect(warnings()).toHaveLength(1);
+ expect(warnings()[0].textContent.replace(/\s+/g, ' ')).toContain(
+ '#coordinate is not a token. Did you mean #coordinates?',
+ );
+ });
+
+ it('is mended everywhere by Fix, which then goes away', () => {
+ const data = open({ body: '#coordinate\n#place #coordinate\n#coordinates' });
+ click(warnings()[0].querySelector('button'));
+ expect(data.body).toBe('#coordinates\n#place #coordinates\n#coordinates');
+ expect(warnings()).toHaveLength(0);
+ expect(target.querySelector('textarea.body').value).toBe(data.body);
+ });
+
+ it('says nothing about a layout made of real tokens and its own hashtags', () => {
+ open({ body: `${DEFAULT_TWEET_BODY}\n#osint` });
+ expect(warnings()).toHaveLength(0);
+ });
+
+ it('appears as the layout is typed', () => {
+ const textarea = () => target.querySelector('textarea.body');
+ open({ body: '#place' });
+ expect(warnings()).toHaveLength(0);
+ textarea().value = '#place\n#plus_code';
+ textarea().dispatchEvent(new Event('input', { bubbles: true }));
+ flushSync();
+ expect(warnings()).toHaveLength(1);
+ });
+});
+
+describe('starting points', () => {
+ const starters = () => target.querySelector('.starters');
+
+ it('are offered for a new template only', () => {
+ open({ fresh: false });
+ expect(starters()).toBeNull();
+ });
+
+ it('are one button each, and Start from says what they are', () => {
+ open({ fresh: true });
+ expect(starters().textContent).toContain('Start from');
+ expect([...starters().querySelectorAll('button')].map((b) => b.textContent.trim())).toEqual(
+ POST_TEMPLATE_STARTERS.map((s) => s.label),
+ );
+ });
+
+ it('replace the layout with theirs and leave the rest of the template alone', () => {
+ const data = open({ fresh: true, mention: '@House', mediaEnabled: false });
+ const short = POST_TEMPLATE_STARTERS.find((s) => s.id === 'short');
+ click([...starters().querySelectorAll('button')].find((b) => b.textContent.trim() === short.label));
+ expect(data.body).toBe(short.body);
+ expect(target.querySelector('textarea.body').value).toBe(short.body);
+ expect(data.mention).toBe('@House');
+ expect(data.mediaEnabled).toBe(false);
+ expect(preview()).toBe(`${sample('#place')}\n48.850000, 2.350000\n\nSource: ${sample('#source')}`);
+ });
+});
diff --git a/frontend/src/components/PostTemplateEditor.svelte b/frontend/src/components/PostTemplateEditor.svelte
index 172a5c7..d83830c 100644
--- a/frontend/src/components/PostTemplateEditor.svelte
+++ b/frontend/src/components/PostTemplateEditor.svelte
@@ -3,15 +3,22 @@
* Editor for one post-thread template. The thread structure is a token body:
* the analyst arranges tokens (#place, #coordinates, …) in the order and line
* layout they want, mixes in literal text, and a live preview fills them with
- * sample values. Plus the default mention, the media-tweet flag and any
+ * sample values or with the post open in the composer, and counts each
+ * platform's limit. Plus the default mention, the media-tweet flag and any
* boilerplate extra tweets. Content-free.
*
- * `data` is the template blob (bindable); the parent owns save/delete.
+ * `data` is the template blob (bindable); the parent owns save/delete. `fresh`
+ * marks a new template, which offers starting layouts to begin from.
*/
- import { TWEET_TOKENS, DEFAULT_TWEET_BODY, buildTweet1 } from '../lib/post.js';
+ import {
+ TWEET_TOKENS, DEFAULT_TWEET_BODY, POST_TARGETS, POST_TEMPLATE_STARTERS, buildTweet1,
+ fixMisspelledToken, misspelledTokens, postCharacterCount,
+ } from '../lib/post.js';
+ import { postDraftState } from '../lib/state.svelte.js';
+ import { bidiSafe } from '../lib/bidi.js';
import Icon from './Icon.svelte';
- let { data = $bindable() } = $props();
+ let { data = $bindable(), fresh = false } = $props();
// guarantee the shape (a hand-edited or legacy blob may omit fields)
if (typeof data.body !== 'string' || !data.body) data.body = DEFAULT_TWEET_BODY;
@@ -42,19 +49,38 @@
data.extraTweets.splice(i, 1);
}
- // Live preview of the first tweet with placeholder facts + the template's own
- // mention, so the effect of the token layout reads without leaving Settings.
+ // A word that looks like a token and is not one goes out as plain text, so it
+ // is named here, with the one click that mends it.
+ const misspelled = $derived(misspelledTokens(data.body));
+
+ // Live preview of the first tweet, so the effect of the token layout reads
+ // without leaving Settings. It fills the tokens with placeholder facts, or with
+ // the post open in the composer when there is one. The template's own mention
+ // wins either way: applying the template is what sets it on a post.
const SAMPLE = Object.fromEntries(TWEET_TOKENS.map((t) => [t.tag.slice(1), t.sample]));
- const preview = $derived(
- buildTweet1(data.body, {
- place: SAMPLE.place,
- plusCode: SAMPLE.pluscode,
- description: SAMPLE.description,
- lat: 48.85,
- lon: 2.35,
- mention: data.mention || SAMPLE.mention,
- source: SAMPLE.source,
- }) || '(empty post)'
+ const SAMPLE_FIELDS = {
+ place: SAMPLE.place,
+ plusCode: SAMPLE.pluscode,
+ description: SAMPLE.description,
+ lat: 48.85,
+ lon: 2.35,
+ source: SAMPLE.source,
+ date: SAMPLE.date,
+ };
+ let previewWith = $state('sample'); // 'sample' | 'open'
+ const openFields = $derived(postDraftState.fields);
+ // The composer can be emptied while this is open, which takes its post away.
+ const useOpen = $derived(previewWith === 'open' && !!openFields);
+ const built = $derived(
+ buildTweet1(data.body, { ...(useOpen ? openFields : SAMPLE_FIELDS), mention: data.mention })
+ );
+ const preview = $derived(built || '(empty post)');
+ // What is copied is the bidi-safe text, so that is what each platform counts.
+ const counts = $derived(
+ Object.values(POST_TARGETS).map((target) => {
+ const count = postCharacterCount(target.id, bidiSafe(built));
+ return { ...target, count, over: count > target.limit };
+ })
);
</script>
@@ -70,6 +96,16 @@
<span>First post layout</span>
<p class="hint">Arrange the tokens in the order you want, add line breaks and
your own text. A token with no value drops its line.</p>
+ {#if fresh}
+ <div class="starters" role="group" aria-label="Start from">
+ <span class="starters-label">Start from</span>
+ {#each POST_TEMPLATE_STARTERS as starter (starter.id)}
+ <button type="button" class="tok starter" onclick={() => (data.body = starter.body)}>
+ {starter.label}
+ </button>
+ {/each}
+ </div>
+ {/if}
<div class="tokens">
{#each TWEET_TOKENS as tok}
<button type="button" class="tok" title={`Insert ${tok.tag}`}
@@ -77,6 +113,14 @@
{/each}
</div>
<textarea class="body" rows="9" bind:this={bodyEl} bind:value={data.body}></textarea>
+ {#each misspelled as word (word.written)}
+ <p class="misspelled" role="status">
+ <span><code>{word.written}</code> is not a token. Did you mean <code>{word.meant}</code>?</span>
+ <button type="button" class="btn btn-sm"
+ onclick={() => (data.body = fixMisspelledToken(data.body, word.written, word.meant))}
+ >Fix</button>
+ </p>
+ {/each}
</fieldset>
<label class="chk">
@@ -100,7 +144,17 @@
<div class="pe-preview">
<span class="pv-label">First post preview</span>
+ <div class="pv-switch" role="group" aria-label="Preview with">
+ <button type="button" class="pv-opt" class:on={!useOpen} aria-pressed={!useOpen}
+ onclick={() => (previewWith = 'sample')}>Sample</button>
+ <button type="button" class="pv-opt" class:on={useOpen} aria-pressed={useOpen}
+ disabled={!openFields}
+ title={openFields ? 'Fill it with the post open in the composer' : 'No post is open in the composer'}
+ onclick={() => (previewWith = 'open')}>Open post</button>
+ </div>
<pre>{preview}</pre>
+ <!-- one line of markup, so no stray whitespace lands between the counts -->
+ <p class="counters">{#each counts as count, i (count.id)}{#if i}<span aria-hidden="true">{' · '}</span>{/if}<span class="counter" class:over={count.over}>{count.label} {count.count}/{count.limitLabel}</span>{/each}</p>
</div>
</div>
</div>
@@ -123,6 +177,14 @@
cursor: pointer;
}
.tok:hover { background: var(--bg-3); }
+ .starters { display: flex; flex-wrap: wrap; align-items: center; gap: 5px; }
+ .starters-label { font-size: 11px; color: var(--text-3); margin-right: 2px; }
+ .starter { color: var(--text-1); font-family: inherit; }
+ .misspelled {
+ display: flex; align-items: center; justify-content: space-between; gap: 8px;
+ margin: 0; font-size: 12px; color: var(--warn, #d8a03d); line-height: 1.4;
+ }
+ .misspelled code { font: 11px var(--font-mono, monospace); }
.chk { display: flex; gap: 6px; align-items: center; font-size: 13px; color: var(--text-2); }
.extra-row { display: grid; grid-template-columns: 1fr auto; gap: 8px; align-items: start; }
.pe-preview {
@@ -131,6 +193,21 @@
position: sticky; top: 0;
}
.pv-label { font-size: 11px; color: var(--text-3); font-weight: 600; }
+ .pv-switch {
+ display: flex; border: 1px solid var(--border); border-radius: 6px; overflow: hidden;
+ align-self: flex-start;
+ }
+ .pv-opt {
+ padding: 3px 10px; background: var(--bg-2); color: var(--text-2); font-size: 11px;
+ border: 0; border-left: 1px solid var(--border); cursor: pointer;
+ }
+ .pv-opt:first-child { border-left: 0; }
+ .pv-opt:hover:not(:disabled) { background: var(--bg-3); color: var(--text-1); }
+ .pv-opt.on { background: var(--accent); color: var(--accent-text); font-weight: 600; }
+ .pv-opt:disabled { opacity: 0.45; cursor: not-allowed; }
+ .counters { margin: 0; font-size: 11px; color: var(--text-3); }
+ .counter { font: 700 11px var(--font-mono, monospace); color: var(--ok); }
+ .counter.over { color: var(--danger); }
.pe-preview pre {
margin: 0; white-space: pre-wrap; word-break: break-word;
font: 12px/1.4 system-ui, sans-serif; color: var(--text-1);
diff --git a/frontend/src/components/QuickClaim.render.test.js b/frontend/src/components/QuickClaim.render.test.js
deleted file mode 100644
index c2b595f..0000000
--- a/frontend/src/components/QuickClaim.render.test.js
+++ /dev/null
@@ -1,200 +0,0 @@
-// @vitest-environment happy-dom
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { flushSync, mount, unmount } from 'svelte';
-
-/**
- * The quick claim form, filled the way an analyst fills it: the entity it was
- * opened from already in its seat, only the fields that entity's family calls for,
- * a sentence that writes itself until one is typed, and one request that files the
- * whole observation.
- */
-
-const CONDITIONS = [
- { value: 'intact', label: 'Intact' },
- { value: 'damaged', label: 'Damaged' },
- { value: 'destroyed', label: 'Destroyed' },
- { value: 'abandoned', label: 'Abandoned' },
-];
-const TYPES = [
- { type: 'equipment-type', family: 'class', label: 'Equipment type', attrs: [] },
- { type: 'vehicle', family: 'asset', label: 'Vehicle', attrs: [] },
- { type: 'person', family: 'actor', label: 'Person', attrs: [] },
- { type: 'place', family: 'place', label: 'Place', attrs: [] },
- { type: 'media', family: 'collected', label: 'Media', attrs: [] },
- {
- type: 'claim',
- family: 'claim',
- label: 'Claim',
- attrs: [
- { key: 'count', label: 'How many', kind: 'number', minimum: 1, maximum: 100000 },
- { key: 'condition', label: 'Condition', kind: 'choice', options: CONDITIONS },
- {
- key: 'confidence',
- label: 'Confidence',
- kind: 'choice',
- options: [
- { value: 'certain', label: 'Certain' },
- { value: 'probable', label: 'Probable' },
- ],
- },
- ],
- },
-];
-const verb = (type, to) => ({ type, label: type, action: 'claim', manual: true, from_types: ['claim'], to_types: to });
-const RELATIONS = [
- verb('about', ['equipment-type', 'vehicle', 'person', 'place', 'media']),
- verb('at', ['place']),
- verb('cites', ['media']),
-];
-
-const get = vi.fn(async (url) => {
- if (url.includes('/entity-types')) return TYPES;
- if (url.includes('/relation-types')) return RELATIONS;
- if (url.includes('/confidence-levels')) return [];
- return { items: [] };
-});
-const post = vi.fn(async () => ({ entity: { id: 'claim-1' } }));
-vi.mock('../lib/api.js', () => ({ api: { get, post } }));
-
-const reloadCase = vi.fn(async () => {});
-const toast = vi.fn();
-vi.mock('../lib/state.svelte.js', () => ({ reloadCase, toast }));
-
-const { default: QuickClaim, claimSeat } = await import('./QuickClaim.svelte');
-
-let live = null;
-let target = null;
-
-async function settle() {
- for (let index = 0; index < 12; index += 1) await Promise.resolve();
- flushSync();
-}
-
-async function open(entity, props = {}) {
- target = document.createElement('div');
- document.body.append(target);
- live = mount(QuickClaim, { target, props: { caseId: 'case-a', entity, ...props } });
- await settle();
-}
-
-const statement = () => target.querySelector('.quick-claim textarea');
-const count = () => target.querySelector('input[type="number"]');
-const conditionSelect = () =>
- [...target.querySelectorAll('select')].find((s) => [...s.options].some((o) => o.value === 'destroyed'));
-const addButton = () => [...target.querySelectorAll('button')].find((b) => b.textContent.trim() === 'Add claim');
-
-function type(element, value) {
- element.value = value;
- element.dispatchEvent(new Event('input', { bubbles: true }));
- flushSync();
-}
-
-function choose(element, value) {
- element.value = value;
- element.dispatchEvent(new Event('change', { bubbles: true }));
- flushSync();
-}
-
-const MODEL = { id: 'model-1', type: 'equipment-type', label: 'T-72B3' };
-
-beforeEach(() => vi.clearAllMocks());
-
-afterEach(() => {
- if (live) unmount(live);
- live = null;
- target?.remove();
-});
-
-describe('filed from a model', () => {
- it('asks how many and in what state, and writes the sentence from them', async () => {
- await open(MODEL);
-
- expect(count()).not.toBeNull();
- expect(conditionSelect()).not.toBeUndefined();
- expect(statement().value).toBe('T-72B3 seen');
-
- type(count(), '2');
- choose(conditionSelect(), 'destroyed');
- expect(statement().value).toBe('2 × T-72B3 destroyed');
- });
-
- it('files the observation about the model in one request, then refreshes the case', async () => {
- const onsaved = vi.fn();
- await open(MODEL, { onsaved });
- type(count(), '2');
- choose(conditionSelect(), 'destroyed');
-
- addButton().click();
- await settle();
-
- expect(post).toHaveBeenCalledWith('/api/cases/case-a/timeline/claims', {
- statement: '2 × T-72B3 destroyed',
- when: null,
- time_role: null,
- confidence: null,
- count: 2,
- condition: 'destroyed',
- about: ['model-1'],
- at: [],
- cites: [],
- });
- expect(reloadCase).toHaveBeenCalled();
- expect(onsaved).toHaveBeenCalled();
- });
-
- it('keeps a sentence the analyst wrote when a field changes under it', async () => {
- await open(MODEL);
- type(statement(), 'Two tanks burning near the bridge');
- type(count(), '3');
-
- expect(statement().value).toBe('Two tanks burning near the bridge');
- const rewrite = [...target.querySelectorAll('button')].find((b) => b.textContent.includes('Rewrite from the fields'));
- rewrite.click();
- flushSync();
- expect(statement().value).toBe('3 × T-72B3 seen');
- });
-});
-
-describe('filed from something else', () => {
- it('asks a named object for its state and never for a count', async () => {
- await open({ id: 'v-1', type: 'vehicle', label: 'Bridge truck' });
- expect(count()).toBeNull();
- expect(conditionSelect()).not.toBeUndefined();
- });
-
- it('asks a person for neither', async () => {
- await open({ id: 'p-1', type: 'person', label: 'Ivan' });
- expect(count()).toBeNull();
- expect(conditionSelect()).toBeUndefined();
- expect(statement().value).toBe('Ivan seen');
- });
-
- it('seats a place where it was seen', async () => {
- await open({ id: 'place-1', type: 'place', label: 'Crossroads' });
- expect(statement().value).toBe('Seen at Crossroads');
-
- type(statement(), 'Convoy seen at Crossroads');
- addButton().click();
- await settle();
- expect(post.mock.calls[0][1]).toMatchObject({ about: [], at: ['place-1'], cites: [] });
- });
-
- it('seats a video as the evidence and leaves the sentence to the analyst', async () => {
- await open({ id: 'm-1', type: 'media', label: 'clip.mp4', attrs: { kind: 'video' } });
- expect(statement().value).toBe('');
- expect(addButton().disabled).toBe(true);
-
- type(statement(), 'A column heading east');
- addButton().click();
- await settle();
- expect(post.mock.calls[0][1]).toMatchObject({ about: [], at: [], cites: ['m-1'] });
- });
-});
-
-describe('claimSeat', () => {
- it('offers no seat on a claim itself, which has its own editor', async () => {
- await open(MODEL); // lands both registries
- expect(claimSeat({ id: 'c', type: 'claim', label: 'x' })).toBeNull();
- expect(claimSeat(MODEL)).toEqual({ slot: 'about', count: true, condition: true });
- });
-});
diff --git a/frontend/src/components/QuickClaim.svelte b/frontend/src/components/QuickClaim.svelte
deleted file mode 100644
index a273a56..0000000
--- a/frontend/src/components/QuickClaim.svelte
+++ /dev/null
@@ -1,217 +0,0 @@
-<script module>
- import { entityFamily } from '../lib/entityTypes.svelte.js';
- import { relationOptions } from '../lib/relations.svelte.js';
- import { quickClaimSeat } from '../lib/quickClaim.js';
-
- /**
- * Where this entity sits on a Claim filed from it, or null when it has no seat.
- * Read off the relation registry, so a host shows its button exactly where this
- * form can file something. Null until both registries have landed.
- */
- export function claimSeat(entity) {
- if (!entity || entity.type === 'claim') return null;
- return quickClaimSeat(entityFamily(entity.type), (verb) =>
- relationOptions('claim', entity, 'claim').some((o) => o.type === verb && o.direction === 'out')
- );
- }
-</script>
-
-<script>
- /**
- * A Claim filed from the entity it is about, in one small form (lib/quickClaim.js).
- *
- * The entity takes its own seat — a model or an object is what the claim is about,
- * a place is where, a file is the evidence — and the form asks only for the rest.
- * The sentence writes itself from the fields until the analyst writes their own.
- * The full editor on the Timeline and the Time tab is still where a claim is
- * reworked; this one files the common observation without going there.
- */
- import { api } from '../lib/api.js';
- import { reloadCase, toast } from '../lib/state.svelte.js';
- import { entityFields, loadEntityTypes } from '../lib/entityTypes.svelte.js';
- import { loadRelationTypes } from '../lib/relations.svelte.js';
- import { composeClaimStatement, quickClaimBody } from '../lib/quickClaim.js';
- import { formatTemporalValue } from '../lib/timeline.js';
- import DateField from './DateField.svelte';
- import TemporalTargetPicker from './TemporalTargetPicker.svelte';
-
- let { caseId, entity, onsaved, oncancel } = $props();
- // Two of these can be open at once — Details beside a board row's — so the
- // labels point at their own fields.
- const uid = $props.id();
-
- loadEntityTypes();
- loadRelationTypes();
-
- const seat = $derived(claimSeat(entity));
- const own = $derived([{ id: entity.id, label: entity.label, type: entity.type }]);
- const lockedAbout = $derived(seat?.slot === 'about' ? own : []);
- const lockedAt = $derived(seat?.slot === 'at' ? own : []);
- const lockedCites = $derived(seat?.slot === 'cites' ? own : []);
-
- const fields = $derived(entityFields('claim'));
- const countField = $derived(fields.find((field) => field.key === 'count'));
- const conditions = $derived(fields.find((field) => field.key === 'condition')?.options ?? []);
- const confidences = $derived(fields.find((field) => field.key === 'confidence')?.options ?? []);
-
- let count = $state(null);
- let condition = $state('');
- let about = $state([]);
- let places = $state([]);
- let cites = $state([]);
- let when = $state('');
- let confidence = $state('');
- let statement = $state('');
- let edited = $state(false);
- let saving = $state(false);
-
- const composed = $derived(
- composeClaimStatement({
- count: Number.isInteger(count) ? count : null,
- condition: conditions.find((option) => option.value === condition)?.label ?? '',
- subjects: [...lockedAbout, ...about].map((item) => item.label),
- places: [...lockedAt, ...places].map((item) => item.label),
- })
- );
- // The fields write the sentence until the analyst writes one; a sentence of
- // their own is never overwritten by a field changing under it.
- $effect(() => {
- if (!edited) statement = composed;
- });
-
- const whenValid = $derived(!when || formatTemporalValue(when).valid);
- const ready = $derived(Boolean(statement.trim()) && whenValid && !saving && Boolean(seat));
-
- async function save() {
- if (!ready) return;
- saving = true;
- try {
- const saved = await api.post(
- `/api/cases/${caseId}/timeline/claims`,
- quickClaimBody({
- statement,
- when,
- confidence,
- count,
- condition,
- seat,
- about: [...lockedAbout, ...about].map((item) => item.id),
- at: [...lockedAt, ...places].map((item) => item.id),
- cites: [...lockedCites, ...cites].map((item) => item.id),
- })
- );
- toast('Claim added', 'ok', 1800);
- await reloadCase();
- onsaved?.(saved);
- } catch (error) {
- toast(error.message, 'danger');
- } finally {
- saving = false;
- }
- }
-
- function onkeydown(event) {
- if (event.key === 'Enter' && (event.ctrlKey || event.metaKey)) {
- event.preventDefault();
- save();
- }
- }
-</script>
-
-<!-- svelte-ignore a11y_no_static_element_interactions -->
-<div class="quick-claim" {onkeydown}>
- <div class="statement-head">
- <label class="modal-label" for="{uid}-statement">Claim</label>
- {#if edited && statement !== composed && composed}
- <button class="btn btn-ghost btn-xs" onclick={() => (edited = false)} title="Write the sentence from the fields again">
- Rewrite from the fields
- </button>
- {/if}
- </div>
- <textarea
- id="{uid}-statement"
- class="textarea"
- rows="2"
- maxlength="300"
- placeholder="What was seen?"
- bind:value={statement}
- oninput={() => (edited = true)}
- ></textarea>
-
- {#if seat?.count || seat?.condition}
- <div class="facts">
- {#if seat.count}
- <label>
- <span class="modal-label">How many</span>
- <input
- class="input"
- type="number"
- min={countField?.minimum ?? 1}
- max={countField?.maximum}
- step="1"
- placeholder="Not counted"
- bind:value={count}
- />
- </label>
- {/if}
- {#if seat.condition}
- <label>
- <span class="modal-label">Condition</span>
- <select class="select" value={condition} onchange={(event) => (condition = event.currentTarget.value)}>
- <option value="">Not stated</option>
- {#each conditions as option (option.value)}
- <option value={option.value}>{option.label}</option>
- {/each}
- </select>
- </label>
- {/if}
- </div>
- {/if}
-
- <section class="connections">
- <TemporalTargetPicker {caseId} relationType="about" label="About" hint="Who or what was seen" bind:selected={about} locked={lockedAbout} />
- <TemporalTargetPicker {caseId} relationType="at" label="Place" hint="Where it was seen" bind:selected={places} locked={lockedAt} />
- <TemporalTargetPicker {caseId} relationType="cites" label="Evidence" hint="What shows it" bind:selected={cites} locked={lockedCites} />
- </section>
-
- <div class="facts">
- <div class="when">
- <span class="modal-label">When</span>
- <DateField
- id="{uid}-when"
- label="When"
- placeholder="Optional · dd/mm/yyyy"
- calendar
- value={when}
- onchange={(value) => (when = value)}
- />
- </div>
- <label>
- <span class="modal-label">Confidence</span>
- <select class="select" value={confidence} onchange={(event) => (confidence = event.currentTarget.value)}>
- <option value="">Not assessed</option>
- {#each confidences as option (option.value)}
- <option value={option.value}>{option.label}</option>
- {/each}
- </select>
- </label>
- </div>
-
- <div class="actions">
- <button class="btn btn-ghost" onclick={oncancel}>Cancel</button>
- <button class="btn btn-primary" disabled={!ready} onclick={save} title="Ctrl+Enter">
- {saving ? 'Saving…' : 'Add claim'}
- </button>
- </div>
-</div>
-
-<style>
- .quick-claim { display: grid; gap: 8px; min-width: 0; }
- .statement-head { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
- .facts { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 10px; align-items: start; }
- .facts label,
- .facts .when { display: grid; gap: 4px; min-width: 0; }
- .connections { display: grid; gap: 12px; margin-top: 4px; padding-top: 10px; border-top: 1px solid var(--border); }
- .actions { display: flex; justify-content: flex-end; gap: 7px; margin-top: 4px; }
- @media (max-width: 560px) { .facts { grid-template-columns: 1fr; } }
-</style>
diff --git a/frontend/src/components/SnapshotDetails.render.test.js b/frontend/src/components/SnapshotDetails.render.test.js
new file mode 100644
index 0000000..9ad7baa
--- /dev/null
+++ b/frontend/src/components/SnapshotDetails.render.test.js
@@ -0,0 +1,25 @@
+// @vitest-environment happy-dom
+import { expect, it, vi } from 'vitest';
+import { flushSync, mount, unmount } from 'svelte';
+const { get, post } = vi.hoisted(() => ({ get: vi.fn(), post: vi.fn() }));
+vi.mock('../lib/api.js', () => ({ api: { get, post } }));
+vi.mock('../lib/relations.svelte.js', () => ({ loadRelationTypes: () => {}, relationVerb: (type) => type }));
+vi.mock('../lib/entityTypes.svelte.js', () => ({ entityLabel: (type) => type }));
+vi.mock('../lib/entityIcon.js', () => ({ entityIcon: () => 'pin' }));
+const { default: SnapshotDetails } = await import('./SnapshotDetails.svelte');
+
+it('marks a merged snapshot subject without replacing captured fields', async () => {
+ post.mockResolvedValue({ redirects: { old: { id: 'kept' } } });
+ get.mockResolvedValue({ entity: { id: 'kept', label: 'Current subject', attrs: { notes: 'Changed later' } } });
+ const target = document.createElement('div'); document.body.append(target);
+ const entity = { id: 'old', type: 'person', label: 'Captured subject', attrs: { notes: 'Captured notes' } };
+ const component = mount(SnapshotDetails, { target, props: { caseId: 'case', entity } });
+ try {
+ for (let i = 0; i < 8; i++) { flushSync(); await Promise.resolve(); }
+ flushSync();
+ expect(target.querySelector('[role="status"]').textContent).toBe('Merged into Current subject');
+ expect(target.textContent).toContain('Captured notes');
+ expect(target.textContent).not.toContain('Changed later');
+ expect(entity.label).toBe('Captured subject');
+ } finally { unmount(component); target.remove(); }
+});
diff --git a/frontend/src/components/SnapshotDetails.svelte b/frontend/src/components/SnapshotDetails.svelte
index 7e23aad..5b23d36 100644
--- a/frontend/src/components/SnapshotDetails.svelte
+++ b/frontend/src/components/SnapshotDetails.svelte
@@ -4,17 +4,34 @@
import { entityLabel } from '../lib/entityTypes.svelte.js';
import { loadRelationTypes, relationVerb } from '../lib/relations.svelte.js';
import Icon from './Icon.svelte';
+ import { api } from '../lib/api.js';
loadRelationTypes();
- let { entity, entities = [], links = [] } = $props();
+ let { entity, entities = [], links = [], caseId = '' } = $props();
+ let mergedInto = $state('');
+ $effect(() => {
+ const id = entity.id;
+ mergedInto = '';
+ if (!caseId) return;
+ let live = true;
+ // Resolve only the identity. Captured fields, relations and images stay frozen.
+ api.post(`/api/cases/${caseId}/entities/redirects`, { ids: [id] })
+ .then(async ({ redirects }) => {
+ if (!live || !redirects?.[id]) return;
+ const chain = await api.get(`/api/cases/${caseId}/entities/${id}/chain`);
+ if (live) mergedInto = chain.entity?.label ?? '';
+ })
+ .catch(() => {});
+ return () => { live = false; };
+ });
const byId = $derived(new Map(entities.map((item) => [item.id, item])));
const relations = $derived(
links.filter((link) => link.from === entity.id || link.to === entity.id)
);
const fields = $derived(
- Object.entries(entity.attrs ?? {}).filter(([, value]) => value != null && value !== '')
+ Object.entries(entity.attrs ?? {}).filter(([key, value]) => !key.startsWith('_') && value != null && value !== '')
);
const label = (key) => key.replaceAll('_', ' ').replace(/^./, (letter) => letter.toUpperCase());
const value = (held) =>
@@ -23,6 +40,7 @@
<div class="snapshot-detail">
<p class="notice"><Icon name="clock" size={13} /> Captured data. Nothing here edits the case.</p>
+ {#if mergedInto}<p class="notice" role="status">Merged into <bdi>{mergedInto}</bdi></p>{/if}
<header>
<Icon name={entityIcon(entity)} size={22} />
diff --git a/frontend/src/components/Sparkline.svelte b/frontend/src/components/Sparkline.svelte
new file mode 100644
index 0000000..74abda6
--- /dev/null
+++ b/frontend/src/components/Sparkline.svelte
@@ -0,0 +1,59 @@
+<script>
+ /**
+ * When something was active, as a dozen bars across the case's own span.
+ *
+ * The same span for every row it is drawn on (`/catalog/events` returns one range),
+ * so a column of these reads as who was busy when rather than as shapes that cannot
+ * be compared. Each row scales to its own busiest bucket: the count sits beside it
+ * in words, and a quiet subject drawn as a flat line would say nothing. An empty
+ * bucket keeps its place on the baseline, so a gap reads as a gap.
+ */
+ let { buckets = [], width = 60, height = 14, label = '' } = $props();
+
+ const peak = $derived(Math.max(1, ...buckets));
+ const step = $derived(width / Math.max(1, buckets.length));
+ const bars = $derived(
+ buckets.map((n, index) => ({
+ index,
+ n,
+ h: n > 0 ? Math.max(2, Math.round((n / peak) * (height - 1))) : 0,
+ }))
+ );
+</script>
+
+<svg
+ class="sparkline"
+ {width}
+ {height}
+ viewBox="0 0 {width} {height}"
+ role="img"
+ aria-label={label}
+>
+ <line class="base" x1="0" x2={width} y1={height - 0.5} y2={height - 0.5} />
+ {#each bars as bar (bar.index)}
+ {#if bar.h}
+ <rect
+ x={bar.index * step + 0.5}
+ y={height - bar.h}
+ width={Math.max(1, step - 1.5)}
+ height={bar.h}
+ rx="1"
+ />
+ {/if}
+ {/each}
+</svg>
+
+<style>
+ .sparkline {
+ display: block;
+ flex-shrink: 0;
+ overflow: visible;
+ }
+ .base {
+ stroke: var(--border-strong);
+ stroke-width: 1;
+ }
+ rect {
+ fill: var(--timeline-statement);
+ }
+</style>
diff --git a/frontend/src/components/SubjectActions.render.test.js b/frontend/src/components/SubjectActions.render.test.js
new file mode 100644
index 0000000..54b1673
--- /dev/null
+++ b/frontend/src/components/SubjectActions.render.test.js
@@ -0,0 +1,97 @@
+// @vitest-environment happy-dom
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { flushSync, mount, unmount } from 'svelte';
+
+const { get, patch, post, changed } = vi.hoisted(() => ({ get: vi.fn(), patch: vi.fn(), post: vi.fn(), changed: vi.fn() }));
+vi.mock('../lib/api.js', () => ({ api: { get, patch, post } }));
+vi.mock('../lib/state.svelte.js', () => ({ reloadCase: vi.fn(), toast: vi.fn() }));
+vi.mock('../lib/entityTypes.svelte.js', () => ({
+ entityTypes: () => [
+ { type: 'vehicle', label: 'Vehicle', retypable: true, mergeable: true },
+ { type: 'vessel', label: 'Vessel', retypable: true, mergeable: true },
+ { type: 'place', label: 'Place', mergeable: true },
+ { type: 'claim', label: 'Claim' },
+ ],
+ entityLabel: (type) => type === 'vehicle' ? 'Vehicle' : type,
+ entityFields: (type) => type === 'vehicle' ? [{ key: 'plate', label: 'Plate' }] : [],
+}));
+const { default: SubjectActions } = await import('./SubjectActions.svelte');
+const { default: MergeSubjects } = await import('./MergeSubjects.svelte');
+const entity = { id: 'newer', label: 'Newer', type: 'vehicle', attrs: {}, provenance: { at: '2026-09-02' } };
+const other = { ...entity, id: 'older', label: 'Older', provenance: { at: '2026-09-01' } };
+const preview = { fields: { kept: {}, added: {}, conflicts: [] }, links: { moved: 2, twins: 1, loops: 0 }, images: {}, pins: {}, views: [], sheets: 0, notes: 0, refused: [] };
+let component;
+async function settle() { for (let i = 0; i < 8; i++) { await Promise.resolve(); flushSync(); } }
+async function open(Component = SubjectActions, props = {}) {
+ const target = document.createElement('div'); document.body.append(target);
+ component = mount(Component, { target, props: { caseId: 'case', entity, onchanged: changed, ...props } });
+ await settle();
+}
+const button = (text) => [...document.querySelectorAll('button')].find((node) => node.textContent.trim() === text);
+beforeEach(() => { get.mockResolvedValue({ merges: [] }); patch.mockResolvedValue(entity); post.mockResolvedValue({}); });
+afterEach(() => { if (component) unmount(component); document.body.innerHTML = ''; vi.resetAllMocks(); });
+
+describe('subject corrections', () => {
+ it('offers only registry-approved types and submits the selected type', async () => {
+ await open(); button('Change type…').click(); await settle();
+ const select = document.querySelector('select');
+ expect([...select.options].map((o) => o.value)).toEqual(['vehicle', 'vessel']);
+ select.options[0].selected = false; select.options[1].selected = true;
+ select.dispatchEvent(new Event('change', { bubbles: true })); await settle();
+ expect(select.value).toBe('vessel');
+ expect(button('Change type').disabled).toBe(false);
+ button('Change type').click(); await settle();
+ expect(patch).toHaveBeenCalledWith('/api/cases/case/entities/newer', { type: 'vessel' });
+ expect(changed).toHaveBeenCalledWith(entity);
+ });
+ it('keeps a refused change open and says what prevents it', async () => {
+ patch.mockRejectedValue(new Error('A relation prevents this change'));
+ await open(); button('Change type…').click(); await settle();
+ const select = document.querySelector('select');
+ select.options[0].selected = false; select.options[1].selected = true;
+ select.dispatchEvent(new Event('change', { bubbles: true })); await settle();
+ button('Change type').click(); await settle();
+ expect(document.querySelector('[role="alert"]').textContent).toContain('A relation prevents');
+ expect(changed).not.toHaveBeenCalled();
+ });
+ it('shows retained fields with their original name and removes them explicitly', async () => {
+ await open(SubjectActions, { entity: { ...entity, type: 'vessel', attrs: { plate: 'AA1234', _retained_fields: { plate: 'vehicle' } } } });
+ expect(document.body.textContent).toContain('Kept from Vehicle');
+ button('Remove Plate').click(); await settle();
+ expect(patch).toHaveBeenCalledWith('/api/cases/case/entities/newer', { attrs: { plate: null } });
+ });
+ it('reloads the survivor after Undo and displays partial restoration', async () => {
+ get.mockImplementation((url) => Promise.resolve(url.endsWith('/merges') ? { merges: [{ id: 'm1', merged_label: 'Old' }] } : { entity: { ...entity, attrs: { notes: 'Restored' } } }));
+ post.mockResolvedValue({ lost: ['A photo was removed since'] });
+ await open(); button('Undo').click(); await settle();
+ expect(post).toHaveBeenCalledWith('/api/cases/case/merges/m1/undo');
+ expect(changed).toHaveBeenCalledWith(expect.objectContaining({ attrs: { notes: 'Restored' } }));
+ expect(document.body.textContent).toContain('A photo was removed since');
+ });
+ it('does not offer correction actions for claims', async () => {
+ await open(SubjectActions, { entity: { ...entity, type: 'claim' } });
+ expect(document.querySelector('button')).toBeNull();
+ expect(get).not.toHaveBeenCalled();
+ });
+});
+
+describe('merge preview', () => {
+ it('keeps the older subject by default, allows switching, and submits that direction', async () => {
+ get.mockResolvedValue(preview);
+ const merged = vi.fn();
+ await open(MergeSubjects, { initialOther: other, onmerged: merged });
+ expect(get).toHaveBeenLastCalledWith('/api/cases/case/entities/older/merge-preview?other=newer');
+ document.querySelector('.choice').click(); await settle();
+ expect(get).toHaveBeenLastCalledWith('/api/cases/case/entities/newer/merge-preview?other=older');
+ button('Merge subjects').click(); await settle();
+ expect(post).toHaveBeenCalledWith('/api/cases/case/entities/newer/merge', { other: 'older' });
+ expect(merged).toHaveBeenCalled();
+ });
+ it('blocks a preview with incompatible relations', async () => {
+ get.mockResolvedValue({ ...preview, refused: [{ type: 'part-of', reason: 'would form a cycle' }] });
+ await open(MergeSubjects, { initialOther: other });
+ expect(button('Merge subjects').disabled).toBe(true);
+ expect(document.body.textContent).toContain('would form a cycle');
+ expect(post).not.toHaveBeenCalled();
+ });
+});
diff --git a/frontend/src/components/SubjectActions.svelte b/frontend/src/components/SubjectActions.svelte
new file mode 100644
index 0000000..7cc0878
--- /dev/null
+++ b/frontend/src/components/SubjectActions.svelte
@@ -0,0 +1,117 @@
+<script>
+ import { api } from '../lib/api.js';
+ import { entityTypes, entityFields, entityLabel } from '../lib/entityTypes.svelte.js';
+ import { reloadCase, toast } from '../lib/state.svelte.js';
+ import MergeSubjects from './MergeSubjects.svelte';
+
+ let { caseId, entity, disabled = false, twin = null, onchanged } = $props();
+ let changing = $state(false);
+ let merging = $state(false);
+ let candidate = $state(null);
+ let nextType = $state('');
+ let busy = $state(false);
+ let error = $state('');
+ let losses = $state([]);
+ let history = $state([]);
+ let historyError = $state('');
+ const entry = $derived(entityTypes().find((type) => type.type === entity.type));
+ const types = $derived(entityTypes().filter((type) => type.retypable));
+ const retained = $derived(Object.entries(entity.attrs?._retained_fields ?? {}).filter(([key]) => entity.attrs?.[key] != null && !entityFields(entity.type).some((field) => field.key === key)));
+ const subjectId = $derived(entity.id);
+ $effect(() => {
+ subjectId;
+ changing = false;
+ merging = false;
+ losses = [];
+ error = '';
+ });
+ $effect(() => {
+ const id = entity.id;
+ entity;
+ history = [];
+ if (!entry?.mergeable) return;
+ let live = true;
+ api.get(`/api/cases/${caseId}/entities/${id}/merges`)
+ .then((result) => { if (live) { history = result.merges; historyError = ''; } })
+ .catch((cause) => { if (live) historyError = cause.message; });
+ return () => { live = false; };
+ });
+ async function patch(body) {
+ if (busy || disabled) return;
+ busy = true;
+ error = '';
+ try {
+ const saved = await api.patch(`/api/cases/${caseId}/entities/${entity.id}`, body);
+ changing = false;
+ onchanged?.(saved);
+ await reloadCase();
+ toast('Subject updated', 'ok');
+ } catch (cause) { error = cause.message; }
+ finally { busy = false; }
+ }
+ async function undo(id) {
+ if (busy || disabled) return;
+ busy = true;
+ error = '';
+ try {
+ const result = await api.post(`/api/cases/${caseId}/merges/${id}/undo`);
+ losses = result.lost ?? [];
+ await reloadCase();
+ const chain = await api.get(`/api/cases/${caseId}/entities/${entity.id}/chain`);
+ onchanged?.(chain.entity);
+ toast(losses.length ? 'Merge undone with changes to review' : 'Merge undone', losses.length ? 'warn' : 'ok');
+ } catch (cause) { error = cause.message; }
+ finally { busy = false; }
+ }
+ async function merged(result) {
+ merging = false;
+ onchanged?.(result.survivor);
+ await reloadCase();
+ losses = result.warnings ?? [];
+ toast(losses.length ? 'Subjects merged with changes to review' : 'Subjects merged', losses.length ? 'warn' : 'ok', 8000, { label: 'Undo', onClick: () => undo(result.merge) });
+ }
+ const shown = (value) => typeof value === 'object' ? JSON.stringify(value) : String(value);
+</script>
+
+{#if entry?.retypable || entry?.mergeable}
+ <div class="subject-actions">
+ <div class="buttons">
+ {#if entry.retypable}<button class="btn btn-ghost btn-sm" disabled={disabled || busy} aria-expanded={changing} onclick={() => { changing = !changing; nextType = entity.type; }}>Change type…</button>{/if}
+ {#if entry.mergeable}<button class="btn btn-ghost btn-sm" disabled={disabled || busy} onclick={() => { candidate = null; merging = true; }}>Merge…</button>{/if}
+ {#if twin && entry.mergeable}<button class="btn btn-ghost btn-sm" disabled={disabled || busy} onclick={() => { candidate = twin; merging = true; }}>Merge with <bdi>{twin.label}</bdi>…</button>{/if}
+ </div>
+ {#if disabled}<small>Save your edits before changing type or merging.</small>{/if}
+ {#if changing}
+ <div class="buttons">
+ <select class="select" aria-label="New type" value={nextType} onchange={(event) => (nextType = event.currentTarget.value)} disabled={busy}>{#each types as type (type.type)}<option value={type.type}>{type.label}</option>{/each}</select>
+ <button class="btn btn-primary btn-sm" disabled={busy || nextType === entity.type} onclick={() => patch({ type: nextType })}>Change type</button>
+ <button class="btn btn-ghost btn-sm" disabled={busy} onclick={() => (changing = false)}>Cancel</button>
+ </div>
+ {/if}
+ {#each retained as [key, oldType] (key)}
+ <div class="retained">
+ <small>Kept from {entityLabel(oldType)}</small>
+ <span><strong>{entityFields(oldType).find((field) => field.key === key)?.label ?? key}:</strong> <bdi>{shown(entity.attrs[key])}</bdi></span>
+ <button class="btn btn-ghost btn-sm" disabled={disabled || busy} onclick={() => patch({ attrs: { [key]: null } })}>Remove {entityFields(oldType).find((field) => field.key === key)?.label ?? key}</button>
+ </div>
+ {/each}
+ {#each history as record (record.id)}
+ <div class="history"><span>Merged from <bdi>{record.merged_label}</bdi></span><button class="btn btn-ghost btn-sm" disabled={disabled || busy} onclick={() => undo(record.id)}>Undo</button></div>
+ {/each}
+ {#if historyError}<p class="error">Could not load merge history: {historyError}</p>{/if}
+ {#if error}<p class="error" role="alert">{error}</p>{/if}
+ {#if losses.length}<div role="status"><p>Changes to review:</p><ul>{#each losses as loss}<li>{loss}</li>{/each}</ul></div>{/if}
+ </div>
+{/if}
+{#if merging}<MergeSubjects {caseId} {entity} initialOther={candidate} onclose={() => (merging = false)} onmerged={merged} />{/if}
+
+<style>
+ .subject-actions { display: grid; gap: 8px; padding-block: 8px; border-block: 1px solid var(--border); }
+ .buttons, .history { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; }
+ .buttons .select { width: auto; flex: 1; min-width: 100px; }
+ .retained { display: grid; gap: 3px; overflow-wrap: anywhere; }
+ .retained button { justify-self: start; }
+ small { color: var(--text-3); font-size: var(--fs-xs); }
+ p { margin: 0; }
+ .error { color: var(--danger); }
+</style>
diff --git a/frontend/src/components/TemporalClaimEditor.svelte b/frontend/src/components/TemporalClaimEditor.svelte
index 918cca4..768e57b 100644
--- a/frontend/src/components/TemporalClaimEditor.svelte
+++ b/frontend/src/components/TemporalClaimEditor.svelte
@@ -10,16 +10,30 @@
item = null,
subject = null,
initialWhen = '',
+ /** The zone `initialWhen` was stated in, from the entry line. */
+ initialWhenZone = null,
initialStatement = '',
initialRole = '',
/** Evidence a new claim cites from the start, such as the picture it was read on. */
initialCites = [],
+ initialConfidence = '',
+ initialAbout = [],
+ initialAt = [],
+ /** A count and a state carried over from the entry line, which asks them there. */
+ initialFacts = null,
+ /** Subjects the entry line named for the first time, created with the claim. */
+ initialCreate = [],
+ /** Whether the editor says it saved. The entry line says it itself, with an Undo. */
+ announce = true,
onsaved,
oncancel,
} = $props();
let statement = $state('');
let when = $state('');
+ // The clock the date was stated on (`when_zone`): which day a date is, and whose
+ // local time a time is.
+ let whenZone = $state(null);
let timeRole = $state('');
let confidence = $state('');
let method = $state('');
@@ -34,14 +48,37 @@
const lockedAbout = $derived(subject ? [subject] : []);
+ /** What the date is of, in a line. */
+ const ROLE_HELP = {
+ '': 'what the date is of, which can wait',
+ occurred: 'when it happened',
+ observed: 'when it was seen, filmed or reported',
+ valid: 'the span during which it held',
+ };
+ /** How strongly the claim is supported, in the words the confidence scale is
+ * served with (`engine/links.py` CONFIDENCE_LEVELS). */
+ const CONFIDENCE_HELP = {
+ '': 'how strongly the claim is supported, once it is weighed',
+ certain: 'established and corroborated',
+ probable: 'more likely than not, and short of established',
+ possible: 'roughly even odds, and it cannot be excluded',
+ refuted: 'checked and eliminated, which is a finding rather than a deletion',
+ };
+
$effect(() => {
if (seeded) return;
seeded = true;
statement = item?.label ?? initialStatement;
when = item?.raw ?? initialWhen;
+ whenZone = item ? (item.tz ?? null) : initialWhenZone;
timeRole = item?.time_role ?? initialRole;
- confidence = item?.confidence ?? '';
- if (!item) cites = initialCites.map((entry) => ({ id: entry.id, label: entry.label, type: entry.type }));
+ confidence = item?.confidence ?? initialConfidence;
+ if (!item) {
+ const keep = (entry) => ({ id: entry.id, label: entry.label, type: entry.type, attrs: entry.attrs });
+ cites = initialCites.map(keep);
+ about = initialAbout.map(keep);
+ places = initialAt.map(keep);
+ }
});
$effect(() => {
@@ -54,6 +91,7 @@
if (!live) return;
statement = chain.entity.label ?? item.label;
when = chain.entity.attrs?.when ?? item.raw ?? '';
+ whenZone = chain.entity.attrs?.when_zone ?? item.tz ?? null;
timeRole = chain.entity.attrs?.time_role ?? item.time_role ?? '';
confidence = chain.entity.attrs?.confidence ?? item.confidence ?? '';
method = chain.entity.attrs?.method ?? '';
@@ -61,7 +99,7 @@
const choices = (type) =>
(chain.relations ?? [])
.filter((row) => row.direction === 'out' && row.link.type === type)
- .map((row) => ({ id: row.entity.id, label: row.entity.label, type: row.entity.type }));
+ .map((row) => ({ id: row.entity.id, label: row.entity.label, type: row.entity.type, attrs: row.entity.attrs }));
about = choices('about').filter((choice) => choice.id !== subject?.id);
places = choices('at');
cites = choices('cites');
@@ -78,6 +116,7 @@
const body = {
statement: text,
when: when || null,
+ when_zone: (when && whenZone) || null,
time_role: timeRole || null,
confidence: confidence || null,
method: method.trim() || null,
@@ -86,11 +125,16 @@
at: places.map((entry) => entry.id),
cites: cites.map((entry) => entry.id),
};
+ if (!item) {
+ if (initialFacts?.count != null) body.count = initialFacts.count;
+ if (initialFacts?.condition) body.condition = initialFacts.condition;
+ if (initialCreate.length) body.create = initialCreate;
+ }
try {
const saved = item
? await api.patch(`/api/cases/${caseId}/timeline/claims/${item.owner_id}`, body)
: await api.post(`/api/cases/${caseId}/timeline/claims`, body);
- toast(item ? 'Claim updated' : 'Claim added', 'ok', 1800);
+ if (announce) toast(item ? 'Claim updated' : 'Claim added', 'ok', 1800);
onsaved?.(saved);
} catch (error) {
toast(error.message, 'danger');
@@ -109,16 +153,21 @@
<textarea
id="temporal-statement"
class="textarea"
+ dir="auto"
rows="2"
bind:value={statement}
maxlength="300"
placeholder="What happened or was observed?"
></textarea>
+ <p class="help">One sentence, in your words. Who, where and the sources go below; the source's own wording goes under Reasoning.</p>
<label class="modal-label" for="temporal-when">When</label>
<TemporalInput
id="temporal-when"
value={when}
+ places={[...places, ...cites]}
+ zone={whenZone}
+ onzonechange={(zone) => (whenZone = zone)}
onchange={(value) => (when = value)}
onvaliditychange={(reading) => (whenValid = reading.valid)}
/>
@@ -143,8 +192,23 @@
<option value="refuted">Refuted</option>
</select>
</label>
+ <!-- Beside the labels rather than in them: a label is the field's name, and
+ a line inside it would be read as part of that name. -->
+ <small class="help">{ROLE_HELP[timeRole]}</small>
+ <small class="help">{CONFIDENCE_HELP[confidence]}</small>
</div>
+ {#if !item && (initialFacts?.count != null || initialFacts?.condition || initialCreate.length)}
+ <p class="carried">
+ Filed with it:
+ {[
+ initialFacts?.count != null ? `${initialFacts.count} counted` : '',
+ initialFacts?.condition ? initialFacts.condition : '',
+ ...initialCreate.map((entry) => `${entry.label} (new)`),
+ ].filter(Boolean).join(' · ')}
+ </p>
+ {/if}
+
<section class="connections">
<TemporalTargetPicker
{caseId}
@@ -173,21 +237,24 @@
<details class="reasoning">
<summary>Reasoning and source wording</summary>
<label class="modal-label" for="temporal-method">How this was worked out</label>
- <textarea id="temporal-method" class="textarea" rows="3" bind:value={method}></textarea>
+ <textarea id="temporal-method" class="textarea" rows="3" dir="auto" bind:value={method}></textarea>
<label class="modal-label" for="temporal-verbatim">As the source put it</label>
- <textarea id="temporal-verbatim" class="textarea" rows="3" bind:value={verbatim}></textarea>
+ <textarea id="temporal-verbatim" class="textarea" rows="3" dir="auto" bind:value={verbatim}></textarea>
</details>
<div class="actions">
<button class="btn btn-ghost" onclick={oncancel}>Cancel</button>
<button class="btn btn-primary" disabled={!statement.trim() || !whenValid || saving || loading} onclick={save}>
- {saving ? 'Saving…' : item ? 'Update claim' : 'Add claim'}
+ {saving ? 'Saving…' : item ? 'Update claim' : 'Add event'}
</button>
</div>
</div>
<style>
.claim-editor { display: grid; gap: 8px; min-width: 0; }
+ .carried { margin: 0; color: var(--text-3); font-size: var(--fs-xs); }
+ .help { margin: -3px 0 2px; color: var(--text-3); font-size: var(--fs-xs); line-height: 1.4; }
+ .two-cols .help { margin: -6px 0 0; }
.loading { padding: 7px 9px; border-radius: var(--r-sm); background: var(--bg-2); color: var(--text-3); }
.two-cols { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 10px; }
.two-cols label { display: grid; gap: 4px; }
diff --git a/frontend/src/components/TemporalClaimEditor.test.js b/frontend/src/components/TemporalClaimEditor.test.js
index e9b4b17..75b45a0 100644
--- a/frontend/src/components/TemporalClaimEditor.test.js
+++ b/frontend/src/components/TemporalClaimEditor.test.js
@@ -25,11 +25,20 @@ describe('temporal Claim editor', () => {
expect(editor).toContain('relationType="at"');
expect(editor).toContain('relationType="cites"');
expect(picker).toContain("relationOptions('claim', entry.type, 'claim')");
- expect(picker).toContain('buildCatalogQuery(caseId, { types, query: term, limit: 200 })');
+ expect(picker).toContain('types={acceptedTypes}');
+ expect(picker).toContain("order={relationType === 'cites' ? '-created' : ''}");
+ });
+
+ it('keeps the zone a date was stated in, and hands the editor its row', () => {
+ expect(editor).toContain("whenZone = chain.entity.attrs?.when_zone ?? item.tz ?? null;");
+ expect(editor).toContain('when_zone: (when && whenZone) || null,');
+ expect(editor).toContain('zone={whenZone}');
+ expect(editor).toContain('onzonechange={(zone) => (whenZone = zone)}');
});
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(');
+ expect(editor).toContain('cites = initialCites.map(keep);');
+ expect(editor).toContain('confidence = item?.confidence ?? initialConfidence;');
});
});
diff --git a/frontend/src/components/TemporalInput.render.svelte.test.js b/frontend/src/components/TemporalInput.render.svelte.test.js
new file mode 100644
index 0000000..e9dfa97
--- /dev/null
+++ b/frontend/src/components/TemporalInput.render.svelte.test.js
@@ -0,0 +1,244 @@
+// @vitest-environment happy-dom
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { flushSync, mount, unmount } from 'svelte';
+
+/** The full editor's date and time, typed as the clock of the place it happened at. */
+
+const get = vi.fn(async (url) => {
+ const lon = Number(new URL(url, 'http://x').searchParams.get('lon'));
+ return { name: lon > 20 ? 'Europe/Kyiv' : 'Europe/Lisbon' };
+});
+vi.mock('../lib/api.js', () => ({ api: { get } }));
+vi.mock('../lib/state.svelte.js', () => ({ caseState: { current: { id: 'case-t' } } }));
+
+const { default: TemporalInput } = await import('./TemporalInput.svelte');
+const { forgetZones } = await import('../lib/localZone.js');
+const { forgetAxisZone, noteAxisZone } = await import('../lib/caseAxis.svelte.js');
+
+const KHARKIV = { id: 'k', type: 'place', label: 'Kharkiv', attrs: { lat: 49.99, lon: 36.23 } };
+const LISBON = { id: 'p', type: 'place', label: 'Lisbon', attrs: { lat: 38.72, lon: -9.14 } };
+
+let live = null;
+let target = null;
+let changes = [];
+let zoneChanges = [];
+
+async function settle() {
+ for (let index = 0; index < 12; index += 1) await Promise.resolve();
+ flushSync();
+}
+
+async function open(props) {
+ target = document.createElement('div');
+ document.body.append(target);
+ changes = [];
+ zoneChanges = [];
+ // The editor hands every change back as the value, as TemporalClaimEditor does.
+ const held = $state({ value: props.value ?? '', zone: props.zone ?? null });
+ live = mount(TemporalInput, {
+ target,
+ props: {
+ id: 'when',
+ places: props.places,
+ get value() {
+ return held.value;
+ },
+ onchange: (value) => {
+ changes.push(value);
+ held.value = value;
+ },
+ get zone() {
+ return held.zone;
+ },
+ onzonechange: props.zoned
+ ? (zone) => {
+ zoneChanges.push(zone);
+ held.zone = zone;
+ }
+ : null,
+ },
+ });
+ await settle();
+}
+
+function set(element, value, event = 'input') {
+ element.value = value;
+ element.dispatchEvent(new Event(event, { bubbles: true }));
+ flushSync();
+}
+
+const format = () => target.querySelector('select[aria-label="Date format"]');
+const datetime = () => target.querySelector('input[type="datetime-local"]');
+const dateInput = () => target.querySelector('input.date-value');
+const clock = () => target.querySelector('.clock-trigger');
+const clockSays = () => clock()?.getAttribute('aria-label');
+
+/** Open the Clock and press the row whose name is `words`, searching for it first. */
+function pick(words, search = '') {
+ clock().click();
+ flushSync();
+ if (search) set(document.querySelector('.clock-menu .search-input'), search);
+ const rows = [...document.querySelectorAll('.clock-menu .rows > button')];
+ const row = rows.find((button) => button.querySelector('span').textContent === words);
+ if (!row) throw new Error(`no ${words} among ${rows.map((button) => button.textContent).join(', ')}`);
+ row.click();
+ flushSync();
+}
+
+function offered() {
+ clock().click();
+ flushSync();
+ const names = [...document.querySelectorAll('.clock-menu .rows > button span')].map((span) => span.textContent);
+ clock().click();
+ flushSync();
+ return names;
+}
+
+beforeEach(() => {
+ forgetZones();
+ get.mockClear();
+});
+
+afterEach(() => {
+ if (live) unmount(live);
+ live = null;
+ target?.remove();
+});
+
+describe('a time at a placed claim', () => {
+ it('is read on the place clock while none is picked, with that day’s offset', async () => {
+ await open({ places: [KHARKIV] });
+ set(format(), 'timestamp', 'change');
+ set(datetime(), '2026-08-11T17:05');
+ await settle();
+
+ expect(changes.at(-1)).toBe('2026-08-11T17:05:00+03:00');
+ expect(clockSays()).toBe('Clock: Kharkiv UTC+03:00');
+ expect(target.textContent).toContain('11 Aug 2026, 17:05:00 Europe/Kyiv (UTC+03:00)');
+
+ set(datetime(), '2026-01-11T17:05');
+ await settle();
+ expect(changes.at(-1)).toBe('2026-01-11T17:05:00+02:00');
+ });
+
+ it('keeps a clock the analyst picked, an unknown one included', async () => {
+ await open({ places: [KHARKIV] });
+ set(format(), 'timestamp', 'change');
+ pick('Clock unknown');
+ set(datetime(), '2026-08-11T17:05');
+ await settle();
+ expect(changes.at(-1)).toBe('2026-08-11T17:05:00');
+ expect(clockSays()).toBe('Clock: Clock unknown');
+ });
+
+ it('never rewrites a stored time because the editor was opened', async () => {
+ await open({ places: [KHARKIV], value: '2026-08-11T17:05:00' });
+ await settle();
+ expect(changes).toEqual([]);
+ expect(clockSays()).toBe('Clock: Clock unknown');
+ });
+
+ it('reads on UTC when the places disagree, and offers each of them', async () => {
+ await open({ places: [KHARKIV, LISBON] });
+ set(format(), 'timestamp', 'change');
+ set(datetime(), '2026-08-11T17:05');
+ await settle();
+
+ expect(changes.at(-1)).toBe('2026-08-11T17:05:00Z');
+ expect(offered()).toEqual(expect.arrayContaining(['Local at Kharkiv', 'Local at Lisbon', 'UTC', 'Clock unknown']));
+ pick('Local at Lisbon');
+ expect(changes.at(-1)).toBe('2026-08-11T17:05:00+01:00');
+ });
+
+ it('reads a value with no place on the case’s clock', async () => {
+ noteAxisZone('case-t', 'Asia/Aden');
+ try {
+ await open({ places: [], zoned: true });
+ set(dateInput(), '2026-09-10');
+ await settle();
+ expect(zoneChanges.at(-1)).toBe('Asia/Aden');
+ set(format(), 'timestamp', 'change');
+ set(datetime(), '2026-09-10T08:00');
+ await settle();
+ expect(changes.at(-1)).toBe('2026-09-10T08:00:00+03:00');
+ } finally {
+ forgetAxisZone();
+ }
+ });
+
+ it('reads a time with no place on UTC while the case has no clock, and says so', async () => {
+ await open({ places: [] });
+ set(format(), 'timestamp', 'change');
+ set(datetime(), '2026-08-11T17:05');
+ await settle();
+ expect(changes.at(-1)).toBe('2026-08-11T17:05:00Z');
+ expect(clockSays()).toBe('Clock: UTC');
+ });
+
+ it('keeps a written offset until another clock is picked', async () => {
+ await open({ places: [], value: '2026-08-11T17:05:00+04:30' });
+ expect(clockSays()).toBe('Clock: UTC+04:30');
+ pick('Tokyo', 'tokyo');
+ expect(changes.at(-1)).toBe('2026-08-11T17:05:00+09:00');
+ });
+});
+
+describe('the day a date is', () => {
+ it('reads a day typed for a place as that place\'s day, and says so', async () => {
+ await open({ places: [KHARKIV], zoned: true });
+ set(dateInput(), '2024-03-12');
+ await settle();
+
+ expect(changes.at(-1)).toBe('2024-03-12');
+ expect(zoneChanges.at(-1)).toBe('Europe/Kyiv');
+ expect(clockSays()).toBe('Clock: Kharkiv UTC+02:00');
+ expect(target.textContent).toContain('12 Mar 2024 (Europe/Kyiv)');
+
+ pick('UTC');
+ expect(zoneChanges.at(-1)).toBe(null);
+ expect(clockSays()).toBe('Clock: UTC');
+ });
+
+ it('gives a day any zone in the world, with no place tied to it', async () => {
+ await open({ places: [], zoned: true });
+ set(dateInput(), '2026-09-10');
+ await settle();
+ expect(clockSays()).toBe('Clock: UTC');
+
+ pick('Tokyo', 'tokyo');
+ expect(zoneChanges.at(-1)).toBe('Asia/Tokyo');
+ expect(clockSays()).toBe('Clock: Tokyo UTC+09:00');
+ expect(target.textContent).toContain('10 Sep 2026 (Asia/Tokyo)');
+ });
+
+ it('opens a stored day on its stated zone without re-reading it', async () => {
+ await open({ places: [], value: '2024-03-12', zone: 'Asia/Tokyo', zoned: true });
+ expect(changes).toEqual([]);
+ expect(zoneChanges).toEqual([]);
+ expect(clockSays()).toBe('Clock: Tokyo UTC+09:00');
+ });
+
+ it('opens a local time stated in a zone on that clock, and leaves it as written', async () => {
+ await open({ places: [], value: '2024-07-12T14:30:00', zone: 'Europe/Kyiv', zoned: true });
+ expect(changes).toEqual([]);
+ expect(clockSays()).toBe('Clock: Kyiv UTC+03:00');
+ });
+
+ it('carries the clock from a day to a time when the format changes', async () => {
+ await open({ places: [], zoned: true });
+ set(dateInput(), '2026-09-10');
+ await settle();
+ pick('Tokyo', 'tokyo');
+ set(format(), 'timestamp', 'change');
+ set(datetime(), '2026-09-10T08:00');
+ await settle();
+ expect(changes.at(-1)).toBe('2026-09-10T08:00:00+09:00');
+ });
+
+ it('has no clock row for a date as a bare field, and one for a time', async () => {
+ await open({ places: [KHARKIV], value: '2024-03-12' });
+ expect(clock()).toBeNull();
+ set(format(), 'timestamp', 'change');
+ expect(clock()).not.toBeNull();
+ });
+});
diff --git a/frontend/src/components/TemporalInput.svelte b/frontend/src/components/TemporalInput.svelte
index f8d94af..03762ad 100644
--- a/frontend/src/components/TemporalInput.svelte
+++ b/frontend/src/components/TemporalInput.svelte
@@ -7,17 +7,88 @@
writeTemporalInput,
} from '../lib/temporalInput.js';
import { formatTemporalValue } from '../lib/timeline.js';
+ import { zonesOf } from '../lib/localZone.js';
+ import { UTC, clockOf } from '../lib/clock.js';
+ import { axisZone, learnAxisZone } from '../lib/caseAxis.svelte.js';
+ import { caseState } from '../lib/state.svelte.js';
+ import ClockField from './ClockField.svelte';
- let { id, value = '', onchange, onvaliditychange } = $props();
+ let {
+ id,
+ value = '',
+ /** Where the claim happened, for a date read on the clock there (D33). */
+ places = [],
+ /** The zone the value was stated in (`when_zone`), and where a change to it goes.
+ * Without the callback a date has no clock row, as a bare field: a time still
+ * has one, since its clock is written into the value. */
+ zone = null,
+ onzonechange = null,
+ onchange,
+ onvaliditychange,
+ } = $props();
let state = $state(readTemporalInput(''));
let sent = $state('');
+ // Whether the analyst picked a clock, whether they typed here, and whether the editor
+ // opened empty. The places' clock, else the case's, is the default only for a value typed
+ // into an empty editor: a stored value keeps its clock, and is never rewritten
+ // because the editor was opened or edited.
+ let chosen = $state(false);
+ let typed = $state(false);
+ let fresh = $state(true);
+ let zones = $state({ zones: [], only: null });
+ const DATE_SHAPED = /^\d{4}(-\d{2}(-\d{2})?)?[~?%]?(\/\d{4}(-\d{2}(-\d{2})?)?[~?%]?)?$/;
+
+ $effect(() => {
+ const held = places.map((entry) => ({ type: entry.type, label: entry.label, attrs: entry.attrs }));
+ let live = true;
+ zonesOf(held).then((found) => { if (live) zones = found; });
+ return () => { live = false; };
+ });
+
const rawValue = $derived(writeTemporalInput(state));
- const reading = $derived(formatTemporalValue(rawValue));
+ const timedMode = $derived(state.mode === 'timestamp' || state.mode === 'time-range');
+ /** A time's clock is written into the value; a date's is the zone kept beside it. */
+ const clock = $derived(
+ timedMode
+ ? { zone: state.zone || null, fixed: state.zone ? '' : state.offset }
+ : { zone: zone || UTC, fixed: '' },
+ );
+ const showClock = $derived(timedMode || Boolean(onzonechange && DATE_SHAPED.test(rawValue)));
+ const reading = $derived(
+ formatTemporalValue(rawValue, timedMode ? (state.zone && state.zone !== UTC ? state.zone : null) : zone),
+ );
+
+ /** Put the value on a clock: a zone name, `UTC`, or null for none known. */
+ function setClock(next) {
+ if (timedMode) emit({ zone: next ?? '', offset: '' });
+ onzonechange?.(next && next !== UTC ? next : null);
+ }
+
+ // A value typed into an empty editor reads on the places' clock, else on the clock
+ // the case's axis reads on, and follows them while the analyst has not picked one.
+ $effect(() => { learnAxisZone(caseState.current?.id); });
+ $effect(() => {
+ if (!fresh || chosen || !typed) return;
+ const fallback = zones.only?.zone ?? axisZone(caseState.current?.id);
+ if (timedMode) {
+ if (rawValue && state.zone !== fallback) setClock(fallback);
+ } else if (onzonechange && DATE_SHAPED.test(rawValue)) {
+ const want = fallback === UTC ? null : fallback;
+ if ((zone || null) !== want) onzonechange(want);
+ }
+ });
$effect(() => {
const incoming = value ?? '';
if (incoming !== sent) {
state = readTemporalInput(incoming);
+ if (incoming) fresh = false;
+ // A time stated with its zone opens on that zone, not on the bare offset it was
+ // written with. Nothing is written until the analyst edits it.
+ if (state.mode === 'timestamp' || state.mode === 'time-range') {
+ const read = clockOf(incoming, zone);
+ state = { ...state, zone: read.zone ?? '', offset: read.zone ? '' : read.fixed };
+ }
sent = incoming;
onvaliditychange?.(formatTemporalValue(incoming));
}
@@ -36,8 +107,10 @@
emit({ mode, raw: writeTemporalInput(state) });
return;
}
+ // The clock goes with the value: a day read in Kyiv becomes a time read in Kyiv.
+ const carried = state.zone || zone || UTC;
state = readTemporalInput('');
- emit({ mode });
+ emit({ mode, zone: carried });
}
function choosePrecision(precision) {
@@ -46,19 +119,24 @@
</script>
<div class="temporal-editor">
- <label class="field format-field">
- <span>Format</span>
- <select
- class="select input-sm format"
- aria-label="Date format"
- value={state.mode}
- onchange={(event) => chooseMode(event.currentTarget.value)}
- >
- {#each TEMPORAL_FORMATS as format (format.value)}
- <option value={format.value}>{format.label}</option>
- {/each}
- </select>
- </label>
+ <div class="format-line">
+ <label class="field format-field">
+ <span>Format</span>
+ <select
+ class="select input-sm format"
+ aria-label="Date format"
+ value={state.mode}
+ onchange={(event) => chooseMode(event.currentTarget.value)}
+ >
+ {#each TEMPORAL_FORMATS as format (format.value)}
+ <option value={format.value}>{format.label}</option>
+ {/each}
+ </select>
+ </label>
+ <small class="format-hint">
+ {TEMPORAL_FORMATS.find((format) => format.value === state.mode)?.hint}{#if !rawValue}. Left empty, the claim waits in Undated{/if}
+ </small>
+ </div>
{#if state.mode === 'date'}
<div class="parts date-parts">
@@ -85,7 +163,7 @@
max={state.precision === 'year' ? 9998 : undefined}
placeholder={state.precision === 'year' ? 'YYYY' : 'Unknown'}
value={state.date}
- oninput={(event) => emit({ date: event.currentTarget.value })}
+ oninput={(event) => { typed = true; emit({ date: event.currentTarget.value }); }}
/>
</label>
<label class="field certainty-field">
@@ -113,37 +191,9 @@
type="datetime-local"
step="any"
value={state.datetime}
- oninput={(event) => emit({ datetime: event.currentTarget.value })}
+ oninput={(event) => { typed = true; emit({ datetime: event.currentTarget.value }); }}
/>
</label>
- <label class="field zone-field">
- <span>Timezone</span>
- <select
- class="select input-sm zone"
- aria-label="Timezone"
- value={state.zone}
- onchange={(event) => emit({ zone: event.currentTarget.value })}
- >
- <option value="local">Unknown</option>
- <option value="utc">UTC</option>
- <option value="offset">UTC offset</option>
- </select>
- </label>
- {#if state.zone === 'offset'}
- <label class="field offset-field">
- <span>Offset</span>
- <input
- class="input input-sm mono offset"
- aria-label="UTC offset"
- type="text"
- value={state.offset}
- placeholder="+02:00"
- autocomplete="off"
- spellcheck="false"
- oninput={(event) => emit({ offset: event.currentTarget.value })}
- />
- </label>
- {/if}
</div>
{:else if state.mode === 'range'}
<div class="parts range-parts">
@@ -155,7 +205,7 @@
aria-label="Start date"
type="date"
value={state.start}
- oninput={(event) => emit({ start: event.currentTarget.value })}
+ oninput={(event) => { typed = true; emit({ start: event.currentTarget.value }); }}
/>
</label>
<label class="field">
@@ -165,7 +215,7 @@
aria-label="End date"
type="date"
value={state.end}
- oninput={(event) => emit({ end: event.currentTarget.value })}
+ oninput={(event) => { typed = true; emit({ end: event.currentTarget.value }); }}
/>
</label>
</div>
@@ -180,7 +230,7 @@
type="datetime-local"
step="any"
value={state.startTime}
- oninput={(event) => emit({ startTime: event.currentTarget.value })}
+ oninput={(event) => { typed = true; emit({ startTime: event.currentTarget.value }); }}
/>
</label>
<label class="field">
@@ -191,22 +241,9 @@
type="datetime-local"
step="any"
value={state.endTime}
- oninput={(event) => emit({ endTime: event.currentTarget.value })}
+ oninput={(event) => { typed = true; emit({ endTime: event.currentTarget.value }); }}
/>
</label>
- <label class="field zone-field">
- <span>Timezone</span>
- <select class="select input-sm zone" aria-label="Range timezone" value={state.rangeZone} onchange={(event) => emit({ rangeZone: event.currentTarget.value })}>
- <option value="utc">UTC</option>
- <option value="offset">UTC offset</option>
- </select>
- </label>
- {#if state.rangeZone === 'offset'}
- <label class="field offset-field">
- <span>Offset</span>
- <input class="input input-sm mono offset" aria-label="Range UTC offset" type="text" value={state.rangeOffset} placeholder="+02:00" autocomplete="off" spellcheck="false" oninput={(event) => emit({ rangeOffset: event.currentTarget.value })} />
- </label>
- {/if}
</div>
{:else}
<div class="advanced-editor">
@@ -261,13 +298,27 @@
<li>Ranges contain two dates or two zoned times.</li>
<li>UTC offsets run from −14:00 to +14:00.</li>
</ul>
- <p>A time without a timezone stays outside the UTC timeline.</p>
+ <p>A time without a clock stays off the UTC axis.</p>
<p>Open ranges and other EDTF Level 2 forms are not supported.</p>
</section>
</details>
</div>
{/if}
+ <!-- Which clock the value is read on, one control whatever its shape: a day spans
+ that zone's day, and a time is that zone's local time. -->
+ {#if showClock}
+ <div class="field clock-field">
+ <span>Clock</span>
+ <ClockField
+ value={rawValue}
+ {clock}
+ here={zones.zones}
+ timed={state.mode === 'timestamp'}
+ onpick={(next) => { chosen = true; setClock(next); }}
+ />
+ </div>
+ {/if}
{#if rawValue}
<div class="temporal-preview" class:error={!reading.valid} aria-live="polite">
<span>{reading.valid ? reading.label : reading.error}</span>
@@ -288,13 +339,15 @@
.input-sm { padding: 4px 7px; font-size: var(--fs-xs); }
.parts { display: grid; align-items: end; gap: 6px; }
.date-parts { grid-template-columns: auto minmax(150px, 1fr) minmax(170px, .8fr); }
- .timestamp-parts { grid-template-columns: minmax(190px, 1fr) auto auto; }
+ .timestamp-parts { grid-template-columns: minmax(190px, 1fr); }
.range-parts { grid-template-columns: repeat(2, minmax(140px, 1fr)); }
- .time-range-parts { grid-template-columns: repeat(2, minmax(180px, 1fr)) auto auto; }
+ .time-range-parts { grid-template-columns: repeat(2, minmax(180px, 1fr)); }
+ .format-line { display: flex; align-items: end; gap: 10px; min-width: 0; }
+ .format-hint { padding-bottom: 5px; color: var(--text-3); font-size: var(--fs-xs); }
.format-field { justify-self: start; }
- .format, .precision, .zone { width: max-content; max-width: 100%; }
+ .clock-field { justify-self: start; }
+ .format, .precision { width: max-content; max-width: 100%; }
.date-value, .datetime-value, .certainty, .advanced { width: 100%; }
- .offset { width: 90px; }
.advanced-editor { position: relative; display: grid; gap: 5px; }
.syntax-help { justify-self: start; }
.syntax-help > summary { color: var(--text-2); font-size: var(--fs-xs); cursor: pointer; }
@@ -328,6 +381,6 @@
@media (max-width: 620px) {
.date-parts, .timestamp-parts, .range-parts, .time-range-parts { grid-template-columns: 1fr; }
.format-field { justify-self: stretch; }
- .format, .precision, .zone, .offset { width: 100%; }
+ .format, .precision { width: 100%; }
}
</style>
diff --git a/frontend/src/components/TemporalTargetPicker.render.test.js b/frontend/src/components/TemporalTargetPicker.render.test.js
index 71de6a6..8705eb5 100644
--- a/frontend/src/components/TemporalTargetPicker.render.test.js
+++ b/frontend/src/components/TemporalTargetPicker.render.test.js
@@ -12,13 +12,15 @@ const TYPES = [
vi.mock('../lib/api.js', () => ({ api: { get: apiGet } }));
vi.mock('../lib/entityTypes.svelte.js', () => ({
entityTypes: () => TYPES,
+ entityLabel: (type) => ({ place: 'Place', media: 'Media', claim: 'Claim' })[type] ?? type,
+ entityFields: () => [],
loadEntityTypes: () => Promise.resolve(),
}));
vi.mock('../lib/relations.svelte.js', () => ({
loadRelationTypes: () => Promise.resolve(),
relationOptions: (_subject, other, action) =>
action === 'claim' && ['place', 'media'].includes(other)
- ? [{ type: 'about', direction: 'out' }]
+ ? [{ type: 'about', direction: 'out' }, { type: 'cites', direction: 'out' }]
: [],
}));
vi.mock('../lib/entityIcon.js', () => ({ entityIcon: () => 'pin' }));
@@ -28,8 +30,16 @@ const { default: TemporalTargetPicker } = await import('./TemporalTargetPicker.s
const ROWS = [
{ id: 'selected', type: 'place', label: 'North quay' },
{ id: 'locked', type: 'media', label: 'Interview frame' },
- { id: 'free', type: 'place', label: 'Old warehouse' },
+ { id: 'free', type: 'place', label: 'Old warehouse', provenance: { at: '2026-08-01T09:00:00Z' } },
+ { id: 'clip', type: 'media', label: 'clip.mp4', attrs: { kind: 'video' }, thumb: '.thumbs/clip.jpg' },
];
+const SUMMARY = { total: 4, by_type: { place: 2, media: 2 } };
+
+/** The summary for the kinds, and the page for everything else. */
+function serve(page) {
+ apiGet.mockImplementation((url) =>
+ url.includes('/catalog/summary') ? Promise.resolve(SUMMARY) : page(url));
+}
let live = null;
@@ -53,7 +63,7 @@ function open(props = {}) {
}
async function settle() {
- for (let i = 0; i < 5; i += 1) await Promise.resolve();
+ for (let i = 0; i < 6; i += 1) await Promise.resolve();
flushSync();
}
@@ -68,12 +78,15 @@ function click(root, text) {
}
function type(root, value) {
- const input = root.querySelector('input[aria-label="Search the case…"]');
+ const input = root.querySelector('input[type="search"]');
input.value = value;
input.dispatchEvent(new Event('input', { bubbles: true }));
flushSync();
}
+const pageCalls = () => apiGet.mock.calls.map(([url]) => url).filter((url) => url.includes('/catalog/entities'));
+const names = (root) => [...root.querySelectorAll('[role="option"] .name')].map((node) => node.textContent);
+
afterEach(() => {
if (live) unmount(live);
live = null;
@@ -82,46 +95,94 @@ afterEach(() => {
});
describe('TemporalTargetPicker', () => {
- it('asks only for endpoint types allowed by the served relation registry', async () => {
- apiGet.mockResolvedValue({ items: [] });
+ it('asks only for endpoint types allowed by the served relation registry, with their pictures', async () => {
+ serve(() => Promise.resolve({ items: [] }));
const root = open();
click(root, 'Add');
await settle();
- expect(apiGet).toHaveBeenCalledWith(
- '/api/cases/case-1/catalog/entities?limit=200&type=place%2Cmedia'
- );
- expect(root.textContent).toContain('No matching case items');
+ expect(pageCalls()).toEqual(['/api/cases/case-1/catalog/entities?limit=30&type=place%2Cmedia&previews=true']);
+ expect(root.textContent).toContain('Nothing of this kind in the case yet');
});
- it('keeps locked and selected endpoints unavailable, while adding and removing another', async () => {
- apiGet.mockResolvedValue({ items: ROWS });
+ it('leaves out what is already attached, and adds and removes another', async () => {
+ serve(() => Promise.resolve({ items: ROWS }));
const root = open();
click(root, 'Add');
await settle();
+ expect(names(root)).toEqual(['Old warehouse', 'clip.mp4']);
- const results = [...root.querySelectorAll('.results > button')];
- expect(results.map((button) => button.disabled)).toEqual([true, true, false]);
-
- results[2].click();
+ root.querySelector('[role="option"]').dispatchEvent(new Event('pointerdown', { bubbles: true, cancelable: true }));
flushSync();
expect(root.querySelector('button[title="Remove Old warehouse"]')).toBeTruthy();
- expect(results[2].disabled).toBe(true);
+ expect(names(root)).toEqual(['clip.mp4']);
root.querySelector('button[title="Remove Old warehouse"]').click();
flushSync();
- expect(root.querySelector('button[title="Remove Old warehouse"]')).toBeNull();
- expect(results[2].disabled).toBe(false);
+ expect(names(root)).toEqual(['Old warehouse', 'clip.mp4']);
+ });
+
+ it('says what each row is, and shows the picture a file has', async () => {
+ serve(() => Promise.resolve({ items: ROWS }));
+ const root = open({ selected: [], locked: [] });
+ click(root, 'Add');
+ await settle();
+
+ const rows = [...root.querySelectorAll('[role="option"]')];
+ expect(rows[2].textContent).toContain('Place · added 1 Aug 2026');
+ expect(rows[3].textContent).toContain('Media · video');
+ expect(rows[3].querySelector('img').getAttribute('src')).toBe('/files/case-1/.thumbs/clip.jpg');
+ });
+
+ it('offers the kinds the case holds as chips, and narrows to one', async () => {
+ serve(() => Promise.resolve({ items: ROWS }));
+ const root = open({ selected: [], locked: [] });
+ click(root, 'Add');
+ await settle();
+
+ const kinds = [...root.querySelectorAll('[aria-label="Kinds"] button')].map((button) => button.textContent.trim());
+ expect(kinds).toEqual(['All', 'Place2', 'Media2']);
+ click(root, 'Media2');
+ await settle();
+ expect(pageCalls().at(-1)).toBe('/api/cases/case-1/catalog/entities?limit=30&type=media&previews=true');
+ });
+
+ it('lists evidence newest first', async () => {
+ serve(() => Promise.resolve({ items: [] }));
+ const root = open({ relationType: 'cites', label: 'Evidence', selected: [], locked: [] });
+ click(root, 'Add');
+ await settle();
+ expect(pageCalls()[0]).toBe('/api/cases/case-1/catalog/entities?limit=30&type=place%2Cmedia&order=-created&previews=true');
+ expect(root.querySelector('input[type="search"]').placeholder).toBe('Find a file, capture, proof, page or note…');
+ });
+
+ it('filters media formats on the server rather than only the loaded page', async () => {
+ serve(() => Promise.resolve({ items: ROWS }));
+ const root = open({ relationType: 'cites', label: 'Evidence', selected: [], locked: [] });
+ click(root, 'Add');
+ await settle();
+ click(root, 'Videos');
+ await settle();
+ const query = new URL(pageCalls().at(-1), 'http://localhost').searchParams;
+ expect(query.get('type')).toBe('media');
+ expect(query.get('attr')).toBe('kind');
+ expect(query.get('value')).toBe('video');
+ click(root, 'Images');
+ await settle();
+ expect(new URL(pageCalls().at(-1), 'http://localhost').searchParams.get('value')).toBe('image');
});
it('keeps the newest search result when an older request finishes last', async () => {
let resolveFirst;
let resolveSecond;
- apiGet
- .mockImplementationOnce(() => new Promise((resolve) => { resolveFirst = resolve; }))
- .mockImplementationOnce(() => new Promise((resolve) => { resolveSecond = resolve; }));
+ const pending = [
+ new Promise((resolve) => { resolveFirst = resolve; }),
+ new Promise((resolve) => { resolveSecond = resolve; }),
+ ];
+ let call = 0;
+ serve(() => pending[call++]);
const root = open({ selected: [], locked: [] });
click(root, 'Add');
@@ -129,28 +190,24 @@ describe('TemporalTargetPicker', () => {
type(root, 'warehouse');
await settle();
- expect(apiGet).toHaveBeenNthCalledWith(
- 2,
- '/api/cases/case-1/catalog/entities?limit=200&type=place%2Cmedia&q=warehouse'
- );
+ expect(pageCalls()[1]).toBe('/api/cases/case-1/catalog/entities?limit=30&type=place%2Cmedia&q=warehouse&previews=true');
resolveSecond({ items: [ROWS[2]] });
await settle();
resolveFirst({ items: [ROWS[0]] });
await settle();
- expect(root.querySelector('.results').textContent).toContain('Old warehouse');
- expect(root.querySelector('.results').textContent).not.toContain('North quay');
+ expect(names(root)).toEqual(['Old warehouse']);
});
it('recovers from a failed search with an empty result', async () => {
- apiGet.mockRejectedValue(new Error('offline'));
+ serve(() => Promise.reject(new Error('offline')));
const root = open({ selected: [], locked: [] });
click(root, 'Add');
expect(root.textContent).toContain('Searching…');
await settle();
- expect(root.textContent).toContain('No matching case items');
+ expect(root.textContent).toContain('Nothing of this kind in the case yet');
});
});
diff --git a/frontend/src/components/TemporalTargetPicker.svelte b/frontend/src/components/TemporalTargetPicker.svelte
index 5d615d3..b01de61 100644
--- a/frontend/src/components/TemporalTargetPicker.svelte
+++ b/frontend/src/components/TemporalTargetPicker.svelte
@@ -1,12 +1,16 @@
<script>
- /** Pick several endpoints for one of a Temporal Claim's typed connectors. */
- import { api } from '../lib/api.js';
- import { buildCatalogQuery } from '../lib/catalog.js';
+ /**
+ * Pick several endpoints for one of a Temporal Claim's typed connectors.
+ *
+ * The finder (`EntityFinder.svelte`) shows the kinds the connector accepts as chips,
+ * so the evidence list reads as files, captures, proofs, pages and notes rather than
+ * as everything the case holds. Evidence comes newest first.
+ */
import { entityIcon } from '../lib/entityIcon.js';
import { entityTypes, loadEntityTypes } from '../lib/entityTypes.svelte.js';
import { loadRelationTypes, relationOptions } from '../lib/relations.svelte.js';
+ import EntityFinder from './EntityFinder.svelte';
import Icon from './Icon.svelte';
- import SearchInput from './SearchInput.svelte';
let {
caseId,
@@ -21,10 +25,6 @@
loadRelationTypes();
let open = $state(false);
- let query = $state('');
- let rows = $state([]);
- let loading = $state(false);
- let seq = 0;
const lockedIds = $derived(new Set(locked.map((item) => item.id)));
const selectedIds = $derived(new Set(selected.map((item) => item.id)));
@@ -38,30 +38,10 @@
.map((entry) => entry.type)
);
- $effect(() => {
- const term = query.trim();
- const types = acceptedTypes;
- if (!open || !caseId || !types.length) return;
- const mine = ++seq;
- loading = true;
- api
- .get(buildCatalogQuery(caseId, { types, query: term, limit: 200 }))
- .then((page) => {
- if (mine === seq) rows = page.items ?? [];
- })
- .catch(() => {
- if (mine === seq) rows = [];
- })
- .finally(() => {
- if (mine === seq) loading = false;
- });
- });
-
function add(entity) {
if (!selectedIds.has(entity.id) && !lockedIds.has(entity.id)) {
- selected = [...selected, { id: entity.id, label: entity.label, type: entity.type }];
+ selected = [...selected, { id: entity.id, label: entity.label, type: entity.type, attrs: entity.attrs }];
}
- query = '';
}
function remove(id) {
@@ -75,7 +55,7 @@
<span class="modal-label">{label}</span>
{#if hint}<p>{hint}</p>{/if}
</div>
- <button class="btn btn-ghost btn-sm" class:on={open} onclick={() => (open = !open)}>
+ <button class="btn btn-ghost btn-sm" class:on={open} aria-expanded={open} onclick={() => (open = !open)}>
<Icon name={open ? 'x' : 'plus'} size={12} /> {open ? 'Close' : 'Add'}
</button>
</div>
@@ -96,22 +76,16 @@
{#if open}
<div class="picker-body">
- <SearchInput bind:value={query} placeholder="Search the case…" width="100%" />
- <div class="results">
- {#each rows as entity (entity.id)}
- <button
- class:selected={selectedIds.has(entity.id) || lockedIds.has(entity.id)}
- disabled={selectedIds.has(entity.id) || lockedIds.has(entity.id)}
- onclick={() => add(entity)}
- >
- <Icon name={entityIcon(entity)} size={12} />
- <span>{entity.label}</span>
- <small>{entity.type}</small>
- </button>
- {:else}
- <p class="empty">{loading ? 'Searching…' : 'No matching case items'}</p>
- {/each}
- </div>
+ <EntityFinder
+ {caseId}
+ types={acceptedTypes}
+ exclude={[...lockedIds, ...selectedIds]}
+ order={relationType === 'cites' ? '-created' : ''}
+ label={`Find ${label.toLowerCase()}`}
+ placeholder={relationType === 'cites' ? 'Find a file, capture, proof, page or note…' : relationType === 'at' ? 'Find a place…' : 'Find a person, a group, an object…'}
+ onpick={add}
+ onclose={() => (open = false)}
+ />
</div>
{/if}
</div>
@@ -128,21 +102,5 @@
}
.chip.locked { border-style: dashed; }
.chip button { display: grid; padding: 0; border: 0; background: none; color: var(--text-3); cursor: pointer; }
- .picker-body { display: grid; gap: 5px; }
- .results {
- max-height: 180px; overflow: auto; border: 1px solid var(--border);
- border-radius: var(--r-sm); background: var(--bg-2);
- }
- .results > button {
- width: 100%; display: grid; grid-template-columns: auto minmax(0, 1fr) auto;
- align-items: center; gap: 7px; padding: 7px 8px; border: 0;
- border-bottom: 1px solid var(--border); background: transparent; color: var(--text-2);
- text-align: left; cursor: pointer;
- }
- .results > button:last-child { border-bottom: 0; }
- .results > button:hover:not(:disabled) { background: var(--bg-3); color: var(--text-1); }
- .results > button.selected { opacity: .45; }
- .results span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
- .results small { color: var(--text-3); }
- .empty { margin: 0; padding: 12px; color: var(--text-3); text-align: center; font-size: var(--fs-xs); }
+ .picker-body { padding: 8px; border: 1px solid var(--border); border-radius: var(--r-sm); background: var(--bg-1); }
</style>
diff --git a/frontend/src/components/TimelineTrackEditor.svelte b/frontend/src/components/TimelineTrackEditor.svelte
index 4b054da..86d17bf 100644
--- a/frontend/src/components/TimelineTrackEditor.svelte
+++ b/frontend/src/components/TimelineTrackEditor.svelte
@@ -20,6 +20,7 @@
let categories = $state(new Set());
let relation = $state('any');
let roles = $state(new Set());
+ let collectedOnly = $state(false);
let filter = $state(emptyFilter());
let summary = $state(null);
let facets = $state([]);
@@ -37,6 +38,7 @@
categories = new Set(track?.categories ?? ['statement']);
relation = track?.query?.relation ?? 'any';
roles = new Set(track?.query?.roles ?? []);
+ collectedOnly = track?.query?.collected_only === true;
filter = normalizeFilter(track?.query?.filter ?? emptyFilter());
});
@@ -121,6 +123,9 @@
label: queryLabel,
relation,
roles: [...roles],
+ collected_only: categories.has('media') && collectedOnly,
+ // a file lane keeps drawing its files through an edit
+ as_files: track?.query?.as_files,
},
}));
}
@@ -161,6 +166,11 @@
<label><input type="checkbox" checked={categories.has(option[0])} onchange={() => toggleCategory(option[0])} />{option[1]}</label>
{/each}
</div>
+ {#if categories.has('media')}
+ <label class="held" title="Frames, captures, collages and renders the case made itself">
+ <input type="checkbox" checked={!collectedOnly} onchange={() => (collectedOnly = !collectedOnly)} />Include working files
+ </label>
+ {/if}
</fieldset>
<label class="match">Match the Search+ question through
@@ -222,7 +232,7 @@
fieldset { display: grid; gap: 8px; margin: 0; padding: 10px 12px; border: 1px solid var(--border); border-radius: var(--r-sm); }
legend, .search-query > span { padding: 0 4px; color: var(--text-2); font-size: var(--fs-xs); font-weight: 650; }
.checks { display: flex; flex-wrap: wrap; gap: 8px 14px; }
- .checks label { display: inline-flex; align-items: center; gap: 6px; color: var(--text-2); font-size: var(--fs-sm); }
+ .checks label, .held { display: inline-flex; align-items: center; gap: 6px; color: var(--text-2); font-size: var(--fs-sm); }
fieldset small { color: var(--text-3); }
.search-query { overflow: visible; border: 1px solid var(--border); border-radius: var(--r-sm); }
.search-query > span { display: block; width: max-content; margin: -7px 0 0 8px; background: var(--bg-1); }
diff --git a/frontend/src/components/TimelineTrackEditor.test.js b/frontend/src/components/TimelineTrackEditor.test.js
index 00f355e..8af3516 100644
--- a/frontend/src/components/TimelineTrackEditor.test.js
+++ b/frontend/src/components/TimelineTrackEditor.test.js
@@ -27,4 +27,15 @@ describe('Timeline track editor', () => {
expect(source).toContain('color = track?.color ?? \'\'');
expect(source).toContain(' color,');
});
+
+ it("offers the Media Library's working-files switch on a track that holds files", () => {
+ expect(source).toContain("{#if categories.has('media')}");
+ expect(source).toContain('Include working files');
+ expect(source).toContain("collected_only: categories.has('media') && collectedOnly,");
+ expect(source).toContain('collectedOnly = track?.query?.collected_only === true;');
+ });
+
+ it('keeps a file lane drawing its files through an edit', () => {
+ expect(source).toContain('as_files: track?.query?.as_files,');
+ });
});
diff --git a/frontend/src/components/ZonePicker.svelte b/frontend/src/components/ZonePicker.svelte
index 82597fa..8c5f8ad 100644
--- a/frontend/src/components/ZonePicker.svelte
+++ b/frontend/src/components/ZonePicker.svelte
@@ -2,9 +2,12 @@
/**
* Which clock a chronology is read on.
*
- * Four kinds of answer, in one searchable list because picking between them is one
+ * Five kinds of answer, in one searchable list because picking between them is one
* decision:
*
+ * - **Where the case is**, the zone most of its places stand in (`lib/caseClock.js`),
+ * which is what a chronology opens on: an investigation argues in the local time of
+ * where things happened.
* - **UTC**, what the case stores and the only reading that means the same thing on
* every machine.
* - **This computer**, a legitimate reading of the analyst's own working day.
@@ -25,20 +28,27 @@
zoneMatches,
zoneWords,
} from '../lib/timeline.js';
+ import { foldText } from '../lib/textFold.js';
+ import { caseZoneWords } from '../lib/caseClock.js';
import Icon from './Icon.svelte';
import SearchInput from './SearchInput.svelte';
let {
- /** `utc` | `machine` | `zone:<IANA>` | `place:<id>` */
- choice = $bindable('utc'),
+ /** `case` | `utc` | `machine` | `zone:<IANA>` | `place:<id>` */
+ choice = $bindable('case'),
/** The case's saved points, as `{ id, label }`. */
places = [],
+ /** The zone the case's places stand in, `{ zone, count, of }`, or null when it has
+ * none: then `case` reads as UTC and says so. */
+ home = null,
/** The instant the offsets are shown at: the window's own start, not today, or a
* winter window would be labelled with a summer offset. */
at = 0,
/** What the parent resolved the choice to, for the trigger's own label. */
resolved = UTC,
disabled = false,
+ /** Told the analyst's pick, so the parent can keep it. */
+ onpick,
} = $props();
/** How many zones the list shows before it asks for a narrower term. Long enough to
@@ -55,12 +65,13 @@
const shown = $derived(matching.slice(0, ROWS));
const matchingPlaces = $derived(
places.filter((place) =>
- place.label.toLowerCase().includes(query.trim().toLowerCase())
+ foldText(place.label).includes(foldText(query.trim()))
)
);
/** What the button says. The point's or zone's own words, never the raw choice. */
const label = $derived.by(() => {
+ if (choice === 'case') return home ? zoneWords(home.zone).place : 'UTC';
if (choice === 'utc') return 'UTC';
if (choice === 'machine') return zoneWords(local).place;
if (choice.startsWith('place:')) {
@@ -82,6 +93,7 @@
choice = value;
open = false;
query = '';
+ onpick?.(value);
}
</script>
@@ -90,20 +102,27 @@
class="trigger"
{disabled}
aria-expanded={open}
- title="Which clock the axis is labelled with"
+ title={choice === 'case' && home ? `The clock of ${caseZoneWords(home)}` : 'Which clock the axis is labelled with'}
onclick={() => (open = !open)}
>
<Icon name="clock" size={12} />
<span>{label}</span>
- <small>{offsetLabel(resolved, at)}</small>
+ <!-- The offset, unless the name already is it: `UTC UTC` said one thing twice. -->
+ {#if label !== 'UTC'}<small>{offsetLabel(resolved, at)}</small>{/if}
</button>
{#if open}
<div class="menu">
<SearchInput bind:value={query} placeholder="Search a zone or a point…" width="100%" />
<div class="rows">
+ {#if home && zoneMatches(home.zone, query, at)}
+ <button class:on={choice === 'case'} onclick={() => pick('case')}>
+ <span>{zoneWords(home.zone).place}</span>
+ <small>{caseZoneWords(home)} · {offsetLabel(home.zone, at)}</small>
+ </button>
+ {/if}
{#if zoneMatches('UTC', query, at)}
- <button class:on={choice === 'utc'} onclick={() => pick('utc')}>
+ <button class:on={choice === 'utc' || (choice === 'case' && !home)} onclick={() => pick('utc')}>
<span>UTC</span><small>what the case stores</small>
</button>
{/if}
diff --git a/frontend/src/components/ZonePicker.test.js b/frontend/src/components/ZonePicker.test.js
index 5b25bc2..328266f 100644
--- a/frontend/src/components/ZonePicker.test.js
+++ b/frontend/src/components/ZonePicker.test.js
@@ -15,6 +15,23 @@ describe('choosing the clock a chronology is read on', () => {
expect(source).toContain('<SearchInput bind:value={query}');
});
+ it('opens on where the case is, and says how much of the case that is', () => {
+ // a video from Sanaa is argued in Sanaa's time, and the case knows where it is
+ expect(source).toContain("choice = $bindable('case')");
+ expect(source).toContain("onclick={() => pick('case')}");
+ expect(source).toContain('{caseZoneWords(home)} · {offsetLabel(home.zone, at)}');
+ // with no placed point the default is UTC, and the UTC row says so
+ expect(source).toContain("if (choice === 'case') return home ? zoneWords(home.zone).place : 'UTC';");
+ expect(source).toContain("class:on={choice === 'utc' || (choice === 'case' && !home)}");
+ // the parent keeps what was picked
+ expect(source).toContain('onpick?.(value);');
+ });
+
+ it('does not print the offset beside a name that already is it', () => {
+ // the trigger read `UTC UTC`
+ expect(source).toContain("{#if label !== 'UTC'}<small>{offsetLabel(resolved, at)}</small>{/if}");
+ });
+
it('names the saved points apart, because picking one does a second thing', () => {
// a point has coordinates, so its daylight can be drawn; a zone name cannot
expect(source).toContain('Saved points · with daylight');
diff --git a/frontend/src/lib/anchoredPanel.js b/frontend/src/lib/anchoredPanel.js
new file mode 100644
index 0000000..fe6e0da
--- /dev/null
+++ b/frontend/src/lib/anchoredPanel.js
@@ -0,0 +1,32 @@
+/** Keep a picker in the viewport, above its field when there is more room there.
+ * The popover top layer escapes scrolling and transformed tool containers. */
+export function anchoredPanel(node, { anchor, width = 560 }) {
+ function position() {
+ const target = anchor();
+ if (!target) return;
+ const rect = target.getBoundingClientRect();
+ const margin = 12;
+ const gap = 6;
+ const availableBelow = window.innerHeight - rect.bottom - margin - gap;
+ const availableAbove = rect.top - margin - gap;
+ const above = availableBelow < 320 && availableAbove > availableBelow;
+ const available = Math.max(80, above ? availableAbove : availableBelow);
+ const size = Math.min(width, window.innerWidth - margin * 2);
+ node.style.width = `${size}px`;
+ node.style.maxHeight = `${available}px`;
+ node.style.left = `${Math.max(margin, Math.min(rect.right - size, window.innerWidth - size - margin))}px`;
+ node.style.top = `${above ? Math.max(margin, rect.top - gap - node.offsetHeight) : Math.max(margin, rect.bottom + gap)}px`;
+ }
+ node.showPopover?.();
+ position();
+ const observer = new ResizeObserver(position);
+ observer.observe(node);
+ window.addEventListener('resize', position);
+ window.addEventListener('scroll', position, true);
+ return { destroy() {
+ observer.disconnect();
+ window.removeEventListener('resize', position);
+ window.removeEventListener('scroll', position, true);
+ node.hidePopover?.();
+ } };
+}
diff --git a/frontend/src/lib/bidi.js b/frontend/src/lib/bidi.js
index ac21149..899fbdb 100644
--- a/frontend/src/lib/bidi.js
+++ b/frontend/src/lib/bidi.js
@@ -12,6 +12,7 @@
const RTL_CHARS = /[\u0590-\u08FF\uFB1D-\uFDFF\uFE70-\uFEFF]/;
export const LRI = '\u2066'; // LEFT-TO-RIGHT ISOLATE
+export const FSI = '\u2068'; // FIRST STRONG ISOLATE
export const PDI = '\u2069'; // POP DIRECTIONAL ISOLATE
// LTR runs worth isolating: URLs, @mentions, plus codes, coordinate pairs.
@@ -29,3 +30,17 @@ export function bidiSafe(text) {
str[offset - 1] === LRI ? run : LRI + run + PDI
);
}
+
+/**
+ * A label drawn where no `dir="auto"` reaches: a canvas node name, an SVG plate.
+ *
+ * Both lay text out in a left-to-right paragraph, so an Arabic name with a number in
+ * it (`مسجد 12`) came out with the number on the wrong side, and a trailing `…` at
+ * the wrong end. A First Strong Isolate takes the direction from the label's own
+ * first letter, as `dir="auto"` does in HTML, and keeps it from reordering what is
+ * drawn beside it. Text without RTL passes through untouched.
+ */
+export function bidiIsolate(text) {
+ const value = String(text ?? '');
+ return hasRtl(value) ? `${FSI}${value}${PDI}` : value;
+}
diff --git a/frontend/src/lib/bidi.test.js b/frontend/src/lib/bidi.test.js
index fd6f345..ead082f 100644
--- a/frontend/src/lib/bidi.test.js
+++ b/frontend/src/lib/bidi.test.js
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest';
-import { bidiSafe, hasRtl, LRI, PDI } from './bidi.js';
+import { bidiIsolate, bidiSafe, FSI, hasRtl, LRI, PDI } from './bidi.js';
const ARABIC = 'قصف على المدينة';
@@ -46,3 +46,16 @@ describe('bidiSafe — isolates LTR runs inside RTL text', () => {
expect(bidiSafe(null)).toBe('');
});
});
+
+describe('bidiIsolate — a drawn label reads in its own direction', () => {
+ it('isolates a label holding RTL, so its number and ellipsis stay on its side', () => {
+ expect(bidiIsolate('مسجد 12')).toBe(`${FSI}مسجد 12${PDI}`);
+ expect(bidiIsolate('שלום…')).toBe(`${FSI}שלום…${PDI}`);
+ });
+
+ it('leaves every other label exactly as it was', () => {
+ expect(bidiIsolate('Quay 4')).toBe('Quay 4');
+ expect(bidiIsolate('Москва')).toBe('Москва');
+ expect(bidiIsolate(null)).toBe('');
+ });
+});
diff --git a/frontend/src/lib/boardGroups.js b/frontend/src/lib/boardGroups.js
new file mode 100644
index 0000000..cb57b42
--- /dev/null
+++ b/frontend/src/lib/boardGroups.js
@@ -0,0 +1,226 @@
+/**
+ * The Board's groups: the case read as who, what and where, with its material below.
+ *
+ * The Board used to open on one table of everything the case holds, and a case is
+ * mostly files: frames, captures, Detect runs, Inspect work. The people, places and
+ * things an investigation is about sat somewhere in that list. So the rows are
+ * **grouped by family rather than hidden**: the groups an investigation is about open
+ * first, the material folds underneath with a way to the tool that reads it, and
+ * nothing leaves the answer. The question stays the one question Board and Graph
+ * share, so a count, a total or a drawing never depends on which groups are open.
+ *
+ * Pure: the family of a type comes in as a resolver, so none of this waits on the
+ * served registry to be testable.
+ */
+
+/** The groups, in reading order. `subject` groups open by default; `material` ones
+ * fold, unless the case holds no subject at all. */
+export const BOARD_GROUPS = [
+ { id: 'actor', label: 'People & organizations', families: ['actor'], kind: 'subject' },
+ { id: 'identifier', label: 'Accounts & identifiers', families: ['identifier'], kind: 'subject' },
+ { id: 'place', label: 'Places', families: ['place'], kind: 'subject' },
+ { id: 'asset', label: 'Things', families: ['asset'], kind: 'subject' },
+ { id: 'class', label: 'Equipment types', families: ['class'], kind: 'subject' },
+ {
+ id: 'claim',
+ label: 'Events',
+ families: ['claim'],
+ kind: 'material',
+ reads: { tool: 'timeline', label: 'Timeline' },
+ },
+ {
+ id: 'collected',
+ label: 'Files',
+ families: ['collected'],
+ kind: 'material',
+ reads: { tool: 'media', label: 'Media Library' },
+ },
+ { id: 'document', label: 'Work', families: ['document'], kind: 'material' },
+ // A free type the registry has never heard of has no family, and still belongs
+ // somewhere: an answer that loses a row because its type is unknown is short.
+ { id: 'other', label: 'Other', families: [null], kind: 'material' },
+];
+
+const BY_ID = new Map(BOARD_GROUPS.map((group) => [group.id, group]));
+
+/** A group by id, or null. */
+export function boardGroup(id) {
+ return BY_ID.get(id) ?? null;
+}
+
+/** Which group a type falls in, from its family. */
+export function groupOfType(type, familyOf) {
+ const family = familyOf(type) ?? null;
+ return BOARD_GROUPS.find((group) => group.families.includes(family)) ?? boardGroup('other');
+}
+
+/** The types of one group among the ones the case holds (`summary.by_type`). */
+export function typesOfGroup(group, caseTypes, familyOf) {
+ return caseTypes.filter((type) => groupOfType(type, familyOf).id === group.id).sort();
+}
+
+/**
+ * The types a group's own page asks for: its types, narrowed by the ones the question
+ * already picked. Empty means the group cannot hold an answer, so it sends nothing.
+ */
+export function groupRequestTypes(group, caseTypes, wantedTypes, familyOf) {
+ const own = typesOfGroup(group, caseTypes, familyOf);
+ if (!wantedTypes?.length) return own;
+ return own.filter((type) => wantedTypes.includes(type));
+}
+
+/** How many of the answer each group holds, from a per-type count. */
+export function groupCounts(byType, familyOf) {
+ const counts = Object.fromEntries(BOARD_GROUPS.map((group) => [group.id, 0]));
+ for (const [type, n] of Object.entries(byType ?? {})) {
+ counts[groupOfType(type, familyOf).id] += Number(n) || 0;
+ }
+ return counts;
+}
+
+/** Whether the case holds anything an investigation is about. */
+export function holdsSubjects(byType, familyOf) {
+ const counts = groupCounts(byType, familyOf);
+ return BOARD_GROUPS.some((group) => group.kind === 'subject' && counts[group.id] > 0);
+}
+
+/**
+ * Whether a group shows its rows.
+ *
+ * The analyst's own fold wins. Without one, a subject group opens and a material
+ * group folds, except in a case that holds no subject yet, where folding the material
+ * would leave nothing on screen. Under a question the groups holding an answer open,
+ * because a count of matches folded away is an answer nobody can read; a fold made
+ * during that question still holds (`asked`, cleared when the question changes).
+ */
+export function groupOpen(group, { folds = {}, asked = {}, filtering = false, subjects = true }) {
+ if (filtering) return asked[group.id] ?? true;
+ if (group.id in folds) return folds[group.id];
+ return group.kind === 'subject' || !subjects;
+}
+
+// ── the layout, kept per case on this machine ─────────────────────────────────
+/**
+ * How this analyst lays the Board out for a case: grouped or flat, the sort, and
+ * which groups they folded. The same standing as the remembered question
+ * (`lib/entityFilter.js`): how somebody looks at their material, not something the
+ * case holds, so it stays in this browser and out of the settings backup.
+ */
+const LAYOUT_KEY = 'azimut:board-layout';
+
+export const GROUPINGS = [
+ { id: 'kind', label: 'By kind', hint: 'People, places and things first, the files below' },
+ { id: 'none', label: 'None', hint: 'One table of everything, the way 0.3.1 showed it' },
+];
+
+/** The orders a grouped Board offers, each over the whole case. */
+export const GROUP_SORTS = [
+ { id: '-events', label: 'Most noted', hint: 'the subjects most events name first, the files newest first' },
+ { id: 'label', label: 'Name', hint: 'alphabetical' },
+ { id: '-created', label: 'Recently added', hint: 'newest filed first' },
+];
+
+export function defaultLayout() {
+ return { group: 'kind', sort: '-events', folds: {} };
+}
+
+/** A stored layout, reshaped so an old or hand-edited value cannot break the Board. */
+export function normalizeLayout(raw) {
+ const base = defaultLayout();
+ if (!raw || typeof raw !== 'object') return base;
+ const group = GROUPINGS.some((entry) => entry.id === raw.group) ? raw.group : base.group;
+ const sort = GROUP_SORTS.some((entry) => entry.id === raw.sort) ? raw.sort : base.sort;
+ const folds = {};
+ for (const [id, open] of Object.entries(raw.folds ?? {})) {
+ if (BY_ID.has(id) && typeof open === 'boolean') folds[id] = open;
+ }
+ return { group, sort, folds };
+}
+
+export function loadLayout(caseId, storage = globalThis.localStorage) {
+ if (!caseId) return defaultLayout();
+ try {
+ return normalizeLayout(JSON.parse(storage?.getItem(`${LAYOUT_KEY}:${caseId}`) ?? 'null'));
+ } catch {
+ return defaultLayout();
+ }
+}
+
+export function saveLayout(caseId, layout, storage = globalThis.localStorage) {
+ if (!caseId) return;
+ try {
+ storage?.setItem(`${LAYOUT_KEY}:${caseId}`, JSON.stringify(normalizeLayout(layout)));
+ } catch {
+ /* a private window without storage keeps the layout for the session */
+ }
+}
+
+/**
+ * What a saved Board view says about the layout. A view saved before the groups
+ * existed has no `group`, and it opens flat: a saved reading reads the way it did.
+ */
+export function viewLayout(board) {
+ const group = board?.group === 'kind' ? 'kind' : 'none';
+ const sort = GROUP_SORTS.some((entry) => entry.id === board?.groupSort)
+ ? board.groupSort
+ : defaultLayout().sort;
+ return { group, sort };
+}
+
+// ── what a row says about its events ──────────────────────────────────────────
+const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
+
+/**
+ * The span a row's dated events cover, short enough for a table cell.
+ *
+ * `last` is the half-open end the store keeps, so a day-precision event ending at
+ * the next midnight reads as the day it is, not as the day after it. UTC, like the
+ * Board's fact-time chip.
+ */
+export function spanWords(first, last) {
+ if (!first || !last) return '';
+ const start = new Date(first);
+ const end = new Date(Math.max(new Date(last).getTime() - 1, start.getTime()));
+ if (Number.isNaN(start.getTime()) || Number.isNaN(end.getTime())) return '';
+ const day = (at) => `${at.getUTCDate()} ${MONTHS[at.getUTCMonth()]}`;
+ const sameYear = start.getUTCFullYear() === end.getUTCFullYear();
+ const sameMonth = sameYear && start.getUTCMonth() === end.getUTCMonth();
+ if (sameMonth && start.getUTCDate() === end.getUTCDate()) {
+ return `${day(start)} ${start.getUTCFullYear()}`;
+ }
+ if (sameMonth) {
+ return `${start.getUTCDate()}–${day(end)} ${end.getUTCFullYear()}`;
+ }
+ if (sameYear) return `${day(start)} – ${day(end)} ${end.getUTCFullYear()}`;
+ const month = (at) => `${MONTHS[at.getUTCMonth()]} ${at.getUTCFullYear()}`;
+ return `${month(start)} – ${month(end)}`;
+}
+
+/** "1 event", "12 events": the count a row reads by. */
+export function eventWords(n) {
+ return `${n} event${n === 1 ? '' : 's'}`;
+}
+
+/** The questions the Board shows as waiting, priced from the summary. Only the ones
+ * with something to answer: a zero is not waiting. */
+export const WAITING = [
+ { id: 'review', read: (summary) => summary?.by_status?.suggested ?? 0, words: () => 'to review' },
+ { id: 'loose', read: (summary) => summary?.unlinked ?? 0, words: () => 'linked to nothing' },
+ {
+ id: 'unsourced',
+ read: (summary) => summary?.lacks?.source ?? 0,
+ words: (n) => `${n === 1 ? 'event' : 'events'} without a source`,
+ },
+ {
+ id: 'unassessed',
+ read: (summary) => summary?.lacks?.assessment ?? 0,
+ words: (n) => `${n === 1 ? 'event' : 'events'} not assessed`,
+ },
+];
+
+export function waitingOf(summary) {
+ return WAITING.map((entry) => {
+ const count = entry.read(summary);
+ return { id: entry.id, count, words: entry.words(count) };
+ }).filter((entry) => entry.count > 0);
+}
diff --git a/frontend/src/lib/boardGroups.test.js b/frontend/src/lib/boardGroups.test.js
new file mode 100644
index 0000000..e02802c
--- /dev/null
+++ b/frontend/src/lib/boardGroups.test.js
@@ -0,0 +1,182 @@
+import { describe, expect, it } from 'vitest';
+import {
+ BOARD_GROUPS,
+ boardGroup,
+ defaultLayout,
+ eventWords,
+ groupCounts,
+ groupOfType,
+ groupOpen,
+ groupRequestTypes,
+ holdsSubjects,
+ loadLayout,
+ normalizeLayout,
+ saveLayout,
+ spanWords,
+ typesOfGroup,
+ viewLayout,
+ waitingOf,
+} from './boardGroups.js';
+
+const FAMILIES = {
+ person: 'actor',
+ organization: 'actor',
+ account: 'identifier',
+ email: 'identifier',
+ place: 'place',
+ vehicle: 'asset',
+ 'equipment-type': 'class',
+ claim: 'claim',
+ media: 'collected',
+ capture: 'collected',
+ proof: 'document',
+ bookmark: 'document',
+};
+const familyOf = (type) => FAMILIES[type] ?? null;
+
+function memory() {
+ const store = new Map();
+ return {
+ getItem: (key) => (store.has(key) ? store.get(key) : null),
+ setItem: (key, value) => store.set(key, String(value)),
+ };
+}
+
+describe('board groups', () => {
+ it('reads the case as who, what and where before its material', () => {
+ expect(BOARD_GROUPS.map((group) => group.label)).toEqual([
+ 'People & organizations',
+ 'Accounts & identifiers',
+ 'Places',
+ 'Things',
+ 'Equipment types',
+ 'Events',
+ 'Files',
+ 'Work',
+ 'Other',
+ ]);
+ const kinds = BOARD_GROUPS.map((group) => group.kind);
+ // every subject group comes before every material group
+ expect(kinds.lastIndexOf('subject')).toBeLessThan(kinds.indexOf('material'));
+ });
+
+ it('puts a type in the group of its family, and a free type in Other', () => {
+ expect(groupOfType('person', familyOf).id).toBe('actor');
+ expect(groupOfType('email', familyOf).id).toBe('identifier');
+ expect(groupOfType('capture', familyOf).id).toBe('collected');
+ expect(groupOfType('invented', familyOf).id).toBe('other');
+ });
+
+ it('lists a group’s types among the ones the case holds', () => {
+ const caseTypes = ['media', 'person', 'organization', 'place', 'claim'];
+ expect(typesOfGroup(boardGroup('actor'), caseTypes, familyOf)).toEqual([
+ 'organization',
+ 'person',
+ ]);
+ expect(typesOfGroup(boardGroup('asset'), caseTypes, familyOf)).toEqual([]);
+ });
+
+ it('narrows a group’s request by the types the question picked', () => {
+ const caseTypes = ['person', 'organization', 'media'];
+ const actor = boardGroup('actor');
+ expect(groupRequestTypes(actor, caseTypes, [], familyOf)).toEqual(['organization', 'person']);
+ expect(groupRequestTypes(actor, caseTypes, ['person'], familyOf)).toEqual(['person']);
+ // a question about media leaves the people group nothing to ask
+ expect(groupRequestTypes(actor, caseTypes, ['media'], familyOf)).toEqual([]);
+ });
+
+ it('adds a per-type count up per group', () => {
+ const counts = groupCounts({ person: 2, organization: 1, media: 20, mystery: 1 }, familyOf);
+ expect(counts.actor).toBe(3);
+ expect(counts.collected).toBe(20);
+ expect(counts.other).toBe(1);
+ expect(counts.place).toBe(0);
+ });
+
+ it('knows a case of files only holds no subject', () => {
+ expect(holdsSubjects({ media: 2, capture: 9, bookmark: 1 }, familyOf)).toBe(false);
+ expect(holdsSubjects({ media: 2, place: 1 }, familyOf)).toBe(true);
+ });
+});
+
+describe('which groups are open', () => {
+ const actor = boardGroup('actor');
+ const files = boardGroup('collected');
+
+ it('opens the subjects and folds the material', () => {
+ expect(groupOpen(actor, {})).toBe(true);
+ expect(groupOpen(files, {})).toBe(false);
+ });
+
+ it('opens the material when the case has no subject to show instead', () => {
+ expect(groupOpen(files, { subjects: false })).toBe(true);
+ });
+
+ it('keeps the analyst’s own fold', () => {
+ expect(groupOpen(actor, { folds: { actor: false } })).toBe(false);
+ expect(groupOpen(files, { folds: { collected: true } })).toBe(true);
+ });
+
+ it('opens every group under a question, unless folded during it', () => {
+ expect(groupOpen(files, { filtering: true, folds: { collected: false } })).toBe(true);
+ expect(groupOpen(files, { filtering: true, asked: { collected: false } })).toBe(false);
+ });
+});
+
+describe('the layout', () => {
+ it('defaults to groups, most noted first, nothing folded', () => {
+ expect(defaultLayout()).toEqual({ group: 'kind', sort: '-events', folds: {} });
+ });
+
+ it('reshapes a stored value it cannot trust', () => {
+ expect(normalizeLayout({ group: 'flat', sort: 'size', folds: { actor: 'no', place: false, nope: true } }))
+ .toEqual({ group: 'kind', sort: '-events', folds: { place: false } });
+ expect(normalizeLayout(null)).toEqual(defaultLayout());
+ });
+
+ it('is kept per case on this machine', () => {
+ const storage = memory();
+ saveLayout('case-a', { group: 'none', sort: 'label', folds: { actor: false } }, storage);
+ expect(loadLayout('case-a', storage)).toEqual({ group: 'none', sort: 'label', folds: { actor: false } });
+ expect(loadLayout('case-b', storage)).toEqual(defaultLayout());
+ storage.setItem('azimut:board-layout:case-c', '{broken');
+ expect(loadLayout('case-c', storage)).toEqual(defaultLayout());
+ });
+
+ it('opens a view saved before the groups flat, as it was saved', () => {
+ expect(viewLayout({ order: 'label', sortKey: 'label', sortDesc: false })).toEqual({
+ group: 'none',
+ sort: '-events',
+ });
+ expect(viewLayout({ group: 'kind', groupSort: 'label' })).toEqual({ group: 'kind', sort: 'label' });
+ });
+});
+
+describe('what a row says', () => {
+ it('writes the span of its events short, reading the half-open end as the day it is', () => {
+ expect(spanWords('2026-03-12T00:00:00.000000Z', '2026-03-13T00:00:00.000000Z')).toBe('12 Mar 2026');
+ expect(spanWords('2026-03-11T00:00:00.000000Z', '2026-03-20T00:00:00.000000Z')).toBe('11–19 Mar 2026');
+ expect(spanWords('2026-03-11T00:00:00.000000Z', '2026-04-03T00:00:00.000000Z')).toBe('11 Mar – 2 Apr 2026');
+ expect(spanWords('2025-12-30T00:00:00.000000Z', '2026-01-03T00:00:00.000000Z')).toBe('Dec 2025 – Jan 2026');
+ expect(spanWords(null, null)).toBe('');
+ });
+
+ it('counts events in words', () => {
+ expect(eventWords(1)).toBe('1 event');
+ expect(eventWords(12)).toBe('12 events');
+ });
+
+ it('shows as waiting only what has something to answer', () => {
+ const waiting = waitingOf({
+ by_status: { suggested: 3 },
+ unlinked: 0,
+ lacks: { source: 1, assessment: 4 },
+ });
+ expect(waiting).toEqual([
+ { id: 'review', count: 3, words: 'to review' },
+ { id: 'unsourced', count: 1, words: 'event without a source' },
+ { id: 'unassessed', count: 4, words: 'events not assessed' },
+ ]);
+ expect(waitingOf(null)).toEqual([]);
+ });
+});
diff --git a/frontend/src/lib/caseAxis.svelte.js b/frontend/src/lib/caseAxis.svelte.js
new file mode 100644
index 0000000..da8d488
--- /dev/null
+++ b/frontend/src/lib/caseAxis.svelte.js
@@ -0,0 +1,77 @@
+/**
+ * The clock the case is read on, shared by every date field in the app.
+ *
+ * The Timeline's axis opens on where the case is (`lib/caseClock.js`) and the analyst
+ * can move it. A date typed with no place of its own opens on that same clock, so it
+ * lands on the axis where it was meant: a `10/09/2026` typed in a Los Angeles case is
+ * Los Angeles's 10th, not UTC's. The Timeline says its clock here as it settles; a
+ * field opened before the Timeline was ever drawn works it out once from the choice
+ * kept for the case and the case's places. UTC until either is known.
+ */
+import { api } from './api.js';
+import { buildCatalogQuery } from './catalog.js';
+import { caseZone, rememberedClock } from './caseClock.js';
+import { zoneAt } from './localZone.js';
+import { UTC, knownZone, machineZone } from './timeline.js';
+
+export const caseAxis = $state({ caseId: null, zone: null });
+
+/** The case being worked out, so two fields asking at once ask once. */
+let asking = null;
+
+/** The zone a new date in this case opens on: the axis's clock, else UTC. */
+export function axisZone(caseId) {
+ return caseId && caseAxis.caseId === caseId && caseAxis.zone ? caseAxis.zone : UTC;
+}
+
+/** Said by the Timeline whenever its axis settles on a clock. */
+export function noteAxisZone(caseId, zone) {
+ if (!caseId || !zone || !knownZone(zone)) return;
+ caseAxis.caseId = caseId;
+ caseAxis.zone = zone;
+}
+
+/** The case's saved points with coordinates, as the Timeline's clock menu lists them. */
+async function casePlaces(caseId, get) {
+ const page = await get(buildCatalogQuery(caseId, { types: ['place'], limit: 50 }));
+ return (page?.items ?? [])
+ .filter((entity) => Number.isFinite(Number(entity.attrs?.lat)) && Number.isFinite(Number(entity.attrs?.lon)))
+ .map((entity) => ({ id: entity.id, label: entity.label, lat: Number(entity.attrs.lat), lon: Number(entity.attrs.lon) }));
+}
+
+/**
+ * Work out the axis's clock for a case the Timeline has not drawn in this session:
+ * the clock kept for the case, and where the case is by default. Asked once per case;
+ * the Timeline's own word replaces it whenever it is drawn.
+ */
+export async function learnAxisZone(caseId, { get = (url) => api.get(url), lookup = zoneAt, storage } = {}) {
+ if (!caseId || caseAxis.caseId === caseId || asking === caseId) return;
+ asking = caseId;
+ const choice = rememberedClock(caseId, storage ?? globalThis.localStorage);
+ let zone = UTC;
+ try {
+ if (choice === 'machine') zone = machineZone();
+ else if (choice.startsWith('zone:')) zone = choice.slice(5);
+ else if (choice !== 'utc') {
+ const places = await casePlaces(caseId, get);
+ if (choice.startsWith('place:')) {
+ const place = places.find((entry) => entry.id === choice.slice(6));
+ zone = place ? (await lookup(place)) || UTC : UTC;
+ } else {
+ zone = (await caseZone(places, { lookup }))?.zone ?? UTC;
+ }
+ }
+ } catch {
+ zone = UTC;
+ }
+ if (asking === caseId) asking = null;
+ // The Timeline may have said it first, and its word is the one on screen.
+ if (caseAxis.caseId !== caseId) noteAxisZone(caseId, knownZone(zone) ? zone : UTC);
+}
+
+/** Forget the clock learned. For tests. */
+export function forgetAxisZone() {
+ caseAxis.caseId = null;
+ caseAxis.zone = null;
+ asking = null;
+}
diff --git a/frontend/src/lib/caseAxis.test.js b/frontend/src/lib/caseAxis.test.js
new file mode 100644
index 0000000..241d544
--- /dev/null
+++ b/frontend/src/lib/caseAxis.test.js
@@ -0,0 +1,70 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { axisZone, forgetAxisZone, learnAxisZone, noteAxisZone } from './caseAxis.svelte.js';
+
+function memory(entries = {}) {
+ const held = new Map(Object.entries(entries));
+ return { getItem: (key) => (held.has(key) ? held.get(key) : null), setItem: (key, value) => held.set(key, value) };
+}
+
+const PLACES = {
+ items: [
+ { id: 'p1', label: 'Oceanside pier', attrs: { lat: 33.19, lon: -117.38 } },
+ { id: 'p2', label: 'Oceanside bluff', attrs: { lat: 33.21, lon: -117.40 } },
+ { id: 'p3', label: 'Tokyo office', attrs: { lat: 35.68, lon: 139.76 } },
+ { id: 'p4', label: 'Nowhere yet', attrs: {} },
+ ],
+};
+const lookup = async ({ lon }) => (lon > 100 ? 'Asia/Tokyo' : 'America/Los_Angeles');
+
+beforeEach(() => forgetAxisZone());
+
+describe('the clock a case is read on', () => {
+ it('is UTC until the case says otherwise, and only for that case', () => {
+ expect(axisZone('case-a')).toBe('UTC');
+ noteAxisZone('case-a', 'America/Los_Angeles');
+ expect(axisZone('case-a')).toBe('America/Los_Angeles');
+ expect(axisZone('case-b')).toBe('UTC');
+ // a zone this browser cannot read is never taken
+ noteAxisZone('case-a', 'Mars/Olympus');
+ expect(axisZone('case-a')).toBe('America/Los_Angeles');
+ });
+
+ it('opens on where most of the case’s places are, as the axis does', async () => {
+ const get = vi.fn(async () => PLACES);
+ await learnAxisZone('case-a', { get, lookup, storage: memory() });
+ expect(axisZone('case-a')).toBe('America/Los_Angeles');
+ expect(get.mock.calls[0][0]).toContain('type=place');
+ });
+
+ it('follows the clock kept for the case', async () => {
+ const get = vi.fn(async () => PLACES);
+ await learnAxisZone('case-a', { get, lookup, storage: memory({ 'azimut:timeline-clock:case-a': 'utc' }) });
+ expect(axisZone('case-a')).toBe('UTC');
+ expect(get).not.toHaveBeenCalled();
+
+ forgetAxisZone();
+ await learnAxisZone('case-a', { get, lookup, storage: memory({ 'azimut:timeline-clock:case-a': 'zone:Asia/Aden' }) });
+ expect(axisZone('case-a')).toBe('Asia/Aden');
+
+ forgetAxisZone();
+ await learnAxisZone('case-a', { get, lookup, storage: memory({ 'azimut:timeline-clock:case-a': 'place:p3' }) });
+ expect(axisZone('case-a')).toBe('Asia/Tokyo');
+ });
+
+ it('asks once, and leaves the Timeline’s word standing', async () => {
+ let answer;
+ const get = vi.fn(() => new Promise((resolve) => { answer = resolve; }));
+ const first = learnAxisZone('case-a', { get, lookup, storage: memory() });
+ const second = learnAxisZone('case-a', { get, lookup, storage: memory() });
+ noteAxisZone('case-a', 'Europe/Paris');
+ answer(PLACES);
+ await Promise.all([first, second]);
+ expect(get).toHaveBeenCalledTimes(1);
+ expect(axisZone('case-a')).toBe('Europe/Paris');
+ });
+
+ it('stays on UTC when the places cannot be read', async () => {
+ await learnAxisZone('case-a', { get: async () => { throw new Error('offline'); }, lookup, storage: memory() });
+ expect(axisZone('case-a')).toBe('UTC');
+ });
+});
diff --git a/frontend/src/lib/caseClock.js b/frontend/src/lib/caseClock.js
new file mode 100644
index 0000000..83890cb
--- /dev/null
+++ b/frontend/src/lib/caseClock.js
@@ -0,0 +1,97 @@
+/**
+ * The clock a case is read on until the analyst picks one: the zone its places stand in.
+ *
+ * An investigation argues in the local time of where things happened. A video from Sanaa
+ * stamped 17:07 UTC was filmed at 20:07, and reading it against UTC (or against the
+ * analyst's own machine) is how an hour goes missing. The case already knows where it
+ * is: its places have points, and each point has a civil zone (`lib/localZone.js`, read
+ * offline). So the axis opens on the zone most of them stand in, and says so.
+ *
+ * Only the axis moves: the case stores UTC, and a value keeps the zone it was stated in.
+ * A case with no placed point, or whose points could not be read, stays on UTC.
+ */
+import { zoneAt } from './localZone.js';
+import { zoneWords, zonedFields } from './timeline.js';
+
+const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
+const pad = (value) => String(value).padStart(2, '0');
+
+/** Where the choice is kept, per case: the clock picked stays picked. */
+const KEY = (caseId) => `azimut:timeline-clock:${caseId}`;
+const CHOICE = /^(utc|case|machine|place:[^\s]{1,64}|zone:[A-Za-z0-9+\-_/]{1,64})$/;
+
+/**
+ * The zone most of these places stand in: `{ zone, count, of, places }`, or null.
+ *
+ * `count` places are in it out of the `of` whose zone was read, so the menu can say
+ * "3 of 5 places" rather than pass a majority off as the whole case. Points closer
+ * than about a kilometre are asked once: a town's dozen places are one question.
+ */
+export async function caseZone(places, { lookup = zoneAt } = {}) {
+ const groups = new Map();
+ for (const place of places ?? []) {
+ const lat = Number(place?.lat);
+ const lon = Number(place?.lon);
+ if (!Number.isFinite(lat) || !Number.isFinite(lon) || Math.abs(lat) > 90 || Math.abs(lon) > 180) continue;
+ const key = `${lat.toFixed(2)},${lon.toFixed(2)}`;
+ const group = groups.get(key) ?? { point: { lat, lon }, labels: [] };
+ group.labels.push(place.label);
+ groups.set(key, group);
+ }
+ const read = await Promise.all(
+ [...groups.values()].map(async (group) => ({ ...group, zone: await lookup(group.point).catch(() => '') }))
+ );
+ const zones = new Map();
+ let of = 0;
+ for (const group of read) {
+ if (!group.zone) continue;
+ of += group.labels.length;
+ const held = zones.get(group.zone) ?? { zone: group.zone, count: 0, places: [] };
+ held.count += group.labels.length;
+ held.places.push(...group.labels);
+ zones.set(group.zone, held);
+ }
+ const [first] = [...zones.values()].sort((a, b) => b.count - a.count || a.zone.localeCompare(b.zone));
+ return first ? { ...first, of } : null;
+}
+
+/** How the choice says where it came from: `the case's places` or `3 of 5 places`. */
+export function caseZoneWords(found) {
+ if (!found) return '';
+ return found.count === found.of ? "the case's places" : `${found.count} of ${found.of} places`;
+}
+
+/** The clock picked for this case, or `case` when none was. */
+export function rememberedClock(caseId, storage = globalThis.localStorage) {
+ try {
+ const held = caseId ? storage?.getItem(KEY(caseId)) : null;
+ return held && CHOICE.test(held) ? held : 'case';
+ } catch {
+ return 'case';
+ }
+}
+
+/** Keep the clock picked for this case. Going back to the default forgets it. */
+export function rememberClock(caseId, choice, storage = globalThis.localStorage) {
+ if (!caseId || !CHOICE.test(String(choice))) return;
+ try {
+ if (choice === 'case') storage?.removeItem(KEY(caseId));
+ else storage?.setItem(KEY(caseId), choice);
+ } catch {
+ // A browser that keeps nothing still reads the case on its default clock.
+ }
+}
+
+/**
+ * An instant on the axis's clock, written the way the rest of the Timeline writes a
+ * date: `22 Jun 2023, 20:07:16 Aden time`. Only for a value that names an instant: a
+ * day has no hour, and printing 00:00 in another zone would invent one.
+ */
+export function clockReading(instant, zone, { named = true } = {}) {
+ const millis = Date.parse(instant);
+ if (!Number.isFinite(millis) || !zone) return '';
+ const at = zonedFields(millis, zone);
+ const day = `${at.day} ${MONTHS[at.month - 1]} ${at.year}`;
+ const time = `${day}, ${pad(at.hour)}:${pad(at.minute)}:${pad(at.second)}`;
+ return named ? `${time} ${zoneWords(zone).place} time` : time;
+}
diff --git a/frontend/src/lib/caseClock.test.js b/frontend/src/lib/caseClock.test.js
new file mode 100644
index 0000000..a6035df
--- /dev/null
+++ b/frontend/src/lib/caseClock.test.js
@@ -0,0 +1,69 @@
+import { describe, expect, it, vi } from 'vitest';
+import { caseZone, caseZoneWords, clockReading, rememberClock, rememberedClock } from './caseClock.js';
+
+const place = (label, lat, lon) => ({ id: label, label, lat, lon });
+
+function memory() {
+ const held = new Map();
+ return {
+ getItem: (key) => (held.has(key) ? held.get(key) : null),
+ setItem: (key, value) => held.set(key, String(value)),
+ removeItem: (key) => held.delete(key),
+ held,
+ };
+}
+
+describe('the clock a case opens on', () => {
+ it('takes the zone most of its places stand in, and says how many', async () => {
+ const lookup = vi.fn(async ({ lon }) => (lon > 44 ? 'Asia/Aden' : 'Africa/Djibouti'));
+ const found = await caseZone(
+ [place('Sanaa', 15.35, 44.2), place('Marib', 15.46, 45.32), place('Djibouti', 11.59, 43.14)],
+ { lookup }
+ );
+ expect(found).toMatchObject({ zone: 'Asia/Aden', count: 2, of: 3, places: ['Sanaa', 'Marib'] });
+ expect(caseZoneWords(found)).toBe('2 of 3 places');
+ expect(caseZoneWords({ ...found, count: 3 })).toBe("the case's places");
+ });
+
+ it('asks once for places a kilometre apart', async () => {
+ const lookup = vi.fn(async () => 'Asia/Aden');
+ const found = await caseZone(
+ [place('Gate', 15.3501, 44.2001), place('Square', 15.3503, 44.2004)],
+ { lookup }
+ );
+ expect(lookup).toHaveBeenCalledTimes(1);
+ expect(found).toMatchObject({ count: 2, of: 2 });
+ });
+
+ it('stays on UTC with no placed point, or none that could be read', async () => {
+ expect(await caseZone([], { lookup: vi.fn() })).toBeNull();
+ expect(await caseZone([{ id: 'x', label: 'Nowhere' }], { lookup: vi.fn() })).toBeNull();
+ expect(await caseZone([place('Sea', 10, 50)], { lookup: async () => '' })).toBeNull();
+ expect(await caseZone([place('Sea', 10, 50)], { lookup: async () => { throw new Error('down'); } })).toBeNull();
+ });
+
+ it('keeps the clock picked per case, and forgets it on the default', () => {
+ const storage = memory();
+ expect(rememberedClock('case-a', storage)).toBe('case');
+ rememberClock('case-a', 'utc', storage);
+ expect(rememberedClock('case-a', storage)).toBe('utc');
+ expect(rememberedClock('case-b', storage)).toBe('case');
+ rememberClock('case-a', 'zone:../../etc', storage);
+ expect(rememberedClock('case-a', storage)).toBe('utc');
+ rememberClock('case-a', 'case', storage);
+ expect(storage.held.size).toBe(0);
+ // a value nobody could have written reads as the default
+ storage.setItem('azimut:timeline-clock:case-c', 'garbage');
+ expect(rememberedClock('case-c', storage)).toBe('case');
+ });
+
+ it('writes an instant on the axis clock the way the Timeline writes dates', () => {
+ // a camera's 17:07:16 UTC in Sanaa was 20:07:16 there
+ expect(clockReading('2023-06-22T17:07:16.000000Z', 'Asia/Aden')).toBe('22 Jun 2023, 20:07:16 Aden time');
+ expect(clockReading('2024-01-05T23:30:00Z', 'America/New_York')).toBe('5 Jan 2024, 18:30:00 New York time');
+ // under a heading that already names the clock
+ expect(clockReading('2023-06-22T17:07:16Z', 'Asia/Aden', { named: false })).toBe('22 Jun 2023, 20:07:16');
+ expect(clockReading('', 'Asia/Aden')).toBe('');
+ expect(clockReading('2023-06-22T17:07:16Z', '')).toBe('');
+ });
+});
diff --git a/frontend/src/lib/caseWorkspaceFixture.test.js b/frontend/src/lib/caseWorkspaceFixture.test.js
new file mode 100644
index 0000000..79000e0
--- /dev/null
+++ b/frontend/src/lib/caseWorkspaceFixture.test.js
@@ -0,0 +1,86 @@
+/**
+ * Saved readings from a 0.3.1 case open the way they were saved.
+ *
+ * `tests/fixtures/case-workspace-0.3.1.json` is the reading of a case built the way
+ * a 0.3.1 analyst leaves one (`tests/caseworkspace.py`), and its `views` are the
+ * specs the server stores and serves back. The Timeline, Board and Graph each turn
+ * a spec into what they draw; whatever those surfaces come to open on by default,
+ * a saved reading keeps its own tracks, pins, hides, mode, clock and question.
+ */
+import { describe, expect, it } from 'vitest';
+import { readFileSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+import { dirname, join } from 'node:path';
+import { timelineViewState } from './timelineTracks.js';
+import { normalizeFilter } from './entityFilter.js';
+import { normalizeAnalysisPeriod } from './analysisPeriod.js';
+
+const here = dirname(fileURLToPath(import.meta.url));
+const fixture = JSON.parse(
+ readFileSync(join(here, '../../../tests/fixtures/case-workspace-0.3.1.json'), 'utf8')
+);
+const views = Object.entries(fixture.views);
+const timelines = views.filter(([, view]) => view.surface === 'timeline');
+const questions = views.filter(([, view]) => view.surface !== 'timeline');
+
+describe('a 0.3.1 case workspace', () => {
+ it('holds every surface in both modes, so a reading of nothing cannot pass', () => {
+ const kinds = new Set(views.map(([, view]) => `${view.surface}:${view.mode}`));
+ for (const surface of ['board', 'graph', 'timeline']) {
+ expect(kinds.has(`${surface}:live`)).toBe(true);
+ expect(kinds.has(`${surface}:snapshot`)).toBe(true);
+ }
+ expect(new Set(timelines.map(([, view]) => view.spec.timeline.view_mode)))
+ .toEqual(new Set(['plot', 'list']));
+ });
+
+ it.each(timelines)('reopens the Timeline view "%s" with its own tracks', (name, view) => {
+ const saved = view.spec.timeline;
+ const state = timelineViewState(saved);
+ expect(state.tracks.map((track) => ({
+ id: track.id,
+ label: track.label,
+ categories: track.categories,
+ color: track.color,
+ collapsed: track.collapsed,
+ hidden: track.hidden,
+ pinned: track.pinned,
+ relation: track.query.relation,
+ terms: track.query.terms,
+ }))).toEqual(saved.tracks.map((track) => ({
+ id: track.id,
+ label: track.label,
+ categories: track.categories,
+ color: track.color,
+ collapsed: track.collapsed,
+ hidden: track.hidden,
+ pinned: track.pinned,
+ relation: track.query.relation,
+ terms: track.query.terms,
+ })));
+ expect(state.viewMode).toBe(saved.view_mode);
+ expect(state.zoneChoice).toBe(saved.zone_choice);
+ expect(state.groupBy).toBe(saved.group_by);
+ expect([state.from, state.to]).toEqual([saved.from, saved.to]);
+ });
+
+ it('keeps a Media track wherever a saved view had one', () => {
+ const withMedia = timelines.filter(([, view]) =>
+ view.spec.timeline.tracks.some((track) => track.categories.includes('media')));
+ expect(withMedia.length).toBeGreaterThan(0);
+ for (const [, view] of withMedia) {
+ expect(timelineViewState(view.spec.timeline).categories).toContain('media');
+ }
+ });
+
+ it.each(questions)('reopens the %s question as it was asked', (name, view) => {
+ const filter = normalizeFilter(view.spec.query.filter);
+ expect(normalizeFilter(filter)).toEqual(filter);
+ for (const [key, value] of Object.entries(view.spec.query.filter)) {
+ expect(filter[key]).toEqual(value);
+ }
+ expect(normalizeAnalysisPeriod(view.spec.timeline)).toEqual(
+ normalizeAnalysisPeriod(normalizeAnalysisPeriod(view.spec.timeline))
+ );
+ });
+});
diff --git a/frontend/src/lib/catalog.js b/frontend/src/lib/catalog.js
index ae5f90f..148800c 100644
--- a/frontend/src/lib/catalog.js
+++ b/frontend/src/lib/catalog.js
@@ -11,7 +11,7 @@ export function settleCatalogSummary(current, next, isCurrent) {
*
* `unfiled` (no folder) wins over an exact `folder` path when both are given.
* `attr` with `value` narrows on one stored field, `linked` on having a neighbour of
- * that type and `unlinked` on having none at all; `since`, `until` and `by` ask how
+ * that type and `unlinked` on having none at all, `lacks` on what a Claim is missing; `since`, `until` and `by` ask how
* the row got here rather than what it says. A field with no value chosen is **not**
* sent: it is the analyst having picked what they are about to ask about, and asked
* as a term it would empty the table between two clicks of one act.
@@ -32,6 +32,7 @@ function narrowing(
value,
linked,
unlinked,
+ lacks,
since,
until,
by,
@@ -53,6 +54,7 @@ function narrowing(
}
if (linked) params.set('linked', linked);
if (unlinked) params.set('unlinked', 'true');
+ if (lacks && lacks.length) params.set('lacks', lacks.join(','));
if (since) params.set('since', since);
if (until) params.set('until', until);
if (by && by.length) params.set('by', by.join(','));
@@ -69,19 +71,34 @@ function narrowing(
/** Build the catalog request path: the narrowing, plus what a *page* needs on top.
*
* `order` sorts the whole filtered set rather than the page — the difference between
- * *the newest in this case* and *the newest of the rows already loaded*. */
+ * *the newest in this case* and *the newest of the rows already loaded*. `previews`
+ * joins the picture a file, a capture or a proof already has, for a picker. */
export function buildCatalogQuery(caseId, options = {}) {
- const { cursor, limit, order, view } = options;
+ const { cursor, limit, order, view, previews, counts } = options;
const params = new URLSearchParams();
if (limit != null) params.set('limit', String(limit));
if (cursor) params.set('cursor', cursor);
narrowing(options, params);
if (order) params.set('order', order);
if (view) params.set('view', view);
+ if (previews) params.set('previews', 'true');
+ // `by_type` beside the page: how much of the answer each type holds, which is what
+ // the Board's groups count themselves from in the one request.
+ if (counts) params.set('counts', counts);
const qs = params.toString();
return `/api/cases/${caseId}/catalog/entities${qs ? `?${qs}` : ''}`;
}
+/**
+ * What the case's Claims say about these rows: how many name each one, when the dated
+ * ones fall, how many sources and places they reach, and a density over the case's
+ * own span. One read per page of rows (at most 200 ids), never one per row.
+ */
+export async function fetchEventRows(caseId, ids, { post = api.post } = {}) {
+ if (!caseId || !ids?.length) return { range: null, rows: {} };
+ return post(`/api/cases/${caseId}/catalog/events`, { ids: ids.slice(0, 200) });
+}
+
/** Build the tally request path: the same narrowing, added up instead of listed.
*
* Nothing about a page applies — a total has no cursor, no order of its own and no
diff --git a/frontend/src/lib/catalog.test.js b/frontend/src/lib/catalog.test.js
index c5ee932..ac92f41 100644
--- a/frontend/src/lib/catalog.test.js
+++ b/frontend/src/lib/catalog.test.js
@@ -55,6 +55,18 @@ describe('buildCatalogQuery', () => {
);
});
+ it('asks for the pictures a picker shows, and only when it is one', () => {
+ expect(buildCatalogQuery('c1', { previews: true, order: '-created' })).toBe(
+ '/api/cases/c1/catalog/entities?order=-created&previews=true'
+ );
+ });
+
+ it('asks what a claim is missing', () => {
+ expect(buildCatalogQuery('c1', { lacks: ['source', 'assessment'] })).toBe(
+ '/api/cases/c1/catalog/entities?lacks=source%2Cassessment'
+ );
+ });
+
it('asks how a row got here: when it was filed, and by what', () => {
expect(
buildCatalogQuery('c1', { since: '2026-08-03', until: '2026-08-10', by: ['user', 'satellite'] })
diff --git a/frontend/src/lib/clock.js b/frontend/src/lib/clock.js
new file mode 100644
index 0000000..499d413
--- /dev/null
+++ b/frontend/src/lib/clock.js
@@ -0,0 +1,133 @@
+/**
+ * The clock a stated date is read on: one rule for every field that takes a date.
+ *
+ * A value is kept as the analyst typed it, with its clock beside it (`when_zone`). A day
+ * spans that zone's day. A time is also written with the offset the zone keeps at that
+ * moment, so it stays an ordinary zoned timestamp the axis can place and drag. UTC is
+ * the one clock stored as no zone: a day without one spans UTC's day, and a time ends
+ * in `Z`. A time with neither an offset nor a zone is on a clock nobody knows, and it
+ * stays off the axis until one is given.
+ */
+import { isDateOnly, offsetAt } from './localZone.js';
+
+export const UTC = 'UTC';
+
+const TIME = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,6})?)(Z|[+-]\d{2}:\d{2})?$/;
+
+/** A value's parts: dates, times with what each writes after it, or null. */
+function partsOf(raw) {
+ const text = String(raw ?? '');
+ if (!text) return null;
+ if (isDateOnly(text)) return { kind: 'date' };
+ const parts = text.split('/');
+ if (parts.length > 2) return null;
+ const times = parts.map((part) => TIME.exec(part));
+ if (!times.every(Boolean)) return null;
+ return { kind: 'time', walls: times.map((match) => match[1]), suffixes: times.map((match) => match[2] ?? '') };
+}
+
+/** Whether the value has a time of day, which is what lets its clock be unknown. */
+export function isTimed(raw) {
+ return partsOf(raw)?.kind === 'time';
+}
+
+/** Whether a time says its own clock, with `Z` or an offset typed after it. */
+export function writesOwnClock(raw) {
+ const parts = partsOf(raw);
+ return parts?.kind === 'time' && Boolean(parts.suffixes[0]);
+}
+
+/** Whether `zone` keeps the offset `suffix` at that wall time: `Z` is `+00:00`. */
+function keeps(wall, zone, suffix) {
+ const offset = zone === UTC ? '+00:00' : offsetAt(wall, zone);
+ return Boolean(offset) && offset === (suffix === 'Z' ? '+00:00' : suffix);
+}
+
+/**
+ * The clock a stored value reads on, `{ zone, fixed }`.
+ *
+ * `zone` is an IANA name or `UTC`, or null when no clock is known. `fixed` is an offset
+ * written in the value with no zone named for it (`+03:00`), as values typed before
+ * zones existed were. `stated` is the zone stored beside the value.
+ */
+export function clockOf(raw, stated = null) {
+ const parts = partsOf(raw);
+ if (!parts) return { zone: stated || null, fixed: '' };
+ if (parts.kind === 'date') return { zone: stated || UTC, fixed: '' };
+ const [wall] = parts.walls;
+ const [suffix] = parts.suffixes;
+ if (stated && (!suffix || keeps(wall, stated, suffix))) return { zone: stated, fixed: '' };
+ if (suffix === 'Z') return { zone: UTC, fixed: '' };
+ return { zone: null, fixed: suffix };
+}
+
+/**
+ * A value put on a clock, as it is stored: `{ raw, zone }`.
+ *
+ * `clock` is a zone name, `UTC`, or null for a time whose clock is unknown. A time
+ * already written with an offset keeps its wall time and takes the new clock's
+ * offset: picking a clock says which clock that 14:30 was read on.
+ */
+export function withClock(raw, clock) {
+ const parts = partsOf(raw);
+ const zone = clock && clock !== UTC ? clock : null;
+ if (!parts) return { raw: raw ?? '', zone: null };
+ if (parts.kind === 'date') return { raw, zone };
+ const suffix = (wall) => (!clock ? '' : clock === UTC ? 'Z' : offsetAt(wall, clock));
+ return { raw: parts.walls.map((wall) => `${wall}${suffix(wall)}`).join('/'), zone };
+}
+
+/**
+ * What a date field holds, put on its clock: `{ clock, raw, zone }`.
+ *
+ * `picked` is the analyst's pick, `undefined` until they make one. `stated` is the zone
+ * the value was saved with, and `fallback` the clock a new value opens on: a place's,
+ * or UTC. A time typed with its own offset or `Z` keeps it until a clock is picked.
+ */
+export function settleClock(raw, { picked = undefined, stated = null, fallback = UTC } = {}) {
+ if (picked !== undefined) return { clock: { zone: picked, fixed: '' }, ...withClock(raw, picked) };
+ if (writesOwnClock(raw)) {
+ const clock = clockOf(raw, stated);
+ return { clock, raw, zone: clock.zone && clock.zone !== UTC ? clock.zone : null };
+ }
+ const zone = stated || fallback;
+ return { clock: { zone, fixed: '' }, ...withClock(raw, zone) };
+}
+
+/** The instant a value's offsets are shown at: midday on its first day, or now. */
+export function clockInstant(raw) {
+ const match = /^(\d{4})(?:-(\d{2}))?(?:-(\d{2}))?/.exec(String(raw ?? ''));
+ if (!match) return Date.now();
+ return Date.UTC(Number(match[1]), Number(match[2] ?? 1) - 1, Number(match[3] ?? 1), 12);
+}
+
+// -- the clocks picked lately, per case -----------------------------------------
+
+const RECENT = (caseId) => `azimut:clock-recent:${caseId}`;
+const NAME = /^[A-Za-z0-9+\-_/]{1,64}$/;
+const KEPT = 3;
+
+/** The zones last picked in this case, newest first. A case is argued on a few
+ * clocks, and the one used a minute ago should not be searched for again. */
+export function recentClocks(caseId, storage = globalThis.localStorage) {
+ if (!caseId) return [];
+ try {
+ const held = JSON.parse(storage?.getItem(RECENT(caseId)) ?? '[]');
+ return Array.isArray(held)
+ ? held.filter((zone) => typeof zone === 'string' && NAME.test(zone) && zone !== UTC).slice(0, KEPT)
+ : [];
+ } catch {
+ return [];
+ }
+}
+
+/** Keep a picked zone at the head of this case's recent clocks. UTC is always offered. */
+export function rememberClockPick(caseId, zone, storage = globalThis.localStorage) {
+ if (!caseId || !zone || zone === UTC || !NAME.test(zone)) return;
+ const kept = [zone, ...recentClocks(caseId, storage).filter((held) => held !== zone)].slice(0, KEPT);
+ try {
+ storage?.setItem(RECENT(caseId), JSON.stringify(kept));
+ } catch {
+ // A browser that keeps nothing still offers every zone by search.
+ }
+}
diff --git a/frontend/src/lib/clock.test.js b/frontend/src/lib/clock.test.js
new file mode 100644
index 0000000..0bba43c
--- /dev/null
+++ b/frontend/src/lib/clock.test.js
@@ -0,0 +1,128 @@
+import { describe, expect, it } from 'vitest';
+import {
+ UTC,
+ clockInstant,
+ clockOf,
+ isTimed,
+ recentClocks,
+ rememberClockPick,
+ settleClock,
+ withClock,
+ writesOwnClock,
+} from './clock.js';
+
+function memory() {
+ const held = new Map();
+ return {
+ getItem: (key) => (held.has(key) ? held.get(key) : null),
+ setItem: (key, value) => held.set(key, String(value)),
+ };
+}
+
+describe('the clock a stored value reads on', () => {
+ it('reads a day on its stated zone, and on UTC without one', () => {
+ expect(clockOf('2026-09-10', 'Asia/Tokyo')).toEqual({ zone: 'Asia/Tokyo', fixed: '' });
+ expect(clockOf('2026-09-10')).toEqual({ zone: UTC, fixed: '' });
+ expect(clockOf('2026-09~/2026-10?')).toEqual({ zone: UTC, fixed: '' });
+ });
+
+ it('reads a time on the clock it writes, or on none', () => {
+ expect(clockOf('2026-09-10T14:30:00Z')).toEqual({ zone: UTC, fixed: '' });
+ expect(clockOf('2026-09-10T14:30:00+04:30')).toEqual({ zone: null, fixed: '+04:30' });
+ expect(clockOf('2026-09-10T14:30:00')).toEqual({ zone: null, fixed: '' });
+ // a stated zone names a local time, and an offset it keeps then
+ expect(clockOf('2026-09-10T14:30:00', 'Europe/Kyiv')).toEqual({ zone: 'Europe/Kyiv', fixed: '' });
+ expect(clockOf('2026-09-10T14:30:00+03:00', 'Europe/Kyiv')).toEqual({ zone: 'Europe/Kyiv', fixed: '' });
+ // but never an offset it does not keep
+ expect(clockOf('2026-09-10T14:30:00+05:00', 'Europe/Kyiv')).toEqual({ zone: null, fixed: '+05:00' });
+ });
+
+ it('knows a time from a date, and a time that says its own clock', () => {
+ expect(isTimed('2026-09-10T14:30:00')).toBe(true);
+ expect(isTimed('2026-09-10T10:00:00Z/2026-09-10T11:00:00Z')).toBe(true);
+ expect(isTimed('2026-09-10')).toBe(false);
+ expect(isTimed('')).toBe(false);
+ expect(writesOwnClock('2026-09-10T14:30:00Z')).toBe(true);
+ expect(writesOwnClock('2026-09-10T14:30:00')).toBe(false);
+ expect(writesOwnClock('2026-09-10')).toBe(false);
+ });
+});
+
+describe('putting a value on a clock', () => {
+ it('keeps a day as typed and states its zone beside it, UTC as none', () => {
+ expect(withClock('2026-09-10', 'Asia/Tokyo')).toEqual({ raw: '2026-09-10', zone: 'Asia/Tokyo' });
+ expect(withClock('2026-09-10', UTC)).toEqual({ raw: '2026-09-10', zone: null });
+ });
+
+ it('writes a time with the offset its zone keeps then, and names the zone', () => {
+ expect(withClock('2026-08-11T17:05:00', 'Europe/Kyiv'))
+ .toEqual({ raw: '2026-08-11T17:05:00+03:00', zone: 'Europe/Kyiv' });
+ expect(withClock('2026-01-11T17:05:00', 'Europe/Kyiv'))
+ .toEqual({ raw: '2026-01-11T17:05:00+02:00', zone: 'Europe/Kyiv' });
+ expect(withClock('2026-08-11T17:05:00', UTC)).toEqual({ raw: '2026-08-11T17:05:00Z', zone: null });
+ expect(withClock('2026-08-11T17:05:00', null)).toEqual({ raw: '2026-08-11T17:05:00', zone: null });
+ });
+
+ it('re-reads a written time at the same wall time on a new clock', () => {
+ // picking a clock says which clock that 17:05 was read on
+ expect(withClock('2026-08-11T17:05:00Z', 'Asia/Tokyo').raw).toBe('2026-08-11T17:05:00+09:00');
+ expect(withClock('2026-08-11T10:00:00Z/2026-08-11T11:00:00Z', 'Europe/Kyiv').raw)
+ .toBe('2026-08-11T10:00:00+03:00/2026-08-11T11:00:00+03:00');
+ });
+
+ it('leaves what it cannot read alone', () => {
+ expect(withClock('circa late summer', 'Asia/Tokyo')).toEqual({ raw: 'circa late summer', zone: null });
+ expect(withClock('', 'Asia/Tokyo')).toEqual({ raw: '', zone: null });
+ });
+});
+
+describe('settling what a date field holds', () => {
+ it('opens a new value on the fallback, and a pick replaces it', () => {
+ expect(settleClock('2026-09-10', { fallback: 'Europe/Kyiv' }))
+ .toEqual({ clock: { zone: 'Europe/Kyiv', fixed: '' }, raw: '2026-09-10', zone: 'Europe/Kyiv' });
+ expect(settleClock('2026-09-10', { fallback: 'Europe/Kyiv', picked: UTC }))
+ .toEqual({ clock: { zone: UTC, fixed: '' }, raw: '2026-09-10', zone: null });
+ expect(settleClock('2026-09-10T14:30:00', { picked: null }))
+ .toEqual({ clock: { zone: null, fixed: '' }, raw: '2026-09-10T14:30:00', zone: null });
+ });
+
+ it('keeps a stored clock over the fallback', () => {
+ expect(settleClock('2026-09-11', { stated: 'Asia/Tokyo', fallback: UTC }).zone).toBe('Asia/Tokyo');
+ });
+
+ it('lets a time typed with its own clock keep it until one is picked', () => {
+ expect(settleClock('2026-09-10T14:30:00Z', { fallback: 'Europe/Kyiv' }))
+ .toEqual({ clock: { zone: UTC, fixed: '' }, raw: '2026-09-10T14:30:00Z', zone: null });
+ expect(settleClock('2026-09-10T14:30:00+03:00', { stated: 'Europe/Kyiv' }).zone).toBe('Europe/Kyiv');
+ expect(settleClock('2026-09-10T14:30:00+04:30', {}).clock).toEqual({ zone: null, fixed: '+04:30' });
+ });
+
+ it('shows offsets on the value’s own day', () => {
+ expect(clockInstant('2026-01-11')).toBe(Date.UTC(2026, 0, 11, 12));
+ expect(clockInstant('2026-08')).toBe(Date.UTC(2026, 7, 1, 12));
+ });
+});
+
+describe('the clocks picked lately', () => {
+ it('keeps the last three zones per case, newest first, and never UTC', () => {
+ const storage = memory();
+ for (const zone of ['Asia/Aden', 'Europe/Kyiv', UTC, 'Asia/Tokyo', 'Europe/Kyiv']) {
+ rememberClockPick('case-a', zone, storage);
+ }
+ expect(recentClocks('case-a', storage)).toEqual(['Europe/Kyiv', 'Asia/Tokyo', 'Asia/Aden']);
+ rememberClockPick('case-a', 'America/Lima', storage);
+ expect(recentClocks('case-a', storage)).toEqual(['America/Lima', 'Europe/Kyiv', 'Asia/Tokyo']);
+ expect(recentClocks('case-b', storage)).toEqual([]);
+ });
+
+ it('reads nothing from a storage that fails or holds junk', () => {
+ const broken = { getItem: () => { throw new Error('blocked'); }, setItem: () => { throw new Error('blocked'); } };
+ expect(recentClocks('case-a', broken)).toEqual([]);
+ expect(() => rememberClockPick('case-a', 'Asia/Tokyo', broken)).not.toThrow();
+ const junk = memory();
+ junk.setItem('azimut:clock-recent:case-a', '{"not":"a list"}');
+ expect(recentClocks('case-a', junk)).toEqual([]);
+ junk.setItem('azimut:clock-recent:case-a', '["Asia/Tokyo", "<script>", 42]');
+ expect(recentClocks('case-a', junk)).toEqual(['Asia/Tokyo']);
+ });
+});
diff --git a/frontend/src/lib/collageThumb.js b/frontend/src/lib/collageThumb.js
new file mode 100644
index 0000000..53689f1
--- /dev/null
+++ b/frontend/src/lib/collageThumb.js
@@ -0,0 +1,179 @@
+import { collageBounds, quadMapUnit } from './inspect.js';
+
+// The picture the collage list shows for a collage. The pieces are already drawn
+// in the open tool, so the browser paints them once more onto a small canvas and
+// hands that to the case, rather than the server rendering every recipe again.
+//
+// A 2D canvas only draws affine maps, and a warped piece is projective. Each piece
+// is cut into a grid of triangles, each drawn with the affine map its three corners
+// fix; at the preview's size the seams are below a pixel.
+
+/** Longest edge of a preview, in pixels. The server shrinks anything larger. */
+export const THUMB_EDGE = 480;
+
+/** Cells per side for a warped piece. A parallelogram is exact in one. */
+const WARP_CELLS = 8;
+
+/**
+ * The affine map sending triangle `s` onto triangle `d`, as the six numbers
+ * `setTransform(a, b, c, d, e, f)` takes: x' = a·x + c·y + e, y' = b·x + d·y + f.
+ * Null for a triangle with no area, which draws nothing.
+ */
+export function affineFromTriangles(s, d) {
+ const [[x0, y0], [x1, y1], [x2, y2]] = s;
+ const det = (x1 - x0) * (y2 - y0) - (x2 - x0) * (y1 - y0);
+ if (Math.abs(det) < 1e-12) return null;
+ const [[u0, v0], [u1, v1], [u2, v2]] = d;
+ const a = ((u1 - u0) * (y2 - y0) - (u2 - u0) * (y1 - y0)) / det;
+ const c = ((u2 - u0) * (x1 - x0) - (u1 - u0) * (x2 - x0)) / det;
+ const b = ((v1 - v0) * (y2 - y0) - (v2 - v0) * (y1 - y0)) / det;
+ const dd = ((v2 - v0) * (x1 - x0) - (v1 - v0) * (x2 - x0)) / det;
+ return [a, b, c, dd, u0 - a * x0 - c * y0, v0 - b * x0 - dd * y0];
+}
+
+/** Whether a quad (TL, TR, BR, BL) is a parallelogram, so one affine map draws it. */
+export function isParallelogram(quad, eps = 0.5) {
+ const [p0, p1, p2, p3] = quad;
+ return Math.abs(p0[0] + p2[0] - p1[0] - p3[0]) < eps && Math.abs(p0[1] + p2[1] - p1[1] - p3[1]) < eps;
+}
+
+/**
+ * The triangles a `w`×`h` picture is drawn in to land on `quad`: pairs of
+ * `{ src, dst }`, the source in the picture's pixels, the target in canvas pixels.
+ */
+export function pieceTriangles(w, h, quad) {
+ const n = isParallelogram(quad) ? 1 : WARP_CELLS;
+ const unit = [];
+ for (let j = 0; j <= n; j++) for (let i = 0; i <= n; i++) unit.push([i / n, j / n]);
+ const mapped = quadMapUnit(quad, unit);
+ const at = (i, j) => j * (n + 1) + i;
+ const out = [];
+ for (let j = 0; j < n; j++) {
+ for (let i = 0; i < n; i++) {
+ const cell = [at(i, j), at(i + 1, j), at(i + 1, j + 1), at(i, j + 1)];
+ for (const tri of [[cell[0], cell[1], cell[2]], [cell[0], cell[2], cell[3]]]) {
+ out.push({
+ src: tri.map((k) => [unit[k][0] * w, unit[k][1] * h]),
+ dst: tri.map((k) => mapped[k]),
+ });
+ }
+ }
+ }
+ return out;
+}
+
+/**
+ * Where the pieces land on a preview: their bounds, scaled to fit `edge` and
+ * never enlarged. Null for a collage with no piece.
+ */
+export function thumbFrame(nodes, edge = THUMB_EDGE) {
+ if (!nodes.length) return null;
+ const b = collageBounds(nodes);
+ const scale = Math.min(1, edge / Math.max(b.width, b.height));
+ return {
+ minX: b.minX,
+ minY: b.minY,
+ scale,
+ width: Math.max(1, Math.round(b.width * scale)),
+ height: Math.max(1, Math.round(b.height * scale)),
+ };
+}
+
+// A triangle clipped exactly leaves hairline gaps between its neighbours, so each
+// is pushed out a fraction of a pixel from its centre before it clips.
+function grown(tri, by) {
+ const cx = (tri[0][0] + tri[1][0] + tri[2][0]) / 3;
+ const cy = (tri[0][1] + tri[1][1] + tri[2][1]) / 3;
+ return tri.map(([x, y]) => {
+ const dx = x - cx;
+ const dy = y - cy;
+ const len = Math.hypot(dx, dy) || 1;
+ return [x + (dx / len) * by, y + (dy / len) * by];
+ });
+}
+
+function tracePath(ctx, pts) {
+ ctx.beginPath();
+ ctx.moveTo(pts[0][0], pts[0][1]);
+ for (const [x, y] of pts.slice(1)) ctx.lineTo(x, y);
+ ctx.closePath();
+}
+
+/**
+ * Paint the pieces bottom to top. `images` maps a piece's id to a loaded image;
+ * a piece whose file is gone is drawn as the hatched gap the canvas shows.
+ */
+export function paintCollage(ctx, nodes, images, frame) {
+ const place = ([x, y]) => [(x - frame.minX) * frame.scale, (y - frame.minY) * frame.scale];
+ for (const node of nodes) {
+ const quad = node.quad.map(place);
+ const image = images.get(node.id);
+ if (!image) {
+ if (!node.missing) continue;
+ ctx.save();
+ tracePath(ctx, quad);
+ ctx.fillStyle = 'rgba(216, 106, 106, 0.18)';
+ ctx.fill();
+ ctx.strokeStyle = 'rgba(216, 106, 106, 0.7)';
+ ctx.lineWidth = 1;
+ ctx.stroke();
+ ctx.restore();
+ continue;
+ }
+ const w = image.naturalWidth || node.w;
+ const h = image.naturalHeight || node.h;
+ if (isParallelogram(quad)) {
+ // One affine map lands the whole picture, so it needs no cut and no clip.
+ const m = affineFromTriangles([[0, 0], [w, 0], [0, h]], [quad[0], quad[1], quad[3]]);
+ if (!m) continue;
+ ctx.save();
+ ctx.setTransform(...m);
+ ctx.drawImage(image, 0, 0);
+ ctx.restore();
+ continue;
+ }
+ for (const { src, dst } of pieceTriangles(w, h, quad)) {
+ const m = affineFromTriangles(src, dst);
+ if (!m) continue;
+ ctx.save();
+ tracePath(ctx, grown(dst, 0.4));
+ ctx.clip();
+ ctx.setTransform(...m);
+ ctx.drawImage(image, 0, 0);
+ ctx.restore();
+ }
+ }
+}
+
+function loadImage(url) {
+ return new Promise((resolve) => {
+ const image = new Image();
+ image.onload = () => resolve(image);
+ image.onerror = () => resolve(null);
+ image.src = url;
+ });
+}
+
+/**
+ * The preview of a collage as a PNG blob, or null when there is nothing to show.
+ * `nodes` are plain copies of the pieces ({ id, quad, url, w, h, missing }), so the
+ * caller can let the open collage go while this finishes.
+ */
+export async function renderCollageThumb(nodes, { edge = THUMB_EDGE, load = loadImage } = {}) {
+ const frame = thumbFrame(nodes, edge);
+ if (!frame) return null;
+ const images = new Map();
+ await Promise.all(
+ nodes.filter((n) => n.url).map(async (n) => {
+ const image = await load(n.url);
+ if (image) images.set(n.id, image);
+ }),
+ );
+ const canvas = document.createElement('canvas');
+ canvas.width = frame.width;
+ canvas.height = frame.height;
+ const ctx = canvas.getContext('2d');
+ if (!ctx) return null;
+ paintCollage(ctx, nodes, images, frame);
+ return new Promise((resolve) => canvas.toBlob((blob) => resolve(blob), 'image/png'));
+}
diff --git a/frontend/src/lib/collageThumb.test.js b/frontend/src/lib/collageThumb.test.js
new file mode 100644
index 0000000..3dc7a17
--- /dev/null
+++ b/frontend/src/lib/collageThumb.test.js
@@ -0,0 +1,115 @@
+import { describe, expect, it } from 'vitest';
+import {
+ affineFromTriangles, isParallelogram, paintCollage, pieceTriangles, thumbFrame, THUMB_EDGE,
+} from './collageThumb.js';
+
+const apply = ([a, b, c, d, e, f], [x, y]) => [a * x + c * y + e, b * x + d * y + f];
+const close = (p, q) => expect(Math.hypot(p[0] - q[0], p[1] - q[1])).toBeLessThan(1e-6);
+
+const rect = (x, y, w, h) => [[x, y], [x + w, y], [x + w, y + h], [x, y + h]];
+
+function recorder() {
+ const calls = [];
+ const ctx = new Proxy({}, {
+ get: (_, name) => (...args) => calls.push([name, ...args]),
+ set: (_, name, value) => (calls.push([`=${String(name)}`, value]), true),
+ });
+ return { ctx, calls, named: (n) => calls.filter((c) => c[0] === n) };
+}
+
+describe('affineFromTriangles', () => {
+ it('sends each corner of one triangle onto the other', () => {
+ const s = [[0, 0], [100, 0], [0, 50]];
+ const d = [[10, 20], [60, 45], [-5, 70]];
+ const m = affineFromTriangles(s, d);
+ s.forEach((p, i) => close(apply(m, p), d[i]));
+ });
+
+ it('has no map for a triangle with no area', () => {
+ expect(affineFromTriangles([[0, 0], [1, 1], [2, 2]], [[0, 0], [1, 0], [0, 1]])).toBeNull();
+ });
+});
+
+describe('pieceTriangles', () => {
+ it('draws a rotated rectangle in one cell, exactly', () => {
+ const quad = [[50, 0], [100, 50], [50, 100], [0, 50]];
+ expect(isParallelogram(quad)).toBe(true);
+ const tris = pieceTriangles(80, 60, quad);
+ expect(tris).toHaveLength(2);
+ const m = affineFromTriangles(tris[0].src, tris[0].dst);
+ close(apply(m, [80, 60]), [50, 100]); // the far corner lands too
+ });
+
+ it('cuts a warped piece into a grid that still meets its four corners', () => {
+ const quad = [[0, 0], [100, 10], [90, 80], [5, 60]];
+ expect(isParallelogram(quad)).toBe(false);
+ const tris = pieceTriangles(200, 100, quad);
+ expect(tris.length).toBeGreaterThan(2);
+ const dst = tris.flatMap((t) => t.dst);
+ for (const corner of quad) expect(dst.some((p) => Math.hypot(p[0] - corner[0], p[1] - corner[1]) < 1e-6)).toBe(true);
+ for (const t of tris) t.src.forEach(([x, y]) => {
+ expect(x).toBeGreaterThanOrEqual(0);
+ expect(x).toBeLessThanOrEqual(200);
+ expect(y).toBeGreaterThanOrEqual(0);
+ expect(y).toBeLessThanOrEqual(100);
+ });
+ });
+});
+
+describe('thumbFrame', () => {
+ it('trims to the pieces and shrinks them to the preview edge', () => {
+ const frame = thumbFrame([{ quad: rect(100, 50, 1200, 400) }, { quad: rect(1300, 50, 200, 600) }]);
+ expect(frame.minX).toBe(100);
+ expect(frame.minY).toBe(50);
+ expect(frame.width).toBe(THUMB_EDGE);
+ expect(frame.height).toBe(Math.round(600 * (THUMB_EDGE / 1400)));
+ });
+
+ it('never enlarges a small collage, and has nothing for an empty one', () => {
+ expect(thumbFrame([{ quad: rect(0, 0, 120, 80) }])).toMatchObject({ scale: 1, width: 120, height: 80 });
+ expect(thumbFrame([])).toBeNull();
+ });
+});
+
+describe('paintCollage', () => {
+ const frame = { minX: 0, minY: 0, scale: 1, width: 300, height: 100 };
+
+ it('draws a loaded piece, hatches a lost one and leaves out one still rendering', () => {
+ const { ctx, named } = recorder();
+ const image = { naturalWidth: 80, naturalHeight: 60 };
+ const nodes = [
+ { id: 'a', quad: rect(0, 0, 80, 60), w: 80, h: 60 },
+ { id: 'b', quad: rect(100, 0, 80, 60), w: 80, h: 60, missing: true },
+ { id: 'c', quad: rect(200, 0, 80, 60), w: 80, h: 60 },
+ ];
+
+ paintCollage(ctx, nodes, new Map([['a', image]]), frame);
+
+ expect(named('drawImage')).toEqual([['drawImage', image, 0, 0]]); // a rectangle in one draw
+ expect(named('clip')).toHaveLength(0);
+ expect(named('fill')).toHaveLength(1); // the lost piece's gap
+ });
+
+ it('draws a warped piece cell by cell, each clipped to its own triangle', () => {
+ const { ctx, named } = recorder();
+ const image = { naturalWidth: 80, naturalHeight: 60 };
+ const quad = [[0, 0], [100, 10], [90, 80], [5, 60]];
+
+ paintCollage(ctx, [{ id: 'a', quad }], new Map([['a', image]]), frame);
+
+ const cells = pieceTriangles(80, 60, quad).length;
+ expect(named('drawImage')).toHaveLength(cells);
+ expect(named('clip')).toHaveLength(cells);
+ });
+
+ it('draws the pieces bottom to top, in the order the canvas stacks them', () => {
+ const { ctx, named } = recorder();
+ const low = { naturalWidth: 10, naturalHeight: 10, name: 'low' };
+ const high = { naturalWidth: 10, naturalHeight: 10, name: 'high' };
+ const nodes = [{ id: 'low', quad: rect(0, 0, 10, 10) }, { id: 'high', quad: rect(5, 5, 10, 10) }];
+
+ paintCollage(ctx, nodes, new Map([['low', low], ['high', high]]), frame);
+
+ expect(named('drawImage').map((c) => c[1].name)).toEqual(['low', 'high']);
+ });
+});
diff --git a/frontend/src/lib/composer.js b/frontend/src/lib/composer.js
index 1758b6b..e1d61ae 100644
--- a/frontend/src/lib/composer.js
+++ b/frontend/src/lib/composer.js
@@ -1205,6 +1205,9 @@ export function toSpec(proof) {
// the description is the proof's notes — so the graph and search see them
// without opening this file (`api/proofs.save_proof`).
when: proof.when?.trim() ? proof.when.trim() : null,
+ // The clock the date is read on when the analyst picked one; null leaves it to
+ // the first point's zone, resolved on save, so moving the point moves the day.
+ whenZone: proof.when?.trim() && proof.whenZone ? proof.whenZone : null,
description: proof.description?.trim() ? proof.description.trim() : null,
// What the plate's footer prints. `footer` is the credit line itself;
// `footerText` is whether it prints at all, and `footerCoords` whether the
diff --git a/frontend/src/lib/composer.test.js b/frontend/src/lib/composer.test.js
index 9c046bf..f3a17e7 100644
--- a/frontend/src/lib/composer.test.js
+++ b/frontend/src/lib/composer.test.js
@@ -2100,4 +2100,12 @@ describe('the date a proof states for its material', () => {
expect(blank.when).toBe(null);
expect(blank.description).toBe(null);
});
+
+ it('keeps the clock the analyst picked for the date, and none left to the point', () => {
+ const bare = { panels: [], pastes: [], shapes: [], points: [], notes: {} };
+ expect(toSpec({ ...bare, when: '2024-03-12', whenZone: 'UTC' }).whenZone).toBe('UTC');
+ expect(toSpec({ ...bare, when: '2024-03-12', whenZone: null }).whenZone).toBe(null);
+ // A zone with no date to read says nothing.
+ expect(toSpec({ ...bare, when: '', whenZone: 'Asia/Tokyo' }).whenZone).toBe(null);
+ });
});
diff --git a/frontend/src/lib/entityFilter.js b/frontend/src/lib/entityFilter.js
index 88842a5..9fa83a0 100644
--- a/frontend/src/lib/entityFilter.js
+++ b/frontend/src/lib/entityFilter.js
@@ -46,6 +46,8 @@ export const AXES = [
kind: 'toggle',
hint: 'filed, and joined to nothing at all',
},
+ { key: 'unsourced', label: 'No source', kind: 'toggle', hint: 'a claim that cites nothing' },
+ { key: 'unassessed', label: 'Not assessed', kind: 'toggle', hint: 'a claim nobody has graded' },
{ key: 'added', label: 'Added', kind: 'added', hint: 'when it was filed into the case' },
{ key: 'by', label: 'Filed by', kind: 'picks', hint: 'which tool filed it, or by hand' },
];
@@ -59,6 +61,11 @@ export const ADDED = [
{ value: '30d', label: 'Last 30 days', days: 30 },
];
+/** What a Claim can be missing, and the axis that asks for it (`store/filters.py`
+ * LACKS). Both ask of Claims only: a file is its own source, and nothing else is
+ * graded. */
+export const LACKS = { unsourced: 'source', unassessed: 'assessment' };
+
/** The two review states, worded as the rest of the app words them. */
export const STATUSES = [
{ value: 'confirmed', label: 'Confirmed' },
@@ -99,6 +106,18 @@ export const QUESTIONS = [
hint: 'in none of your folders',
terms: { unfiled: true },
},
+ {
+ id: 'unsourced',
+ label: 'No source',
+ hint: 'a claim that cites nothing to show it',
+ terms: { lacks: ['source'] },
+ },
+ {
+ id: 'unassessed',
+ label: 'Not assessed',
+ hint: 'a claim nobody has graded yet',
+ terms: { lacks: ['assessment'] },
+ },
];
/** A question with no term set. Every field is present, so nothing downstream has to
@@ -116,6 +135,7 @@ export function emptyFilter() {
attrValue: '',
linked: '',
connections: '', // '' | 'none'
+ lacks: [], // of LACKS' values
added: '', // one of ADDED, or '' when since/until say it in dates
since: '',
until: '',
@@ -146,6 +166,7 @@ export function normalizeFilter(value) {
attrValue: text(raw.attrValue),
linked: text(raw.linked, 40),
connections: raw.connections === 'none' ? 'none' : '',
+ lacks: strings(raw.lacks).filter((value) => Object.values(LACKS).includes(value)),
added: ADDED.some((entry) => entry.value === raw.added) ? raw.added : '',
since: text(raw.since, 10),
until: text(raw.until, 10),
@@ -182,6 +203,9 @@ export function hasTerm(filter, axis) {
return Boolean(filter.linked);
case 'connections':
return filter.connections === 'none';
+ case 'unsourced':
+ case 'unassessed':
+ return filter.lacks.includes(LACKS[axis]);
case 'added':
return Boolean(filter.added || filter.since || filter.until);
case 'by':
@@ -210,6 +234,9 @@ export function clearAxis(filter, axis) {
return { ...filter, linked: '' };
case 'connections':
return { ...filter, connections: '' };
+ case 'unsourced':
+ case 'unassessed':
+ return { ...filter, lacks: filter.lacks.filter((value) => value !== LACKS[axis]) };
case 'added':
return { ...filter, added: '', since: '', until: '' };
case 'by':
@@ -219,10 +246,19 @@ export function clearAxis(filter, axis) {
}
}
-/** Ask one of the standing questions, over whatever is already set. */
+/** Ask one of the standing questions, over whatever is already set. What a Claim
+ * lacks adds up: no source and not assessed is one question with two terms. */
export function askQuestion(filter, id) {
const question = QUESTIONS.find((entry) => entry.id === id);
- return question ? { ...filter, ...question.terms } : filter;
+ if (!question) return filter;
+ const asked = { ...filter, ...question.terms };
+ if (question.terms.lacks) asked.lacks = [...new Set([...filter.lacks, ...question.terms.lacks])];
+ return asked;
+}
+
+/** Turn one of the toggles for what a Claim lacks on or off. */
+export function toggleLack(filter, axis) {
+ return { ...filter, lacks: toggleValue(filter.lacks, LACKS[axis]) };
}
/** Add or drop one value of a multi-value axis. */
@@ -264,6 +300,7 @@ export function toQuery(filter, { types = [], now = Date.now() } = {}) {
value: filter.attrKey && filter.attrValue ? filter.attrValue : undefined,
linked: filter.linked || undefined,
unlinked: filter.connections === 'none' || undefined,
+ lacks: filter.lacks.length ? filter.lacks : undefined,
since: relative || filter.since || undefined,
until: (!filter.added && filter.until) || undefined,
by: filter.by.length ? filter.by : undefined,
@@ -293,6 +330,7 @@ export function toGraphQuery(filter, { types = [], now = Date.now() } = {}) {
}
if (asked.linked) params.linked = asked.linked;
if (asked.unlinked) params.unlinked = 'true';
+ if (asked.lacks?.length) params.lacks = asked.lacks.join(',');
if (asked.since) params.since = asked.since;
if (asked.until) params.until = asked.until;
if (asked.by?.length) params.by = asked.by.join(',');
@@ -338,6 +376,11 @@ export function chipsOf(filter, names = {}) {
if (filter.connections === 'none') {
chips.push({ axis: 'connections', text: 'Nothing linked' });
}
+ for (const [axis, value] of Object.entries(LACKS)) {
+ if (filter.lacks.includes(value)) {
+ chips.push({ axis, text: AXES.find((entry) => entry.key === axis).label });
+ }
+ }
if (filter.added) {
const range = ADDED.find((entry) => entry.value === filter.added);
chips.push({ axis: 'added', text: `Added: ${(range?.label ?? filter.added).toLowerCase()}` });
diff --git a/frontend/src/lib/entityFilter.test.js b/frontend/src/lib/entityFilter.test.js
index 812deac..a1fe32a 100644
--- a/frontend/src/lib/entityFilter.test.js
+++ b/frontend/src/lib/entityFilter.test.js
@@ -13,8 +13,11 @@ import {
loadFilter,
orderFor,
saveFilter,
+ normalizeFilter,
sinceFor,
+ toGraphQuery,
toQuery,
+ toggleLack,
toggleValue,
} from './entityFilter.js';
@@ -88,6 +91,35 @@ describe('the questions every case is asked', () => {
});
});
+describe('what a claim is missing', () => {
+ it('asks for the claims with no source, or not assessed, or both', () => {
+ const unsourced = askQuestion(emptyFilter(), 'unsourced');
+ expect(toQuery(unsourced).lacks).toEqual(['source']);
+ expect(chipsOf(unsourced)[0]).toEqual({ axis: 'unsourced', text: 'No source' });
+
+ const both = askQuestion(unsourced, 'unassessed');
+ expect(both.lacks).toEqual(['source', 'assessment']);
+ expect(toGraphQuery(both).lacks).toBe('source,assessment');
+ expect(activeAxes(both)).toEqual(['unsourced', 'unassessed']);
+
+ const left = clearAxis(both, 'unsourced');
+ expect(left.lacks).toEqual(['assessment']);
+ expect(toggleLack(left, 'unassessed').lacks).toEqual([]);
+ expect(toQuery(emptyFilter()).lacks).toBeUndefined();
+ });
+
+ it('keeps only the terms it knows from a remembered question', () => {
+ expect(normalizeFilter({ lacks: ['source', 'photo', 3] }).lacks).toEqual(['source']);
+ expect(normalizeFilter({}).lacks).toEqual([]);
+ });
+
+ it('comes after the four questions the Overview prices', () => {
+ expect(QUESTIONS.map((question) => question.id)).toEqual([
+ 'review', 'loose', 'week', 'unfiled', 'unsourced', 'unassessed',
+ ]);
+ });
+});
+
describe('the question as a request', () => {
it('sends only the terms that are set', () => {
const params = toQuery(emptyFilter());
diff --git a/frontend/src/lib/entitySearch.js b/frontend/src/lib/entitySearch.js
index 054d056..ef0050e 100644
--- a/frontend/src/lib/entitySearch.js
+++ b/frontend/src/lib/entitySearch.js
@@ -15,27 +15,27 @@
*/
import { entityFields } from './entityTypes.svelte.js';
import { folderOf } from './folderTree.js';
+import { foldTerms, foldText } from './textFold.js';
/** Declared kinds a value is worth finding an entity by. Mirrors
* `entities.SEARCHABLE_KINDS`. */
const SEARCHABLE_KINDS = new Set(['text', 'longtext', 'url']);
-/** Everything a term is compared against, lowercased, in one string. */
+/** Everything a term is compared against, folded like the server's index, in one string. */
export function entitySearchText(entity) {
if (!entity) return '';
const declared = entityFields(entity.type)
.filter((field) => SEARCHABLE_KINDS.has(field.kind ?? 'text'))
.map((field) => entity.attrs?.[field.key]);
- return [entity.label, entity.type, folderOf(entity), entity.attrs?.notes, ...declared]
+ return foldText([entity.label, entity.type, folderOf(entity), entity.attrs?.notes, ...declared]
.filter((value) => value !== null && value !== undefined && value !== '')
- .join('\n')
- .toLowerCase();
+ .join('\n'));
}
/** The fields that explain a hit, with the same declared-kind boundary as the index. */
export function entitySearchMatches(entity, query) {
if (!entity) return [];
- const terms = String(query ?? '').trim().toLowerCase().split(/\s+/).filter(Boolean);
+ const terms = foldTerms(query);
if (!terms.length) return [];
const fields = [
{ field: 'label', label: 'Name', value: entity.label },
@@ -51,7 +51,7 @@ export function entitySearchMatches(entity, query) {
for (const field of fields) {
if (field.value === null || field.value === undefined || field.value === '') continue;
const value = String(field.value);
- const folded = value.toLowerCase();
+ const folded = foldText(value);
const hit = terms.filter((term) => folded.includes(term));
if (!hit.length) continue;
hit.forEach((term) => covered.add(term));
@@ -63,7 +63,7 @@ export function entitySearchMatches(entity, query) {
/** True when the entity answers the term. An empty term matches everything, so a
* caller can hand the box straight through without a guard of its own. */
export function matchesEntity(entity, query) {
- const terms = String(query ?? '').trim().toLowerCase().split(/\s+/).filter(Boolean);
+ const terms = foldTerms(query);
const text = entitySearchText(entity);
return !terms.length || terms.every((term) => text.includes(term));
}
diff --git a/frontend/src/lib/entitySearch.test.js b/frontend/src/lib/entitySearch.test.js
index b3106ff..08cac86 100644
--- a/frontend/src/lib/entitySearch.test.js
+++ b/frontend/src/lib/entitySearch.test.js
@@ -31,6 +31,16 @@ vi.mock('./entityTypes.svelte.js', () => ({
const { entitySearchMatches, entitySearchText, matchesEntity } = await import('./entitySearch.js');
describe('entity search', () => {
+ it('finds a name whatever accents or vowels it was written with, as the index does', () => {
+ const cafe = { label: 'Café du Port', type: 'place', attrs: {} };
+ const name = { label: 'مُحَمَّد', type: 'person', attrs: { notes: 'Ки́їв' } };
+ expect(matchesEntity(cafe, 'cafe')).toBe(true);
+ expect(matchesEntity(name, 'محمد київ')).toBe(true);
+ expect(entitySearchText(cafe)).toBe('cafe du port\nplace');
+ // the field that explains the hit is shown as written
+ expect(entitySearchMatches(cafe, 'CAFE')).toEqual([{ field: 'label', label: 'Name', value: 'Café du Port' }]);
+ });
+
it('matches the label, the type, the folder and the notes', () => {
const entity = {
label: 'Truck 12',
diff --git a/frontend/src/lib/entryLine.js b/frontend/src/lib/entryLine.js
new file mode 100644
index 0000000..d1026f0
--- /dev/null
+++ b/frontend/src/lib/entryLine.js
@@ -0,0 +1,163 @@
+/**
+ * The entry line's pure half: what `@` offers, in what order, and what a name the
+ * case has never held is guessed to be.
+ *
+ * Nothing here reaches the network or Svelte. The line (`EntryLine.svelte`) asks the
+ * catalog, and these decide what the answer looks like on screen.
+ */
+import { entitySearchMatches } from './entitySearch.js';
+import { foldText } from './textFold.js';
+
+/**
+ * The names an entity is also known by, one per entry.
+ *
+ * `aliases` is one free field, and analysts separate names the way they separate
+ * anything: a semicolon, a comma or a line each. All three split.
+ */
+export function aliasesOf(entity) {
+ return String(entity?.attrs?.aliases ?? '')
+ .split(/[;,\n]/)
+ .map((name) => name.trim())
+ .filter(Boolean);
+}
+
+/** Whether the typed term names the entity exactly, by its label or one of its other names. */
+export function namesExactly(entity, term) {
+ const wanted = foldText(String(term ?? '').trim());
+ if (!wanted) return false;
+ return [entity?.label, ...aliasesOf(entity)].some((name) => foldText(String(name ?? '').trim()) === wanted);
+}
+
+/**
+ * The catalog's answer to `@term`, in the order the line offers it.
+ *
+ * An exact name first, label or other name alike, since that is the entity being
+ * typed. Then what this draft already mentions, which is the likeliest second pick.
+ * Then the rest, in the catalog's order. Each row says which field matched when it
+ * was not the name, so a vehicle found by its plate does not read as a stray result.
+ */
+export function rankMentions(rows, term, mentioned = new Set()) {
+ const ranked = rows.map((entity, index) => {
+ const exact = namesExactly(entity, term);
+ const rank = exact ? 0 : mentioned.has(entity.id) ? 1 : 2;
+ const matches = String(term ?? '').trim() ? entitySearchMatches(entity, term) : [];
+ const named = matches.some((match) => match.field === 'label');
+ const alias = exact && !foldText(String(entity.label ?? '')).includes(foldText(String(term).trim()))
+ ? aliasesOf(entity).find((name) => foldText(name) === foldText(String(term).trim()))
+ : '';
+ const reason = alias
+ ? { label: 'Also known as', value: alias }
+ : named ? null : matches[0] ?? null;
+ return { entity, rank, index, reason };
+ });
+ return ranked
+ .sort((one, other) => one.rank - other.rank || one.index - other.index)
+ .map(({ entity, reason }) => ({ entity, reason }));
+}
+
+/**
+ * The `@term` being typed at the caret, or null.
+ *
+ * An `@` starts a mention at the start of the text or after a space, so an address
+ * like `[email protected]` stays text. The term runs to the caret and stops at a
+ * line break; a space is allowed, since subjects have names with spaces in them.
+ */
+export function mentionAt(text, caret) {
+ const before = String(text ?? '').slice(0, caret);
+ // The last `@` that opens a word; one inside a word, as in an address typed after
+ // it, belongs to the term.
+ const found = /(?:^|\s)@([^\n]*)$/.exec(before);
+ if (!found) return null;
+ const term = found[1];
+ const start = before.length - term.length - 1;
+ if (term.length > 80 || /\s{2}/.test(term)) return null;
+ return { start, end: caret, term };
+}
+
+/** The text with the `@term` replaced by the name, and where the caret goes next. */
+export function insertMention(text, mention, name) {
+ const after = String(text).slice(mention.end);
+ const joint = after.startsWith(' ') ? '' : ' ';
+ const next = `${String(text).slice(0, mention.start)}${name}${joint}${after}`;
+ return { text: next, caret: mention.start + name.length + joint.length };
+}
+
+// What an identifier looks like. Each one is checked on its own and none of them
+// guesses between two readings: a value that could be either stays unguessed.
+const URL = /^https?:\/\/\S+$/i;
+const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@.]+$/;
+const IPV4 = /^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/;
+const IPV6 = /^(?=.*:.*:)[0-9a-f:]+(?:\.\d+){0,3}$/i;
+const HANDLE = /^@[\p{L}\p{N}_.]{1,64}$/u;
+const PHONE = /^\+?[\d\s().-]+$/;
+const DOMAIN = /^(?=.{4,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}\.?$/i;
+
+function identifierOf(value) {
+ if (URL.test(value)) return { type: 'account', rule: 'looks like a profile address' };
+ if (EMAIL.test(value)) return { type: 'email', rule: 'looks like an email' };
+ const [address, bits, extra] = value.split('/');
+ if (bits !== undefined && extra === undefined && /^\d{1,3}$/.test(bits)
+ && (IPV4.test(address) || IPV6.test(address))) {
+ return { type: 'network', rule: 'looks like a network' };
+ }
+ if (IPV4.test(value) || IPV6.test(value)) return { type: 'ip', rule: 'looks like an IP address' };
+ if (HANDLE.test(value)) return { type: 'account', rule: 'looks like a handle' };
+ const digits = value.replace(/\D/g, '').length;
+ if (PHONE.test(value) && digits >= 7 && digits <= 15 && /^\+|\s|-/.test(value)) {
+ return { type: 'phone', rule: 'looks like a phone number' };
+ }
+ if (DOMAIN.test(value) && /[a-z]/i.test(value.split('.').at(-2) ?? '')) {
+ return { type: 'domain', rule: 'looks like a domain' };
+ }
+ return null;
+}
+
+/**
+ * What a new subject is taken to be, and the rule that says so.
+ *
+ * An identifier is recognised by its shape. Anything else is the subject type this
+ * case uses most, read off the catalog summary, and a case with none is a person. A
+ * place is never guessed: a place is a point, and a name is not one.
+ */
+export function guessSubjectType(label, { mostUsed = '' } = {}) {
+ const value = String(label ?? '').trim();
+ const identifier = value ? identifierOf(value) : null;
+ if (identifier) return identifier;
+ if (mostUsed) return { type: mostUsed, rule: 'the type this case uses most' };
+ return { type: 'person', rule: 'no other hint' };
+}
+
+/** The types a new subject is offered as, before `Other…`. */
+export const QUICK_TYPES = ['person', 'organization', 'account'];
+
+/**
+ * The subject type the case holds most of, among the ones a line can create.
+ *
+ * `creatable` is the registry's hand-made types. A Claim is not a subject here, and a
+ * tie goes to the one the registry lists first.
+ */
+export function mostUsedType(summary, creatable) {
+ let best = '';
+ let most = 0;
+ for (const entry of creatable) {
+ if (entry.type === 'claim') continue;
+ const held = Number(summary?.by_type?.[entry.type] ?? 0);
+ if (held > most) {
+ best = entry.type;
+ most = held;
+ }
+ }
+ return best;
+}
+
+/** The menu a new subject's type chip opens on: the quick types, the case's own
+ * favourite when it is not one of them, then everything else a line can create. */
+export function typeMenu(creatable, mostUsed = '') {
+ const known = new Set(creatable.map((entry) => entry.type));
+ const quick = [...QUICK_TYPES, mostUsed].filter((type, index, all) =>
+ type && known.has(type) && all.indexOf(type) === index);
+ const other = creatable
+ .map((entry) => entry.type)
+ .filter((type) => type !== 'claim' && !quick.includes(type));
+ return { quick, other };
+}
diff --git a/frontend/src/lib/entryLine.test.js b/frontend/src/lib/entryLine.test.js
new file mode 100644
index 0000000..0d154ad
--- /dev/null
+++ b/frontend/src/lib/entryLine.test.js
@@ -0,0 +1,118 @@
+import { describe, expect, it } from 'vitest';
+import {
+ aliasesOf,
+ guessSubjectType,
+ insertMention,
+ mentionAt,
+ mostUsedType,
+ namesExactly,
+ rankMentions,
+ typeMenu,
+} from './entryLine.js';
+
+describe('aliasesOf', () => {
+ it('splits other names on a semicolon, a comma or a line', () => {
+ expect(aliasesOf({ attrs: { aliases: 'Perekhrestia; X-roads,Crossroads N.\nПерехрестя ' } }))
+ .toEqual(['Perekhrestia', 'X-roads', 'Crossroads N.', 'Перехрестя']);
+ expect(aliasesOf({ attrs: {} })).toEqual([]);
+ expect(aliasesOf(null)).toEqual([]);
+ });
+});
+
+describe('namesExactly', () => {
+ const place = { label: 'Kyïv', attrs: { aliases: 'Kiev; Київ' } };
+
+ it('matches the name or one other name whole, accents and case aside', () => {
+ expect(namesExactly(place, 'kyiv')).toBe(true);
+ expect(namesExactly(place, 'KIEV')).toBe(true);
+ expect(namesExactly(place, 'київ')).toBe(true);
+ expect(namesExactly(place, 'Ki')).toBe(false);
+ expect(namesExactly(place, '')).toBe(false);
+ });
+});
+
+describe('rankMentions', () => {
+ const rows = [
+ { id: 'a', type: 'place', label: 'Kyiv oblast' },
+ { id: 'b', type: 'person', label: 'Ivan' },
+ { id: 'c', type: 'place', label: 'Capital', attrs: { aliases: 'Kyiv' } },
+ { id: 'd', type: 'place', label: 'Kyiv' },
+ ];
+
+ it('puts exact names first, then what the draft mentions, then the rest', () => {
+ const ranked = rankMentions(rows, 'kyiv', new Set(['b']));
+ expect(ranked.map((row) => row.entity.id)).toEqual(['c', 'd', 'b', 'a']);
+ });
+
+ it('says why a row matched when it was not by its name', () => {
+ const ranked = rankMentions(rows, 'kyiv');
+ expect(ranked.find((row) => row.entity.id === 'c').reason).toEqual({ label: 'Also known as', value: 'Kyiv' });
+ expect(ranked.find((row) => row.entity.id === 'd').reason).toBeNull();
+ expect(ranked.find((row) => row.entity.id === 'a').reason).toBeNull();
+ });
+});
+
+describe('mentionAt', () => {
+ it('finds the @term being typed at the caret', () => {
+ expect(mentionAt('Seen at @Cross', 14)).toEqual({ start: 8, end: 14, term: 'Cross' });
+ expect(mentionAt('@4th brig', 9)).toEqual({ start: 0, end: 9, term: '4th brig' });
+ expect(mentionAt('Mail from @[email protected]', 26)).toEqual({ start: 10, end: 26, term: '[email protected]' });
+ });
+
+ it('leaves an address, a finished line and a closed mention alone', () => {
+ expect(mentionAt('[email protected]', 15)).toBeNull();
+ expect(mentionAt('no mention here', 15)).toBeNull();
+ expect(mentionAt('@a\nb', 4)).toBeNull();
+ expect(mentionAt('@name and more', 15)).toBeNull();
+ });
+});
+
+describe('insertMention', () => {
+ it('puts the name where the term was, with one space after it', () => {
+ expect(insertMention('Seen at @Cro', { start: 8, end: 12 }, 'Crossroads')).toEqual({ text: 'Seen at Crossroads ', caret: 19 });
+ expect(insertMention('At @Cro today', { start: 3, end: 7 }, 'Crossroads')).toEqual({ text: 'At Crossroads today', caret: 13 });
+ });
+});
+
+describe('guessSubjectType', () => {
+ it.each([
+ ['[email protected]', 'email', 'looks like an email'],
+ ['203.0.113.42', 'ip', 'looks like an IP address'],
+ ['2001:db8::1', 'ip', 'looks like an IP address'],
+ ['203.0.113.0/24', 'network', 'looks like a network'],
+ ['example.org', 'domain', 'looks like a domain'],
+ ['+380 44 123 4567', 'phone', 'looks like a phone number'],
+ ['@spotter_ua', 'account', 'looks like a handle'],
+ ['https://t.me/spotter_ua', 'account', 'looks like a profile address'],
+ ])('reads %s as a %s', (value, type, rule) => {
+ expect(guessSubjectType(value, { mostUsed: 'organization' })).toEqual({ type, rule });
+ });
+
+ it('takes the type the case uses most for a name, and a person with nothing to go on', () => {
+ expect(guessSubjectType('4th brigade', { mostUsed: 'organization' }))
+ .toEqual({ type: 'organization', rule: 'the type this case uses most' });
+ expect(guessSubjectType('Ivan Petrenko')).toEqual({ type: 'person', rule: 'no other hint' });
+ // A version number or a year is not a domain or a phone.
+ expect(guessSubjectType('T-72B3').type).toBe('person');
+ expect(guessSubjectType('2026').type).toBe('person');
+ expect(guessSubjectType('v1.2').type).toBe('person');
+ });
+});
+
+describe('mostUsedType and typeMenu', () => {
+ const creatable = ['person', 'organization', 'vehicle', 'account', 'email', 'claim'].map((type) => ({ type }));
+
+ it('picks the subject type the case holds most of, never a claim', () => {
+ expect(mostUsedType({ by_type: { claim: 40, vehicle: 6, person: 6 } }, creatable)).toBe('person');
+ expect(mostUsedType({ by_type: { claim: 40, vehicle: 7 } }, creatable)).toBe('vehicle');
+ expect(mostUsedType(null, creatable)).toBe('');
+ });
+
+ it('offers the quick types, the case favourite, then the rest, and never a place', () => {
+ expect(typeMenu(creatable, 'vehicle')).toEqual({
+ quick: ['person', 'organization', 'account', 'vehicle'],
+ other: ['email'],
+ });
+ expect(typeMenu(creatable, 'person').quick).toEqual(['person', 'organization', 'account']);
+ });
+});
diff --git a/frontend/src/lib/fileDates.js b/frontend/src/lib/fileDates.js
new file mode 100644
index 0000000..32ba57d
--- /dev/null
+++ b/frontend/src/lib/fileDates.js
@@ -0,0 +1,87 @@
+/**
+ * What a file says about its own dates: the camera's clock, the date it was
+ * published, the day an image was taken from orbit.
+ *
+ * Offered beside the date an analyst gives an event, one press each, and never put
+ * in by itself (D3): a date filled in automatically is accepted without being read,
+ * which is the argument Geo Proof settled. A press is the analyst's own gesture, like
+ * a click on the axis, and what it fills is theirs to correct: a post's date is when
+ * it went online, rarely when it happened. The dates come from the Timeline's own
+ * projection of the file (`/timeline?entity=…`), so nothing is read twice.
+ *
+ * What an analyst already concluded comes first: the date typed on a proof is stated
+ * for the footage the proof rests on (`api/proofs.py`, `_date_the_material`), and a
+ * correction of a file's date is the same kind of statement. Both are events about the
+ * file with the `observed` role, in the same projection.
+ */
+import { api } from './api.js';
+import { formatTemporalValue, temporalKindLabel } from './timeline.js';
+
+/** The types whose own dates are worth offering: files, map captures, proofs. */
+export const FILE_TYPES = new Set(['media', 'capture', 'proof']);
+
+/** The kinds that date what a file shows, most trusted first. When it was collected
+ * or added says when the analyst had it, not what happened, so those stay out. */
+export const FILE_DATE_KINDS = ['captured', 'taken', 'imagery', 'imagery-a', 'imagery-b', 'published'];
+
+/** What pressing each one takes, and what to keep in mind about it. */
+const HINTS = {
+ captured: "Use the camera's date, whose clock can be off",
+ taken: "Use the camera's date, whose clock can be off",
+ imagery: 'Use the day the picture was taken from orbit',
+ 'imagery-a': 'Use the day picture A was taken',
+ 'imagery-b': 'Use the day picture B was taken',
+ published: "Use the post's date, rarely when it happened",
+};
+
+/** A camera clock read to the microsecond says the same thing to the second, which
+ * is as far as anybody reads it beside a field. */
+function shortClock(raw) {
+ return String(raw).replace(/(T\d\d:\d\d:\d\d)\.\d+/, '$1');
+}
+
+/** The dates already stated for the file: a proof's first, then a correction. */
+function statedOffers(items, fileId) {
+ return (items ?? [])
+ .filter((item) => item.kind === 'claim' && item.raw && item.time_role === 'observed'
+ && (item.subject_entities ?? []).some((entity) => entity.id === fileId))
+ .map((item) => {
+ const value = shortClock(item.raw);
+ const proof = (item.source_entities ?? []).some((entity) => entity.type === 'proof');
+ const kind = proof ? 'proof' : 'stated';
+ return {
+ kind,
+ value,
+ words: `${kind} ${formatTemporalValue(value, item.tz).label}`,
+ hint: proof ? 'Use the date its proof gives' : 'Use the date already stated for this file',
+ };
+ })
+ .sort((a, b) => (a.kind === b.kind ? 0 : a.kind === 'proof' ? -1 : 1));
+}
+
+/**
+ * The dates a file offers, from its Timeline rows: `{ kind, value, words, hint }`.
+ * What was already stated for it comes first, then the camera, and the post last.
+ * `value` is what a press puts in the field.
+ */
+export function fileDateOffers(items, ownerId) {
+ const seen = new Set();
+ const own = (items ?? [])
+ .filter((item) => item.owner_id === ownerId && item.raw && FILE_DATE_KINDS.includes(item.kind))
+ .sort((a, b) => FILE_DATE_KINDS.indexOf(a.kind) - FILE_DATE_KINDS.indexOf(b.kind))
+ .map((item) => {
+ const value = shortClock(item.raw);
+ const kind = temporalKindLabel(item.kind).toLowerCase();
+ return { kind, value, words: `${kind} ${formatTemporalValue(value).label}`, hint: HINTS[item.kind] ?? '' };
+ });
+ return [...statedOffers(items, ownerId), ...own]
+ .filter((offer) => (seen.has(offer.value) ? false : seen.add(offer.value)));
+}
+
+export async function fetchFileDates(caseId, entityId, { get = api.get } = {}) {
+ const params = new URLSearchParams({ entity: entityId, include_undated: 'false', limit: '50' });
+ params.append('category', 'media');
+ params.append('category', 'statement');
+ const page = await get(`/api/cases/${caseId}/timeline?${params}`);
+ return fileDateOffers(page?.items, entityId);
+}
diff --git a/frontend/src/lib/fileDates.test.js b/frontend/src/lib/fileDates.test.js
new file mode 100644
index 0000000..1770931
--- /dev/null
+++ b/frontend/src/lib/fileDates.test.js
@@ -0,0 +1,77 @@
+import { describe, expect, it, vi } from 'vitest';
+import { fetchFileDates, fileDateOffers } from './fileDates.js';
+
+const row = (kind, raw, owner = 'm1') => ({ owner_id: owner, kind, raw, category: 'media' });
+
+describe('the dates a file offers', () => {
+ it('names each date, the camera first and the post last', () => {
+ const offers = fileDateOffers(
+ [row('published', '2026-03-14'), row('captured', '2026-03-12T14:02:00Z')],
+ 'm1'
+ );
+ expect(offers.map((offer) => offer.words)).toEqual([
+ 'captured 12 Mar 2026, 14:02:00 UTC',
+ 'published 14 Mar 2026',
+ ]);
+ expect(offers.map((offer) => offer.value)).toEqual(['2026-03-12T14:02:00Z', '2026-03-14']);
+ });
+
+ it('says a post date is rarely when it happened', () => {
+ const [post] = fileDateOffers([row('published', '2026-03-14')], 'm1');
+ expect(post.hint).toBe("Use the post's date, rarely when it happened");
+ });
+
+ it('reads a camera clock to the second, which is what a press puts in the field', () => {
+ const [camera] = fileDateOffers([row('captured', '2023-06-22T17:07:16.000000Z')], 'm1');
+ expect(camera).toMatchObject({ value: '2023-06-22T17:07:16Z', words: 'captured 22 Jun 2023, 17:07:16 UTC' });
+ });
+
+ it('leaves out when the analyst had the file, dates owned by something else, and repeats', () => {
+ expect(
+ fileDateOffers(
+ [row('collected', '2026-08-01'), row('added', '2026-08-01'), row('imagery', '2026-03-11', 'other')],
+ 'm1'
+ )
+ ).toEqual([]);
+ expect(fileDateOffers([row('captured', '2026-03-12'), row('taken', '2026-03-12')], 'm1')).toHaveLength(1);
+ });
+
+ it('offers what was already stated for the file first, a proof’s date before a correction', () => {
+ const stated = (raw, sources, extra = {}) => ({
+ owner_id: `claim-${raw}`, kind: 'claim', raw, category: 'statement', time_role: 'observed',
+ subject_entities: [{ id: 'm1', label: 'clip', type: 'media' }], source_entities: sources, ...extra,
+ });
+ const offers = fileDateOffers([
+ row('published', '2026-03-14'),
+ row('captured', '2026-03-12T14:02:00Z'),
+ stated('2026-03-10', []),
+ stated('2026-03-11~', [{ id: 'p1', label: 'Dated proof', type: 'proof' }]),
+ // an event that only names the file happened then, it does not date the footage
+ stated('2026-03-09', [], { time_role: 'occurred' }),
+ // and one about another file says nothing about this one
+ stated('2026-03-08', [], { subject_entities: [{ id: 'm2', label: 'other', type: 'media' }] }),
+ ], 'm1');
+ expect(offers.map((offer) => offer.kind)).toEqual(['proof', 'stated', 'captured', 'published']);
+ expect(offers[0]).toMatchObject({ value: '2026-03-11~', hint: 'Use the date its proof gives' });
+ expect(offers[0].words).toBe('proof 11 Mar 2026');
+ });
+
+ it('keeps one press per date, the stated one when the camera agrees', () => {
+ const offers = fileDateOffers([
+ row('captured', '2026-03-12'),
+ { owner_id: 'c1', kind: 'claim', raw: '2026-03-12', time_role: 'observed',
+ subject_entities: [{ id: 'm1' }], source_entities: [{ id: 'p1', type: 'proof' }] },
+ ], 'm1');
+ expect(offers.map((offer) => offer.kind)).toEqual(['proof']);
+ });
+
+ it('reads the file’s own rows off the Timeline projection', async () => {
+ const get = vi.fn(async () => ({ items: [row('imagery', '2026-03-11')] }));
+ const offers = await fetchFileDates('case-a', 'm1', { get });
+ expect(offers.map((offer) => offer.words)).toEqual(['imagery 11 Mar 2026']);
+ expect(get.mock.calls[0][0]).toContain('/api/cases/case-a/timeline?entity=m1');
+ expect(get.mock.calls[0][0]).toContain('category=media');
+ // and the statements about it, which is where a proof's date lives
+ expect(get.mock.calls[0][0]).toContain('category=statement');
+ });
+});
diff --git a/frontend/src/lib/guide.js b/frontend/src/lib/guide.js
index c31946f..854f92a 100644
--- a/frontend/src/lib/guide.js
+++ b/frontend/src/lib/guide.js
@@ -63,8 +63,8 @@ export const GUIDE = [
text: 'Sources, Examine, Map and Compose read top to bottom in the order an investigation runs. Tools are tabs inside a workspace.',
},
{
- label: 'The case is in the topbar, not the rail',
- text: 'It is not a stage. It is what every stage files into, so it hangs off the case name beside the Board button.',
+ label: 'The case sits under the stages',
+ text: 'On the rail, a rule apart from Sources, Examine, Map and Compose, since it is what every stage files into. It opens on its Timeline, Board, Graph and Sheet.',
},
{
label: 'You do not need a case to start',
@@ -126,7 +126,7 @@ export const GUIDE = [
{ 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 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.' },
+ { tool: 'timeline', text: 'Date the claim; the axis reads it in the local time of the place, UTC one pick away.' },
],
},
{
@@ -244,11 +244,11 @@ export const GUIDE = [
},
{
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.',
+ text: 'Analyzers → New analyzer asks what it reads first, Sentinel-2 or radar and one date or two, then starts blank or from an example. Each rule is a line a pixel has to cross, before, after or as the change between them.',
},
{
- 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: 'Checks prove an analyzer, and one is needed to save it',
+ text: 'On the map, New check takes its passes, then Should be found and Should stay empty drop pins where a candidate should come out and where none may. Test paints what each rule keeps under the pins, says its cost first and turns each pin green or red; a line that loses the burn or catches the reef shows at once. The examples come with theirs.',
},
{
label: 'Coords & Sky keeps calculations separate',
@@ -292,11 +292,19 @@ export const GUIDE = [
id: 'case',
title: 'Case',
lead: 'Four readings of one case, and the first three share the same question.',
- tools: ['board', 'graph', 'timeline', 'sheet'],
+ tools: ['timeline', 'board', 'graph', 'sheet'],
points: [
+ {
+ label: 'The Board reads as an index',
+ text: 'People, accounts, places and things come first, each with how many events name it and when. Events, files and work fold below, and Group: None is the one table.',
+ },
+ {
+ label: 'Details opens beside the row',
+ text: 'The arrow keys walk the rows and Details follows. Its top line says how many events name the entity, and Add event notes the next one about it.',
+ },
{
label: 'The filter is a sentence you can edit',
- text: 'The + Filter menu opens on four standing questions. Picking one drops its terms into the bar as ordinary chips, which is also how the filter language is learned.',
+ text: 'The + Filter menu opens on six standing questions. Picking one drops its terms into the bar as ordinary chips, which is also how the filter language is learned.',
},
{
label: 'The count is a proportion',
@@ -311,12 +319,16 @@ export const GUIDE = [
text: 'Expanding, hiding, folding and dragging are your picture. Undo reaches all of them and reaches nothing the case holds.',
},
{
- label: 'Add claim starts from what you are looking at',
- text: 'On a Board row, a Graph node or the Claims group in Details, the entity is already in its place: a model asks how many, and a place becomes where it was seen.',
+ label: 'One line notes what happened',
+ text: 'Under the Timeline axis, behind Add event in Details, and from any tool with Add event in the topbar, what it shows already cited. Type @ to mention a subject, even a new one; only a date you give is used.',
},
{
- label: 'Timeline reads in a clock you choose',
- text: 'UTC, this computer, any zone in the world, or local time at a place the case saved. Undated work is counted apart rather than hidden.',
+ label: 'Timeline reads in the place\'s own time',
+ text: 'It opens on the zone the case\'s places stand in, or UTC when it has none. UTC, this computer, any zone, or a saved place with its daylight is one pick away.',
+ },
+ {
+ label: 'Timeline puts your files where you dated them',
+ text: 'Media draws a video or a picture at the date you gave it, on its proof or in an event about it; Events is every sentence you dated. Imagery and File dates wait under ⋯. A point is an instant, a bracket a date known to the day, month or year, a bar a period.',
},
{
label: 'Sheet works on real CSV files',
@@ -336,7 +348,8 @@ export const GUIDE = [
keys: [
{ combo: 'Ctrl+V', does: 'files a screenshot or a copied address, on Media, Files, Board and Graph' },
{ combo: 'Escape', does: 'closes whatever is open, shallowest first' },
- { combo: 'Ctrl+Enter', does: 'files an Add claim form' },
+ { combo: 'Ctrl+Enter', does: 'adds the entry line, from any of its fields' },
+ { combo: 'Alt+N', does: 'opens Add event over the tool on screen, with what it shows already cited' },
],
},
{
@@ -369,6 +382,28 @@ export const GUIDE = [
{ combo: '+ / -', does: 'narrows and widens the window' },
{ combo: 'Home', does: 'shows the whole filtered extent' },
{ combo: 'Shift-wheel', does: 'pans, as does a horizontal trackpad gesture' },
+ { combo: 'Alt+← / →', does: 'moves from a focused entry to the one before or after it on its track' },
+ { combo: '↑ / ↓', does: 'walks the rows of the list under the axis' },
+ { combo: 'Enter', does: 'opens the focused row in the inspector' },
+ { combo: 'Escape', does: 'closes the menu that is open' },
+ ],
+ },
+ {
+ where: 'Board',
+ keys: [
+ { combo: '↑ / ↓', does: 'walks the rows, and Details beside them follows' },
+ { combo: 'Enter', does: 'opens the focused row in Details' },
+ { combo: 'Escape', does: 'closes Details beside the rows' },
+ ],
+ },
+ {
+ where: 'Timeline, Board, Graph',
+ keys: [
+ { combo: '@', does: 'mentions a subject on the entry line, one the case holds or a new one' },
+ { combo: '↑ / ↓, Enter or Tab', does: 'moves through the mentions offered and picks one' },
+ { combo: 'Escape', does: 'closes the mentions and keeps the @ as text' },
+ { combo: 'Enter', does: 'adds the entry, from its sentence' },
+ { combo: 'Alt+↓', does: 'moves a focused mention to its next seat' },
],
},
{
diff --git a/frontend/src/lib/inspect.js b/frontend/src/lib/inspect.js
index dccbf11..041307d 100644
--- a/frontend/src/lib/inspect.js
+++ b/frontend/src/lib/inspect.js
@@ -44,6 +44,12 @@ export function timecode(seconds) {
return `${pad(Math.floor(t / 3600))}-${pad(Math.floor((t % 3600) / 60))}-${pad(t % 60)}`;
}
+/** Where a frame sits in its video, as a player shows it: 1:04.5. */
+export function clockTime(seconds) {
+ const t = Math.max(0, Number(seconds) || 0);
+ return `${Math.floor(t / 60)}:${(t % 60).toFixed(1).padStart(4, '0')}`;
+}
+
/**
* A captured frame's default name, timecode first.
*
@@ -495,13 +501,50 @@ export function scaleQuads(quads, k, center = null) {
return quads.map((q) => scaleQuad(q, k, c));
}
-// A collage canvas is the resolution ceiling of everything on it: a piece is
-// added at whatever fits it (`initialQuad`), auto-stitch fits its answer into it,
-// and the export follows the pieces' bounds. So the size is the analyst's, within
-// the bounds the compose route accepts (`api/inspect.ComposeIn`).
+// A collage canvas is only where the pieces are worked: a piece is added at
+// whatever fits it (`initialQuad`) and auto-stitch grows it to hold its answer. The
+// export does not follow it (`exportFrame`), and neither side ever passes the bounds
+// the compose route accepts (`api/inspect.ComposeIn`).
export const COLLAGE_MIN_DIM = 16;
export const COLLAGE_MAX_DIM = 8192;
export const COLLAGE_DEFAULT_SIZE = { width: 1600, height: 800 };
+/** The most pixels an export holds, so a wide panorama stays within a laptop's memory. */
+export const COLLAGE_MAX_EXPORT_PIXELS = 40_000_000;
+
+const dist = (a, b) => Math.hypot(b[0] - a[0], b[1] - a[1]);
+
+/**
+ * The size a collage exports at: its pieces' bounds, enlarged until the sharpest
+ * piece is back at its own pixels, so what was placed small on the canvas does not
+ * come out small. Held under `COLLAGE_MAX_DIM` a side and `COLLAGE_MAX_EXPORT_PIXELS`
+ * in all; `capped` says the limit, not the pieces, set the size.
+ */
+export function exportFrame(nodes) {
+ const b = collageBounds(nodes);
+ let wanted = 1;
+ for (const n of nodes) {
+ const [p0, p1, p2, p3] = n.quad;
+ const across = (dist(p0, p1) + dist(p3, p2)) / 2;
+ const down = (dist(p0, p3) + dist(p1, p2)) / 2;
+ if (n.w > 0 && across > 0) wanted = Math.max(wanted, n.w / across);
+ if (n.h > 0 && down > 0) wanted = Math.max(wanted, n.h / down);
+ }
+ const limit = Math.min(
+ COLLAGE_MAX_DIM / b.width,
+ COLLAGE_MAX_DIM / b.height,
+ Math.sqrt(COLLAGE_MAX_EXPORT_PIXELS / (b.width * b.height)),
+ );
+ const scale = Math.min(wanted, limit);
+ const side = (v) => Math.min(COLLAGE_MAX_DIM, Math.max(COLLAGE_MIN_DIM, Math.round(v * scale)));
+ return {
+ minX: b.minX,
+ minY: b.minY,
+ scale,
+ width: side(b.width),
+ height: side(b.height),
+ capped: wanted > limit,
+ };
+}
/** A new, empty collage — one spelling, used wherever one is created. */
export function newCollage(name) {
diff --git a/frontend/src/lib/inspect.test.js b/frontend/src/lib/inspect.test.js
index 68a0c43..1c46f91 100644
--- a/frontend/src/lib/inspect.test.js
+++ b/frontend/src/lib/inspect.test.js
@@ -6,6 +6,7 @@ import {
buildFrameOps, hasVideoEdits, normalizeRightAngleRotation, rotationOps,
sourceStem, timecode, frameSaveName, frameSaveNames, saveNameOf,
newCollage, clampCollageDim, stitchCanvas, COLLAGE_MIN_DIM, COLLAGE_MAX_DIM,
+ exportFrame, COLLAGE_MAX_EXPORT_PIXELS, clockTime,
COLLAGE_DEFAULT_SIZE,
} from './inspect.js';
@@ -486,3 +487,54 @@ describe('stitchCanvas', () => {
expect(stitchCanvas({}, current)).toEqual({ ...current, scale: 1 });
});
});
+
+describe('exportFrame', () => {
+ const rect = (x, y, w, h) => [[x, y], [x + w, y], [x + w, y + h], [x, y + h]];
+
+ it('brings a piece placed small back to its own pixels', () => {
+ // a 1920×1080 frame shown at 800×450 on the canvas
+ const frame = exportFrame([{ w: 1920, h: 1080, quad: rect(100, 50, 800, 450) }]);
+ expect(frame).toMatchObject({ minX: 100, minY: 50, scale: 2.4, width: 1920, height: 1080, capped: false });
+ });
+
+ it('follows the sharpest piece, and never shrinks one placed larger than it is', () => {
+ const frame = exportFrame([
+ { w: 400, h: 300, quad: rect(0, 0, 800, 600) }, // blown up: would take 0.5
+ { w: 1200, h: 900, quad: rect(800, 0, 400, 300) }, // shown at a third
+ ]);
+ expect(frame.scale).toBe(3);
+ expect(frame.width).toBe(3600);
+ });
+
+ it('reads a turned piece by its sides, not by its bounding box', () => {
+ const c = Math.SQRT1_2 * 100;
+ const turned = [[c, 0], [2 * c, c], [c, 2 * c], [0, c]]; // a 100×100 square turned 45°
+ expect(exportFrame([{ w: 200, h: 200, quad: turned }]).scale).toBeCloseTo(2);
+ });
+
+ it('holds a wide panorama inside the side limit and says the limit set it', () => {
+ const frame = exportFrame([{ w: 20000, h: 2000, quad: rect(0, 0, 2000, 200) }]);
+ expect(frame.width).toBe(COLLAGE_MAX_DIM);
+ expect(frame.capped).toBe(true);
+ });
+
+ it('holds a large square inside the pixel budget', () => {
+ const frame = exportFrame([{ w: 9000, h: 9000, quad: rect(0, 0, 1000, 1000) }]);
+ expect(frame.width * frame.height).toBeLessThanOrEqual(COLLAGE_MAX_EXPORT_PIXELS + 2 * frame.width);
+ expect(frame.capped).toBe(true);
+ });
+
+ it('shrinks a layout already past what compose accepts', () => {
+ const frame = exportFrame([{ w: 100, h: 100, quad: rect(0, 0, 10000, 500) }]);
+ expect(frame.width).toBe(COLLAGE_MAX_DIM);
+ expect(frame.scale).toBeLessThan(1);
+ });
+});
+
+describe('clockTime', () => {
+ it('reads as a player shows it', () => {
+ expect(clockTime(64.5)).toBe('1:04.5');
+ expect(clockTime(0)).toBe('0:00.0');
+ expect(clockTime(-3)).toBe('0:00.0');
+ });
+});
diff --git a/frontend/src/lib/localZone.js b/frontend/src/lib/localZone.js
new file mode 100644
index 0000000..3f7bfea
--- /dev/null
+++ b/frontend/src/lib/localZone.js
@@ -0,0 +1,94 @@
+/**
+ * A time typed as the local time at a place (D33 of the Case transition).
+ *
+ * A Claim tied to a point was seen somewhere, and the hour a witness or a caption
+ * gives is that place's clock. The zone comes from the server's bundled boundaries
+ * (`GET /api/geo/zone`, nothing reaches the network) and the offset from this
+ * browser's own zone database, for the instant itself: an August hour in Kyiv is
+ * `+03:00` and a January one `+02:00`. How a value is put on a clock and stored is
+ * `lib/clock.js`; this module finds the zones and their offsets.
+ */
+import { api } from './api.js';
+import { instantOf, zoneOffset } from './timeline.js';
+
+const UNZONED = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(\.\d{1,6})?$/;
+
+const pad = (value) => String(value).padStart(2, '0');
+
+/** The offset in force at that wall-clock time in the zone, as `+03:00`. */
+export function offsetAt(raw, zone) {
+ const match = UNZONED.exec(String(raw ?? ''));
+ if (!match || !zone) return '';
+ const [, year, month, day, hour, minute, second] = match.map(Number);
+ const instant = instantOf({ year, month, day, hour, minute, second }, zone);
+ const minutes = Math.round(zoneOffset(instant, zone) / 60_000);
+ const size = Math.abs(minutes);
+ return `${minutes < 0 ? '-' : '+'}${pad(Math.floor(size / 60))}:${pad(size % 60)}`;
+}
+
+const DAYS = /^\d{4}(-\d{2}(-\d{2})?)?[~?%]?(\/\d{4}(-\d{2}(-\d{2})?)?[~?%]?)?$/;
+
+/** Whether a stored value is a date or a span of dates, with no hour. A day has no
+ * offset to carry, so the zone it is a day of travels beside it (`when_zone`). */
+export function isDateOnly(raw) {
+ return DAYS.test(String(raw ?? ''));
+}
+
+/** Where an entity stands, when it is a point: a place, or a proof with its own. */
+export function pointOf(entity) {
+ if (!entity || !['place', 'proof'].includes(entity.type)) return null;
+ const lat = Number(entity.attrs?.lat);
+ const lon = Number(entity.attrs?.lon);
+ if (entity.attrs?.lat == null || entity.attrs?.lon == null) return null;
+ if (!Number.isFinite(lat) || !Number.isFinite(lon)) return null;
+ if (Math.abs(lat) > 90 || Math.abs(lon) > 180) return null;
+ return { lat, lon };
+}
+
+/** Zones already asked for, by point. A handful of places per case, capped anyway. */
+const ZONES = new Map();
+const MAX_ZONES = 200;
+
+/** The civil zone at a point, asked once per point per session. */
+export function zoneAt({ lat, lon }) {
+ const key = `${lat.toFixed(4)},${lon.toFixed(4)}`;
+ let held = ZONES.get(key);
+ if (!held) {
+ held = api
+ .get(`/api/geo/zone?lat=${encodeURIComponent(lat)}&lon=${encodeURIComponent(lon)}`)
+ .then((body) => body?.name || '')
+ .catch(() => {
+ ZONES.delete(key);
+ return '';
+ });
+ if (ZONES.size >= MAX_ZONES) ZONES.delete(ZONES.keys().next().value);
+ ZONES.set(key, held);
+ }
+ return held;
+}
+
+/**
+ * The zones a draft's points stand in, one entry per zone.
+ *
+ * Two places in one zone are one choice. Two zones are two, and neither is taken on
+ * the analyst's behalf: `only` is set only when every point agrees.
+ */
+export async function zonesOf(entities) {
+ const placed = entities
+ .map((entity) => ({ entity, point: pointOf(entity) }))
+ .filter((entry) => entry.point);
+ const named = await Promise.all(placed.map(async (entry) => ({
+ zone: await zoneAt(entry.point),
+ place: entry.entity.label,
+ })));
+ const zones = [];
+ for (const entry of named) {
+ if (entry.zone && !zones.some((held) => held.zone === entry.zone)) zones.push(entry);
+ }
+ return { zones, only: zones.length === 1 ? zones[0] : null };
+}
+
+/** Forget every zone asked for. For tests. */
+export function forgetZones() {
+ ZONES.clear();
+}
diff --git a/frontend/src/lib/localZone.test.js b/frontend/src/lib/localZone.test.js
new file mode 100644
index 0000000..5e44da2
--- /dev/null
+++ b/frontend/src/lib/localZone.test.js
@@ -0,0 +1,65 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const get = vi.fn(async (url) => {
+ const lon = Number(new URL(url, 'http://x').searchParams.get('lon'));
+ return { name: lon > 20 ? 'Europe/Kyiv' : 'Europe/Lisbon' };
+});
+vi.mock('./api.js', () => ({ api: { get } }));
+
+const { forgetZones, isDateOnly, offsetAt, pointOf, zoneAt, zonesOf } = await import('./localZone.js');
+
+beforeEach(() => {
+ get.mockClear();
+ forgetZones();
+});
+
+describe('offsetAt', () => {
+ it('gives the offset the zone keeps at that very time, daylight saving included', () => {
+ expect(offsetAt('2026-08-11T17:05:00', 'Europe/Kyiv')).toBe('+03:00');
+ expect(offsetAt('2026-01-11T17:05:00', 'Europe/Kyiv')).toBe('+02:00');
+ expect(offsetAt('2026-08-11T17:05:00', 'America/New_York')).toBe('-04:00');
+ expect(offsetAt('2026-08-11T17:05:00', 'Asia/Kolkata')).toBe('+05:30');
+ });
+});
+
+describe('a day and its zone', () => {
+ it('knows a date from a time', () => {
+ for (const raw of ['2024', '2024-03', '2024-03-12', '2024-03~', '2024-03-12/2024-03-14?']) {
+ expect(isDateOnly(raw), raw).toBe(true);
+ }
+ for (const raw of ['', '2024-03-12T14:30:00', '2024-03-12T14:30:00Z', 'March']) {
+ expect(isDateOnly(raw), raw).toBe(false);
+ }
+ });
+});
+
+describe('pointOf', () => {
+ it('reads a place or a proof with a point, and nothing else', () => {
+ expect(pointOf({ type: 'place', attrs: { lat: 49.9, lon: 36.2 } })).toEqual({ lat: 49.9, lon: 36.2 });
+ expect(pointOf({ type: 'proof', attrs: { lat: '49.9', lon: '36.2' } })).toEqual({ lat: 49.9, lon: 36.2 });
+ expect(pointOf({ type: 'place', attrs: {} })).toBeNull();
+ expect(pointOf({ type: 'place', attrs: { lat: 95, lon: 0 } })).toBeNull();
+ expect(pointOf({ type: 'person', attrs: { lat: 1, lon: 1 } })).toBeNull();
+ });
+});
+
+describe('zoneAt and zonesOf', () => {
+ it('asks the local server once per point', async () => {
+ await zoneAt({ lat: 49.99, lon: 36.23 });
+ await zoneAt({ lat: 49.99, lon: 36.23 });
+ expect(get).toHaveBeenCalledTimes(1);
+ expect(get.mock.calls[0][0]).toBe('/api/geo/zone?lat=49.99&lon=36.23');
+ });
+
+ it('takes the one zone the places agree on, and none when they disagree', async () => {
+ const kharkiv = { type: 'place', label: 'Kharkiv', attrs: { lat: 49.99, lon: 36.23 } };
+ const lviv = { type: 'place', label: 'Lviv', attrs: { lat: 49.84, lon: 24.03 } };
+ const lisbon = { type: 'place', label: 'Lisbon', attrs: { lat: 38.72, lon: -9.14 } };
+
+ expect((await zonesOf([kharkiv, lviv])).only).toEqual({ zone: 'Europe/Kyiv', place: 'Kharkiv' });
+ const split = await zonesOf([kharkiv, lisbon]);
+ expect(split.only).toBeNull();
+ expect(split.zones.map((entry) => entry.place)).toEqual(['Kharkiv', 'Lisbon']);
+ expect((await zonesOf([{ type: 'person', label: 'Ivan' }])).zones).toEqual([]);
+ });
+});
diff --git a/frontend/src/lib/looseDate.js b/frontend/src/lib/looseDate.js
index 31e9284..0ad4dc8 100644
--- a/frontend/src/lib/looseDate.js
+++ b/frontend/src/lib/looseDate.js
@@ -21,11 +21,13 @@
* it again gives the same stored value — `looseDate.test.js` holds both
* directions to every example the profile documents.
*/
+import { foldText } from './textFold.js';
import { validateTemporalValue } from './timeline.js';
const MONTH_ABBR = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
-// English and French month names, accents folded, full and short.
+// English and French month names, accents folded, full and short. The base every
+// machine reads, whatever its languages.
const MONTH_WORDS = new Map(
[
['january', 'jan', 'janvier', 'janv'],
@@ -48,7 +50,7 @@ export const LOOSE_DATE_HINT =
const HELP = 'Try 24/10/2025, Oct 2025, 2025, 24/10/2025 14:30 UTC, or two dates joined by "to".';
-const fold = (text) => text.normalize('NFD').replace(/\p{Diacritic}/gu, '').toLowerCase();
+const fold = foldText;
const pad = (value, size = 2) => String(value).padStart(size, '0');
/** `{ value }` in the stored profile, or `{ value: null, error }`. Empty reads as ''. */
@@ -242,12 +244,14 @@ function readDate(text) {
if (match) return day(match[1]);
// Words: a month name, a year, and perhaps a day, in either order.
- const tokens = fold(text).replace(/[,.]/g, ' ').split(/\s+/).filter(Boolean);
+ const tokens = fold(text).replace(/[,.،]/g, ' ').split(/\s+/).filter(Boolean);
+ const local = browserMonthWords();
let year = '';
let month = 0;
let dayOf = '';
for (const token of tokens) {
- const word = MONTH_WORDS.get(token);
+ const word = MONTH_WORDS.get(token) ?? local.months.get(token);
+ if (local.fillers.has(token)) continue;
if (word && !month) month = word;
else if (/^\d{4}$/.test(token) && !year) year = token;
else if (/^\d{1,2}(?:st|nd|rd|th|er)?$/.test(token) && !dayOf) dayOf = token.replace(/\D/g, '');
@@ -269,3 +273,70 @@ function write(part) {
const marker = part.approx && part.unsure ? '%' : part.approx ? '~' : part.unsure ? '?' : '';
return `${part.date}${marker}`;
}
+
+/**
+ * The month names of the languages this browser is set to, read from `Intl` rather
+ * than typed into a table: `12 марта 2026`, `12 de marzo de 2026`, `12 במרץ 2026`.
+ *
+ * Each month is taken in the four shapes a date is written in, on its own and inside
+ * a date, long and short, because a language like Russian or Greek spells the month
+ * differently in each (`март`, `марта`). The words a date wraps around its parts in
+ * that language (`de`, `г.`) are read the same way and skipped. Folded like every
+ * other word here, and never sent anywhere: the server only ever sees the stored
+ * value.
+ */
+export function monthWordsFor(languages = []) {
+ const months = new Map();
+ const fillers = new Set();
+ const shapes = [
+ { month: 'long' }, { month: 'short' },
+ { day: 'numeric', month: 'long', year: 'numeric' }, { day: 'numeric', month: 'short', year: 'numeric' },
+ ];
+ for (const language of languages) {
+ for (const shape of shapes) {
+ let format;
+ try {
+ format = new Intl.DateTimeFormat(language, { ...shape, timeZone: 'UTC', calendar: 'gregory' });
+ } catch {
+ continue;
+ }
+ for (let index = 0; index < 12; index += 1) {
+ const parts = format.formatToParts(new Date(Date.UTC(2026, index, 12)));
+ parts.forEach((part, at) => {
+ if (part.type === 'literal') {
+ for (const word of fold(part.value).split(/[\s,.،]+/)) {
+ if (word && !/\d/.test(word)) fillers.add(word);
+ }
+ return;
+ }
+ if (part.type !== 'month') return;
+ const word = fold(part.value).replace(/\.$/, '');
+ if (!word || /\d/.test(word)) return;
+ if (!months.has(word)) months.set(word, index + 1);
+ // Hebrew writes "in March" as one word, `במרץ`: a literal that runs straight
+ // into the month is part of how the month is written.
+ const before = /(\S+)$/.exec(fold(parts[at - 1]?.type === 'literal' ? parts[at - 1].value : ''));
+ if (before && !/\d/.test(before[1]) && !months.has(before[1] + word)) {
+ months.set(before[1] + word, index + 1);
+ }
+ });
+ }
+ }
+ }
+ for (const word of months.keys()) fillers.delete(word);
+ for (const word of MONTH_WORDS.keys()) fillers.delete(word);
+ return { months, fillers };
+}
+
+let cachedFor = null;
+let cached = { months: new Map(), fillers: new Set() };
+
+function browserMonthWords() {
+ const languages = [...(globalThis.navigator?.languages ?? [])];
+ const key = languages.join(',');
+ if (key !== cachedFor) {
+ cachedFor = key;
+ cached = monthWordsFor(languages);
+ }
+ return cached;
+}
diff --git a/frontend/src/lib/looseDate.test.js b/frontend/src/lib/looseDate.test.js
index d088f08..ef5d405 100644
--- a/frontend/src/lib/looseDate.test.js
+++ b/frontend/src/lib/looseDate.test.js
@@ -1,8 +1,9 @@
-import { describe, expect, it } from 'vitest';
+import { afterEach, describe, expect, it, vi } from 'vitest';
import {
composeLooseDate,
decomposeLooseDate,
friendlyDate,
+ monthWordsFor,
parseLooseDate,
} from './looseDate.js';
import { TEMPORAL_SYNTAX } from './temporalInput.js';
@@ -175,3 +176,44 @@ describe('a date built by pointing at it', () => {
}
});
});
+
+describe('month names in the languages the browser is set to', () => {
+ afterEach(() => vi.unstubAllGlobals());
+
+ it('reads each month in the forms its language writes it, on its own and in a date', () => {
+ const { months, fillers } = monthWordsFor(['ru', 'uk', 'ar', 'es', 'de', 'el', 'he']);
+ // Russian and Ukrainian decline the month inside a date, and both forms are read
+ for (const word of ['март', 'марта', 'березень', 'березня', 'marzo', 'marz', 'μαρτιου', 'مارس', 'מרץ', 'במרץ']) {
+ expect([word, months.get(word)]).toEqual([word, 3]);
+ }
+ expect(months.get('августа')).toBe(8);
+ expect(months.get('dezember')).toBe(12);
+ // the words a date wraps around its parts are skipped, never read as a month
+ expect(fillers.has('de')).toBe(true);
+ expect(fillers.has('г')).toBe(true);
+ expect(fillers.has('marzo')).toBe(false);
+ expect(monthWordsFor(['not a language']).months.size).toBe(0);
+ });
+
+ it('reads a date written in them to the same stored value', () => {
+ vi.stubGlobal('navigator', { languages: ['ru', 'es', 'he', 'ar', 'de'] });
+ expect(read('12 марта 2026')).toBe('2026-03-12');
+ expect(read('12 марта 2026 г.')).toBe('2026-03-12');
+ expect(read('Март 2026')).toBe('2026-03');
+ expect(read('12 de marzo de 2026')).toBe('2026-03-12');
+ expect(read('12 במרץ 2026')).toBe('2026-03-12');
+ expect(read('12 مارس 2026')).toBe('2026-03-12');
+ expect(read('12. März 2026')).toBe('2026-03-12');
+ expect(read('~ марта 2026')).toBe('2026-03~');
+ // the day still comes first, and the fixed base reads whatever the machine is set to
+ expect(read('3/12/2026')).toBe('2026-12-03');
+ expect(read('octobre 2025')).toBe('2025-10');
+ });
+
+ it('keeps English and French on a machine set to neither', () => {
+ vi.stubGlobal('navigator', { languages: ['ja'] });
+ expect(read('12 March 2026')).toBe('2026-03-12');
+ expect(read('12 mars 2026')).toBe('2026-03-12');
+ expect(parseLooseDate('12 марта 2026').value).toBeNull();
+ });
+});
diff --git a/frontend/src/lib/map/acquisitions.js b/frontend/src/lib/map/acquisitions.js
index f9e2713..e7ac152 100644
--- a/frontend/src/lib/map/acquisitions.js
+++ b/frontend/src/lib/map/acquisitions.js
@@ -15,8 +15,7 @@
import { daysBefore, isoDay } from '../sentinel.js';
/**
- * How far back to look. A month is several passes, a year the most one preset
- * reaches; anything older is two days picked in the calendar, `{ start, end }`.
+ * How far back the pass list looks. A calendar asks for one chosen month instead.
*/
export const LOOKBACK_WINDOWS = Object.freeze([
{ id: 30, label: '30 days' },
@@ -34,13 +33,6 @@ export function lookupSpan(lookback, now = new Date()) {
: { start: lookback?.start ?? '', end: lookback?.end ?? '' };
}
-/** What stops two picked days from being looked up, or '' when nothing does. */
-export function spanProblem(lookback) {
- if (typeof lookback === 'number') return '';
- if (!lookback?.start || !lookback?.end) return 'Pick the first and the last day.';
- return lookback.start > lookback.end ? 'The first day comes after the last.' : '';
-}
-
/**
* Where to look for what a list stopped short of, or null when nothing is left.
*
diff --git a/frontend/src/lib/map/acquisitions.test.js b/frontend/src/lib/map/acquisitions.test.js
index 844ad87..5d81ddc 100644
--- a/frontend/src/lib/map/acquisitions.test.js
+++ b/frontend/src/lib/map/acquisitions.test.js
@@ -9,7 +9,6 @@ import {
coverageWarning,
lookupSpan,
olderSpan,
- spanProblem,
sweptNote,
withOlder,
} from './acquisitions.js';
@@ -33,19 +32,12 @@ describe('acquisitions over drawn areas', () => {
expect(Object.keys(query.zones[0]).sort()).toEqual(['id', 'kind', 'name', 'points']);
});
- it('asks about two days picked in the calendar as they are', () => {
- const query = acquisitionQuery([zone('a')], { start: '2019-03-01', end: '2019-06-30' }, undefined, 'sentinel1');
- expect([query.start, query.end, query.collection]).toEqual(['2019-03-01', '2019-06-30', 'sentinel1']);
+ it('asks about a calendar month by its start and end days', () => {
+ const query = acquisitionQuery([zone('a')], { start: '2019-03-01', end: '2019-03-31' }, undefined, 'sentinel1');
+ expect([query.start, query.end, query.collection]).toEqual(['2019-03-01', '2019-03-31', 'sentinel1']);
expect(lookupSpan(90, new Date('2026-05-31T09:00:00Z'))).toEqual({ start: '2026-03-02', end: '2026-05-31' });
});
- it('needs both days, in order, and nothing of a preset', () => {
- expect(spanProblem(30)).toBe('');
- expect(spanProblem({ start: '2019-03-01', end: '' })).toBe('Pick the first and the last day.');
- expect(spanProblem({ start: '2019-06-30', end: '2019-03-01' })).toBe('The first day comes after the last.');
- expect(spanProblem({ start: '2019-03-01', end: '2019-03-01' })).toBe('');
- });
-
it('looks for what a cut list lacks before its oldest pass, that day included', () => {
const list = [{ date: '2026-05-11' }, { date: '2026-02-03' }];
expect(olderSpan({ start: '2025-01-01', end: '2026-05-31' }, list)).toEqual({ start: '2025-01-01', end: '2026-02-03' });
diff --git a/frontend/src/lib/map/addedLayer.js b/frontend/src/lib/map/addedLayer.js
index 548f10d..621f8fe 100644
--- a/frontend/src/lib/map/addedLayer.js
+++ b/frontend/src/lib/map/addedLayer.js
@@ -652,6 +652,23 @@ export function createAddedLayer(
return true;
},
+ /** The lowest of this layer's GL layers, or null while nothing is built. */
+ floor() {
+ return built && map.getLayer(FILL) ? FILL : null;
+ },
+
+ /**
+ * Move every GL layer of this one, in its own order, to just under `other`,
+ * another added layer. Nothing moves until both are built.
+ */
+ stackUnder(other) {
+ const below = other?.floor();
+ if (!built || !below) return;
+ for (const layer of PAINTED) {
+ if (map.getLayer(layer)) map.moveLayer(layer, below);
+ }
+ },
+
/** Keep the features, take them off the map (or put them back). */
visible(on) {
shown = on;
diff --git a/frontend/src/lib/map/addedLayer.test.js b/frontend/src/lib/map/addedLayer.test.js
index dcd961e..b748af7 100644
--- a/frontend/src/lib/map/addedLayer.test.js
+++ b/frontend/src/lib/map/addedLayer.test.js
@@ -39,6 +39,15 @@ function stubMap() {
addLayer: (layer) => layers.set(layer.id, { ...layer }),
getLayer: (id) => layers.get(id),
removeLayer: (id) => layers.delete(id),
+ // MapLibre's: the layer goes just under `before`, keeping everything else
+ moveLayer: (id, before) => {
+ const moved = layers.get(id);
+ const rest = [...layers].filter(([key]) => key !== id);
+ const at = rest.findIndex(([key]) => key === before);
+ rest.splice(at < 0 ? rest.length : at, 0, [id, moved]);
+ layers.clear();
+ for (const [key, value] of rest) layers.set(key, value);
+ },
setFilter: (id, filter) => layers.set(id, { ...layers.get(id), filter }),
setPaintProperty: (id, key, value) =>
layers.set(id, { ...layers.get(id), paint: { ...layers.get(id).paint, [key]: value } }),
@@ -459,6 +468,36 @@ describe('an added layer on the map', () => {
expect(engine.map.sources.size).toBe(1);
});
+ it('restacks under another added layer as one block, in its own order', async () => {
+ const engine = stubEngine();
+ const lower = createAddedLayer(engine);
+ const upper = createAddedLayer(engine);
+ await lower.set(COLLECTION, { categories: CATEGORIES });
+ await upper.set(COLLECTION, { categories: CATEGORIES });
+
+ // built last, so on top: now asked under the one built first
+ upper.stackUnder(lower);
+
+ const ids = [...engine.map.layers.keys()];
+ const own = (layer) => ids.filter((id) => id.startsWith(layer.floor().replace(/-fill$/, '-')));
+ expect(ids).toEqual([...own(upper), ...own(lower)]);
+ expect(own(upper).map((id) => id.split('-').pop())).toEqual(['fill', 'line', 'dot', 'mark', 'own']);
+ });
+
+ it('moves nothing while either layer is still unbuilt', async () => {
+ const engine = stubEngine();
+ const built = createAddedLayer(engine);
+ const waiting = createAddedLayer(engine);
+ await built.set(COLLECTION, { categories: CATEGORIES });
+ const before = [...engine.map.layers.keys()];
+
+ expect(waiting.floor()).toBeNull();
+ built.stackUnder(waiting);
+ waiting.stackUnder(built);
+
+ expect([...engine.map.layers.keys()]).toEqual(before);
+ });
+
it('drops its source and its layers when it is removed', async () => {
const engine = stubEngine();
const layer = createAddedLayer(engine);
diff --git a/frontend/src/lib/map/addedLayers.js b/frontend/src/lib/map/addedLayers.js
index ddda626..e73b30d 100644
--- a/frontend/src/lib/map/addedLayers.js
+++ b/frontend/src/lib/map/addedLayers.js
@@ -180,6 +180,27 @@ export function drawable(layers = []) {
return layers.filter((layer) => layer.enabled);
}
+/**
+ * The names in their new order once one row is dropped at `to`, which counts
+ * places in the list as it stood before the drag. Top of the map first.
+ */
+export function moveName(names, name, to) {
+ const from = names.indexOf(name);
+ if (from < 0) return [...names];
+ const rest = names.filter((entry) => entry !== name);
+ const at = Math.max(0, Math.min(rest.length, to > from ? to - 1 : to));
+ return [...rest.slice(0, at), name, ...rest.slice(at)];
+}
+
+/** What a Refresh on every followed layer found, in one toast. */
+export function refreshedLabel({ moved = 0, failed = 0, total = 0 }) {
+ if (total && failed === total) {
+ return total === 1 ? 'That source could not be reached' : 'No source could be reached';
+ }
+ const found = moved ? `${moved} updated` : 'Nothing new';
+ return failed ? `${found}, ${failed} could not be reached` : found;
+}
+
/** One category switched, as the PATCH body expects it: the whole hidden list. */
export function toggleCategory(layer, name) {
const hidden = new Set(layer?.hidden ?? []);
diff --git a/frontend/src/lib/map/addedLayers.test.js b/frontend/src/lib/map/addedLayers.test.js
index da569a8..e800a1b 100644
--- a/frontend/src/lib/map/addedLayers.test.js
+++ b/frontend/src/lib/map/addedLayers.test.js
@@ -11,7 +11,9 @@ import {
freshness,
legend,
looksLikeUrl,
+ moveName,
PALETTE,
+ refreshedLabel,
renewsOnShow,
searchFeatures,
SEARCH_LIMIT,
@@ -241,6 +243,43 @@ describe('what the map draws and what switching on re-reads', () => {
});
});
+describe('the order the rows were dragged into', () => {
+ const names = ['North', 'South', 'East', 'West'];
+
+ it('moves a row down past the ones it was dropped below', () => {
+ // dropped on the gap above West: counted in the list as it stood
+ expect(moveName(names, 'North', 3)).toEqual(['South', 'East', 'North', 'West']);
+ expect(moveName(names, 'North', 4)).toEqual(['South', 'East', 'West', 'North']);
+ });
+
+ it('moves a row up, and leaves it where it was when dropped on itself', () => {
+ expect(moveName(names, 'West', 0)).toEqual(['West', 'North', 'South', 'East']);
+ expect(moveName(names, 'South', 1)).toEqual(names);
+ expect(moveName(names, 'South', 2)).toEqual(names);
+ });
+
+ it('changes nothing for a name it does not hold', () => {
+ expect(moveName(names, 'Nowhere', 0)).toEqual(names);
+ });
+});
+
+describe('what a refresh of every layer says', () => {
+ it('counts what moved and what could not be reached, in one line', () => {
+ expect(refreshedLabel({ moved: 0, failed: 0, total: 3 })).toBe('Nothing new');
+ expect(refreshedLabel({ moved: 2, failed: 0, total: 3 })).toBe('2 updated');
+ expect(refreshedLabel({ moved: 1, failed: 1, total: 3 })).toBe(
+ '1 updated, 1 could not be reached'
+ );
+ });
+
+ it('says it plainly when no source answered', () => {
+ expect(refreshedLabel({ moved: 0, failed: 2, total: 2 })).toBe('No source could be reached');
+ expect(refreshedLabel({ moved: 0, failed: 1, total: 1 })).toBe(
+ 'That source could not be reached'
+ );
+ });
+});
+
describe('finding a pin in somebody else’s map', () => {
const feature = (name, category, over = {}) => ({
type: 'Feature',
diff --git a/frontend/src/lib/map/analyzerRules.js b/frontend/src/lib/map/analyzerRules.js
index bb2fd56..cdaaf34 100644
--- a/frontend/src/lib/map/analyzerRules.js
+++ b/frontend/src/lib/map/analyzerRules.js
@@ -1,14 +1,19 @@
/**
* 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.
+ * (engine/detect_rules.py). A rule is a quantity, the date it is read on (the
+ * before pass, the after pass, or the change from one to the other) 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.
+ *
+ * The engine names the two passes A and B, and so do the saved recipes; the
+ * words here are Before and After, which is what they are to someone building
+ * a rule. An analyzer declares when it is made which satellite it reads and
+ * whether it judges one date or the change between two (`sensor`, `dates`).
*/
import { CHANGE_INDICES, indexThreshold } from './changeAssist.js';
-import { toMercator } from './groundFrame.js';
-export const MEASURES = Object.freeze([
+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.' },
@@ -66,12 +71,60 @@ export function unitOf(rule) {
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;
+/**
+ * How a rule's line is said. A change is a drop, a rise or a move of some
+ * amount, and a state on one date is at least or at most some value; both can
+ * also sit between two values. The engine keeps an operator and a signed value,
+ * and these are the same thing in words.
+ */
+export function directionsFor(rule) {
+ if (rule.measure === 'class') return [['is', 'Is'], ['not', 'Is not']];
+ const between = ['between', 'Between'];
+ if (rule.on === 'change' && rule.measure !== 'colour') {
+ return [['drop', 'Dropped'], ['rise', 'Rose'], ['moved', 'Either way'], between];
+ }
+ return [['ge', 'At least'], ['le', 'At most'], between];
+}
+
+/** Which of `directionsFor` a rule says. */
+export function directionOf(rule) {
+ if (rule.measure === 'class' || rule.op === 'between') return rule.op;
+ if (rule.on === 'change' && rule.measure !== 'colour') {
+ return rule.op === 'le' ? 'drop' : rule.op === 'ge' ? 'rise' : 'moved';
+ }
+ return rule.op;
+}
+
+/** The fields of a rule after it is said another way, keeping the amount it had. */
+export function withDirection(rule, direction) {
+ const amount = Math.abs(rule.value);
+ if (direction === 'drop') return retarget(rule, { op: 'le', value: -amount });
+ if (direction === 'rise') return retarget(rule, { op: 'ge', value: amount });
+ return retarget(rule, { op: direction });
+}
+
+/** A rule's line as an amount: how big a drop, a rise or a move, or else the value itself. */
+export function amountOf(rule, value = rule.value) {
+ if (rule.on !== 'change' || rule.measure === 'colour') return value;
+ if (rule.op === 'le') return -value;
+ return rule.op === 'moved' ? Math.abs(value) : value;
+}
+
+/** The value a rule's line takes for an amount, the opposite of `amountOf`. */
+export function withAmount(rule, amount) {
+ const number = Number(amount);
+ if (rule.on !== 'change' || rule.measure === 'colour' || rule.op === 'between') return number;
+ return rule.op === 'le' ? -Math.abs(number) : Math.abs(number);
+}
+
+/**
+ * The slider a rule's line moves on: the amount of a drop, a rise or a move
+ * from nothing up, or else the value across its whole range.
+ */
+export function lineScale(rule) {
+ const scale = scaleOf(rule);
+ const directional = rule.on === 'change' && rule.measure !== 'colour' && rule.op !== 'between';
+ return directional ? { ...scale, min: 0, max: scale.max } : scale;
}
/**
@@ -219,8 +272,38 @@ export function recipeBands(recipe) {
}
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');
+
+/**
+ * What an analyzer reads: the satellite and the number of dates it declared.
+ * One saved before it declared them is worked out from its rules, as the
+ * engine does when it loads it.
+ */
+export const sensorOf = (recipe) => recipe?.sensor
+ ?? ((recipe?.rules ?? []).some((rule) => rule.measure === 'radar') ? 'sentinel1' : 'sentinel2');
+export const datesOf = (recipe) => recipe?.dates
+ ?? ((recipe?.rules ?? []).every((rule) => rule.on === 'b') ? 'one' : 'two');
+export const readsRadar = (recipe) => isRules(recipe) && sensorOf(recipe) === 'sentinel1';
+export const readsOneDate = (recipe) => isRules(recipe) && datesOf(recipe) === 'one';
+
+/** What an analyzer reads, in a few words: "Sentinel-2 · two dates". */
+export function describeReads(recipe) {
+ const radar = sensorOf(recipe) === 'sentinel1';
+ return `${radar ? 'Sentinel-1 radar' : 'Sentinel-2'} · ${datesOf(recipe) === 'one' ? 'one date' : 'two dates'}`;
+}
+
+/** The measures an analyzer can use: its satellite's, and a colour distance only where two dates give it a change. */
+export const measuresFor = (recipe) => MEASURES.filter((measure) => (measure.id === 'radar') === readsRadar(recipe)
+ && !(measure.id === 'colour' && readsOneDate(recipe)));
+
+/** The dates a rule can be read on, in the words an analyst uses. A single
+ * date needs no choice, and a colour distance or a ground class fix theirs. */
+export function whensFor(recipe, rule) {
+ if (readsOneDate(recipe)) return [];
+ const all = [['a', 'Before'], ['b', 'After'], ['change', 'Change']];
+ if (rule.measure === 'colour') return all.filter(([id]) => id === 'change');
+ if (rule.measure === 'class') return all.filter(([id]) => id !== 'change');
+ return all;
+}
/** Band products one date costs: every three bands are one request. */
export function productCount(recipe) {
@@ -241,11 +324,36 @@ export function recipeProblem(recipe, limits = {}) {
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.';
+ if (radar.has(true) !== readsRadar(recipe)) {
+ return radar.has(true) ? 'Radar rules need a radar analyzer.' : 'Optical rules need a Sentinel-2 analyzer.';
+ }
+ const single = rules.every((rule) => rule.on === 'b');
+ if (readsOneDate(recipe) && !single) return 'A one-date analyzer has no before pass for this rule to read.';
+ if (!readsOneDate(recipe) && single) return 'Put a rule on the before date or on the change, or the before pass is read for nothing.';
const bands = limits.max_bands ?? 6;
if (recipeBands(recipe).length > bands) return `An analyzer reads at most ${bands} bands.`;
return '';
}
+/**
+ * Why the analyzer cannot be saved yet, or '' when it can. Checks are how it
+ * is proved, so it needs one, with a pin where something should be found.
+ */
+export function savingProblem(recipe, limits = {}) {
+ const problem = recipeProblem(recipe, limits);
+ if (problem) return problem;
+ const checks = recipe?.checks ?? [];
+ if (!checks.length) return 'Add a check: a place where this analyzer should find something.';
+ const unpinned = checks.find((check) => !check.marks?.length);
+ if (unpinned) return `The check “${unpinned.name}” needs a pin.`;
+ const undated = checks.find((check) => !checkDated(recipe, check));
+ if (undated) return `The check “${undated.name}” needs its passes.`;
+ if (!checks.some((check) => check.marks.some((mark) => mark.expect === 'found'))) {
+ return 'A check needs a pin where something should be found.';
+ }
+ 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
@@ -276,7 +384,7 @@ function pairName(bands) {
}
/** What a rule measures, in a few words. */
-export function quantityLabel(rule) {
+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]})`;
@@ -289,23 +397,41 @@ export function quantityLabel(rule) {
}
}
-const sideName = (on) => (on === 'a' ? 'A' : 'B');
+/**
+ * A rule in a couple of words, for a chip on the map: "NDVI change", "B12
+ * after", "VV". An analyzer of one date has no before or after to say.
+ */
+export function shortRule(rule, { single = false } = {}) {
+ const name = rule.measure === 'index' ? INDICES.find((entry) => entry.id === rule.index)?.label ?? rule.index.toUpperCase()
+ : rule.measure === 'nd' ? pairName(rule.bands) ?? `${rule.bands[0]}/${rule.bands[1]}`
+ : rule.measure === 'band' ? rule.band
+ : rule.measure === 'radar' ? POLARISATIONS.find((entry) => entry.id === rule.polarisation)?.label ?? 'VV'
+ : rule.measure === 'class' ? 'ground' : rule.measure;
+ if (single) return name;
+ return `${name} ${rule.on === 'change' ? 'change' : rule.on === 'a' ? 'before' : 'after'}`;
+}
+
+/** Where a state rule is read, for a sentence: nothing on a single date, else before or after. */
+const whenName = (on, single) => (single ? '' : on === 'a' ? ' before' : ' after');
-/** A rule as a clause: "NDVI dropped by 0.25 or more", "ground on B is water". */
-export function describeRule(rule) {
+/**
+ * A rule as a clause: "NDVI dropped by 0.25 or more", "NDVI after is at least
+ * 0.40", "ground is water". An analyzer of one date has no before or after to say.
+ */
+export function describeRule(rule, { single = false } = {}) {
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}`;
+ return `ground${whenName(rule.on, single)} ${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)}`;
+ const on = `${quantity}${whenName(rule.on, single)} is`;
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.around) return `${on} ${rule.op === 'ge' ? 'at least' : 'at most'} ${value(rule.value, true)}${around}`;
+ return `${on} ${rule.op === 'ge' ? 'at least' : 'at 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}`;
@@ -321,7 +447,8 @@ export function describeRule(rule) {
/** 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);
+ const single = readsOneDate(recipe);
+ const clauses = (recipe?.rules ?? []).map((rule) => describeRule(rule, { single }));
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];
@@ -351,13 +478,21 @@ export const DEFAULT_PARAMETERS = Object.freeze({
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 All sizes like every built-in. */
-export function newRecipe(methods = []) {
- const sizes = methods.find((entry) => entry.id === 'rules')?.sizes;
+/**
+ * A new analyzer of your own, for the satellite and the number of dates it
+ * was made for: one rule on the first usual line, at All sizes like every
+ * built-in. Radar starts from radar change's sizes, whose averaging is what
+ * keeps speckle from reading as a target.
+ */
+export function newRecipe(methods = [], { sensor = 'sentinel2', dates = 'two' } = {}) {
+ const radar = sensor === 'sentinel1';
+ const sizes = methods.find((entry) => entry.id === (radar ? 'sar-change' : 'rules'))?.sizes;
+ const two = dates === 'two';
+ const first = radar ? newRule('radar', two ? 'change' : 'b') : newRule('index', two ? 'change' : 'b');
return {
- id: 'custom', name: '', description: '', phenomenon: 'Candidate', method: 'rules',
+ id: 'custom', name: '', description: '', phenomenon: 'Candidate', method: 'rules', sensor, dates,
parameters: { ...DEFAULT_PARAMETERS, ...(sizes?.all ?? {}) },
- colour: '#f6a81a', style: 'both', rules: [newRule('index', 'change')], match: 'all', checks: [],
+ colour: '#f6a81a', style: 'both', rules: [first], match: 'all', checks: [],
};
}
@@ -386,6 +521,7 @@ export function fromDifference(settings) {
ignore_shadows: !!settings.ignore_shadows,
cloud_margin: Math.min(10, Math.max(0, Math.round((settings.cloud_margin ?? 0) / 10))),
},
+ sensor: 'sentinel2', dates: 'two',
colour: '#f6a81a', style: 'both', rules: [{ ...rule, ...tuned }], match: 'all', checks: [],
};
}
@@ -395,12 +531,17 @@ function rgb(hex) {
return [(value >> 16) & 255, (value >> 8) & 255, value & 255];
}
+/** The tint over ground a test judged, before any rule has painted it. */
+const VEIL = [120, 170, 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.
+ * A tile's 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. With a `veil` the ground the
+ * test measured is tinted first, so a pixel no rule kept still reads as
+ * tested, and cloud or missing imagery stays clear.
*/
-export function paintMask(bits, { shown = [], hover = null, colours = RULE_COLOURS, alpha = 110 } = {}) {
+export function paintMask(bits, { shown = [], hover = null, colours = RULE_COLOURS, alpha = 110, veil = 0 } = {}) {
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);
@@ -408,6 +549,9 @@ export function paintMask(bits, { shown = [], hover = null, colours = RULE_COLOU
for (let p = 0; p < bits.length; p++) {
const value = bits[p];
if (!value) continue;
+ if (veil && value & (1 << MEASURED_BIT)) {
+ out[p * 4] = VEIL[0]; out[p * 4 + 1] = VEIL[1]; out[p * 4 + 2] = VEIL[2]; out[p * 4 + 3] = veil;
+ }
for (const i of order) {
if (!(value & (1 << i))) continue;
const [r, g, b] = tints[i % tints.length];
@@ -418,31 +562,13 @@ export function paintMask(bits, { shown = [], hover = null, colours = RULE_COLOU
}
/**
- * Keep a painted mask to the ground inside `bounds` ({ west, south, east, north }
- * in degrees), clearing every pixel outside. The mask covers `box`, its extent in
- * Web Mercator metres; both are aligned with the ground, so the kept part is a
- * pixel rectangle however the map is turned. Used while a check is open: it
- * judges its own frame, so the map paints nothing past it.
+ * Which part of a split map a rule is painted on: what reads the before pass
+ * on the before half, the after pass on the after half, and a change across
+ * both, since it belongs to neither. A map that is not split has one part.
*/
-export function clipToBounds(rgba, width, height, box, bounds) {
- const [west, north] = toMercator(bounds.west, bounds.north);
- const [east, south] = toMercator(bounds.east, bounds.south);
- const column = (x) => ((x - box.west) / (box.east - box.west)) * width;
- const row = (y) => ((box.north - y) / (box.north - box.south)) * height;
- const x0 = Math.max(0, Math.floor(column(west)));
- const x1 = Math.min(width, Math.ceil(column(east)));
- const y0 = Math.max(0, Math.floor(row(north)));
- const y1 = Math.min(height, Math.ceil(row(south)));
- const out = new Uint8ClampedArray(rgba.length);
- for (let y = y0; y < y1; y++) {
- out.set(rgba.subarray((y * width + x0) * 4, (y * width + x1) * 4), (y * width + x0) * 4);
- }
- return out;
-}
-
-/** Whether a [lon, lat] point is inside `bounds`. */
-export function insideBounds([lon, lat], bounds) {
- return lon >= bounds.west && lon <= bounds.east && lat >= bounds.south && lat <= bounds.north;
+export function sideOf(rule, split) {
+ if (!split) return 'shared';
+ return rule.on === 'a' ? 'before' : rule.on === 'b' ? 'after' : 'shared';
}
/** A share of the measured ground, as the funnel prints it. */
@@ -480,29 +606,64 @@ export function signature(recipe) {
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 }) {
+/** A check on the passes shown, with the pins dropped on them so far. */
+export function newCheck({ name, a = {}, b = { date: '' }, marks = [] }) {
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 };
+ return { id, name, a: { ...a }, b: { ...b }, marks: marks.map((mark) => ({ ...mark, point: [...mark.point] })), 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.
- */
+/** A check with one more pin. Its last result goes, since it answered for the pins 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 };
+ return { ...check, marks: [...check.marks, { point: [point[0], point[1]], expect }], result: null };
}
export function withoutMark(check, index) {
return { ...check, marks: check.marks.filter((_, i) => i !== index), result: null };
}
+/** A check with one pin turned the other way: where it should be found, or where none should. */
+export function withFlippedMark(check, index) {
+ const marks = check.marks.map((mark, i) => (i === index ? { ...mark, expect: mark.expect === 'found' ? 'empty' : 'found' } : mark));
+ return { ...check, marks, result: null };
+}
+
+/** Whether a check has the passes this analyzer reads: the after pass, and the before one when it has two dates. */
+export const checkDated = (recipe, check) => !!check.b?.date && (readsOneDate(recipe) || !!check.a?.date);
+
+/** The box round a check's pins, widened so one pin alone still frames some ground. */
+export function marksBounds(marks, margin = 0.004) {
+ const lons = marks.map((mark) => mark.point[0]);
+ const lats = marks.map((mark) => mark.point[1]);
+ return { west: Math.min(...lons) - margin, east: Math.max(...lons) + margin,
+ south: Math.min(...lats) - margin, north: Math.max(...lats) + margin };
+}
+
+const passKey = (source) => [source?.provider ?? '', source?.date ?? '', source?.time ?? ''];
+
+/**
+ * What a check reads, for telling whether its last test still holds: its
+ * passes and its pins. The layer they are shown in is how they look, not what
+ * is read, so it is not in it.
+ */
+export const checkKey = (check) => canonical({ a: passKey(check.a), b: passKey(check.b),
+ marks: (check.marks ?? []).map((mark) => [mark.point, mark.expect]) });
+
+/** The recipe a test is asked with: what the rules read, and nothing that only names or colours them. */
+export function readingRecipe(recipe) {
+ return { name: 'Test', method: 'rules', sensor: sensorOf(recipe), dates: datesOf(recipe),
+ rules: recipe.rules, match: recipe.match, parameters: recipe.parameters };
+}
+
+/** A check in the form a test is asked with: without the result it would be told. */
+export const testedCheck = (check) => ({ ...check, result: null });
+
+/** A pass as a source the engine reads: Sentinel-2 in the layer it is shown in, or a radar pass at its time. */
+export function passSource(recipe, pass, layer = 'TRUE_COLOR') {
+ return readsRadar(recipe)
+ ? { provider: 'sentinel1', date: pass.date, time: pass.time ?? '' }
+ : { provider: 'sentinel2', date: pass.date, layer, maxcc: 100 };
+}
+
/** Mark by mark, whether it came out as expected, from the last result. */
export function markOutcomes(check) {
const covered = check.result?.covered ?? [];
@@ -511,23 +672,23 @@ export function markOutcomes(check) {
/**
* 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.
+ * 'fail' when one did not, 'unpinned' for a check with no pin yet, 'stale'
+ * when its last result was read with other rules, 'unrun' when it has none.
*/
export function checkState(check, current) {
+ if (!check.marks.length) return 'unpinned';
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'}`;
+ if (state === 'unpinned') return 'Needs a pin';
+ if (state === 'unrun') return 'Not tested yet';
+ if (state === 'stale') return 'Rules changed since its last test';
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');
@@ -540,13 +701,37 @@ export function describeOutcome(check, current) {
return parts.join(' · ');
}
+/**
+ * What the pins would have come to without one rule, in a few words, from
+ * whether each was on a candidate now and without it. A pin comes out right
+ * when a candidate is on it and it should be found, or none is and it should
+ * stay empty, so a rule that keeps pins right is one their count falls
+ * without, and one that loses pins is one it rises without.
+ */
+export function describeWithout(marks, covered, without) {
+ if (!without || !covered?.length || without.length !== marks.length) return '';
+ let wrong = 0;
+ let right = 0;
+ marks.forEach((mark, i) => {
+ const wanted = mark.expect === 'found';
+ const now = covered[i] === wanted;
+ const then = without[i] === wanted;
+ if (now && !then) wrong++;
+ else if (!now && then) right++;
+ });
+ if (!wrong && !right) return 'Without it, no pin changes.';
+ const pins = (n) => `${n} pin${n === 1 ? '' : 's'}`;
+ if (wrong && right) return `Without it, ${pins(right)} would come out right and ${wrong} wrong.`;
+ return right ? `Without it, ${pins(right)} would come out right.` : `Without it, ${pins(wrong)} would come out wrong.`;
+}
+
/** 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') };
+ return { total: states.length, pass: count('pass'), fail: count('fail'),
+ waiting: count('stale') + count('unrun') + count('unpinned') };
}
/** The summary as the library prints it under an analyzer. */
@@ -555,7 +740,7 @@ export function describeChecks(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 (waiting === total) return `${head} · not tested`;
if (pass && !waiting) return `${head} · all pass`;
return `${head} · ${pass} pass`;
}
@@ -590,3 +775,29 @@ export function suggestedLayer(rule, layers = []) {
}
return firstOf(wanted, ids) ?? fallback;
}
+
+// -- pins on a rule's line -----------------------------------------------------------
+
+const unit = (value) => Math.max(0, Math.min(1, value));
+
+/**
+ * Where each pin's reading falls along a rule's slider, 0 to 1, so the line
+ * can be set between the pins that should come out and the ones that should
+ * not. A drop is measured as the size of the drop, so a pin where the ground
+ * rose sits at nothing. A reading past an end of the slider is pinned to that
+ * end. `readings` is what a test read under each pin, in the order of the
+ * check's pins.
+ */
+export function pinTicks(rule, marks, readings, index) {
+ if (rule.measure === 'class') return [];
+ const { factor, min, max } = lineScale(rule);
+ const ticks = [];
+ marks.forEach((mark, i) => {
+ const row = readings?.[i]?.rules?.[index];
+ if (!row || row.value === null || row.value === undefined || !Number.isFinite(row.value)) return;
+ const shown = amountOf(rule, row.value) * factor;
+ ticks.push({ pin: i, expect: mark.expect, at: unit((shown - min) / (max - min)),
+ clipped: shown < min || shown > max, value: row.value, passes: !!row.passes });
+ });
+ return ticks;
+}
diff --git a/frontend/src/lib/map/analyzerRules.test.js b/frontend/src/lib/map/analyzerRules.test.js
index f6504f8..35967d9 100644
--- a/frontend/src/lib/map/analyzerRules.test.js
+++ b/frontend/src/lib/map/analyzerRules.test.js
@@ -1,13 +1,14 @@
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,
- clipToBounds, insideBounds,
+ DEFAULT_PARAMETERS, KEPT_BIT, MEASURED_BIT, amountOf, describeReading, describeReads, describeRecipe, describeRule,
+ describeWithout, directionOf, directionsFor, lineScale, shortRule, withAmount, withDirection,
+ formatShare, formatValue, fromDifference, measuresFor, newRecipe, newRule, paintMask, passSource,
+ pinTicks, productCount, readingRecipe, recipeBands, recipeCapability, recipeProblem, retarget, savingProblem,
+ scaleOf, sideOf, signalOf, toEngine, whensFor,
+ checkDated, checkKey, checkState, checksSummary, describeChecks, describeOutcome, marksBounds, markOutcomes,
+ newCheck, signature, testedCheck, withFlippedMark, withMark, withoutMark,
} from './analyzerRules.js';
import { changeSettings } from './changeAssist.js';
-import { toMercator } from './groundFrame.js';
const METHODS = [
{ id: 'rules', single: false, clouds: true, sensor: 'sentinel2', frames: 4, sizes: { medium: { min_area: 2000, cleanup: 1 }, all: { min_area: 0, cleanup: 0 } }, rules: true },
@@ -15,7 +16,11 @@ const METHODS = [
{ id: 'vessels', single: true, clouds: true, sensor: 'sentinel2', frames: 2 },
];
-const recipe = (...rules) => ({ ...newRecipe(METHODS), rules });
+// A recipe that has not said what it reads, as one saved before it did: the rules tell.
+const recipe = (...rules) => {
+ const { sensor, dates, ...rest } = newRecipe(METHODS);
+ return { ...rest, rules };
+};
describe('a new rule', () => {
it('starts on the published line for what it measures', () => {
@@ -46,11 +51,52 @@ describe('a new rule', () => {
expect(retarget(tuned, { op: 'moved' }).value).toBe(0.4);
expect(retarget(newRule('index', 'b'), { measure: 'class' })).toMatchObject({ on: 'b', op: 'is' });
});
+});
+
+describe('saying a rule’s line', () => {
+ const labels = (rule) => directionsFor(rule).map(([, label]) => label);
+
+ it('offers a change a drop, a rise or a move, and a state at least or at most', () => {
+ expect(labels(newRule('index', 'change'))).toEqual(['Dropped', 'Rose', 'Either way', 'Between']);
+ expect(labels(newRule('index', 'a'))).toEqual(['At least', 'At most', 'Between']);
+ expect(labels(newRule('colour', 'change'))).toEqual(['At least', 'At most', 'Between']);
+ expect(labels(newRule('class', 'b'))).toEqual(['Is', 'Is not']);
+ });
+
+ it('reads the direction off the operator and the sign, and back', () => {
+ const drop = newRule('index', 'change'); // at most -0.25
+ expect(directionOf(drop)).toBe('drop');
+ expect(directionOf({ ...drop, op: 'ge', value: 0.25 })).toBe('rise');
+ expect(directionOf({ ...drop, op: 'moved', value: 0.25 })).toBe('moved');
+ expect(directionOf({ ...drop, op: 'between', upper: 0 })).toBe('between');
+ expect(directionOf(newRule('index', 'a'))).toBe('ge');
+ expect(directionOf(newRule('class', 'b'))).toBe('is');
+ const rise = withDirection(drop, 'rise');
+ expect(rise).toMatchObject({ op: 'ge', value: 0.25 });
+ expect(withDirection(rise, 'drop')).toMatchObject({ op: 'le', value: -0.25 });
+ expect(withDirection(rise, 'moved')).toMatchObject({ op: 'moved', value: 0.25 });
+ expect(withDirection(rise, 'between').upper).toBeGreaterThan(0.25);
+ expect(withDirection(newRule('index', 'a'), 'le')).toMatchObject({ op: 'le', value: 0.4 });
+ });
- 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']);
+ it('sets a line by the size of the drop, and keeps the sign the direction needs', () => {
+ const drop = newRule('index', 'change');
+ expect(amountOf(drop)).toBe(0.25);
+ expect(withAmount(drop, 0.4)).toBe(-0.4);
+ expect(withAmount({ ...drop, op: 'ge' }, 0.4)).toBe(0.4);
+ expect(amountOf({ ...drop, op: 'moved', value: 0.3 })).toBe(0.3);
+ // a state, a colour distance and a range are the value itself
+ expect(amountOf(newRule('index', 'a'))).toBe(0.4);
+ expect(amountOf(newRule('colour', 'change'))).toBe(0.05);
+ expect(withAmount({ ...drop, op: 'between', value: -0.4 }, -0.1)).toBe(-0.1);
+ });
+
+ it('runs a drop’s slider from nothing up, and a state’s across its whole range', () => {
+ expect(lineScale(newRule('index', 'change'))).toMatchObject({ min: 0, max: 1 });
+ expect(lineScale(newRule('band', 'change'))).toMatchObject({ min: 0, max: 50, suffix: '%' });
+ expect(lineScale(newRule('radar', 'change'))).toMatchObject({ min: 0, max: 20 });
+ expect(lineScale(newRule('index', 'a'))).toMatchObject({ min: -1, max: 1 });
+ expect(lineScale({ ...newRule('index', 'change'), op: 'between', upper: 0 })).toMatchObject({ min: -1, max: 1 });
});
});
@@ -86,6 +132,50 @@ describe('what a recipe reads', () => {
expect(recipeCapability({ method: 'vessels' }, METHODS)).toBe(METHODS[2]);
});
+ it('keeps to what it declared when it was made, and works it out only when it never did', () => {
+ const declared = newRecipe(METHODS, { sensor: 'sentinel1', dates: 'two' });
+ expect(recipeCapability(declared, METHODS)).toMatchObject({ sensor: 'sentinel1', single: false, clouds: false });
+ // one date, declared, whatever a rule says: the rules have to agree, not the other way round
+ const one = { ...newRecipe(METHODS, { dates: 'one' }), rules: [newRule('band', 'change')] };
+ expect(recipeCapability(one, METHODS).single).toBe(true);
+ expect(recipeProblem(one)).toMatch(/no before pass for this rule/);
+ const two = { ...newRecipe(METHODS), rules: [newRule('band', 'b')] };
+ expect(recipeProblem(two)).toMatch(/before date or on the change/);
+ expect(recipeProblem({ ...newRecipe(METHODS), rules: [newRule('radar', 'change')] })).toBe('Radar rules need a radar analyzer.');
+ expect(recipeProblem({ ...declared, rules: [newRule('index', 'change')] })).toBe('Optical rules need a Sentinel-2 analyzer.');
+ expect(describeReads(declared)).toBe('Sentinel-1 radar · two dates');
+ expect(describeReads(newRecipe(METHODS, { dates: 'one' }))).toBe('Sentinel-2 · one date');
+ expect(describeReads(recipe(newRule('band', 'b')))).toBe('Sentinel-2 · one date');
+ });
+
+ it('offers a rule only the measures and dates its analyzer can use', () => {
+ expect(measuresFor(newRecipe(METHODS)).map((measure) => measure.id)).not.toContain('radar');
+ expect(measuresFor(newRecipe(METHODS, { sensor: 'sentinel1' })).map((measure) => measure.id)).toEqual(['radar']);
+ // a colour distance is a change, which one date does not have
+ expect(measuresFor(newRecipe(METHODS)).map((measure) => measure.id)).toContain('colour');
+ expect(measuresFor(newRecipe(METHODS, { dates: 'one' })).map((measure) => measure.id)).not.toContain('colour');
+ const two = newRecipe(METHODS);
+ expect(whensFor(two, newRule('index', 'b')).map(([id]) => id)).toEqual(['a', 'b', 'change']);
+ expect(whensFor(two, newRule('class', 'b')).map(([id]) => id)).toEqual(['a', 'b']);
+ expect(whensFor(two, newRule('colour', 'b')).map(([id]) => id)).toEqual(['change']);
+ expect(whensFor(newRecipe(METHODS, { dates: 'one' }), newRule('index', 'b'))).toEqual([]);
+ expect(whensFor(two, newRule('index', 'b')).map(([, label]) => label)).toEqual(['Before', 'After', 'Change']);
+ });
+
+ it('starts every kind of analyzer on a rule it can run', () => {
+ for (const sensor of ['sentinel2', 'sentinel1']) {
+ for (const dates of ['one', 'two']) {
+ const made = newRecipe(METHODS, { sensor, dates });
+ expect(recipeProblem(made), `${sensor} ${dates}`).toBe('');
+ expect([made.sensor, made.dates]).toEqual([sensor, dates]);
+ }
+ }
+ // radar starts from radar change's averaging, which is what keeps speckle from reading as a target
+ expect(newRecipe(METHODS, { sensor: 'sentinel1' }).parameters.smoothing).toBe(0);
+ const radarSizes = METHODS.map((method) => (method.id === 'sar-change' ? { ...method, sizes: { all: { smoothing: 2, min_area: 0 } } } : method));
+ expect(newRecipe(radarSizes, { sensor: 'sentinel1' }).parameters.smoothing).toBe(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/);
@@ -105,20 +195,35 @@ 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('index', 'a'))).toBe('NDVI before is at least 0.40');
+ expect(describeRule(newRule('index', 'a'), { single: true })).toBe('NDVI is at least 0.40');
+ expect(describeRule(newRule('band', 'b', { band: 'B12' }))).toBe('B12 (short-wave 2.2 µm) after is 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');
+ .toBe('B08 (near infrared) after is 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/);
+ .toBe('ground after is not water or bare ground');
+ expect(describeRule({ ...newRule('class', 'b'), classes: ['water'] }, { single: true })).toBe('ground is water');
+ expect(describeRule(newRule('nd', 'b', { bands: ['B8A', 'B11'] }))).toMatch(/^NDMI after is/);
expect(describeRule(newRule('radar', 'change'))).toBe('VV moved by 3.0 dB or more either way');
});
+ it('names a rule in a couple of words for its chip on the map', () => {
+ expect(shortRule(newRule('index', 'change'))).toBe('NDVI change');
+ expect(shortRule(newRule('index', 'a'))).toBe('NDVI before');
+ expect(shortRule(newRule('band', 'b', { band: 'B12' }))).toBe('B12 after');
+ expect(shortRule(newRule('nd', 'b', { bands: ['B8A', 'B11'] }))).toBe('NDMI after');
+ expect(shortRule(newRule('nd', 'b', { bands: ['B02', 'B11'] }))).toBe('B02/B11 after');
+ expect(shortRule(newRule('class', 'b'))).toBe('ground after');
+ expect(shortRule(newRule('colour', 'change'))).toBe('colour change');
+ expect(shortRule(newRule('radar', 'change', { polarisation: 'ratio' }))).toBe('VV − VH change');
+ expect(shortRule(newRule('band', 'b', { band: 'B12' }), { single: true })).toBe('B12');
+ });
+
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/);
+ expect(describeRecipe(built)).toBe('Keeps ground where NDVI dropped by 0.25 or more and NDVI before is at least 0.40, outside cloud.');
+ expect(describeRecipe(recipe(newRule('band', 'b')))).toBe('Keeps ground where B08 (near infrared) is at least 25.0%, outside cloud.');
+ expect(describeRecipe({ ...built, match: 'any' })).toMatch(/or NDVI before is/);
});
it('words a candidate from its signal rule', () => {
@@ -146,12 +251,13 @@ describe('from Difference', () => {
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([built.sensor, built.dates]).toEqual(['sentinel2', 'two']);
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', () => {
+describe('the test 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'];
@@ -166,6 +272,66 @@ describe('the preview mask', () => {
expect(hovered[15]).toBeGreaterThan(both[15]);
expect([...hovered.slice(12, 15)]).toEqual([255, 0, 0]);
});
+
+ it('tints the ground a test measured, under the rules, and leaves cloud and missing imagery clear', () => {
+ const bits = new Uint8Array([0, 1 << MEASURED_BIT, 0b1 | (1 << MEASURED_BIT)]);
+ const tinted = paintMask(bits, { shown: [true], colours: ['#ff0000'], veil: 30 });
+ expect([...tinted.slice(0, 4)]).toEqual([0, 0, 0, 0]); // not measured: clear
+ expect(tinted[7]).toBe(30); // measured, no rule: the veil alone
+ expect([...tinted.slice(8, 12)]).toEqual([255, 0, 0, 110]); // a rule over the veil
+ // no veil unless asked for, so the parts of a split map do not tint twice
+ expect(paintMask(bits, { shown: [true], colours: ['#ff0000'] })[7]).toBe(0);
+ // a rule hidden on the map leaves the veil
+ expect(paintMask(bits, { shown: [false], colours: ['#ff0000'], veil: 30 })[11]).toBe(30);
+ });
+
+ it('puts a rule on the half of a split map it reads, and a change across both', () => {
+ const before = newRule('index', 'a');
+ const after = newRule('index', 'b');
+ const change = newRule('index', 'change');
+ expect([before, after, change].map((rule) => sideOf(rule, true))).toEqual(['before', 'after', 'shared']);
+ expect([before, after, change].map((rule) => sideOf(rule, false))).toEqual(['shared', 'shared', 'shared']);
+ });
+});
+
+describe('pins on a rule’s line', () => {
+ const marks = [{ point: [2, 48], expect: 'found' }, { point: [2.01, 48], expect: 'empty' }, { point: [2.02, 48], expect: 'found' }];
+ const readings = [
+ { rules: [{ passes: true, value: -0.6 }] },
+ { rules: [{ passes: false, value: -0.05 }] },
+ { rules: [{ passes: true, value: -1.4 }] },
+ ];
+
+ it('places each pin’s reading along the slider, pinned to an end when it lies past it', () => {
+ const rule = newRule('index', 'a'); // a state: the slider runs -1 to 1
+ const ticks = pinTicks(rule, marks, readings, 0);
+ expect(ticks.map((tick) => [tick.pin, tick.expect, tick.passes])).toEqual([[0, 'found', true], [1, 'empty', false], [2, 'found', true]]);
+ expect(ticks[0].at).toBeCloseTo(0.2);
+ expect(ticks[1].at).toBeCloseTo(0.475);
+ expect(ticks[2]).toMatchObject({ at: 0, clipped: true });
+ expect(ticks[0].clipped).toBe(false);
+ });
+
+ it('measures a drop by its size, so a pin where the ground rose sits at nothing', () => {
+ const drop = newRule('index', 'change'); // the slider runs 0 to 1
+ const ticks = pinTicks(drop, marks, [{ rules: [{ value: -0.6 }] }, { rules: [{ value: 0.1 }] }, { rules: [{ value: -1.4 }] }], 0);
+ expect(ticks[0]).toMatchObject({ at: expect.closeTo(0.6), clipped: false });
+ expect(ticks[1]).toMatchObject({ at: 0, clipped: true });
+ expect(ticks[2]).toMatchObject({ at: 1, clipped: true });
+ });
+
+ it('reads the size of a move either way, and in the units the slider shows', () => {
+ const moved = { ...newRule('index', 'change'), op: 'moved', value: 0.2 };
+ expect(pinTicks(moved, marks, readings, 0)[0].at).toBeCloseTo(0.6); // |-0.6| on a 0 to 1 slider
+ const band = newRule('band', 'b'); // percent, 0 to 100
+ expect(pinTicks(band, [marks[0]], [{ rules: [{ passes: true, value: 0.25 }] }], 0)[0].at).toBeCloseTo(0.25);
+ });
+
+ it('draws nothing for a ground class, an unread pin or a reading off the ground', () => {
+ expect(pinTicks(newRule('class', 'b'), marks, readings, 0)).toEqual([]);
+ expect(pinTicks(newRule('index', 'change'), marks, [], 0)).toEqual([]);
+ expect(pinTicks(newRule('index', 'change'), [marks[0]], [{ rules: [{ passes: false, value: null }] }], 0)).toEqual([]);
+ });
});
describe('layers', () => {
@@ -184,8 +350,9 @@ describe('layers', () => {
});
describe('checks', () => {
- const place = { west: 2, south: 48, east: 2.02, north: 48.02 };
const pass = (date) => ({ provider: 'sentinel2', date, layer: 'SWIR' });
+ const pins = [{ point: [2.01, 48.01], expect: 'found' }, { point: [2.015, 48.01], expect: 'found' },
+ { point: [2.005, 48.005], expect: 'empty' }];
it('reads the same signature whatever order the recipe’s keys come in', () => {
const built = recipe(newRule('index', 'change'));
@@ -199,44 +366,89 @@ describe('checks', () => {
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 });
+ it('is its passes and its pins, with no frame of its own', () => {
+ const check = newCheck({ name: 'Here', a: pass('2023-08-08'), b: pass('2023-08-13') });
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' } });
+ expect(check).not.toHaveProperty('bounds');
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(marked.result).toBe(null); // it answered for the pins it had
expect(withoutMark(marked, 0).marks).toEqual([]);
+ const flipped = withFlippedMark(withMark(marked, [2.06, 48.01], 'found'), 0);
+ expect(flipped.marks.map((mark) => mark.expect)).toEqual(['found', 'found']);
+ // what it is made from is copied, so the pin on the map is not the one in the list
+ const copied = newCheck({ name: 'Copy', marks: pins });
+ copied.marks[0].point[0] = 0;
+ expect(pins[0].point[0]).toBe(2.01);
+ });
+
+ it('tells a check from another by the passes and pins it is read on, and nothing else', () => {
+ const one = newCheck({ name: 'One', a: pass('2023-08-08'), b: pass('2023-08-13'), marks: pins });
+ expect(checkKey({ ...one, name: 'Renamed', id: 'other', result: { signature: 'x', count: 1, covered: [] } })).toBe(checkKey(one));
+ expect(checkKey(withMark(one, [2.02, 48.02], 'found'))).not.toBe(checkKey(one));
+ expect(checkKey({ ...one, b: pass('2023-08-14') })).not.toBe(checkKey(one));
+ // how the passes are shown is not what is read
+ expect(checkKey({ ...one, a: { ...one.a, layer: 'NDVI' }, b: { ...one.b, layer: 'NDVI' } })).toBe(checkKey(one));
+ expect(testedCheck(one).result).toBe(null);
+ });
+
+ it('has the passes its analyzer reads', () => {
+ const two = recipe(newRule('index', 'change'));
+ const one = recipe(newRule('band', 'b'));
+ const after = { b: pass('2023-08-13') };
+ expect(checkDated(two, newCheck({ name: 'x', ...after }))).toBe(false);
+ expect(checkDated(two, newCheck({ name: 'x', a: pass('2023-08-08'), ...after }))).toBe(true);
+ expect(checkDated(one, newCheck({ name: 'x', ...after }))).toBe(true);
+ expect(checkDated(one, newCheck({ name: 'x' }))).toBe(false);
+ });
+
+ it('turns a source into the pass the engine reads, in the layer it is shown in', () => {
+ const optical = recipe(newRule('index', 'change'));
+ expect(passSource(optical, { date: '2023-08-13' }, 'SWIR')).toEqual({ provider: 'sentinel2', date: '2023-08-13', layer: 'SWIR', maxcc: 100 });
+ const radar = newRecipe(METHODS, { sensor: 'sentinel1' });
+ expect(passSource(radar, { date: '2023-08-13', time: '05:30:12' }, 'SWIR')).toEqual({ provider: 'sentinel1', date: '2023-08-13', time: '05:30:12' });
+ expect(passSource(radar, { date: '2023-08-13' })).toEqual({ provider: 'sentinel1', date: '2023-08-13', time: '' });
+ });
+
+ it('asks a test only for what reads, and frames the pins', () => {
+ const built = { ...newRecipe(METHODS), name: 'Mine', description: 'x', colour: '#ff0000', checks: [{ id: 'a' }], rules: [newRule('index', 'change')] };
+ expect(readingRecipe(built)).toEqual({ name: 'Test', method: 'rules', sensor: 'sentinel2', dates: 'two',
+ rules: built.rules, match: 'all', parameters: built.parameters });
+ const box = marksBounds(pins);
+ expect(box.west).toBeLessThan(2.005);
+ expect(box.east).toBeGreaterThan(2.015);
+ const alone = marksBounds([pins[0]]);
+ expect(alone.east - alone.west).toBeGreaterThan(0);
});
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 base = newCheck({ name: 'Here', a: pass('2023-08-08'), b: pass('2023-08-13'), marks: pins });
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(describeOutcome(base, current)).toBe('Not tested 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');
+ expect(describeOutcome(read([true, true, false], 3, 'old'), current)).toBe('Rules changed since its last test');
+ // one saved with no pin, before a check was pins alone, cannot be tested until it has one
+ const bare = { ...base, marks: [] };
+ expect(checkState(bare, current)).toBe('unpinned');
+ expect(describeOutcome(bare, current)).toBe('Needs a pin');
});
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 });
+ 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(null), check(null)] })).toBe('2 checks · not tested');
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');
@@ -244,33 +456,59 @@ describe('checks', () => {
});
});
+describe('what the pins would come to without a rule', () => {
+ const pins = [{ point: [2, 48], expect: 'found' }, { point: [2.1, 48], expect: 'empty' }, { point: [2.2, 48], expect: 'empty' }];
+
+ it('says a rule helps when pins would come out wrong without it', () => {
+ // now: found on the first, none on the others. Without it: the trap is flagged too.
+ expect(describeWithout(pins, [true, false, false], [true, true, false])).toBe('Without it, 1 pin would come out wrong.');
+ expect(describeWithout(pins, [true, false, false], [true, true, true])).toBe('Without it, 2 pins would come out wrong.');
+ });
+
+ it('says a rule hurts when pins would come out right without it', () => {
+ // now: the plot is lost and a trap is flagged. Without it: both come out right.
+ expect(describeWithout(pins, [false, true, false], [true, false, false])).toBe('Without it, 2 pins would come out right.');
+ expect(describeWithout(pins, [false, false, false], [true, false, false])).toBe('Without it, 1 pin would come out right.');
+ });
+
+ it('says both when it does both, and that nothing changes when nothing does', () => {
+ expect(describeWithout(pins, [false, false, false], [true, true, false])).toBe('Without it, 1 pin would come out right and 1 wrong.');
+ expect(describeWithout(pins, [true, false, false], [true, false, false])).toBe('Without it, no pin changes.');
+ });
+
+ it('says nothing without an answer for every pin', () => {
+ expect(describeWithout(pins, [true, false, false], undefined)).toBe('');
+ expect(describeWithout(pins, [true, false, false], [true])).toBe('');
+ expect(describeWithout(pins, [], [true, false, false])).toBe('');
+ });
+});
-describe('an open check keeps the preview to its frame', () => {
- // A 4x4 mask over a box of four degrees a side, every pixel painted.
- const [west, north] = toMercator(0, 4);
- const [east, south] = toMercator(4, 0);
- const box = { west, east, north, south };
- const painted = () => new Uint8ClampedArray(4 * 4 * 4).fill(255);
- const alphaAt = (rgba, x, y) => rgba[(y * 4 + x) * 4 + 3];
+describe('what stops an analyzer being saved', () => {
+ const built = (...checks) => ({ ...newRecipe(METHODS), name: 'Mine', checks });
+ const good = () => newCheck({ name: 'Plot', a: { date: '2023-08-08' }, b: { date: '2023-08-13' },
+ marks: [{ point: [2.01, 48.01], expect: 'found' }] });
- it('clears every pixel outside the frame and keeps the ones inside', () => {
- // the frame covers the west half, full height
- const kept = clipToBounds(painted(), 4, 4, box, { west: 0, south: 0, east: 2, north: 4 });
- expect([0, 1].every((x) => [0, 1, 2, 3].every((y) => alphaAt(kept, x, y) === 255))).toBe(true);
- expect([2, 3].every((x) => [0, 1, 2, 3].every((y) => alphaAt(kept, x, y) === 0))).toBe(true);
+ it('needs a check, and one with a pin where something should be found', () => {
+ expect(savingProblem(built())).toMatch(/Add a check/);
+ expect(savingProblem(built(good()))).toBe('');
+ const trap = newCheck({ name: 'Reef', a: { date: '2023-08-08' }, b: { date: '2023-08-13' },
+ marks: [{ point: [2.03, 48.01], expect: 'empty' }] });
+ // a place where nothing may be found proves a rule, but something has to be found somewhere
+ expect(savingProblem(built(trap))).toMatch(/something should be found/);
+ expect(savingProblem(built(good(), trap))).toBe('');
});
- it('keeps nothing when the frame is off the mask, and everything when it holds it', () => {
- const off = clipToBounds(painted(), 4, 4, box, { west: 10, south: 10, east: 12, north: 12 });
- expect(off.every((value) => value === 0)).toBe(true);
- const all = clipToBounds(painted(), 4, 4, box, { west: -1, south: -1, east: 5, north: 5 });
- expect(all.every((value) => value === 255)).toBe(true);
+ it('names the check that is missing its pin or its passes', () => {
+ expect(savingProblem(built({ ...good(), marks: [] }))).toBe('The check “Plot” needs a pin.');
+ expect(savingProblem(built({ ...good(), a: {} }))).toBe('The check “Plot” needs its passes.');
+ expect(savingProblem(built({ ...good(), b: { date: '' } }))).toBe('The check “Plot” needs its passes.');
+ // one date needs only the after pass
+ const single = { ...newRecipe(METHODS, { dates: 'one' }), name: 'Mine', checks: [{ ...good(), a: {} }] };
+ expect(savingProblem(single)).toBe('');
});
- it('says whether a candidate stands inside the frame', () => {
- const frame = { west: 0, south: 0, east: 2, north: 4 };
- expect(insideBounds([1, 2], frame)).toBe(true);
- expect(insideBounds([3, 2], frame)).toBe(false);
- expect(insideBounds([1, 5], frame)).toBe(false);
+ it('puts a problem with the rules first, so the fix is where the eye is', () => {
+ const broken = { ...built(good()), rules: [] };
+ expect(savingProblem(broken)).toMatch(/Add a rule/);
});
});
diff --git a/frontend/src/lib/map/bench.svelte.js b/frontend/src/lib/map/bench.svelte.js
new file mode 100644
index 0000000..34855c9
--- /dev/null
+++ b/frontend/src/lib/map/bench.svelte.js
@@ -0,0 +1,679 @@
+/**
+ * The bench an analyzer of your own is built on.
+ *
+ * A check is a pair of passes and the pins laid on them, and the map is where
+ * it lives: one check is on the bench at a time, its passes are the imagery,
+ * its pins are dropped by a click, and a press of Test runs the rules on the
+ * ground under the pins and paints what they kept. The bench holds what the
+ * map and the panel both need to agree on: which check, the pins being
+ * dropped, the passes under them, the last test and whether it still holds.
+ *
+ * Nothing reaches Copernicus unasked. Finding passes, and testing with frames
+ * the cache lacks, are presses; the cost of the next test is asked of the
+ * engine beforehand (`/check/plan`, which fetches nothing) and said on the
+ * button, and a test that changes a rule is never run by itself.
+ *
+ * The map shows what `imagery` asks for and draws `detail`, `pins` and
+ * `probe`; the panel shows the rules and the list of checks. Both call the
+ * methods here, so neither needs to know the other.
+ */
+import { untrack } from 'svelte';
+import { acquisitionQuery, olderSpan, withOlder } from './acquisitions.js';
+import { clone, viewZone } from './analyzers.js';
+import { canPickPass } from './detectWhen.js';
+import { isoDay } from '../sentinel.js';
+import {
+ RULE_COLOURS, checkDated, checkKey, datesOf, markOutcomes, marksBounds, newCheck, passSource, readingRecipe,
+ readsOneDate, readsRadar, recipeBands, recipeProblem, sensorOf, signalOf, signature, suggestedLayer, testedCheck,
+ withFlippedMark, withMark, withoutMark,
+} from './analyzerRules.js';
+
+/** What a configuration that has not answered yet still offers. */
+const STANDARD_LAYERS = Object.freeze([
+ { 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)' },
+]);
+
+/** A lookup looks at the ground round the middle of the map, never a whole country. */
+const LOOKUP_REACH = 0.15;
+
+const lon = (value) => Math.max(-180, Math.min(180, value));
+const lat = (value) => Math.max(-85, Math.min(85, value));
+
+/** The ground a pass lookup covers: the view, held to a small box round its middle. */
+export function lookupBounds(view) {
+ if (!view) return null;
+ const middle = [(view.west + view.east) / 2, (view.south + view.north) / 2];
+ const half = [Math.min((view.east - view.west) / 2, LOOKUP_REACH), Math.min((view.north - view.south) / 2, LOOKUP_REACH)];
+ return { west: lon(middle[0] - half[0]), south: lat(middle[1] - half[1]), east: lon(middle[0] + half[0]), north: lat(middle[1] + half[1]) };
+}
+
+export class Bench {
+ #api;
+ #recipe;
+ #limits;
+ #layers;
+ #viewBounds;
+ #fly;
+ #say;
+ #dispose;
+ #gone = false;
+ #returnTo = null;
+ #lookups = 0;
+ #probes = 0;
+ #calendars = 0;
+ #months = new Map();
+
+ /** The id of the saved check on the bench, or null for the basemap alone. */
+ selected = $state(null);
+ /** A check being made: `{ step: 'passes' | 'pins', check }`. The panel waits for it. */
+ draft = $state(null);
+ /** The passes of a saved check are being changed. */
+ editingPasses = $state(false);
+ /** The pin a click on the map drops: 'found', 'empty' or null. */
+ pinning = $state(null);
+ /** The basemap instead of the passes, for a check that has them. */
+ basemap = $state(false);
+ layer = $state('TRUE_COLOR');
+ /** Where the split sits, as a percentage of the map from its left edge. */
+ divider = $state(50);
+ /** What the map paints: each rule's pixels, or the detections alone. */
+ view = $state('rules');
+ /** Per rule, whether its pixels are painted. One added since the last toggle is shown. */
+ shown = $state([]);
+ hover = $state(null);
+ probe = $state(null);
+ passes = $state({ list: [], lookback: 90, busy: false, error: '', searched: false, truncated: false });
+ /** The calendar a day is picked from: which side it is for, and the passes of the month shown. */
+ calendar = $state({ side: '', list: [], busy: false, error: '' });
+ /** Per check id: what testing it costs, `{ key, tiles, missing, busy, error }`. */
+ plans = $state({});
+ /** Per check id: its last test, `{ busy, error, detail, signature, key }`. */
+ tests = $state({});
+ /** What Test all is doing, or ''. */
+ running = $state('');
+ /** How much of the map's bottom edge the console covers, in pixels, for a card to keep clear of it. */
+ reach = $state(0);
+
+ constructor({ api, recipe, limits = {}, layers = () => [], viewBounds = () => null, fly = () => {}, say = () => {} }) {
+ this.#api = api;
+ this.#recipe = recipe;
+ this.#limits = limits;
+ this.#layers = layers;
+ this.#viewBounds = viewBounds;
+ this.#fly = fly;
+ this.#say = say;
+ this.layer = this.#suggested();
+ // The cost of the next test follows what it would read, and nothing else:
+ // a line moved on a slider costs no request and asks no question.
+ this.#dispose = $effect.root(() => {
+ $effect(() => {
+ const keys = this.planKeys;
+ const timer = setTimeout(() => untrack(() => void this.#refreshPlans(keys)), 250);
+ return () => clearTimeout(timer);
+ });
+ });
+ }
+
+ destroy() {
+ this.#gone = true;
+ this.#dispose?.();
+ }
+
+ // -- what is being built ---------------------------------------------------------
+
+ get recipe() { return this.#recipe; }
+ get radar() { return readsRadar(this.#recipe); }
+ get single() { return readsOneDate(this.#recipe); }
+ get problem() { return recipeProblem(this.#recipe, this.#limits); }
+ get current() { return signature(this.#recipe); }
+ get colours() { return RULE_COLOURS; }
+ /** The Copernicus layers the configuration offers, or the standard four. */
+ get offered() {
+ const layers = this.#layers();
+ return layers.length ? layers : STANDARD_LAYERS;
+ }
+
+ /** The panel waits while a check is being made: nothing else is touched until it is valid. */
+ get locked() { return !!this.draft; }
+ get checks() { return this.#recipe.checks; }
+ get atMostChecks() { return this.#recipe.checks.length >= (this.#limits.max_checks ?? 12); }
+
+ /** The check on the bench: the one being made, or the saved one picked. */
+ get check() {
+ if (this.draft) return this.draft.check;
+ return this.#recipe.checks.find((check) => check.id === this.selected) ?? null;
+ }
+ get marks() { return this.check?.marks ?? []; }
+ get dated() { return !!this.check && checkDated(this.#recipe, this.check); }
+ get canFinish() { return !!this.draft && this.dated && this.marks.length > 0; }
+ /** Whether the passes are being chosen, for a check being made or one already kept. */
+ get choosingPasses() { return this.draft?.step === 'passes' || this.editingPasses; }
+
+ // -- choosing a check ------------------------------------------------------------
+
+ /** Put a saved check on the bench and go to its pins; null puts the basemap back alone. */
+ select(id, { frame = true } = {}) {
+ if (this.draft) return;
+ this.editingPasses = false;
+ this.selected = id;
+ this.pinning = null;
+ this.probe = null;
+ this.basemap = false;
+ const check = this.#recipe.checks.find((entry) => entry.id === id);
+ if (!check) return;
+ this.#adoptLayer(check);
+ if (frame) this.#frame(check);
+ }
+
+ /** A new check, where the map is: passes first, then the pins. */
+ startDraft() {
+ if (this.draft || this.atMostChecks) return;
+ this.#returnTo = this.selected;
+ this.selected = null;
+ this.pinning = null;
+ this.probe = null;
+ this.basemap = false;
+ this.passes = { ...this.passes, list: [], searched: false, truncated: false, error: '' };
+ this.draft = { step: 'passes', check: newCheck({ name: this.#freeName() }) };
+ }
+
+ /** From the passes to the pins. */
+ continueDraft() {
+ if (!this.draft || !this.dated) return;
+ this.draft.step = 'pins';
+ this.pinning = 'found';
+ }
+
+ finishDraft() {
+ if (!this.canFinish) return;
+ const { check } = this.draft;
+ this.#recipe.checks = [...this.#recipe.checks, clone(check)];
+ this.draft = null;
+ this.pinning = null;
+ this.selected = check.id;
+ }
+
+ cancelDraft() {
+ if (!this.draft) return;
+ this.draft = null;
+ this.pinning = null;
+ this.selected = this.#returnTo;
+ this.#returnTo = null;
+ }
+
+ /** Open the passes of the check on the bench again, to change them. */
+ changePasses() {
+ if (this.draft) {
+ this.draft.step = 'passes';
+ this.pinning = null;
+ } else if (this.check) {
+ this.editingPasses = true;
+ this.pinning = null;
+ }
+ }
+
+ closePasses() {
+ if (this.draft) {
+ if (this.dated) this.continueDraft();
+ } else {
+ this.editingPasses = false;
+ }
+ }
+
+ /** The name of the check being made, as it is typed. */
+ nameDraft(name) {
+ if (this.draft) this.draft.check.name = name;
+ }
+
+ rename(id, name) {
+ const text = name.trim();
+ if (!text) return;
+ this.#recipe.checks = this.#recipe.checks.map((check) => (check.id === id ? { ...check, name: text } : check));
+ }
+
+ remove(id) {
+ this.#recipe.checks = this.#recipe.checks.filter((check) => check.id !== id);
+ if (this.selected === id) this.select(null);
+ delete this.tests[id];
+ delete this.plans[id];
+ }
+
+ // -- passes ----------------------------------------------------------------------
+
+ /** Use a pass for one side of the check on the bench: 'a' is Before, 'b' After. */
+ setPass(side, pass) {
+ this.#patch((check) => ({ ...check, [side]: passSource(this.#recipe, pass, this.layer), result: null }));
+ this.basemap = false;
+ }
+
+ /** The passes the ground round the middle of the map has, newest first. */
+ lookUpPasses(lookback = this.passes.lookback) {
+ this.passes = { ...this.passes, lookback };
+ return typeof lookback === 'number' ? this.#search(lookback, false) : undefined;
+ }
+
+ lookOlder() {
+ return this.#search(olderSpan(this.passes.lookback, this.passes.list), true);
+ }
+
+ async #search(span, more) {
+ const region = lookupBounds(this.#viewBounds());
+ if (!region || !span) return;
+ const mine = ++this.#lookups;
+ this.passes = { ...this.passes, busy: true, error: '' };
+ try {
+ const found = await this.#api.post('/api/satellite/sentinel/acquisitions',
+ acquisitionQuery([viewZone(region, 'Preview')], span, new Date(), this.radar ? 'sentinel1' : 'sentinel2'));
+ if (mine !== this.#lookups || this.#gone) return;
+ const list = more ? withOlder(this.passes.list, found.dates) : found.dates ?? [];
+ this.passes = { ...this.passes, list, searched: true, truncated: !!found.truncated };
+ } catch (error) {
+ if (mine === this.#lookups) this.passes = { ...this.passes, error: error.message };
+ } finally {
+ if (mine === this.#lookups) this.passes = { ...this.passes, busy: false };
+ }
+ }
+
+ // -- pins ------------------------------------------------------------------------
+
+ /** Arm a pin so every click on the map drops it, or disarm the one armed. */
+ arm(mode) {
+ if (!this.check || this.choosingPasses) return;
+ this.pinning = this.pinning === mode ? null : mode;
+ if (this.pinning) this.probe = null;
+ }
+
+ dropPin({ lon: x, lat: y }) {
+ if (!this.check || !this.pinning || this.choosingPasses) return;
+ const most = this.#limits.max_marks ?? 20;
+ if (this.marks.length >= most) {
+ this.#say(`A check holds at most ${most} pins.`, 'warn');
+ return;
+ }
+ const expect = this.pinning;
+ this.#patch((check) => withMark(check, [x, y], expect));
+ this.probe = null;
+ }
+
+ removePin(index) { this.#patch((check) => withoutMark(check, index)); }
+ flipPin(index) { this.#patch((check) => withFlippedMark(check, index)); }
+
+ // -- the imagery under the pins --------------------------------------------------
+
+ /**
+ * What the map should show: the basemap, the after pass alone, or the two
+ * passes either side of a split. A pass not chosen yet is not shown, so a
+ * check being made shows each pass as it is picked.
+ */
+ get imagery() {
+ const check = this.check;
+ if (!check || this.basemap || !check.b?.date) return { mode: 'basemap' };
+ const after = { ...check.b, layer: this.layer };
+ const before = this.single || !check.a?.date ? null : { ...check.a, layer: this.layer };
+ const shape = (source) => (this.radar ? { provider: 'sentinel1', date: source.date, time: source.time ?? '' }
+ : { provider: 'sentinel2', date: source.date, layer: this.layer });
+ return before ? { mode: 'swipe', a: shape(before), b: shape(after) } : { mode: 'single', b: shape(after) };
+ }
+
+ /** Whether the map is split between the two passes. */
+ get split() { return this.imagery.mode === 'swipe'; }
+
+ setBasemap(on) { this.basemap = on; }
+
+ setLayer(id) {
+ this.layer = id;
+ this.basemap = false;
+ if (this.radar) return;
+ this.#patch((check) => ({ ...check, a: check.a?.date ? { ...check.a, layer: id } : check.a,
+ b: check.b?.date ? { ...check.b, layer: id } : check.b }));
+ }
+
+ /** The layer that shows best what the ranking rule reads, among those offered. */
+ #suggested() {
+ return suggestedLayer(this.#recipe.rules[Math.max(0, signalOf(this.#recipe))], this.offered);
+ }
+
+ #adoptLayer(check) {
+ const own = check.b?.layer;
+ this.layer = own && this.offered.some((entry) => entry.id === own) ? own : this.#suggested();
+ }
+
+ get suggestion() { return this.#suggested(); }
+
+ // -- what each rule paints -------------------------------------------------------
+
+ isShown(index) { return this.shown[index] ?? true; }
+
+ /** Whether a rule's pixels are on the map now: the eye is open and the map shows rules. */
+ painted(index) { return this.view === 'rules' && this.isShown(index); }
+
+ /** A rule's eye; with the detections alone on the map every eye reads closed, so one pressed opens its rule. */
+ toggleRule(index) {
+ const opening = this.view === 'detections';
+ this.view = 'rules';
+ this.shown = this.#recipe.rules.map((_, i) => (i === index ? opening || !this.isShown(i) : this.isShown(i)));
+ }
+
+ /** A rule was removed: its eye goes with it. */
+ ruleRemoved(index) {
+ this.shown = this.#recipe.rules.map((_, i) => this.isShown(i)).filter((_, i) => i !== index);
+ this.hover = null;
+ }
+
+ /** The ranking rule was moved to the top: the eyes follow it. */
+ rulesReordered(order) {
+ this.shown = order.map((i) => this.isShown(i));
+ }
+
+ hoverRule(index) { this.hover = index; }
+
+ /** The rule the pointer is on, shown alone on the map; a hidden one stays hidden. */
+ get hovered() { return this.hover !== null && this.painted(this.hover) ? this.hover : null; }
+
+ // -- testing ---------------------------------------------------------------------
+
+ /** What each test would read, by check: the pins, the passes and the bands the rules need. */
+ planKeys = $derived.by(() => {
+ const list = this.draft ? [...this.#recipe.checks, this.draft.check] : this.#recipe.checks;
+ return JSON.stringify(list.filter((check) => check.marks.length && checkDated(this.#recipe, check))
+ .map((check) => [check.id, this.#planKeyOf(check)]));
+ });
+
+ /** The satellite, the dates and the bands: what the rules ask of a frame, and not where their lines sit. */
+ #planKeyOf(check) {
+ const reads = [sensorOf(this.#recipe), datesOf(this.#recipe), recipeBands(this.#recipe).join(',')].join('|');
+ return `${checkKey(check)}|${reads}`;
+ }
+
+ async #refreshPlans(keys) {
+ if (this.#gone) return;
+ const wanted = JSON.parse(keys).map(([id]) => id);
+ const list = [...this.#recipe.checks, ...(this.draft ? [this.draft.check] : [])].filter((check) => wanted.includes(check.id));
+ for (const check of list) {
+ const key = this.#planKeyOf(check);
+ if (this.plans[check.id]?.key === key && !this.plans[check.id].busy) continue;
+ this.plans[check.id] = { key, tiles: 0, missing: 0, busy: true, error: '' };
+ try {
+ const answer = await this.#api.post('/api/compare/analyzers/check/plan',
+ { recipe: readingRecipe(this.#recipe), check: testedCheck(check) });
+ if (this.#gone) return;
+ this.plans[check.id] = { key, tiles: answer.tiles, missing: answer.missing, busy: false, error: '' };
+ } catch (error) {
+ if (this.#gone) return;
+ this.plans[check.id] = { key, tiles: 0, missing: 0, busy: false, error: error.message };
+ }
+ }
+ }
+
+ /** What testing the check on the bench costs, once the engine has said; null while it is being asked. */
+ get plan() {
+ const check = this.check;
+ const plan = check ? this.plans[check.id] : null;
+ return plan && !plan.busy && plan.key === this.#planKeyOf(check) ? plan : null;
+ }
+ get planning() {
+ const check = this.check;
+ return !!check && check.marks.length > 0 && this.dated && !this.plan;
+ }
+
+ /** The last test of the check on the bench, if any. */
+ get last() {
+ const check = this.check;
+ return check ? this.tests[check.id] ?? null : null;
+ }
+ get testing() { return !!this.last?.busy; }
+ /** What the map draws of the last test, while it is still about the rules and pins on the bench. */
+ get detail() { return this.last?.detail ?? null; }
+ /** Whether what the map draws is older than the rules or the pins. */
+ get stale() {
+ const last = this.last;
+ return !!last?.detail && (last.signature !== this.current || last.key !== checkKey(this.check));
+ }
+
+ /** Why the check on the bench cannot be tested yet, or ''. */
+ get blocked() {
+ const check = this.check;
+ if (!check) return 'Pick a check to try the rules on.';
+ if (!this.dated) return this.single ? 'Pick the pass this check is read on.' : 'Pick the before and after passes.';
+ if (!check.marks.length) return 'Drop a pin to choose what this check reads.';
+ if (this.problem) return this.problem;
+ if (this.plan?.error) return this.plan.error;
+ return '';
+ }
+
+ /** What each pin made of the last test, in pin order: true when it came out as it should. */
+ get outcomes() {
+ const check = this.check;
+ return check?.result?.signature === this.current ? markOutcomes(check) : [];
+ }
+ /** The pins as the map draws them: where, what they should do, and whether they did. */
+ get pins() {
+ const outcomes = this.outcomes;
+ return this.marks.map((mark, i) => ({ ...mark, ok: outcomes[i] ?? null }));
+ }
+
+ /** Whether what the map draws is the answer to the rules and pins as they stand. */
+ get tested() { return !!this.detail && !this.stale && !this.testing; }
+
+ /** Whether pressing Test now does anything: it can, and what the map draws is not already its answer. */
+ get canTest() {
+ return !!this.check && !this.blocked && !this.planning && !this.testing && !(this.detail && !this.stale);
+ }
+
+ /** What the Test button says: the cost of the next one when it reads frames, and that it is done when nothing changed. */
+ get testLabel() {
+ if (this.testing) return 'Testing…';
+ if (this.detail && !this.stale) return 'Tested';
+ const missing = this.plan?.missing ?? 0;
+ return `${this.detail ? 'Test again' : 'Test'}${missing ? ` · ${missing} request${missing === 1 ? '' : 's'}` : ''}`;
+ }
+
+ /** Test the check on the bench with the rules as they stand. The one press that may fetch frames. */
+ async test() {
+ const check = this.check;
+ if (!check || !this.canTest) return;
+ await this.#run(check, { detail: true });
+ }
+
+ /** Test every check that has its passes and a pin, one after the other. */
+ async testAll() {
+ if (this.running || this.problem) return;
+ const list = this.#recipe.checks.filter((check) => check.marks.length && checkDated(this.#recipe, check));
+ try {
+ for (const [i, check] of list.entries()) {
+ this.running = `Testing ${i + 1} of ${list.length}…`;
+ await this.#run(check, { detail: check.id === this.check?.id });
+ if (this.#gone) return;
+ }
+ } finally {
+ this.running = '';
+ }
+ }
+
+ /** What Test all would ask of Copernicus, at most: every check's missing frames. */
+ get allMissing() {
+ return this.#recipe.checks.reduce((sum, check) => sum + (this.plans[check.id]?.missing ?? 0), 0);
+ }
+
+ async #run(check, { detail }) {
+ const id = check.id;
+ const signed = this.current;
+ const key = checkKey(check);
+ const before = this.tests[id];
+ this.tests[id] = { ...before, busy: true, error: '' };
+ try {
+ const answer = await this.#api.post('/api/compare/analyzers/check',
+ { recipe: readingRecipe(this.#recipe), check: testedCheck(check), read: true, detail });
+ if (this.#gone) return;
+ if (!answer.ready) {
+ this.tests[id] = { ...before, busy: false, error: 'Copernicus returned nothing for this check.' };
+ return;
+ }
+ const next = { busy: false, error: '', detail: before?.detail ?? null, signature: before?.signature ?? '', key: before?.key ?? '' };
+ if (detail) Object.assign(next, { detail: answer, signature: signed, key });
+ this.tests[id] = next;
+ // The answer belongs to the rules and pins it was asked with; if either moved meanwhile it is only shown.
+ const latest = this.#find(id);
+ if (latest && checkKey(latest) === key && this.current === signed) {
+ this.#setResult(id, { signature: signed, count: answer.count, covered: answer.covered });
+ }
+ if (this.plans[id]) this.plans[id] = { ...this.plans[id], missing: 0 };
+ } catch (error) {
+ if (this.#gone) return;
+ this.tests[id] = { ...before, busy: false, error: error.message };
+ }
+ }
+
+ // -- a point of the ground -------------------------------------------------------
+
+ /**
+ * Read every rule at a point of the map, tested ground or not: the answer
+ * says which. `pin` is the index of the pin the point is, when it is one.
+ */
+ async probeAt(point, { pin = null } = {}) {
+ const check = this.check;
+ if (!check) return;
+ const mine = ++this.#probes;
+ const base = { point, pin, result: null, error: '' };
+ if (!this.dated) { this.probe = { ...base, unread: 'passes' }; return; }
+ if (!this.detail) { this.probe = { ...base, unread: 'frames' }; return; }
+ this.probe = base;
+ try {
+ const result = await this.#api.post('/api/compare/analyzers/probe',
+ { recipe: readingRecipe(this.#recipe), check: testedCheck(check), point: [point.lon, point.lat] });
+ if (mine === this.#probes && !this.#gone) this.probe = { ...base, result };
+ } catch (error) {
+ if (mine === this.#probes) this.probe = { ...base, error: error.message };
+ }
+ }
+
+ /** Read the ground under one of the pins. */
+ probePin(index) {
+ const mark = this.marks[index];
+ if (mark) return this.probeAt({ lon: mark.point[0], lat: mark.point[1] }, { pin: index });
+ }
+
+ closeProbe() {
+ this.#probes++;
+ this.probe = null;
+ }
+
+ /** Escape: close the reading, else put the armed pin down. True when it did something. */
+ escape() {
+ if (this.probe) { this.closeProbe(); return true; }
+ if (this.pinning) { this.pinning = null; return true; }
+ return false;
+ }
+
+ /** Move the split between the two passes. */
+ setDivider(percent) { this.divider = Math.max(0, Math.min(100, percent)); }
+
+ setLookback(lookback) {
+ this.passes = { ...this.passes, lookback };
+ if (lookback !== 'dates') this.calendar = { ...this.calendar, side: '' };
+ }
+
+ // -- a day picked from the calendar ----------------------------------------------
+
+ /** Open the calendar for one side of the check, 'a' (Before) or 'b' (After). */
+ openCalendar(side) {
+ this.calendar = { side, list: [], busy: false, error: '' };
+ }
+
+ closeCalendar() { this.calendar = { ...this.calendar, side: '' }; }
+
+ /** Whether a pass can be that side of the check: in order, and on one radar track. */
+ eligible(side) {
+ return (pass) => canPickPass(side, pass, this.check?.a, this.check?.b, this.radar);
+ }
+
+ /** A pass picked from the calendar: it is the side's, and the calendar closes. */
+ pickFromCalendar(side, pass) {
+ this.setPass(side, { date: pass.date, time: pass.time ?? '' });
+ this.closeCalendar();
+ }
+
+ /** A day typed in: it has no time yet, and the engine settles which pass of it. */
+ typeDay(side, date) {
+ if (date) this.setPass(side, { date, time: '' });
+ }
+
+ /**
+ * The passes of one month over the middle of the map, for the calendar to colour
+ * its days with. A month is a catalogue request, so each is asked once and kept.
+ */
+ async loadMonth(month) {
+ const region = lookupBounds(this.#viewBounds());
+ if (!region) return;
+ const key = `${month}@${Math.round(region.west * 20)},${Math.round(region.south * 20)}|${this.radar ? 1 : 2}`;
+ const cached = this.#months.get(key);
+ const mine = ++this.#calendars;
+ if (cached) {
+ this.calendar = { ...this.calendar, list: cached, busy: false, error: '' };
+ return;
+ }
+ this.calendar = { ...this.calendar, list: [], busy: true, error: '' };
+ const last = new Date(Date.UTC(Number(month.slice(0, 4)), Number(month.slice(5, 7)), 0)).toISOString().slice(0, 10);
+ const today = isoDay(new Date());
+ try {
+ const found = await this.#api.post('/api/satellite/sentinel/acquisitions',
+ acquisitionQuery([viewZone(region, 'Preview')], { start: `${month}-01`, end: last < today ? last : today },
+ new Date(), this.radar ? 'sentinel1' : 'sentinel2'));
+ if (this.#gone) return;
+ this.#months.set(key, found.dates ?? []);
+ if (mine === this.#calendars) this.calendar = { ...this.calendar, list: found.dates ?? [], busy: false };
+ } catch (error) {
+ if (mine === this.#calendars) this.calendar = { ...this.calendar, busy: false, error: error.message };
+ }
+ }
+
+ /** Drop a pin where the point was read. */
+ markProbe(expect) {
+ if (!this.probe || !this.check) return;
+ const { point } = this.probe;
+ if (this.marks.length >= (this.#limits.max_marks ?? 20)) {
+ this.#say(`A check holds at most ${this.#limits.max_marks ?? 20} pins.`, 'warn');
+ return;
+ }
+ this.#patch((check) => withMark(check, [point.lon, point.lat], expect));
+ this.probe = null;
+ }
+
+ // -- internals -------------------------------------------------------------------
+
+ #find(id) {
+ if (this.draft?.check.id === id) return this.draft.check;
+ return this.#recipe.checks.find((check) => check.id === id) ?? null;
+ }
+
+ #patch(change) {
+ if (this.draft) {
+ this.draft.check = change(this.draft.check);
+ return;
+ }
+ const id = this.selected;
+ if (!id) return;
+ this.#recipe.checks = this.#recipe.checks.map((check) => (check.id === id ? change(check) : check));
+ }
+
+ #setResult(id, result) {
+ if (this.draft?.check.id === id) {
+ this.draft.check = { ...this.draft.check, result };
+ return;
+ }
+ this.#recipe.checks = this.#recipe.checks.map((check) => (check.id === id ? { ...check, result } : check));
+ }
+
+ #freeName() {
+ const taken = new Set(this.#recipe.checks.map((check) => check.name));
+ let n = this.#recipe.checks.length + 1;
+ while (taken.has(`Check ${n}`)) n++;
+ return `Check ${n}`;
+ }
+
+ #frame(check) {
+ if (!check.marks.length) return;
+ this.#fly({ bounds: marksBounds(check.marks) });
+ }
+}
diff --git a/frontend/src/lib/map/bench.svelte.test.js b/frontend/src/lib/map/bench.svelte.test.js
new file mode 100644
index 0000000..5034565
--- /dev/null
+++ b/frontend/src/lib/map/bench.svelte.test.js
@@ -0,0 +1,659 @@
+// @vitest-environment happy-dom
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { flushSync } from 'svelte';
+import { Bench, lookupBounds } from './bench.svelte.js';
+import { newCheck, newRecipe, newRule, signature } from './analyzerRules.js';
+
+const METHODS = [{ id: 'rules', sizes: { all: { min_area: 0, cleanup: 0 } } }];
+const VIEW = { west: 2, south: 48, east: 2.2, north: 48.2 };
+const PLOT = [2.01, 48.01];
+const REEF = [2.05, 48.05];
+const settle = async () => {
+ await vi.advanceTimersByTimeAsync(300);
+ flushSync();
+};
+
+/** A bench on a recipe of two dates, with an engine that answers what a real one would. */
+function make({ dates = 'two', sensor = 'sentinel2', checks = [], answers = {}, limits = { max_checks: 12, max_marks: 20 } } = {}) {
+ const recipe = $state({ ...newRecipe(METHODS, { sensor, dates }), name: 'Mine', checks });
+ const calls = [];
+ const api = {
+ post: vi.fn(async (url, body) => {
+ calls.push([url, body]);
+ const answer = answers[url];
+ if (answer instanceof Error) throw answer;
+ if (typeof answer === 'function') return answer(body);
+ if (url.endsWith('/check/plan')) return answer ?? { tiles: 1, missing: 2 };
+ if (url.endsWith('/check')) {
+ return answer ?? { ready: true, missing: 0, count: 1, covered: body.check.marks.map((mark) => mark.expect === 'found'),
+ tiles: [{ x: 1, y: 2, box: { west: 0, east: 1, north: 1, south: 0 }, mask: 'AAAA' }], size: 512,
+ rules: body.recipe.rules.map(() => ({ share: 0.05, kept: 0.05 })), candidates: [], readings: [] };
+ }
+ if (url.endsWith('/probe')) return answer ?? { ready: true, imaged: true, measured: true, kept: true, rules: [] };
+ if (url.endsWith('/acquisitions')) return answer ?? { dates: [{ date: '2023-08-13', cloud: 3, coverage: 1 }], truncated: false };
+ throw new Error(`unexpected ${url}`);
+ }),
+ };
+ const fly = vi.fn();
+ const say = vi.fn();
+ const bench = new Bench({ api, recipe, limits, layers: () => [], viewBounds: () => VIEW, fly, say });
+ return { recipe, api, calls, bench, fly, say };
+}
+
+const pass = (date) => ({ provider: 'sentinel2', date, layer: 'TRUE_COLOR', maxcc: 100 });
+const made = (name, marks = [{ point: PLOT, expect: 'found' }]) =>
+ newCheck({ name, a: pass('2023-08-08'), b: pass('2023-08-13'), marks });
+
+let live = [];
+const open = (options) => {
+ const made = make(options);
+ live.push(made.bench);
+ return made;
+};
+
+beforeEach(() => vi.useFakeTimers());
+afterEach(() => {
+ live.forEach((bench) => bench.destroy());
+ live = [];
+ vi.useRealTimers();
+});
+
+describe('making a check', () => {
+ it('takes the passes, then the pins, and keeps the panel waiting until it is valid', () => {
+ const { bench, recipe } = open();
+ bench.startDraft();
+ expect(bench.locked).toBe(true);
+ expect(bench.draft.step).toBe('passes');
+ expect(bench.choosingPasses).toBe(true);
+ expect(bench.check.name).toBe('Check 1');
+ bench.setPass('b', { date: '2023-08-13' });
+ bench.continueDraft(); // a before pass is missing, so it cannot go on
+ expect(bench.draft.step).toBe('passes');
+ bench.setPass('a', { date: '2023-08-08' });
+ expect(bench.dated).toBe(true);
+ bench.continueDraft();
+ expect(bench.draft.step).toBe('pins');
+ expect(bench.pinning).toBe('found');
+ expect(bench.canFinish).toBe(false); // no pin yet
+ bench.dropPin({ lon: PLOT[0], lat: PLOT[1] });
+ expect(bench.marks).toEqual([{ point: PLOT, expect: 'found' }]);
+ expect(bench.canFinish).toBe(true);
+ expect(recipe.checks).toHaveLength(0); // nothing is kept until it is finished
+ bench.finishDraft();
+ expect(recipe.checks).toHaveLength(1);
+ expect(bench.locked).toBe(false);
+ expect(bench.selected).toBe(recipe.checks[0].id);
+ expect(bench.pinning).toBe(null);
+ });
+
+ it('puts back what was on the bench when it is given up', () => {
+ const first = made('Plot');
+ const { bench, recipe } = open({ checks: [first] });
+ bench.select(first.id);
+ bench.startDraft();
+ expect(bench.selected).toBe(null);
+ bench.cancelDraft();
+ expect(bench.draft).toBe(null);
+ expect(bench.selected).toBe(first.id);
+ expect(recipe.checks).toHaveLength(1);
+ });
+
+ it('takes the name of a check being made as it is typed, and none once it is given up', () => {
+ const { bench } = open();
+ bench.startDraft();
+ bench.nameDraft('The plot');
+ expect(bench.check.name).toBe('The plot');
+ bench.cancelDraft();
+ bench.nameDraft('Too late'); // nothing is being made
+ expect(bench.draft).toBe(null);
+ });
+
+ it('names each check with a number nobody has used', () => {
+ const { bench } = open({ checks: [made('Check 1'), made('Check 3')] });
+ bench.startDraft();
+ expect(bench.check.name).toBe('Check 3'.replace('3', '4'));
+ });
+
+ it('asks for one date only when the analyzer reads one', () => {
+ const { bench } = open({ dates: 'one' });
+ bench.startDraft();
+ bench.setPass('b', { date: '2023-08-13' });
+ expect(bench.dated).toBe(true);
+ bench.continueDraft();
+ expect(bench.draft.step).toBe('pins');
+ });
+
+ it('refuses a twelfth-and-one check and a pin past the limit, and says so', () => {
+ const { bench, say } = open({ limits: { max_checks: 1, max_marks: 1 }, checks: [made('Plot')] });
+ bench.startDraft();
+ expect(bench.draft).toBe(null);
+ bench.select(bench.checks[0].id);
+ bench.arm('empty');
+ bench.dropPin({ lon: REEF[0], lat: REEF[1] });
+ expect(bench.marks).toHaveLength(1);
+ expect(say).toHaveBeenCalledWith('A check holds at most 1 pins.', 'warn');
+ });
+
+ it('changes the passes of a check already kept, and forgets what they had answered', () => {
+ const kept = { ...made('Plot'), result: { signature: 'x', count: 1, covered: [true] } };
+ const { bench, recipe } = open({ checks: [kept] });
+ bench.select(kept.id);
+ bench.changePasses();
+ expect(bench.choosingPasses).toBe(true);
+ expect(bench.locked).toBe(false);
+ bench.setPass('b', { date: '2023-09-01' });
+ expect(recipe.checks[0].b.date).toBe('2023-09-01');
+ expect(recipe.checks[0].result).toBe(null);
+ bench.closePasses();
+ expect(bench.choosingPasses).toBe(false);
+ });
+
+ it('drops no pin while the passes are being chosen', () => {
+ const { bench } = open();
+ bench.startDraft();
+ bench.arm('found');
+ expect(bench.pinning).toBe(null);
+ bench.dropPin({ lon: PLOT[0], lat: PLOT[1] });
+ expect(bench.marks).toEqual([]);
+ });
+});
+
+describe('choosing a check', () => {
+ it('goes to its pins, takes its layer and lets the basemap back', () => {
+ const kept = made('Plot');
+ kept.b.layer = 'SWIR';
+ const { bench, fly } = open({ checks: [kept] });
+ bench.select(kept.id);
+ expect(bench.check.name).toBe('Plot');
+ expect(fly).toHaveBeenCalledWith({ bounds: expect.objectContaining({ west: expect.any(Number) }) });
+ expect(bench.layer).toBe('SWIR');
+ bench.select(null);
+ expect(bench.check).toBe(null);
+ expect(bench.imagery).toEqual({ mode: 'basemap' });
+ });
+
+ it('puts a check away with its tests', () => {
+ const kept = made('Plot');
+ const { bench, recipe } = open({ checks: [kept] });
+ bench.select(kept.id);
+ bench.remove(kept.id);
+ expect(recipe.checks).toEqual([]);
+ expect(bench.selected).toBe(null);
+ });
+
+ it('renames a check, and keeps its name when the new one is blank', () => {
+ const kept = made('Plot');
+ const { bench, recipe } = open({ checks: [kept] });
+ bench.rename(kept.id, ' The plot ');
+ expect(recipe.checks[0].name).toBe('The plot');
+ bench.rename(kept.id, ' ');
+ expect(recipe.checks[0].name).toBe('The plot');
+ });
+});
+
+describe('the imagery under the pins', () => {
+ it('is the basemap until a check has a pass, then each pass as it is picked', () => {
+ const { bench } = open();
+ expect(bench.imagery).toEqual({ mode: 'basemap' });
+ bench.startDraft();
+ expect(bench.imagery).toEqual({ mode: 'basemap' });
+ bench.setPass('b', { date: '2023-08-13' });
+ expect(bench.imagery).toEqual({ mode: 'single', b: { provider: 'sentinel2', date: '2023-08-13', layer: 'NDVI' } });
+ bench.setPass('a', { date: '2023-08-08' });
+ expect(bench.imagery).toEqual({ mode: 'swipe', a: expect.objectContaining({ date: '2023-08-08' }),
+ b: expect.objectContaining({ date: '2023-08-13' }) });
+ expect(bench.split).toBe(true);
+ });
+
+ it('shows one date alone for an analyzer of one date, and radar by its time of day', () => {
+ const one = open({ dates: 'one' });
+ one.bench.startDraft();
+ one.bench.setPass('b', { date: '2023-08-13' });
+ expect(one.bench.imagery.mode).toBe('single');
+ const radar = open({ sensor: 'sentinel1' });
+ radar.bench.startDraft();
+ radar.bench.setPass('a', { date: '2023-08-08', time: '05:30:12' });
+ radar.bench.setPass('b', { date: '2023-08-13', time: '05:30:12' });
+ expect(radar.bench.imagery).toEqual({ mode: 'swipe', a: { provider: 'sentinel1', date: '2023-08-08', time: '05:30:12' },
+ b: { provider: 'sentinel1', date: '2023-08-13', time: '05:30:12' } });
+ });
+
+ it('goes back to the basemap on request, and to the passes when one is picked', () => {
+ const kept = made('Plot');
+ const { bench } = open({ checks: [kept] });
+ bench.select(kept.id);
+ expect(bench.imagery.mode).toBe('swipe');
+ bench.setBasemap(true);
+ expect(bench.imagery.mode).toBe('basemap');
+ bench.setLayer('SWIR');
+ expect(bench.imagery.mode).toBe('swipe');
+ expect(bench.imagery.b.layer).toBe('SWIR');
+ });
+
+ it('starts on the layer that shows what the ranking rule reads, and the layer is not what is read', () => {
+ const kept = made('Plot');
+ const { bench, recipe } = open({ checks: [kept] });
+ expect(bench.layer).toBe('NDVI'); // the first rule is NDVI
+ bench.select(kept.id);
+ bench.setLayer('SWIR');
+ expect(recipe.checks[0].b.layer).toBe('SWIR');
+ expect(recipe.checks[0].a.layer).toBe('SWIR');
+ });
+});
+
+describe('what a test would cost', () => {
+ it('asks the engine once the pins and passes are there, and says what it will read', async () => {
+ const kept = made('Plot');
+ const { bench, calls } = open({ checks: [kept] });
+ bench.select(kept.id);
+ expect(bench.planning).toBe(true);
+ await settle();
+ const [url, body] = calls[0];
+ expect(url).toBe('/api/compare/analyzers/check/plan');
+ expect(body.recipe).toMatchObject({ method: 'rules', sensor: 'sentinel2', dates: 'two' });
+ expect(body.check.result).toBe(null);
+ expect(bench.plan).toMatchObject({ tiles: 1, missing: 2 });
+ expect(bench.planning).toBe(false);
+ expect(bench.blocked).toBe('');
+ });
+
+ it('is not asked again when a line moves, but is when a pin or a band does', async () => {
+ const kept = made('Plot');
+ const { bench, recipe, calls } = open({ checks: [kept] });
+ bench.select(kept.id);
+ await settle();
+ expect(calls).toHaveLength(1);
+ recipe.rules[0].value = -0.4;
+ await settle();
+ expect(calls).toHaveLength(1);
+ bench.arm('empty');
+ bench.dropPin({ lon: REEF[0], lat: REEF[1] });
+ await settle();
+ expect(calls).toHaveLength(2);
+ recipe.rules[0].index = 'nbr';
+ await settle();
+ expect(calls).toHaveLength(3);
+ });
+
+ it('says what stops a check being tested, before anything is asked', async () => {
+ const { bench } = open();
+ expect(bench.blocked).toBe('Pick a check to try the rules on.');
+ bench.startDraft();
+ expect(bench.blocked).toBe('Pick the before and after passes.');
+ bench.setPass('b', { date: '2023-08-13' });
+ bench.setPass('a', { date: '2023-08-08' });
+ expect(bench.blocked).toBe('Drop a pin to choose what this check reads.');
+ bench.continueDraft();
+ bench.dropPin({ lon: PLOT[0], lat: PLOT[1] });
+ await settle();
+ expect(bench.blocked).toBe('');
+ });
+
+ it('carries the engine’s own words when the pins reach too much ground', async () => {
+ const refusal = new Error('these pins reach 14 tiles and a check reads at most 12');
+ const kept = made('Plot');
+ const { bench } = open({ checks: [kept], answers: { '/api/compare/analyzers/check/plan': refusal } });
+ bench.select(kept.id);
+ await settle();
+ expect(bench.blocked).toBe(refusal.message);
+ expect(bench.plan.error).toBe(refusal.message);
+ });
+
+ it('adds up what every check still lacks for Test all', async () => {
+ const { bench } = open({ checks: [made('One'), made('Two', [{ point: REEF, expect: 'empty' }])] });
+ bench.select(bench.checks[0].id);
+ await settle();
+ expect(bench.allMissing).toBe(4);
+ });
+});
+
+describe('testing', () => {
+ async function ready(options) {
+ const kept = made('Plot', [{ point: PLOT, expect: 'found' }, { point: REEF, expect: 'empty' }]);
+ const made_ = open({ checks: [kept], ...options });
+ made_.bench.select(kept.id);
+ await settle();
+ return { ...made_, kept };
+ }
+
+ it('reads what is missing, keeps what the map draws and the answer on the check', async () => {
+ const { bench, recipe, calls } = await ready();
+ await bench.test();
+ const [, body] = calls.at(-1);
+ expect(calls.at(-1)[0]).toBe('/api/compare/analyzers/check');
+ expect(body).toMatchObject({ read: true, detail: true });
+ expect(bench.detail.tiles).toHaveLength(1);
+ expect(bench.stale).toBe(false);
+ expect(recipe.checks[0].result).toEqual({ signature: signature(recipe), count: 1, covered: [true, false] });
+ expect(bench.outcomes).toEqual([true, true]);
+ expect(bench.pins.map((pin) => pin.ok)).toEqual([true, true]);
+ expect(bench.plan.missing).toBe(0);
+ });
+
+ it('does not run by itself when a line moves, and says the picture is older than the rules', async () => {
+ const { bench, recipe, calls } = await ready();
+ await bench.test();
+ const asked = calls.length;
+ recipe.rules[0].value = -0.4;
+ await settle();
+ expect(calls.length).toBe(asked);
+ expect(bench.stale).toBe(true);
+ expect(bench.detail).not.toBe(null); // still there to look at
+ expect(bench.outcomes).toEqual([]); // but no pin claims to have passed
+ await bench.test();
+ expect(bench.stale).toBe(false);
+ });
+
+ it('goes stale too when a pin is moved, and keeps no result for pins it did not read', async () => {
+ const { bench, recipe } = await ready();
+ await bench.test();
+ bench.arm('empty');
+ bench.dropPin({ lon: 2.06, lat: 48.06 });
+ expect(bench.stale).toBe(true);
+ expect(recipe.checks[0].result).toBe(null);
+ bench.removePin(2);
+ bench.flipPin(1);
+ expect(bench.marks.map((mark) => mark.expect)).toEqual(['found', 'found']);
+ });
+
+ it('keeps the answer to the rules it was asked with when they change while it reads', async () => {
+ let release;
+ const slow = () => new Promise((resolve) => { release = resolve; });
+ const { bench, recipe } = await ready({ answers: { '/api/compare/analyzers/check': slow } });
+ const running = bench.test();
+ expect(bench.testing).toBe(true);
+ recipe.rules[0].value = -0.4;
+ release({ ready: true, missing: 0, count: 1, covered: [true, false], tiles: [], size: 512, rules: [], candidates: [], readings: [] });
+ await running;
+ expect(recipe.checks[0].result).toBe(null);
+ expect(bench.stale).toBe(true);
+ });
+
+ it('says on its button what the next test costs, and that there is nothing to do once it is done', async () => {
+ const { bench, recipe } = await ready();
+ expect(bench.testLabel).toBe('Test · 2 requests');
+ expect(bench.canTest).toBe(true);
+ await bench.test();
+ expect(bench.testLabel).toBe('Tested');
+ expect(bench.tested).toBe(true);
+ expect(bench.canTest).toBe(false);
+ recipe.rules[0].value = -0.4;
+ expect(bench.testLabel).toBe('Test again');
+ expect(bench.tested).toBe(false);
+ expect(bench.canTest).toBe(true);
+ });
+
+ it('does not test while it is asking what the test costs, or with a rule that cannot run', async () => {
+ const kept = made('Plot');
+ const { bench, recipe, calls } = open({ checks: [kept] });
+ bench.select(kept.id);
+ await bench.test(); // still asking what it costs
+ expect(calls.filter(([url]) => url.endsWith('/check'))).toHaveLength(0);
+ await settle();
+ recipe.rules = [];
+ await bench.test();
+ expect(bench.blocked).toBe('Add a rule.');
+ expect(calls.filter(([url]) => url.endsWith('/check'))).toHaveLength(0);
+ });
+
+ it('says what went wrong in the engine’s words', async () => {
+ const { bench } = await ready({ answers: { '/api/compare/analyzers/check': new Error('Copernicus could not be reached') } });
+ await bench.test();
+ expect(bench.last.error).toBe('Copernicus could not be reached');
+ expect(bench.testing).toBe(false);
+ expect(bench.detail).toBe(null);
+ });
+
+ it('tests every check, one after the other, and draws only the one on the bench', async () => {
+ const one = made('One');
+ const two = made('Two', [{ point: REEF, expect: 'empty' }]);
+ const { bench, recipe, calls } = open({ checks: [one, two] });
+ bench.select(one.id);
+ await settle();
+ const all = bench.testAll();
+ expect(bench.running).toBe('Testing 1 of 2…');
+ await all;
+ expect(bench.running).toBe('');
+ const tests = calls.filter(([url]) => url.endsWith('/check'));
+ expect(tests.map(([, body]) => [body.check.id, body.detail])).toEqual([[one.id, true], [two.id, false]]);
+ expect(recipe.checks.map((check) => check.result?.signature)).toEqual([signature(recipe), signature(recipe)]);
+ expect(bench.detail).not.toBe(null);
+ });
+});
+
+describe('a point of the ground', () => {
+ it('says why nothing is read where nothing has been', async () => {
+ const { bench } = open();
+ await bench.probeAt({ lon: 2, lat: 48 });
+ expect(bench.probe).toBe(null); // no check, nothing to read against
+ bench.startDraft();
+ await bench.probeAt({ lon: 2, lat: 48 });
+ expect(bench.probe.unread).toBe('passes');
+ bench.setPass('b', { date: '2023-08-13' });
+ bench.setPass('a', { date: '2023-08-08' });
+ await bench.probeAt({ lon: 2, lat: 48 });
+ expect(bench.probe.unread).toBe('frames');
+ });
+
+ it('reads every rule at the point once the check has been tested, and drops a pin from it', async () => {
+ const kept = made('Plot');
+ const { bench, calls } = open({ checks: [kept] });
+ bench.select(kept.id);
+ await settle();
+ await bench.test();
+ await bench.probeAt({ lon: 2.02, lat: 48.02 });
+ const [url, body] = calls.at(-1);
+ expect(url).toBe('/api/compare/analyzers/probe');
+ expect(body.point).toEqual([2.02, 48.02]);
+ expect(bench.probe.result.kept).toBe(true);
+ bench.markProbe('empty');
+ expect(bench.marks.at(-1)).toEqual({ point: [2.02, 48.02], expect: 'empty' });
+ expect(bench.probe).toBe(null);
+ });
+
+ it('reads the ground under a pin, which is then the pin the card is about', async () => {
+ const kept = made('Plot');
+ const { bench, calls } = open({ checks: [kept] });
+ bench.select(kept.id);
+ await settle();
+ await bench.test();
+ await bench.probePin(0);
+ expect(calls.at(-1)[1].point).toEqual(PLOT);
+ expect(bench.probe).toMatchObject({ pin: 0, point: { lon: PLOT[0], lat: PLOT[1] } });
+ await bench.probePin(7); // no such pin: nothing changes
+ expect(bench.probe.pin).toBe(0);
+ await bench.probeAt({ lon: 2, lat: 48 });
+ expect(bench.probe.pin).toBe(null);
+ });
+
+ it('forgets a reading that comes back after it was closed', async () => {
+ const kept = made('Plot');
+ let release;
+ const { bench } = open({ checks: [kept], answers: { '/api/compare/analyzers/probe': () => new Promise((resolve) => { release = resolve; }) } });
+ bench.select(kept.id);
+ await settle();
+ await bench.test();
+ const reading = bench.probeAt({ lon: 2, lat: 48 });
+ bench.closeProbe();
+ release({ ready: true, rules: [] });
+ await reading;
+ expect(bench.probe).toBe(null);
+ });
+});
+
+describe('a day picked from the calendar', () => {
+ const june = { dates: [{ date: '2026-06-03', cloud: 5, coverage: 1 }, { date: '2026-06-18', cloud: 40, coverage: 1 }] };
+
+ it('asks for a month once, over the middle of the map, and keeps the answer', async () => {
+ const { bench, calls } = open({ answers: { '/api/satellite/sentinel/acquisitions': june } });
+ bench.startDraft();
+ bench.openCalendar('b');
+ expect(bench.calendar).toMatchObject({ side: 'b', list: [] });
+ await bench.loadMonth('2026-06');
+ const [url, body] = calls[0];
+ expect(url).toBe('/api/satellite/sentinel/acquisitions');
+ expect(body).toMatchObject({ collection: 'sentinel2', start: '2026-06-01', end: expect.stringMatching(/^2026-06-(30|\d\d)$/) });
+ expect(bench.calendar.list).toHaveLength(2);
+ expect(bench.calendar.busy).toBe(false);
+ // the same month again costs nothing, and another month is asked for
+ await bench.loadMonth('2026-06');
+ expect(calls).toHaveLength(1);
+ await bench.loadMonth('2026-05');
+ expect(calls).toHaveLength(2);
+ expect(calls[1][1].start).toBe('2026-05-01');
+ expect(calls[1][1].end).toBe('2026-05-31');
+ });
+
+ it('holds a month read for radar apart from one read for optical, and says what went wrong', async () => {
+ const radar = open({ sensor: 'sentinel1', answers: { '/api/satellite/sentinel/acquisitions': new Error('Copernicus could not be reached') } });
+ radar.bench.startDraft();
+ radar.bench.openCalendar('a');
+ await radar.bench.loadMonth('2026-06');
+ expect(radar.calls[0][1].collection).toBe('sentinel1');
+ expect(radar.bench.calendar).toMatchObject({ error: 'Copernicus could not be reached', busy: false });
+ });
+
+ it('takes a pass from the calendar as that side of the check and closes', () => {
+ const { bench } = open();
+ bench.startDraft();
+ bench.openCalendar('b');
+ bench.pickFromCalendar('b', { date: '2026-06-18', cloud: 40 });
+ expect(bench.check.b).toMatchObject({ date: '2026-06-18', provider: 'sentinel2' });
+ expect(bench.calendar.side).toBe('');
+ bench.typeDay('a', '2026-06-03');
+ expect(bench.check.a.date).toBe('2026-06-03');
+ bench.typeDay('a', ''); // a cleared field changes nothing
+ expect(bench.check.a.date).toBe('2026-06-03');
+ expect(bench.dated).toBe(true);
+ });
+
+ it('offers only the days that keep the passes in order', () => {
+ const { bench } = open();
+ bench.startDraft();
+ bench.setPass('b', { date: '2026-06-10' });
+ const before = bench.eligible('a');
+ expect(before({ date: '2026-06-03' })).toBe(true);
+ expect(before({ date: '2026-06-18' })).toBe(false);
+ bench.setPass('a', { date: '2026-06-03' });
+ const after = bench.eligible('b');
+ expect(after({ date: '2026-06-18' })).toBe(true);
+ expect(after({ date: '2026-05-30' })).toBe(false);
+ });
+
+ it('looks up the recent passes only for a window of days, never for the calendar', async () => {
+ const { bench, calls } = open();
+ bench.setLookback('dates');
+ await bench.lookUpPasses();
+ expect(calls).toHaveLength(0);
+ expect(bench.passes.lookback).toBe('dates');
+ bench.openCalendar('a');
+ bench.setLookback(30);
+ expect(bench.calendar.side).toBe('');
+ await bench.lookUpPasses();
+ expect(calls).toHaveLength(1);
+ });
+});
+
+describe('the room the console takes', () => {
+ it('starts with none, for a card to keep clear of', () => {
+ const { bench } = open();
+ expect(bench.reach).toBe(0);
+ });
+});
+
+describe('the keyboard and the split', () => {
+ it('lets go of the reading first, then of the armed pin, and says when it had nothing to do', async () => {
+ const kept = made('Plot');
+ const { bench } = open({ checks: [kept] });
+ bench.select(kept.id);
+ bench.arm('found');
+ await bench.probeAt({ lon: 2, lat: 48 });
+ expect(bench.escape()).toBe(true);
+ expect(bench.probe).toBe(null);
+ expect(bench.pinning).toBe('found');
+ expect(bench.escape()).toBe(true);
+ expect(bench.pinning).toBe(null);
+ expect(bench.escape()).toBe(false);
+ });
+
+ it('keeps the split on the map', () => {
+ const { bench } = open();
+ expect(bench.divider).toBe(50);
+ bench.setDivider(130);
+ expect(bench.divider).toBe(100);
+ bench.setDivider(-5);
+ expect(bench.divider).toBe(0);
+ bench.setLookback(365);
+ expect(bench.passes.lookback).toBe(365);
+ });
+});
+
+describe('the rules on the map', () => {
+ it('opens and closes each rule’s eye, and opens the one pressed while the detections stand alone', () => {
+ const { bench, recipe } = open();
+ recipe.rules = [newRule('index', 'change'), newRule('index', 'a'), newRule('band', 'b')];
+ expect([0, 1, 2].map((i) => bench.painted(i))).toEqual([true, true, true]);
+ bench.toggleRule(1);
+ expect([0, 1, 2].map((i) => bench.painted(i))).toEqual([true, false, true]);
+ bench.view = 'detections';
+ expect([0, 1, 2].map((i) => bench.painted(i))).toEqual([false, false, false]);
+ bench.toggleRule(1);
+ expect(bench.view).toBe('rules');
+ expect([0, 1, 2].map((i) => bench.painted(i))).toEqual([true, true, true]);
+ });
+
+ it('shows the rule the pointer is on alone, unless its eye is shut', () => {
+ const { bench, recipe } = open();
+ recipe.rules = [newRule('index', 'change'), newRule('index', 'a')];
+ bench.hoverRule(1);
+ expect(bench.hovered).toBe(1);
+ bench.toggleRule(1);
+ expect(bench.hovered).toBe(null); // hidden stays hidden while the pointer is on its row
+ bench.hoverRule(null);
+ expect(bench.hovered).toBe(null);
+ });
+
+ it('keeps an eye with its rule when one is removed or moved up', () => {
+ const { bench, recipe } = open();
+ recipe.rules = [newRule('index', 'change'), newRule('index', 'a'), newRule('band', 'b')];
+ bench.toggleRule(2);
+ bench.rulesReordered([2, 0, 1]);
+ expect([0, 1, 2].map((i) => bench.isShown(i))).toEqual([false, true, true]);
+ bench.hoverRule(1);
+ recipe.rules = recipe.rules.filter((_, i) => i !== 0);
+ bench.ruleRemoved(0);
+ expect(bench.hover).toBe(null);
+ expect([0, 1].map((i) => bench.isShown(i))).toEqual([true, true]);
+ });
+});
+
+describe('the passes a lookup finds', () => {
+ it('looks round the middle of the map, for the satellite the analyzer reads', async () => {
+ const { bench, calls } = open();
+ await bench.lookUpPasses(30);
+ const [url, body] = calls[0];
+ expect(url).toBe('/api/satellite/sentinel/acquisitions');
+ expect(body.collection).toBe('sentinel2');
+ expect(body.zones[0].points).toEqual([[2, 48.2], [2.2, 48]]);
+ expect(bench.passes).toMatchObject({ searched: true, busy: false, lookback: 30 });
+ expect(bench.passes.list[0].date).toBe('2023-08-13');
+ const radar = open({ sensor: 'sentinel1' });
+ await radar.bench.lookUpPasses();
+ expect(radar.calls[0][1].collection).toBe('sentinel1');
+ });
+
+ it('says what went wrong and is not left reading', async () => {
+ const { bench } = open({ answers: { '/api/satellite/sentinel/acquisitions': new Error('Copernicus could not be reached') } });
+ await bench.lookUpPasses();
+ expect(bench.passes).toMatchObject({ error: 'Copernicus could not be reached', busy: false, searched: false });
+ });
+
+ it('holds a wide view to the ground round its middle', () => {
+ expect(lookupBounds({ west: 0, south: 40, east: 10, north: 50 })).toEqual({ west: 4.85, south: 44.85, east: 5.15, north: 45.15 });
+ expect(lookupBounds(VIEW)).toEqual(VIEW);
+ const corner = lookupBounds({ west: 179.9, south: 84.9, east: 181, north: 86 });
+ expect(corner.east).toBe(180); // never past what the engine accepts
+ expect(corner.north).toBe(85);
+ expect(lookupBounds(null)).toBe(null);
+ });
+});
diff --git a/frontend/src/lib/map/changeAssist.js b/frontend/src/lib/map/changeAssist.js
index 72d713c..6a52a8c 100644
--- a/frontend/src/lib/map/changeAssist.js
+++ b/frontend/src/lib/map/changeAssist.js
@@ -183,10 +183,10 @@ export function changeCompatibility(a, b) {
if (a.sentinel?.layer === b.sentinel?.layer && same(layerReading(a), layerReading(b))) {
methods.unshift(...PIXEL_METHODS);
} else {
- notes.push('Pixel methods need the same layer and reference layers on A and B.');
+ notes.push('Pixel methods need the same layers on A and B.');
}
if (a.sentinel?.maxcc !== b.sentinel?.maxcc) {
- notes.push('The two sides use different cloud ceilings.');
+ notes.push('A and B use different cloud ceilings.');
}
return {
ok: true,
@@ -226,7 +226,7 @@ export function changeCompatibility(a, b) {
label: 'Sentinel-1 radar',
from: passA.date,
to: passB.date,
- notes: ['Reads the rendered radar picture. Detect measures the backscatter itself.'],
+ notes: ['Reads the radar picture, not the backscatter.'],
methods: PIXEL_METHODS,
};
}
@@ -253,8 +253,8 @@ export function changeCompatibility(a, b) {
from: releaseA == null ? 'latest' : String(releaseA),
to: releaseB == null ? 'latest' : String(releaseB),
notes: [
- ...(mixed ? ['World Imagery is the live mosaic, so its date varies from place to place.'] : []),
- 'Releases often share pixels, so an unchanged spot is not proof of no change.',
+ ...(mixed ? ['World Imagery’s date varies by place.'] : []),
+ 'Releases share pixels, so no highlight is no proof.',
],
methods: PIXEL_METHODS,
};
@@ -289,7 +289,7 @@ export function changeCompatibility(a, b) {
label: `VIIRS · ${a.nightlights.source === 'noaa20' ? 'NOAA-20' : 'Suomi NPP'}`,
from: a.nightlights.day,
to: b.nightlights.day,
- notes: ['Moonlight and cloud change a single night. Compare several before concluding.'],
+ notes: ['Moon and cloud sway one night. Compare several.'],
methods: ['brightness', 'colour'],
};
}
diff --git a/frontend/src/lib/map/changeAssist.test.js b/frontend/src/lib/map/changeAssist.test.js
index 09c20c4..5b54dfa 100644
--- a/frontend/src/lib/map/changeAssist.test.js
+++ b/frontend/src/lib/map/changeAssist.test.js
@@ -37,7 +37,7 @@ describe('which pairs Difference reads', () => {
it('reads World Imagery against a Wayback release as indicative, with the reason', () => {
const answer = changeCompatibility(side({ provider: 'esri-world-imagery' }), side());
expect(answer).toMatchObject({ ok: true, grade: 'indicative' });
- expect(answer.notes.join(' ')).toContain('live mosaic');
+ expect(answer.notes.join(' ')).toContain('varies by place');
});
it('reads dated Sentinel-2 passes, and offers indices even across layers', () => {
diff --git a/frontend/src/lib/map/compareExport.js b/frontend/src/lib/map/compareExport.js
index 9dd48d3..7cbebe1 100644
--- a/frontend/src/lib/map/compareExport.js
+++ b/frontend/src/lib/map/compareExport.js
@@ -41,14 +41,26 @@ export const EXPORT_STYLE = Object.freeze({ INK, MUTED, BAND, ACCENT, FONT, MONO
/** The plate a mark's label sits on, and the ink written on it (`compareAnnotations.js`). */
const LABEL_INKS = ['#f5f6f7'];
+const rgbHex = ([red, green, blue]) => `#${[red, green, blue]
+ .map((value) => Number(value).toString(16).padStart(2, '0')).join('')}`;
+
/**
- * The colours a GIF must keep exactly, as the `keep` form field: every mark's
- * colour and the ink of its numeral, then the export's own inks and the
- * signature's. The server builds each frame's palette around them; the imagery
- * gets the rest.
+ * The colours a GIF must keep exactly, as the `keep` form field: the colours
+ * visible in Difference first, then every mark's colour and the ink of its
+ * numeral, followed by the export's own inks and the signature's. The server
+ * builds each frame's palette around them; the imagery gets the rest.
+ *
+ * `changePalette` is supplied only when the exported comparison carries a
+ * Difference reading. The final PNG frames already contain the reading; this
+ * list keeps its palette from being changed while the GIF encoder quantizes
+ * the satellite imagery around it.
*/
-export function gifColours(annotations = [], { signed = false } = {}) {
+export function gifColours(annotations = [], { signed = false, changePalette = null } = {}) {
const colours = [];
+ if (changePalette) {
+ const palette = CHANGE_PALETTES[changePalette] ?? CHANGE_PALETTES.directional;
+ colours.push(...Object.values(palette).map(rgbHex));
+ }
for (const mark of comparisonAnnotations(annotations)) {
colours.push(mark.colour);
if (mark.kind === 'number') colours.push(stampInk(mark));
diff --git a/frontend/src/lib/map/compareExport.test.js b/frontend/src/lib/map/compareExport.test.js
index 472f4e4..4a49851 100644
--- a/frontend/src/lib/map/compareExport.test.js
+++ b/frontend/src/lib/map/compareExport.test.js
@@ -271,6 +271,14 @@ describe('keeping colours in a GIF', () => {
expect(gifColours([], { signed: true }).split(',')).toContain('#e3e3e3');
});
+ it('keeps the active Difference palette when the comparison carries one', () => {
+ const kept = gifColours([], { changePalette: 'colourblind' }).split(',');
+ expect(kept.slice(0, 3)).toEqual(['#0072b2', '#e69f00', '#cc79a7']);
+ expect(gifColours([])).not.toContain('#0072b2');
+ expect(gifColours([], { changePalette: 'missing' }).split(',').slice(0, 3))
+ .toEqual(['#00e5ff', '#ff00aa', '#ffdd00']);
+ });
+
it('stays inside what the server reads', () => {
const marks = Array.from({ length: 60 }, (_, index) => ({
id: `m${index}`, kind: 'line', colour: `#${index.toString(16).padStart(6, '0')}`, points: [[0, 0], [1, 1]],
diff --git a/frontend/src/lib/map/detectWhen.js b/frontend/src/lib/map/detectWhen.js
index 8222fb9..f422c6e 100644
--- a/frontend/src/lib/map/detectWhen.js
+++ b/frontend/src/lib/map/detectWhen.js
@@ -13,7 +13,7 @@
import { sunPosition } from './changeDetect.js';
import { zoneRing } from './analyzers.js';
import { FULL_COVER } from './acquisitions.js';
-import { onTrack } from '../radar.js';
+import { onTrack, sameTrack } from '../radar.js';
/** How much a 10 m building's shadow may change length between two passes,
* in metres, before it reads as a change: half a Sentinel-2 pixel. */
@@ -115,16 +115,29 @@ export function withRule(pairs, against) {
return pairs.map((pair) => ({ ...pair, date_rule: rule }));
}
+/** A dated comparison needs A before B. Radar can compare two timed passes on one day. */
+export function passBefore(a, b, radar = false) {
+ if (!a?.date || !b?.date) return true;
+ if (a.date !== b.date) return a.date < b.date;
+ return !!(radar && a.time && b.time && a.time < b.time);
+}
+
+/** A calendar choice must keep dated comparisons ordered and radar passes on one track. */
+export function canPickPass(letter, pass, a, b, radar = false) {
+ const other = letter === 'a' ? b : a;
+ const ordered = letter === 'a' ? passBefore(pass, b, radar) : passBefore(a, pass, radar);
+ return ordered && (!radar || !other?.time || sameTrack(pass.time, other.time));
+}
+
/**
* What still stops the step, in one sentence, or ''.
*
* A routine that compares with its previous pass needs A only until a run has
* finished, which a saved routine may already have.
*/
-export function whenNeed({ single, routine, against, followupId, pairs, chooseB }) {
- const waived = routine && followupId && against === 'previous';
- const noA = pairs.filter((pair) => !pair.a?.date);
- if (!single && !waived && noA.length) {
+export function whenNeed({ single, routine, against, pairs, chooseB, lastPasses = {}, radar = false }) {
+ const noA = pairs.filter((pair) => !pair.a?.date && !(routine && against === 'previous' && lastPasses[pair.area_id]));
+ if (!single && noA.length) {
if (noA.length < pairs.length) return 'Choose A for every area.';
if (!routine) return 'Choose A, the picture before.';
return `Choose A, the picture ${against === 'previous' ? 'the first run' : 'every run'} compares with.`;
@@ -132,6 +145,9 @@ export function whenNeed({ single, routine, against, followupId, pairs, chooseB
if (!routine && chooseB && pairs.some((pair) => !pair.b?.date)) {
return single ? 'Choose the day, or take the newest pass.' : 'Choose the day of B, or take the newest pass.';
}
+ if (!single && pairs.some((pair) => !passBefore(
+ routine && against === 'previous' && lastPasses[pair.area_id] || pair.a, pair.b, radar
+ ))) return 'Date A must be before date B.';
return '';
}
diff --git a/frontend/src/lib/map/detectWhen.test.js b/frontend/src/lib/map/detectWhen.test.js
index 719ef3d..9c3d0f9 100644
--- a/frontend/src/lib/map/detectWhen.test.js
+++ b/frontend/src/lib/map/detectWhen.test.js
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest';
import {
- ADVISED_MAXCC, areaLine, ceilingWarning, newestLabel, newestLine, newestPick, setSide, shadowLength, shadowWarning, sharedSide, sideLine, uniform,
+ ADVISED_MAXCC, areaLine, canPickPass, ceilingWarning, newestLabel, newestLine, newestPick, passBefore, setSide, shadowLength, shadowWarning, sharedSide, sideLine, uniform,
whenNeed, whenSummary, withRule,
} from './detectWhen.js';
@@ -61,12 +61,37 @@ describe('the When step of a detection', () => {
expect(whenNeed({ ...base, single: true, pairs: [pair('x')] })).toBe('');
});
+ it('requires A before B for each dated comparison, including radar time', () => {
+ const base = { single: false, routine: false, against: 'previous', chooseB: true };
+ expect(passBefore({ date: '2026-09-05' }, { date: '2026-09-06' })).toBe(true);
+ expect(passBefore({ date: '2026-09-07' }, { date: '2026-09-06' })).toBe(false);
+ expect(passBefore({ date: '2026-09-06' }, { date: '2026-09-06' })).toBe(false);
+ expect(passBefore({ date: '2026-09-06', time: '05:00:00' },
+ { date: '2026-09-06', time: '17:00:00' }, true)).toBe(true);
+ expect(whenNeed({ ...base, pairs: [pair('x', '2026-09-07', '2026-09-06')] }))
+ .toBe('Date A must be before date B.');
+ expect(whenNeed({ ...base, pairs: [pair('x', '2026-09-05', '2026-09-06'),
+ pair('y', '2026-09-07', '2026-09-06')] })).toBe('Date A must be before date B.');
+ });
+
+ it('keeps radar calendar choices on the other date\'s track', () => {
+ const a = { date: '2026-09-05', time: '05:00:00' };
+ const same = { date: '2026-09-17', time: '05:00:02' };
+ const other = { date: '2026-09-17', time: '05:08:00' };
+ expect(canPickPass('b', same, a, null, true)).toBe(true);
+ expect(canPickPass('b', other, a, null, true)).toBe(false);
+ expect(canPickPass('a', a, null, other, true)).toBe(false);
+ expect(canPickPass('b', { ...same, date: '2026-09-04' }, a, null, true)).toBe(false);
+ });
+
it('asks a routine for A until a run has finished', () => {
const base = { single: false, routine: true, chooseB: true, pairs: [pair('x')] };
expect(whenNeed({ ...base, against: 'previous', followupId: null }))
.toBe('Choose A, the picture the first run compares with.');
- expect(whenNeed({ ...base, against: 'previous', followupId: 'abcdef123456' })).toBe('');
- expect(whenNeed({ ...base, against: 'reference', followupId: 'abcdef123456' }))
+ expect(whenNeed({ ...base, against: 'previous', lastPasses: { x: { date: '2026-08-01' } } })).toBe('');
+ expect(whenNeed({ ...base, against: 'previous', lastPasses: {} }))
+ .toBe('Choose A, the picture the first run compares with.');
+ expect(whenNeed({ ...base, against: 'reference', lastPasses: { x: { date: '2026-08-01' } } }))
.toBe('Choose A, the picture every run compares with.');
// a routine names no B, whatever the switch last said
expect(whenNeed({ ...base, single: true, against: 'previous', followupId: null })).toBe('');
diff --git a/frontend/src/lib/map/detections.js b/frontend/src/lib/map/detections.js
index 9431501..20aacf0 100644
--- a/frontend/src/lib/map/detections.js
+++ b/frontend/src/lib/map/detections.js
@@ -5,6 +5,8 @@
* the runs started without saving one stand on their own.
*/
+import { foldText } from '../textFold.js';
+
export const ACTIVE = Object.freeze(['queued', 'running']);
export const isActive = (row) => ACTIVE.includes(row?.status);
@@ -81,6 +83,15 @@ export function runState(run) {
}
/** How a detection picks its imagery, short enough for a list row. */
+/** Past five routines the list gets a search box; below, a glance finds one. */
+export const ROUTINE_SEARCH_FROM = 6;
+
+/** Whether a routine answers every word of a search, in its title, note or analyzer. */
+export function routineMatches(routine, query) {
+ const text = foldText([routine.title, routine.note, routine.analyzer].filter(Boolean).join(' '));
+ return foldText(query).split(/\s+/).filter(Boolean).every((word) => text.includes(word));
+}
+
export function ruleLabel(rule, single) {
if (rule === 'manual') return 'fixed dates';
if (single) return 'newest pass';
diff --git a/frontend/src/lib/map/detections.test.js b/frontend/src/lib/map/detections.test.js
index 7ec5e82..fbef0e9 100644
--- a/frontend/src/lib/map/detections.test.js
+++ b/frontend/src/lib/map/detections.test.js
@@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest';
import {
detectionsWithRuns,
isActive,
+ routineMatches,
ruleLabel,
runDays,
runState,
@@ -81,3 +82,17 @@ describe('what a row says', () => {
expect(settledMessage({ title: 'Harbour', status: 'cancelled' })).toBe(null);
});
});
+
+describe('routineMatches', () => {
+ const routine = { title: 'Port de Tartous', note: 'Quai nord, jetée', analyzer: 'Vessels by radar' };
+ it('finds a routine by any word of its title, note or analyzer, accents and case aside', () => {
+ expect(routineMatches(routine, 'tartous')).toBe(true);
+ expect(routineMatches(routine, 'JETEE')).toBe(true);
+ expect(routineMatches(routine, 'radar port')).toBe(true);
+ expect(routineMatches(routine, ' ')).toBe(true);
+ });
+ it('needs every word', () => {
+ expect(routineMatches(routine, 'radar airbase')).toBe(false);
+ expect(routineMatches({ title: 'Airbase' }, 'port')).toBe(false);
+ });
+});
diff --git a/frontend/src/lib/markdown.js b/frontend/src/lib/markdown.js
index ff395a7..8825d8b 100644
--- a/frontend/src/lib/markdown.js
+++ b/frontend/src/lib/markdown.js
@@ -99,7 +99,7 @@ function imageMarkup({ href, alt, title, width, align }) {
return { attrs, className: `markdown-image align-${align}` };
}
-function renderer({ entities, caseId }) {
+function renderer({ entities, caseId, redirects }) {
const byId = new Map(entities.map((entity) => [entity.id, entity]));
const mediaByPath = new Map(entities
.filter((entity) => (entity.type === 'media' || entity.type === 'capture') && entity.attrs?.path)
@@ -120,8 +120,11 @@ function renderer({ entities, caseId }) {
const body = this.parser.parseInline(token.tokens);
const entityMatch = /^azimut:\/\/entity\/([A-Za-z0-9_-]+)$/.exec(token.href);
if (entityMatch) {
- return byId.has(entityMatch[1])
- ? `<a href="#" data-entity-id="${entityMatch[1]}" class="entity-ref">${body}</a>`
+ const id = redirects[entityMatch[1]]?.id ?? entityMatch[1];
+ const entity = byId.get(id);
+ const title = id !== entityMatch[1] && entity ? ` title="Merged into ${escapeHtml(entity.label)}"` : '';
+ return entity
+ ? `<a href="#" data-entity-id="${escapeHtml(id)}" class="entity-ref"${title}>${body}</a>`
: broken('Reference unavailable', body);
}
const mediaMatch = /^azimut:\/\/media\/([A-Za-z0-9_-]+)$/.exec(token.href);
@@ -175,11 +178,11 @@ function renderAlignmentBlocks(source, options) {
}
/** Render GitHub-flavored Markdown, then remove unsafe HTML before previewing it. */
-export function markdownHtml(text = '', { entities = [], caseId = '' } = {}) {
+export function markdownHtml(text = '', { entities = [], caseId = '', redirects = {} } = {}) {
const options = {
gfm: true,
breaks: false,
- renderer: renderer({ entities, caseId }),
+ renderer: renderer({ entities, caseId, redirects }),
};
const rendered = renderAlignmentBlocks(sourceWithCaseReferences(text), options);
return sanitize(rendered);
diff --git a/frontend/src/lib/markdown.test.js b/frontend/src/lib/markdown.test.js
index 9f047b5..90594ed 100644
--- a/frontend/src/lib/markdown.test.js
+++ b/frontend/src/lib/markdown.test.js
@@ -28,6 +28,19 @@ describe('markdownHtml', () => {
.toContain('Media unavailable: Deleted image');
});
+ it('opens the survivor while preserving the original wording and escaping its label', () => {
+ const source = '[[entity:old|Earlier name]]';
+ const html = markdownHtml(source, {
+ entities: [{ id: 'kept', label: 'Kept "subject" <test>' }],
+ redirects: { old: { id: 'kept', label: 'Earlier name' } },
+ });
+ expect(html).toContain('data-entity-id="kept"');
+ expect(html).toContain('Merged into Kept &quot;subject&quot; &lt;test&gt;');
+ expect(html).toContain('>Earlier name</a>');
+ expect(markdownHtml(source, { redirects: { old: { id: 'gone' } } }))
+ .toContain('Reference unavailable');
+ });
+
it('sizes and aligns images without allowing unsafe values', () => {
const html = markdownHtml('![Map](/map.png){width=50% align=center}');
expect(html).toContain('class="markdown-image align-center"');
diff --git a/frontend/src/lib/mediaFilter.js b/frontend/src/lib/mediaFilter.js
index 77c1505..3ac941a 100644
--- a/frontend/src/lib/mediaFilter.js
+++ b/frontend/src/lib/mediaFilter.js
@@ -2,13 +2,15 @@
* Free-text search + sorting for the Media Library grid. Pure functions so a
* case with hundreds of items stays navigable and the behavior stays testable.
*/
+import { foldTerms, foldText } from './textFold.js';
-/** Case-insensitive match against everything the analyst might remember:
- * filename, title, notes, folder, and the download's title/uploader/URL. */
+/** A match against everything the analyst might remember: filename, title, notes,
+ * folder, and the download's title/uploader/URL. Folded like the server's index
+ * (`store/rows._media_search_text`), so `cafe` finds `Café` on either side. */
export function matchesQuery(item, query) {
- const q = (query ?? '').trim().toLowerCase();
- if (!q) return true;
- const haystack = [
+ const terms = foldTerms(query);
+ if (!terms.length) return true;
+ const haystack = foldText([
item.filename,
item.title,
item.notes,
@@ -18,9 +20,8 @@ export function matchesQuery(item, query) {
item.source?.webpage_url ?? item.source?.url,
]
.filter(Boolean)
- .join('\n')
- .toLowerCase();
- return q.split(/\s+/).every((term) => haystack.includes(term));
+ .join('\n'));
+ return terms.every((term) => haystack.includes(term));
}
/** True for native satellite captures and extension screenshots whose URL
diff --git a/frontend/src/lib/mediaFilter.test.js b/frontend/src/lib/mediaFilter.test.js
index 17eb04c..fb11b8d 100644
--- a/frontend/src/lib/mediaFilter.test.js
+++ b/frontend/src/lib/mediaFilter.test.js
@@ -33,6 +33,11 @@ describe('matchesQuery', () => {
expect(matchesQuery(item(), 'mosque')).toBe(false);
});
+ it('finds a title whatever accents it was written with, as the index does', () => {
+ expect(matchesQuery(item({ title: 'Arrivée au quai' }), 'arrivee')).toBe(true);
+ expect(matchesQuery(item({ notes: 'Москва́' }), 'МОСКВА')).toBe(true);
+ });
+
it('matches on title, notes and folder', () => {
expect(matchesQuery(item({ title: 'Mosque strike' }), 'mosque')).toBe(true);
expect(matchesQuery(item({ notes: 'seen near the bridge' }), 'bridge')).toBe(true);
@@ -116,6 +121,7 @@ describe('the shared facet list', () => {
const links = read('../../../src/azimut/engine/links.py');
const types = [
...quoted(links.match(/^MADE_HERE: .* = \(([^)]*)\)/m)[1]),
+ ...quoted(links.match(/^FROM_ABOVE: .* = \(([^)]*)\)/m)[1]),
...quoted(links.match(/^PRODUCED_HERE: .* = \(([^)]*)\)/m)[1]),
];
expect(types).toContain('compare');
diff --git a/frontend/src/lib/navigate.js b/frontend/src/lib/navigate.js
index 881499d..d23bf4e 100644
--- a/frontend/src/lib/navigate.js
+++ b/frontend/src/lib/navigate.js
@@ -5,6 +5,7 @@
* the Details editor send an analyst to the same place.
*/
import { caseState, toast, uiState } from './state.svelte.js';
+import { api } from './api.js';
import { mediaKindOf } from './entityIcon.js';
import { GUIDE, guideFor } from './guide.js';
import { revealMediaFolder } from './reveal.js';
@@ -78,8 +79,44 @@ export function showInFolder(entity) {
return revealMediaFolder(caseId, path).catch((e) => toast(e.message, 'warn', 5000));
}
+/** The window a Claim's entry is read in: the entry, with as much again on either
+ * side and never less than half a day, so its neighbours are in view. */
+export function claimWindow(item) {
+ const first = new Date(item?.earliest ?? '').getTime();
+ const last = new Date(item?.latest ?? '').getTime();
+ if (!Number.isFinite(first) || !Number.isFinite(last)) return null;
+ const pad = Math.max((last - first) * 2, 12 * 3600 * 1000);
+ return { from: new Date(first - pad).toISOString(), to: new Date(last + pad).toISOString() };
+}
+
+/**
+ * Where a Claim is read: on the Timeline, at its own entry.
+ *
+ * A dated one opens the window around it with the entry selected; an undated one
+ * opens the Undated queue, and one whose clock is unknown the "Not on UTC axis" list,
+ * with the entry selected either way. The row comes from the route that says where a
+ * Claim sits, so a Claim past the first page still lands.
+ */
+export function openClaim(item) {
+ if (!item?.id) return;
+ const window = item.sortable ? claimWindow(item) : null;
+ if (window) uiState.timelineRange = { ...window, itemId: item.id, item };
+ else uiState.timelineQueue = { queue: item.earliest || !item.raw ? 'undated' : 'unplaced', itemId: item.id, item };
+ uiState.tool = 'timeline';
+}
+
/** Reopen an artifact in its tool, loading whatever spec/draft it carries. */
-export function openEntity(entity) {
+export function openEntity(entity, resolved = false) {
+ // Places navigate by coordinates, so resolve an old snapshot's id before flying.
+ // Other mergeable subjects open Details, whose chain read resolves the id.
+ if (entity?.type === 'place' && entity.id && caseState.current?.id && !resolved) {
+ const cid = caseState.current.id;
+ return api.get(`/api/cases/${cid}/entities/${entity.id}/chain`).then((chain) => {
+ if (caseState.current?.id !== cid) return;
+ if (chain.merged_from) toast(`Merged into ${chain.entity.label}`, 'info');
+ openEntity(chain.entity, true);
+ }).catch((error) => toast(error.message, 'danger'));
+ }
// A file the app cannot show is opened where it actually lives. This runs before
// the type branches below, so every surface that follows an entity — a relation
// row, a chain row, the sidebar — makes the same call.
@@ -87,6 +124,19 @@ export function openEntity(entity) {
void showInFolder(entity);
return;
}
+ // A Claim is an event, and events are read on the Timeline. The Board still lists
+ // it with the rest of the case, and its Details are one click from the entry.
+ if (entity?.type === 'claim' && entity.id && caseState.current?.id) {
+ const cid = caseState.current.id;
+ return api.get(`/api/cases/${cid}/timeline/claims/${entity.id}`).then((body) => {
+ if (caseState.current?.id !== cid) return;
+ openClaim(body.item);
+ }).catch(() => {
+ if (caseState.current?.id !== cid) return;
+ uiState.openBoardEntity = entity.id;
+ uiState.tool = 'board';
+ });
+ }
if (entity.type === 'note') {
uiState.openNotebook = { noteId: entity.id };
uiState.tool = 'notebook';
@@ -175,10 +225,10 @@ export function openEntity(entity) {
uiState.tool = tool;
return;
}
- // A person, an account, a claim: the graph-only types have no tool that reopens
- // them, and until the board existed this call ended here doing nothing at all —
- // a relation row on the map said "Open …" and swallowed the click. The board is
- // where they are read, so that is where the jump lands.
+ // A person, an account, a place-less subject: the graph-only types have no tool
+ // that reopens them, and until the board existed this call ended here doing nothing
+ // at all — a relation row on the map said "Open …" and swallowed the click. The
+ // board is where they are read, so that is where the jump lands.
if (entity.id) {
uiState.openBoardEntity = entity.id;
uiState.tool = 'board';
diff --git a/frontend/src/lib/navigate.test.js b/frontend/src/lib/navigate.test.js
index f28cca0..28cd2e3 100644
--- a/frontend/src/lib/navigate.test.js
+++ b/frontend/src/lib/navigate.test.js
@@ -1,7 +1,8 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
const post = vi.fn().mockResolvedValue({ path: '/cases/c1/azimut/media' });
-vi.mock('./api.js', () => ({ api: { post: (...a) => post(...a), get: vi.fn() } }));
+const get = vi.fn();
+vi.mock('./api.js', () => ({ api: { post: (...a) => post(...a), get: (...a) => get(...a) } }));
const { caseState, uiState } = await import('./state.svelte.js');
const { gotoCapture, gotoPoint, openComparison, openEntity, openGuide, openInReverseSearch, openMapAt, opensInFileManager } =
@@ -56,6 +57,14 @@ describe('openInReverseSearch', () => {
});
describe('openEntity', () => {
+ it('opens a merged place at the survivor coordinates instead of frozen coordinates', async () => {
+ get.mockResolvedValue({ entity: { id: 'kept', type: 'place', label: 'Kept place', attrs: { lat: 3, lon: 4 } }, merged_from: { id: 'old', label: 'Old place' } });
+ openEntity({ id: 'old', type: 'place', attrs: { lat: 1, lon: 2 } });
+ for (let i = 0; i < 5; i++) await Promise.resolve();
+ expect(get).toHaveBeenCalledWith('/api/cases/c1/entities/old/chain');
+ expect(uiState.gotoCoords.lat).toBe(3);
+ expect(uiState.gotoCoords.lon).toBe(4);
+ });
it('opens bookmarks and external captures in a new browser tab', () => {
openEntity({ type: 'bookmark', attrs: { url: 'https://example.test/bookmark' } });
openEntity({ type: 'capture', attrs: { source_url: 'https://maps.example.test/view' } });
@@ -114,6 +123,59 @@ describe('a type with no tool of its own', () => {
});
});
+describe('a Claim', () => {
+ beforeEach(() => {
+ uiState.timelineRange = null;
+ uiState.timelineQueue = null;
+ get.mockReset();
+ });
+ const claim = { id: 'e-claim', type: 'claim', label: 'Column seen', attrs: {} };
+
+ it('opens on the Timeline at its entry, with its neighbours in view', async () => {
+ const item = {
+ id: 'temporal:claim:e-claim', raw: '2026-03-12', sortable: true,
+ earliest: '2026-03-12T00:00:00.000000Z', latest: '2026-03-13T00:00:00.000000Z',
+ };
+ get.mockResolvedValueOnce({ item });
+ await openEntity(claim);
+
+ expect(get).toHaveBeenCalledWith('/api/cases/c1/timeline/claims/e-claim');
+ expect(uiState.tool).toBe('timeline');
+ expect(uiState.timelineRange).toEqual({
+ from: '2026-03-10T00:00:00.000Z',
+ to: '2026-03-15T00:00:00.000Z',
+ itemId: 'temporal:claim:e-claim',
+ item,
+ });
+ expect(uiState.openBoardEntity).toBeNull();
+ });
+
+ it('opens the Undated queue on an entry with no date', async () => {
+ const item = { id: 'temporal:claim:e-claim', raw: null, earliest: null, latest: null, sortable: false };
+ get.mockResolvedValueOnce({ item });
+ await openEntity(claim);
+
+ expect(uiState.tool).toBe('timeline');
+ expect(uiState.timelineQueue).toEqual({ queue: 'undated', itemId: item.id, item });
+ });
+
+ it('opens the list of entries off the UTC axis on one it cannot place', async () => {
+ const item = { id: 'temporal:claim:e-claim', raw: '2026-03-12T14:00', earliest: null, latest: null, sortable: false };
+ get.mockResolvedValueOnce({ item });
+ await openEntity(claim);
+
+ expect(uiState.timelineQueue).toEqual({ queue: 'unplaced', itemId: item.id, item });
+ });
+
+ it('falls back to its row on the Board when the Timeline cannot say', async () => {
+ get.mockRejectedValueOnce(new Error('gone'));
+ await openEntity(claim);
+
+ expect(uiState.tool).toBe('board');
+ expect(uiState.openBoardEntity).toBe('e-claim');
+ });
+});
+
describe('gotoCapture', () => {
it('leaves the zoom to the map when the capture records none', () => {
gotoCapture({ type: 'capture', attrs: { lat: 48.8584, lon: 2.2945, zoom: null } });
diff --git a/frontend/src/lib/noteHere.svelte.js b/frontend/src/lib/noteHere.svelte.js
new file mode 100644
index 0000000..6be576d
--- /dev/null
+++ b/frontend/src/lib/noteHere.svelte.js
@@ -0,0 +1,102 @@
+/**
+ * What the tool on screen is looking at, for the Add event bar.
+ *
+ * The bar opens over whichever tool the analyst is in, and an event noted from a
+ * video should already cite that video. So each tool that has a current thing says
+ * so here; the bar reads it for the tool it is opened over and nothing else, so a
+ * selection left in a hidden tab never seats itself on a line typed somewhere else.
+ *
+ * Only what the tool knows for certain: the thing selected. A date is never offered
+ * (D3), a place only when the file has exactly one confirmed (`placeOf`), and no
+ * subject is guessed from anything.
+ */
+export const noteHere = $state({ byTool: {}, datesByTool: {} });
+
+/**
+ * A tool says what is selected in it, or null for nothing, and the dates it can
+ * offer beside the date field (a pair's "between A and B"), each one press, never
+ * filled in by itself. Kept per tool, since every visited tool stays mounted and one
+ * hidden tab must not overwrite another's.
+ */
+export function offerNote(tool, entity, { dates = [] } = {}) {
+ noteHere.byTool[tool] = entity?.id
+ ? { id: entity.id, label: entity.label ?? '', type: entity.type, attrs: entity.attrs ?? {} }
+ : null;
+ // A function is read when the bar opens: a map's pictures know their dates only
+ // when asked, and a list copied at every pan would be work nobody reads.
+ noteHere.datesByTool[tool] = typeof dates === 'function' ? dates : dates.filter((offer) => offer?.value);
+}
+
+/** A tool going away takes its selection back. */
+export function withdrawNote(tool) {
+ delete noteHere.byTool[tool];
+ delete noteHere.datesByTool[tool];
+}
+
+/** The thing the bar seats for this tool, or null. */
+export function noteEntityFor(tool) {
+ return noteHere.byTool[tool] ?? null;
+}
+
+/** The dates this tool offers the bar. */
+export function noteDatesFor(tool) {
+ const held = noteHere.datesByTool[tool];
+ const dates = typeof held === 'function' ? held() : held;
+ return (dates ?? []).filter((offer) => offer?.value);
+}
+
+/**
+ * The dates a pair of pictures offers: each one, and the span between them, which is
+ * what a change seen between two pictures is known to within. `a` and `b` are
+ * `{ value, exact }`, each picture's date as the case writes it and whether it is
+ * the picture's own or a release's; the span is `lib/timeline`'s `changeInterval`,
+ * handed in so this stays pure.
+ */
+export function pairOffers(a, b, { interval, label }) {
+ // A picture known only to its release date is an estimate, and says so, in the
+ // value it offers and in its words.
+ const mark = (side) => (side?.value ? `${side.value}${side.exact === false ? '~' : ''}` : '');
+ const say = (side) => (side?.value ? `${side.exact === false ? '~' : ''}${label(side.value)}` : '');
+ const first = mark(a);
+ const second = mark(b);
+ const offers = [];
+ const between = first && second ? interval(first, second) : '';
+ if (between) {
+ offers.push({ kind: 'between', value: between, words: `between ${say(a)} and ${say(b)}`, hint: 'The change happened between the two pictures' });
+ }
+ if (first) offers.push({ kind: 'picture A', value: first, words: `A ${say(a)}`, hint: 'Use the day picture A was taken' });
+ if (second) offers.push({ kind: 'picture B', value: second, words: `B ${say(b)}`, hint: 'Use the day picture B was taken' });
+ return offers;
+}
+
+/** The verbs that put a file at a place. */
+const PLACING = new Set(['located-at', 'depicts', 'sited-at']);
+
+/**
+ * The one place a file is confirmed at, read off its chain, or null.
+ *
+ * Only a single confirmed place is seated: two places are a choice for the analyst,
+ * and seating a suggested one would confirm it through the one-hop rule without the
+ * analyst having decided it.
+ */
+export function placeOf(chain) {
+ const places = new Map();
+ for (const relation of chain?.relations ?? []) {
+ const { entity, link, direction } = relation ?? {};
+ if (direction !== 'out' || !PLACING.has(link?.type) || entity?.type !== 'place') continue;
+ if ((link.provenance?.status ?? 'confirmed') !== 'confirmed') return null;
+ if ((entity.provenance?.status ?? 'confirmed') !== 'confirmed') return null;
+ places.set(entity.id, entity);
+ }
+ if (places.size !== 1) return null;
+ const [place] = places.values();
+ return { id: place.id, label: place.label, type: place.type, attrs: place.attrs ?? {}, slot: 'at' };
+}
+
+/** Whether a keypress is the Add event shortcut, Alt+N, outside any field. */
+export function isNoteKey(event) {
+ if (!event?.altKey || event.ctrlKey || event.metaKey || event.shiftKey) return false;
+ if (event.code !== 'KeyN') return false;
+ const editable = 'input, textarea, select, [contenteditable=""], [contenteditable="true"]';
+ return !event.target?.closest?.(editable);
+}
diff --git a/frontend/src/lib/noteHere.test.js b/frontend/src/lib/noteHere.test.js
new file mode 100644
index 0000000..c769a66
--- /dev/null
+++ b/frontend/src/lib/noteHere.test.js
@@ -0,0 +1,106 @@
+// @vitest-environment happy-dom
+import { beforeEach, describe, expect, it } from 'vitest';
+import { changeInterval, formatTemporalValue } from './timeline.js';
+import {
+ isNoteKey, noteDatesFor, noteEntityFor, noteHere, offerNote, pairOffers, placeOf, withdrawNote,
+} from './noteHere.svelte.js';
+
+const relation = (place, { type = 'located-at', status = 'confirmed', direction = 'out' } = {}) => ({
+ entity: { id: place, type: 'place', label: place, attrs: {}, provenance: { status: 'confirmed' } },
+ link: { type, provenance: { status } },
+ direction,
+});
+
+beforeEach(() => {
+ for (const tool of Object.keys(noteHere.byTool)) withdrawNote(tool);
+});
+
+describe('what a tool offers the Add event bar', () => {
+ it('keeps each tool’s selection to that tool', () => {
+ offerNote('media', { id: 'm1', label: 'VID_0312', type: 'media', attrs: { path: 'a.mp4' } });
+ offerNote('satellite', { id: 'p1', label: 'Crossroads', type: 'place' });
+ expect(noteEntityFor('media')).toEqual({ id: 'm1', label: 'VID_0312', type: 'media', attrs: { path: 'a.mp4' } });
+ expect(noteEntityFor('satellite').id).toBe('p1');
+ expect(noteEntityFor('proof')).toBeNull();
+ });
+
+ it('takes it back when nothing is selected or the tool goes', () => {
+ offerNote('media', { id: 'm1', type: 'media' });
+ offerNote('media', null);
+ expect(noteEntityFor('media')).toBeNull();
+ offerNote('media', { id: 'm1', type: 'media' });
+ withdrawNote('media');
+ expect(noteEntityFor('media')).toBeNull();
+ });
+});
+
+describe('the place a file is seated at', () => {
+ it('is its one confirmed place', () => {
+ expect(placeOf({ relations: [relation('p1')] })).toMatchObject({ id: 'p1', slot: 'at' });
+ expect(placeOf({ relations: [relation('p1', { type: 'depicts' }), relation('p1')] })).toMatchObject({ id: 'p1' });
+ });
+
+ it('is nothing when there are two, or one a tool only suggested', () => {
+ // seating a suggestion would confirm it without the analyst having decided it
+ expect(placeOf({ relations: [relation('p1'), relation('p2')] })).toBeNull();
+ expect(placeOf({ relations: [relation('p1', { status: 'suggested' })] })).toBeNull();
+ expect(placeOf({ relations: [relation('p1', { direction: 'in' })] })).toBeNull();
+ expect(placeOf(null)).toBeNull();
+ });
+});
+
+describe('the shortcut', () => {
+ const key = (init, target = document.body) => ({ altKey: true, code: 'KeyN', target, ...init });
+
+ it('is Alt+N, whatever letter the layout types for it', () => {
+ expect(isNoteKey(key({ key: '˜' }))).toBe(true);
+ expect(isNoteKey(key({ ctrlKey: true }))).toBe(false);
+ expect(isNoteKey(key({ metaKey: true }))).toBe(false);
+ expect(isNoteKey(key({ altKey: false }))).toBe(false);
+ expect(isNoteKey(key({ code: 'KeyM' }))).toBe(false);
+ });
+
+ it('never fires from inside a field', () => {
+ const input = document.createElement('input');
+ document.body.append(input);
+ expect(isNoteKey(key({}, input))).toBe(false);
+ input.remove();
+ });
+});
+
+describe('the dates a place offers', () => {
+ const label = (value) => formatTemporalValue(value).label;
+
+ it('offers a pair its span first, then each picture', () => {
+ const offers = pairOffers(
+ { value: '2026-03-11', exact: true },
+ { value: '2026-03-19', exact: true },
+ { interval: changeInterval, label }
+ );
+ expect(offers.map((offer) => [offer.value, offer.words])).toEqual([
+ ['2026-03-11/2026-03-19', 'between 11 Mar 2026 and 19 Mar 2026'],
+ ['2026-03-11', 'A 11 Mar 2026'],
+ ['2026-03-19', 'B 19 Mar 2026'],
+ ]);
+ });
+
+ it('marks a release date as an estimate', () => {
+ const [between, first] = pairOffers(
+ { value: '2024-05-03', exact: false },
+ { value: '2026-09-02', exact: true },
+ { interval: changeInterval, label }
+ );
+ expect(first).toMatchObject({ value: '2024-05-03~', words: 'A ~3 May 2024' });
+ expect(between.value).toBe('2024-05-03~/2026-09-02');
+ });
+
+ it('reads a tool’s dates when the bar asks, not when the tool moves', () => {
+ let calls = 0;
+ offerNote('compare', null, { dates: () => { calls += 1; return [{ kind: 'between', value: '2026-03-11/2026-03-19' }]; } });
+ expect(calls).toBe(0);
+ expect(noteDatesFor('compare')).toHaveLength(1);
+ expect(calls).toBe(1);
+ withdrawNote('compare');
+ expect(noteDatesFor('compare')).toEqual([]);
+ });
+});
diff --git a/frontend/src/lib/overview.test.js b/frontend/src/lib/overview.test.js
index 73e2d2d..47ffcd0 100644
--- a/frontend/src/lib/overview.test.js
+++ b/frontend/src/lib/overview.test.js
@@ -40,6 +40,8 @@ describe('what the case is waiting on', () => {
it('leaves "added this week" out: it says what happened, not what is outstanding', () => {
expect(WAITING.map((row) => row.id)).not.toContain('week');
+ // Four tiles, two by two: the questions about claims stay in the Board's menu.
+ expect(WAITING).toHaveLength(4);
});
it('reads each count off the payload that already holds it', () => {
diff --git a/frontend/src/lib/plate.js b/frontend/src/lib/plate.js
index 65c9954..e4abc39 100644
--- a/frontend/src/lib/plate.js
+++ b/frontend/src/lib/plate.js
@@ -13,6 +13,7 @@
*/
import { exactStamp } from './analysisViews.js';
+import { bidiIsolate } from './bidi.js';
/**
* The plate's own geometry, in SVG user units (a unit is a pixel at 1:1).
@@ -116,7 +117,7 @@ const attrs = (pairs) =>
export function svgText(text, {
x, y, size = PLATE.metaSize, fill = PLATE_COLOURS.ink, weight, anchor, opacity, halo,
} = {}) {
- const clean = String(text ?? '');
+ const clean = bidiIsolate(text);
if (!clean.trim()) return '';
return `<text ${attrs({
x: round(x),
diff --git a/frontend/src/lib/plate.test.js b/frontend/src/lib/plate.test.js
index 7b7f8c6..3721c2e 100644
--- a/frontend/src/lib/plate.test.js
+++ b/frontend/src/lib/plate.test.js
@@ -186,6 +186,11 @@ describe('serialising text', () => {
expect(svgText('Quay 4', { x: 1, y: 2 })).not.toContain('paint-order');
});
+ it('draws an Arabic or Hebrew label in its own direction', () => {
+ expect(svgText('مسجد 12', { x: 1, y: 2 })).toContain('>\u2068مسجد 12\u2069</text>');
+ expect(svgText('Quay 4', { x: 1, y: 2 })).toContain('>Quay 4</text>');
+ });
+
it('writes nothing for a label with nothing in it', () => {
expect(svgText(' ', { x: 1, y: 2 })).toBe('');
expect(svgText(null, { x: 1, y: 2 })).toBe('');
diff --git a/frontend/src/lib/post.js b/frontend/src/lib/post.js
index 3a77eeb..170ba36 100644
--- a/frontend/src/lib/post.js
+++ b/frontend/src/lib/post.js
@@ -20,6 +20,7 @@ export const TWEET_TOKENS = [
{ tag: '#description', label: 'Description', sample: 'Rooftop match against the reference imagery' },
{ tag: '#mention', label: 'Mention', sample: '@GeoConfirmed' },
{ tag: '#source', label: 'Source', sample: 'https://x.com/example/status/1' },
+ { tag: '#date', label: 'Date', sample: '2025-10-24 14:30 UTC+3' },
];
export const MAX_POST_MEDIA = 4;
@@ -359,6 +360,7 @@ const TOKEN_FIELD = {
'#description': 'description',
'#mention': 'mention',
'#source': 'source',
+ '#date': 'date',
};
// A template can omit a draft field by leaving its token out of the body.
@@ -370,9 +372,62 @@ const FIELD_TOKENS = {
place: ['#place'],
mention: ['#mention'],
source: ['#source'],
+ date: ['#date'],
};
-const TOKEN_RE = /#(?:place|pluscode|coordinates|description|mention|source)/gi;
+// A token ends where the word does: `#placement` is text, not `#place` and "ment",
+// and a `#dates` hashtag a template already carried stays a hashtag.
+const TOKEN_TAIL = '(?![\\p{L}\\p{N}_])';
+const TOKEN_RE = new RegExp(
+ `#(?:${Object.keys(TOKEN_FIELD).map((tag) => tag.slice(1)).join('|')})${TOKEN_TAIL}`,
+ 'giu',
+);
+
+/** The tokens a body holds, lower-cased, in the order it holds them. */
+export function bodyTokens(body) {
+ return (String(body ?? '').match(TOKEN_RE) ?? []).map((token) => token.toLowerCase());
+}
+
+/**
+ * `#words` in a body that look like a token and are not one: `#coordinate`,
+ * `#Sources`, `#plus_code`. Each would go out as text, silently, so the editor
+ * names them. Close means one edit away, or the same letters with the
+ * separators and a final `s` taken out; a real hashtag is left alone.
+ */
+export function misspelledTokens(body) {
+ const tags = Object.keys(TOKEN_FIELD).map((tag) => tag.slice(1));
+ const found = [];
+ for (const [whole, word] of String(body ?? '').matchAll(/#([\p{L}\p{N}_-]+)/gu)) {
+ const lower = word.toLowerCase();
+ if (tags.includes(lower)) continue;
+ const bare = lower.replace(/[-_]/g, '').replace(/s$/, '');
+ const near = tags.find((tag) => bare === tag || editDistance(lower, tag) === 1);
+ if (near && !found.some((f) => f.written === whole)) found.push({ written: whole, meant: `#${near}` });
+ }
+ return found;
+}
+
+/** A body with every whole-word `written` swapped for `meant`, and nothing else touched. */
+export function fixMisspelledToken(body, written, meant) {
+ const escaped = String(written).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+ return String(body ?? '').replace(
+ new RegExp(`${escaped}(?![\\p{L}\\p{N}_-])`, 'gu'),
+ () => meant,
+ );
+}
+
+function editDistance(a, b) {
+ if (Math.abs(a.length - b.length) > 1) return 2;
+ let row = Array.from({ length: b.length + 1 }, (_, i) => i);
+ for (let i = 1; i <= a.length; i++) {
+ const next = [i];
+ for (let j = 1; j <= b.length; j++) {
+ next[j] = Math.min(row[j] + 1, next[j - 1] + 1, row[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
+ }
+ row = next;
+ }
+ return row[b.length];
+}
// The classic GeoConfirmed thread, as a token body. Place + plus code on the
// first line, then description, decimal coordinates, mention, and a labelled
@@ -389,6 +444,34 @@ export const DEFAULT_TWEET_BODY = [
'Source: #source',
].join('\n');
+/**
+ * Layouts a new post template can start from, so a blank body is never the first
+ * thing an analyst faces. Each one only replaces the body: the mention, the media
+ * post and the boilerplate stay as they were.
+ */
+export const POST_TEMPLATE_STARTERS = Object.freeze([
+ { id: 'classic', label: 'Classic', body: DEFAULT_TWEET_BODY },
+ { id: 'coordinates', label: 'Coordinates only', body: '#coordinates\n\n#mention' },
+ { id: 'short', label: 'Short', body: '#place\n#coordinates\n\nSource: #source' },
+ {
+ id: 'dated',
+ label: 'With date',
+ body: [
+ '#place - #pluscode',
+ '',
+ '#description',
+ '',
+ 'Filmed: #date',
+ '',
+ '#coordinates',
+ '',
+ '#mention',
+ '',
+ 'Source: #source',
+ ].join('\n'),
+ },
+].map((starter) => Object.freeze(starter)));
+
/** What separates a point's name from its coordinates, on the one line it gets. */
export const POINT_SEPARATOR = ' — ';
@@ -434,7 +517,7 @@ export function postCoordinates(text, { lat, lon } = {}) {
/** Resolve the live draft into the string each token stands for ('' when absent). */
export function tweetFields({
- place, plusCode, description, lat, lon, coordsText, mention, source,
+ place, plusCode, description, lat, lon, coordsText, mention, source, date,
} = {}) {
return {
place: place?.trim() ?? '',
@@ -445,9 +528,97 @@ export function tweetFields({
description: description?.trim() ?? '',
mention: mention?.trim() ?? '',
source: source?.trim() ?? '',
+ date: date?.trim() ?? '',
};
}
+const STAMP = /^(\d{4}-\d{2}-\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(Z|[+-]\d{2}:\d{2})?$/;
+
+/** An offset as a reader writes it: `UTC+2`, `UTC-3:30`, plain `UTC` at zero. */
+function offsetLabel(minutes) {
+ if (!minutes) return 'UTC';
+ const sign = minutes < 0 ? '-' : '+';
+ const whole = Math.abs(minutes);
+ const tail = whole % 60 ? `:${String(whole % 60).padStart(2, '0')}` : '';
+ return `UTC${sign}${Math.floor(whole / 60)}${tail}`;
+}
+
+function offsetAtInstant(zone, millis) {
+ const part = new Intl.DateTimeFormat('en-US', { timeZone: zone, timeZoneName: 'longOffset' })
+ .formatToParts(new Date(millis))
+ .find((one) => one.type === 'timeZoneName')?.value ?? '';
+ const match = /GMT(?:([+-])(\d{1,2})(?::(\d{2}))?)?/.exec(part);
+ if (!match) return null;
+ if (!match[1]) return 0;
+ const value = Number(match[2]) * 60 + Number(match[3] ?? 0);
+ return match[1] === '-' ? -value : value;
+}
+
+/**
+ * Minutes a named zone stands from UTC at a local wall-clock reading. Read twice:
+ * the first guess takes the clock as UTC, which lands up to a day off and can sit
+ * across a clock change from the moment meant, so the offset is read again at the
+ * instant that guess points to.
+ */
+function zoneOffsetAt(zone, day, hour, minute) {
+ try {
+ const wall = Date.parse(`${day}T${hour}:${minute}:00Z`);
+ const first = offsetAtInstant(zone, wall);
+ if (first == null) return null;
+ return offsetAtInstant(zone, wall - first * 60_000);
+ } catch {
+ return null;
+ }
+}
+
+function stampParts(raw) {
+ const match = STAMP.exec(raw);
+ if (!match) return null;
+ const [, day, hour, minute, second, offset] = match;
+ const clock = second === '00' ? `${hour}:${minute}` : `${hour}:${minute}:${second}`;
+ return { day, hour, minute, clock, offset };
+}
+
+function stampZone(parts, zone) {
+ if (parts.offset === 'Z') return 'UTC';
+ if (parts.offset) {
+ const [h, m] = parts.offset.slice(1).split(':').map(Number);
+ return offsetLabel((parts.offset[0] === '-' ? -1 : 1) * (h * 60 + m));
+ }
+ if (!zone) return '';
+ const minutes = zoneOffsetAt(zone, parts.day, parts.hour, parts.minute);
+ return minutes == null ? '' : offsetLabel(minutes);
+}
+
+/**
+ * A stated date as a post carries it: the case's own value, written the same way
+ * in every language. A date or a range of dates goes out exactly as stored,
+ * qualifiers included. A time drops the `T` nobody reads and says which clock it
+ * is on, as an offset from UTC: the zone it was stated in, read on that day, so a
+ * summer reading in Kyiv says `UTC+3` and a winter one `UTC+2`. A time with no zone
+ * goes out bare, since naming one would be inventing it.
+ */
+export function postDate(when, zone = null) {
+ const raw = String(when ?? '').trim();
+ if (!raw) return '';
+ const [from, to] = raw.split('/');
+ const start = stampParts(from);
+ if (!start) return raw;
+ if (to === undefined) {
+ const label = stampZone(start, zone);
+ return `${start.day} ${start.clock}${label ? ` ${label}` : ''}`;
+ }
+ const end = stampParts(to);
+ if (!end) return raw;
+ const startLabel = stampZone(start, zone);
+ const endLabel = stampZone(end, zone);
+ const tail = end.day === start.day ? end.clock : `${end.day} ${end.clock}`;
+ if (startLabel === endLabel) {
+ return `${start.day} ${start.clock}/${tail}${endLabel ? ` ${endLabel}` : ''}`;
+ }
+ return `${start.day} ${start.clock}${startLabel ? ` ${startLabel}` : ''}/${tail}${endLabel ? ` ${endLabel}` : ''}`;
+}
+
/**
* Render a thread body into the first tweet, substituting tokens with the
* draft's values. Layout rules, so a partly-filled draft still reads clean:
@@ -487,8 +658,8 @@ export function buildTweet1(body, rawFields = {}) {
export function templateUsesPostField(body, field) {
const tokens = FIELD_TOKENS[field];
if (!tokens) return true;
- const lowerBody = String(body ?? '').toLowerCase();
- return tokens.some((token) => lowerBody.includes(token));
+ const held = bodyTokens(body);
+ return tokens.some((token) => held.includes(token));
}
//: What an address looks like inside a source line. The composer joins several with
diff --git a/frontend/src/lib/post.test.js b/frontend/src/lib/post.test.js
index d548a96..b90094b 100644
--- a/frontend/src/lib/post.test.js
+++ b/frontend/src/lib/post.test.js
@@ -7,7 +7,8 @@ import {
proofSourceMediaPaths, renumberMediaTweetText, retargetMediaTweetText,
sourceSection, sourceUrls,
templateFromPost, templateUsesPostField, togglePostMedia,
- pointLines, postCoordinates, splitPointLine,
+ pointLines, postCoordinates, splitPointLine, postDate,
+ POST_TEMPLATE_STARTERS, bodyTokens, fixMisspelledToken, misspelledTokens,
} from './post.js';
const full = {
@@ -83,7 +84,7 @@ describe('buildTweet1 — token ordering + line control', () => {
it('exposes the insertable token palette', () => {
expect(TWEET_TOKENS.map((t) => t.tag)).toEqual([
- '#place', '#pluscode', '#coordinates', '#description', '#mention', '#source',
+ '#place', '#pluscode', '#coordinates', '#description', '#mention', '#source', '#date',
]);
for (const t of TWEET_TOKENS) expect(t.sample).toBeTruthy();
});
@@ -328,6 +329,87 @@ describe('templateUsesPostField — compose fields controlled by a template', ()
});
});
+describe('bodyTokens and misspelledTokens — what a layout will and will not fill', () => {
+ it('lists the tokens a body holds, in order, and leaves a longer word alone', () => {
+ expect(bodyTokens('#Place - #pluscode\n#placement #dates')).toEqual(['#place', '#pluscode']);
+ });
+
+ it('names a word that is one edit from a token, with the token it meant', () => {
+ expect(misspelledTokens('#coordinate\n#Sources and #plus_code')).toEqual([
+ { written: '#coordinate', meant: '#coordinates' },
+ { written: '#Sources', meant: '#source' },
+ { written: '#plus_code', meant: '#pluscode' },
+ ]);
+ });
+
+ it('says nothing about real tokens, real hashtags, or a word named twice', () => {
+ expect(misspelledTokens('#place #mention #osint #geolocation')).toEqual([]);
+ expect(misspelledTokens('#coordinate and #coordinate')).toHaveLength(1);
+ });
+});
+
+describe('fixMisspelledToken — the one-click correction', () => {
+ it('swaps every whole-word occurrence and leaves the longer token next to it alone', () => {
+ const body = '#coordinate\n#coordinates\nagain #coordinate, and #coordinate-x';
+ expect(fixMisspelledToken(body, '#coordinate', '#coordinates')).toBe(
+ '#coordinates\n#coordinates\nagain #coordinates, and #coordinate-x',
+ );
+ });
+
+ it('matches the case it was written in, and takes a separator as part of the word', () => {
+ expect(fixMisspelledToken('#Sources #sources', '#Sources', '#source')).toBe('#source #sources');
+ expect(fixMisspelledToken('#plus_code and #plus_codes', '#plus_code', '#pluscode')).toBe(
+ '#pluscode and #plus_codes',
+ );
+ });
+
+ it('leaves a body with no such word exactly as it was, and a fixed one clean', () => {
+ expect(fixMisspelledToken('#place', '#coordinate', '#coordinates')).toBe('#place');
+ const fixed = fixMisspelledToken('#coordinate\n#Sources', '#coordinate', '#coordinates');
+ expect(misspelledTokens(fixed)).toEqual([{ written: '#Sources', meant: '#source' }]);
+ });
+});
+
+describe('POST_TEMPLATE_STARTERS — where a new template starts', () => {
+ it('starts with the classic thread, unchanged', () => {
+ expect(POST_TEMPLATE_STARTERS[0]).toMatchObject({ id: 'classic', body: DEFAULT_TWEET_BODY });
+ });
+
+ it('gives every starter its own id and a name to show', () => {
+ const ids = POST_TEMPLATE_STARTERS.map((starter) => starter.id);
+ expect(new Set(ids).size).toBe(ids.length);
+ for (const starter of POST_TEMPLATE_STARTERS) expect(starter.label.trim()).not.toBe('');
+ });
+
+ it('writes only real tokens, so no starter goes out with text that looks like one', () => {
+ for (const starter of POST_TEMPLATE_STARTERS) {
+ expect(misspelledTokens(starter.body), starter.id).toEqual([]);
+ expect(bodyTokens(starter.body).length, starter.id).toBeGreaterThan(0);
+ }
+ });
+
+ it('is read-only, so one editor cannot change what the next one offers', () => {
+ expect(Object.isFrozen(POST_TEMPLATE_STARTERS)).toBe(true);
+ for (const starter of POST_TEMPLATE_STARTERS) expect(Object.isFrozen(starter)).toBe(true);
+ });
+
+ it('offers a dated layout that shows the date, and one that leaves it out', () => {
+ const byId = Object.fromEntries(POST_TEMPLATE_STARTERS.map((s) => [s.id, s]));
+ const fields = { ...full, date: '2025-10-24 14:30 UTC+3' };
+ expect(buildTweet1(byId.dated.body, fields)).toContain('Filmed: 2025-10-24 14:30 UTC+3');
+ expect(buildTweet1(byId.classic.body, fields)).not.toContain('2025-10-24');
+ expect(buildTweet1(byId.dated.body, full)).not.toContain('Filmed');
+ });
+
+ it('builds the short and coordinates-only layouts the way their names promise', () => {
+ const byId = Object.fromEntries(POST_TEMPLATE_STARTERS.map((s) => [s.id, s]));
+ expect(buildTweet1(byId.coordinates.body, full)).toBe('48.850000, 2.350000\n\n@GeoConfirmed');
+ expect(buildTweet1(byId.short.body, full)).toBe(
+ 'Bakhmut, Donetsk, Ukraine\n48.850000, 2.350000\n\nSource: https://x.com/a/1',
+ );
+ });
+});
+
describe('proofSourceMediaPaths — source media selected from a proof', () => {
it('uses original source media behind a derived frame', () => {
const data = {
@@ -574,3 +656,55 @@ describe('the points a post carries', () => {
expect(report).not.toContain('## Points');
});
});
+
+describe('#date — the date a proof states, only where a template asks for it', () => {
+ it('fills its own line and drops it when there is no date', () => {
+ const body = '#place\n\nFilmed: #date\n\n#coordinates';
+ expect(buildTweet1(body, { ...full, date: '2024-03-12' }))
+ .toBe('Bakhmut, Donetsk, Ukraine\n\nFilmed: 2024-03-12\n\n48.850000, 2.350000');
+ expect(buildTweet1(body, { ...full, date: '' }))
+ .toBe('Bakhmut, Donetsk, Ukraine\n\n48.850000, 2.350000');
+ });
+
+ it('never enters the classic thread on its own', () => {
+ expect(DEFAULT_TWEET_BODY).not.toContain('#date');
+ expect(templateUsesPostField(DEFAULT_TWEET_BODY, 'date')).toBe(false);
+ expect(templateUsesPostField('Filmed: #Date', 'date')).toBe(true);
+ });
+
+ it('leaves a longer hashtag a template already carried alone', () => {
+ expect(templateUsesPostField('#dates #placement', 'date')).toBe(false);
+ expect(templateUsesPostField('#dates #placement', 'place')).toBe(false);
+ expect(buildTweet1('#placement #dates', { ...full, date: '2024-03-12' })).toBe('#placement #dates');
+ });
+});
+
+describe('postDate — the stored value, in no language, with its clock', () => {
+ it('keeps a date or a range of dates exactly as the case holds it', () => {
+ expect(postDate('2024-03-12', 'Europe/Kyiv')).toBe('2024-03-12');
+ expect(postDate('2024-03~')).toBe('2024-03~');
+ expect(postDate('2024-03-12/2024-03-15?')).toBe('2024-03-12/2024-03-15?');
+ expect(postDate('')).toBe('');
+ });
+
+ it('says which clock a time is on, as an offset from UTC on that day', () => {
+ expect(postDate('2024-07-12T14:30:00', 'Europe/Kyiv')).toBe('2024-07-12 14:30 UTC+3');
+ expect(postDate('2024-01-12T14:30:00', 'Europe/Kyiv')).toBe('2024-01-12 14:30 UTC+2');
+ expect(postDate('2024-01-12T14:30:00Z')).toBe('2024-01-12 14:30 UTC');
+ expect(postDate('2024-01-12T14:30:15+05:30')).toBe('2024-01-12 14:30:15 UTC+5:30');
+ // Across a clock change the offset is the one in force at that hour.
+ expect(postDate('2024-03-31T01:30:00', 'Europe/Paris')).toBe('2024-03-31 01:30 UTC+1');
+ expect(postDate('2024-03-31T03:30:00', 'Europe/Paris')).toBe('2024-03-31 03:30 UTC+2');
+ });
+
+ it('names no clock it does not know', () => {
+ expect(postDate('2024-01-12T14:30:00')).toBe('2024-01-12 14:30');
+ expect(postDate('2024-01-12T14:30:00', 'Not/AZone')).toBe('2024-01-12 14:30');
+ });
+
+ it('writes a span of times once, with its clock at the end', () => {
+ expect(postDate('2024-01-12T14:30:00/2024-01-12T15:00:00', 'Asia/Tokyo')).toBe('2024-01-12 14:30/15:00 UTC+9');
+ expect(postDate('2024-01-12T23:30:00Z/2024-01-13T01:00:00Z')).toBe('2024-01-12 23:30/2024-01-13 01:00 UTC');
+ });
+});
+
diff --git a/frontend/src/lib/quickClaim.js b/frontend/src/lib/quickClaim.js
index 4a058c0..9e350d7 100644
--- a/frontend/src/lib/quickClaim.js
+++ b/frontend/src/lib/quickClaim.js
@@ -1,5 +1,5 @@
/**
- * A Claim filed from the entity it is about — the pure half of `QuickClaim.svelte`.
+ * A Claim filed from the entity it is about — the pure half of `EntryLine.svelte`.
*
* The shape being filled is the one ONTOLOGY §2 calls a filed observation: a count
* and a condition on the statement, `about` the model or the object, `at` a place,
@@ -37,13 +37,15 @@ export function quickClaimSeat(family, accepts) {
};
}
-/** What the press files, said from where it is pressed: a tooltip per seat. */
+/** What the press adds, said from where it is pressed: a tooltip per seat. One verb
+ * on every surface, "Add event", where the same act used to be filed, noted and
+ * added under three names. */
export function claimActionTitle(slot) {
return (
{
- about: 'File a claim about this',
- at: 'File a claim placed here',
- cites: 'File a claim that rests on this',
+ about: 'Add an event about this',
+ at: 'Add an event that happened here',
+ cites: 'Add an event this shows',
}[slot] ?? ''
);
}
@@ -53,16 +55,23 @@ const names = (list) => list.map((entry) => String(entry ?? '').trim()).filter(B
/**
* The sentence the fields add up to, offered until the analyst writes their own.
*
- * `2 × T-72B3 destroyed at Crossroads`, `Bridge 4 damaged`, `Seen at Crossroads`.
- * The count takes a `×` rather than a bare number because model names carry digits
- * of their own. With neither a subject nor a place there is nothing to say, and the
- * field stays empty rather than holding a sentence about nothing.
+ * `2 × T-72B3 destroyed at Crossroads`, `Bridge 4 damaged`, `Seen at Crossroads`,
+ * `Seen in clip.mp4`. The count takes a `×` rather than a bare number because model
+ * names carry digits of their own. With neither a subject, a place nor a source there
+ * is nothing to say, and the field stays empty rather than holding a sentence about
+ * nothing.
*/
-export function composeClaimStatement({ count = null, condition = '', subjects = [], places = [] }) {
+export function composeClaimStatement({
+ count = null, condition = '', subjects = [], places = [], sources = [],
+}) {
const subject = names(subjects);
const place = names(places);
const state = String(condition ?? '').trim().toLowerCase();
- if (!subject) return place ? `Seen at ${place}` : '';
+ if (!subject && !place) {
+ const source = names(sources);
+ return source ? `Seen in ${source}` : '';
+ }
+ if (!subject) return `Seen at ${place}`;
const counted = Number.isInteger(count) && count > 0 ? `${count} × ${subject}` : subject;
return `${counted} ${state || 'seen'}${place ? ` at ${place}` : ''}`;
}
@@ -74,11 +83,15 @@ export function composeClaimStatement({ count = null, condition = '', subjects =
* `observed` role; without a date there is no role to state. A count or a condition
* the form did not ask for is never sent, whatever is left in its field.
*/
-export function quickClaimBody({ statement, when, confidence, count, condition, about, at, cites, seat }) {
+export function quickClaimBody({
+ statement, when, whenZone = null, confidence, count, condition, about, at, cites, seat, create = [],
+}) {
const whole = Number(count);
return {
statement: String(statement ?? '').trim(),
when: when || null,
+ // The zone a day was stated in rides only with a day: a time carries its offset.
+ ...(when && whenZone ? { when_zone: whenZone } : {}),
time_role: when ? 'observed' : null,
confidence: confidence || null,
count: seat?.count && Number.isInteger(whole) && whole > 0 ? whole : null,
@@ -86,5 +99,6 @@ export function quickClaimBody({ statement, when, confidence, count, condition,
about: [...new Set(about)],
at: [...new Set(at)],
cites: [...new Set(cites)],
+ create: create.map(({ slot, type, label }) => ({ slot, type, label: String(label).trim() })),
};
}
diff --git a/frontend/src/lib/quickClaim.test.js b/frontend/src/lib/quickClaim.test.js
index 89660e0..a43518d 100644
--- a/frontend/src/lib/quickClaim.test.js
+++ b/frontend/src/lib/quickClaim.test.js
@@ -67,6 +67,12 @@ describe('composeClaimStatement', () => {
expect(composeClaimStatement({ subjects: ['A', 'B'], places: ['X', ' '] })).toBe('A, B seen at X');
});
+ it('says where it was seen when a source is all there is', () => {
+ expect(composeClaimStatement({ sources: ['clip.mp4'] })).toBe('Seen in clip.mp4');
+ expect(composeClaimStatement({ sources: ['clip.mp4'], places: ['Crossroads'] })).toBe('Seen at Crossroads');
+ expect(composeClaimStatement({ sources: ['clip.mp4'], subjects: ['T-72B3'] })).toBe('T-72B3 seen');
+ });
+
it('offers nothing with nothing to say', () => {
expect(composeClaimStatement({})).toBe('');
expect(composeClaimStatement({ count: 2, condition: 'destroyed' })).toBe('');
@@ -74,6 +80,13 @@ describe('composeClaimStatement', () => {
});
describe('quickClaimBody', () => {
+ it('sends the zone a day was stated in, and only with a date', () => {
+ const base = { statement: 'x', about: [], at: [], cites: [], seat: {} };
+ expect(quickClaimBody({ ...base, when: '2024-03-12', whenZone: 'Europe/Kyiv' }).when_zone).toBe('Europe/Kyiv');
+ expect(quickClaimBody({ ...base, when: '', whenZone: 'Europe/Kyiv' })).not.toHaveProperty('when_zone');
+ expect(quickClaimBody({ ...base, when: '2024-03-12' })).not.toHaveProperty('when_zone');
+ });
+
const seat = { slot: 'about', count: true, condition: true };
it('files the observation in the shape the claim route takes', () => {
@@ -99,7 +112,16 @@ describe('quickClaimBody', () => {
about: ['model'],
at: ['crossroads'],
cites: ['video'],
+ create: [],
+ });
+ });
+
+ it('names the new subjects the line creates, trimmed', () => {
+ const body = quickClaimBody({
+ statement: 'x', about: [], at: [], cites: [], seat,
+ create: [{ slot: 'about', type: 'organization', label: ' 4th brigade ', key: 'new:1', rule: 'chosen' }],
});
+ expect(body.create).toEqual([{ slot: 'about', type: 'organization', label: '4th brigade' }]);
});
it('states no role without a date, and no count that is not a whole number', () => {
@@ -128,9 +150,9 @@ describe('quickClaimBody', () => {
describe('claimActionTitle', () => {
it('says what the press files from each seat', () => {
- expect(claimActionTitle('about')).toBe('File a claim about this');
- expect(claimActionTitle('at')).toBe('File a claim placed here');
- expect(claimActionTitle('cites')).toBe('File a claim that rests on this');
+ expect(claimActionTitle('about')).toBe('Add an event about this');
+ expect(claimActionTitle('at')).toBe('Add an event that happened here');
+ expect(claimActionTitle('cites')).toBe('Add an event this shows');
expect(claimActionTitle(null)).toBe('');
});
});
diff --git a/frontend/src/lib/sidebarSearch.js b/frontend/src/lib/sidebarSearch.js
index 674a430..e5b45e6 100644
--- a/frontend/src/lib/sidebarSearch.js
+++ b/frontend/src/lib/sidebarSearch.js
@@ -6,6 +6,7 @@
* would have to badge each folder with a per-type count the catalog summary
* cannot give, so the two modes are exclusive rather than combined.
*/
+import { foldText } from './textFold.js';
/** True when the body should show results instead of the tree. */
export const isFiltering = ({ query = '', type = null } = {}) => !!query.trim() || !!type;
@@ -26,15 +27,11 @@ export function typeChips(summary) {
* label alone.
*/
export function filterEntities(items, { query = '', type = null } = {}) {
- const q = query.trim().toLowerCase();
+ const q = foldText(query.trim());
return items.filter((e) => {
if (type && e.type !== type) return false;
if (!q) return true;
- return [e.label, e.type, e.attrs?.folder]
- .filter(Boolean)
- .join(' ')
- .toLowerCase()
- .includes(q);
+ return foldText([e.label, e.type, e.attrs?.folder].filter(Boolean).join(' ')).includes(q);
});
}
diff --git a/frontend/src/lib/sidebarSearch.test.js b/frontend/src/lib/sidebarSearch.test.js
index fb38ead..2b66917 100644
--- a/frontend/src/lib/sidebarSearch.test.js
+++ b/frontend/src/lib/sidebarSearch.test.js
@@ -36,6 +36,11 @@ describe('filterEntities', () => {
expect(filterEntities(items, { query: 'CLIP' }).map((e) => e.id)).toEqual(['1']);
});
+ it('finds a label whatever accents it was written with', () => {
+ const accented = [...items, { id: '4', label: 'Café du Port', type: 'place', attrs: {} }];
+ expect(filterEntities(accented, { query: 'cafe' }).map((e) => e.id)).toEqual(['4']);
+ });
+
it('matches the folder too, so typing a folder name reveals its contents', () => {
expect(filterEntities(items, { query: 'terrain' }).map((e) => e.id)).toEqual(['1', '2']);
});
diff --git a/frontend/src/lib/state.svelte.js b/frontend/src/lib/state.svelte.js
index 51e23df..4c2b8e4 100644
--- a/frontend/src/lib/state.svelte.js
+++ b/frontend/src/lib/state.svelte.js
@@ -24,10 +24,11 @@ export const prefs = $state({
units: 'metric', // 'metric' | 'imperial'
homeView: { lat: 43, lon: 25, zoom: 3 }, // where Satellite opens
mapSync: true, // Satellite, Compare and Detect share one camera
- detectView: { collapsed: false, basemap: 'esri-world-imagery', overlays: ['boundaries', 'placenames'], saved: true },
+ detectView: { collapsed: false, width: 380, basemap: 'esri-world-imagery', overlays: ['boundaries', 'placenames'], saved: true },
captureScaleNorth: false, // burn a scale bar and a north arrow into captures
postMention: '@GeoConfirmed', // handle a fresh post draft is addressed to
postTarget: 'x', // social composer a fresh post draft starts with
+ postTemplate: '', // id of the post template a fresh draft starts with; '' = classic
postPrefill: true, // let the capture extension fill that composer on Publish
reversePrefill: true, // let it hand the image to the engine on Reverse Search
signatureHandle: '', // account handle stamped onto proofs that opt into it
@@ -99,6 +100,7 @@ export function applyPrefs(s) {
if (s.capture_scale_north !== undefined) prefs.captureScaleNorth = s.capture_scale_north;
if (s.post_mention !== undefined) prefs.postMention = s.post_mention; // '' = none
if (s.post_target !== undefined) prefs.postTarget = s.post_target;
+ if (s.post_template !== undefined) prefs.postTemplate = s.post_template; // '' = none
if (s.post_prefill !== undefined) prefs.postPrefill = s.post_prefill;
if (s.reverse_prefill !== undefined) prefs.reversePrefill = s.reverse_prefill;
if (s.signature_handle !== undefined) prefs.signatureHandle = s.signature_handle; // '' = none
@@ -197,6 +199,13 @@ export const caseState = $state({
*/
export const templatesState = $state({ proof: [], post: [] });
+/**
+ * The Post composer's live draft, mirrored for the template editor's preview so
+ * a layout can be judged on the post that is open. Content only: the values the
+ * tokens stand for, or `null` while the composer holds nothing.
+ */
+export const postDraftState = $state({ fields: null });
+
export async function loadTemplates() {
try {
const t = await api.get('/api/templates');
@@ -271,9 +280,16 @@ export const uiState = $state({
* from the node. */
openGraphEntity: null,
/** Entity/item handed to Timeline from Details. Timeline consumes and clears it. */
- timelineFocus: null, // { entityId, entityLabel, itemId }
+ timelineFocus: null, // { entityId, entityLabel, itemId, producedHere }
/** A fact-time range handed back to Timeline. Consumed once, never persisted. */
- timelineRange: null, // { from, to }
+ timelineRange: null, // { from, to, itemId?, item? }
+ /** A holding queue the Timeline should open onto, from a count that named it. */
+ timelineQueue: null, // 'undated', or { queue: 'undated' | 'unplaced', itemId, item }
+ /** Whether the Add event bar is open over the tool on screen. Session only. */
+ noting: false,
+ /** Bumped to send the Timeline to its own entry line, which is the Add event bar
+ * the Timeline already has. */
+ timelineLineFocus: 0,
/** A fact-time range handed to the Satellite map as a temporary event layer. */
mapTimelineRange: null, // { from, to }
/**
@@ -585,6 +601,8 @@ function clearCaseHandoffs() {
uiState.openGraphEntity = null;
uiState.timelineFocus = null;
uiState.timelineRange = null;
+ uiState.timelineQueue = null;
+ uiState.noting = false;
uiState.mapTimelineRange = null;
uiState.gotoCoords = null;
uiState.lookAt = null;
diff --git a/frontend/src/lib/state.test.js b/frontend/src/lib/state.test.js
index 86eae3a..d54747d 100644
--- a/frontend/src/lib/state.test.js
+++ b/frontend/src/lib/state.test.js
@@ -171,6 +171,12 @@ describe('applyPrefs', () => {
applyPrefs({ post_target: 'bluesky' });
expect(prefs.postTarget).toBe('bluesky');
+ expect(prefs.postTemplate).toBe(''); // no default template until one is chosen
+ applyPrefs({ post_template: 'tpl_1' });
+ expect(prefs.postTemplate).toBe('tpl_1');
+ applyPrefs({ post_template: '' }); // clearing it is a real choice too
+ expect(prefs.postTemplate).toBe('');
+
applyPrefs({ signature_handle: '@example' });
expect(prefs.signatureHandle).toBe('@example');
});
diff --git a/frontend/src/lib/temporalInput.js b/frontend/src/lib/temporalInput.js
index 12371b5..c0a47ca 100644
--- a/frontend/src/lib/temporalInput.js
+++ b/frontend/src/lib/temporalInput.js
@@ -1,12 +1,14 @@
+import { offsetAt } from './localZone.js';
+
const DATE = /^(\d{4})(?:-(\d{2})(?:-(\d{2}))?)?([~?%])?$/;
const TIMESTAMP = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,6})?)(Z|[+-]\d{2}:\d{2})?$/;
export const TEMPORAL_FORMATS = [
- { value: 'date', label: 'Date' },
- { value: 'timestamp', label: 'Date and time' },
- { value: 'range', label: 'Date range' },
- { value: 'time-range', label: 'Time range' },
- { value: 'advanced', label: 'Advanced syntax' },
+ { value: 'date', label: 'Date', hint: 'a day, a month or a year, and how sure' },
+ { value: 'timestamp', label: 'Date and time', hint: 'a time of day, on the clock picked below' },
+ { value: 'range', label: 'Date range', hint: 'from one day to another' },
+ { value: 'time-range', label: 'Time range', hint: 'between two times, on one clock' },
+ { value: 'advanced', label: 'Advanced syntax', hint: 'the stored form, for what the others cannot say' },
];
export const TEMPORAL_SYNTAX = [
@@ -31,71 +33,59 @@ export const TEMPORAL_MARKERS = [
{ value: '%', meaning: 'Approximate and uncertain' },
];
+/**
+ * The editor's state for a stored value. A time's clock is `zone` (a zone name or
+ * `UTC`), or the `offset` it was written with and no zone named, or neither while
+ * no clock is known. A date's clock lives beside it, with the field's owner.
+ */
export function readTemporalInput(value) {
const raw = typeof value === 'string' ? value : '';
+ const blank = {
+ mode: 'date', precision: 'day', certainty: '', date: '', datetime: '', zone: '', offset: '',
+ start: '', end: '', startTime: '', endTime: '', raw,
+ };
+ const clock = (suffix) => (suffix === 'Z' ? { zone: 'UTC', offset: '' } : { zone: '', offset: suffix ?? '' });
const date = DATE.exec(raw);
if (date) {
const precision = date[3] ? 'day' : date[2] ? 'month' : 'year';
- return {
- mode: 'date', precision, certainty: date[4] ?? '', date: raw.slice(0, raw.length - (date[4] ? 1 : 0)),
- datetime: '', zone: 'local', offset: '+00:00', start: '', end: '',
- startTime: '', endTime: '', rangeZone: 'utc', rangeOffset: '+00:00', raw,
- };
+ return { ...blank, precision, certainty: date[4] ?? '', date: raw.slice(0, raw.length - (date[4] ? 1 : 0)) };
}
const timestamp = TIMESTAMP.exec(raw);
- if (timestamp) {
- const suffix = timestamp[2] ?? '';
- return {
- mode: 'timestamp', precision: 'day', certainty: '', date: '',
- datetime: timestamp[1], zone: suffix === 'Z' ? 'utc' : suffix ? 'offset' : 'local',
- offset: suffix && suffix !== 'Z' ? suffix : '+00:00', start: '', end: '',
- startTime: '', endTime: '', rangeZone: 'utc', rangeOffset: '+00:00', raw,
- };
- }
+ if (timestamp) return { ...blank, mode: 'timestamp', datetime: timestamp[1], ...clock(timestamp[2]) };
const interval = raw.split('/');
if (interval.length === 2 && interval.every((part) => /^\d{4}-\d{2}-\d{2}$/.test(part))) {
- return {
- mode: 'range', precision: 'day', certainty: '', date: '', datetime: '',
- zone: 'local', offset: '+00:00', start: interval[0], end: interval[1],
- startTime: '', endTime: '', rangeZone: 'utc', rangeOffset: '+00:00', raw,
- };
+ return { ...blank, mode: 'range', start: interval[0], end: interval[1] };
}
if (interval.length === 2) {
const start = TIMESTAMP.exec(interval[0]);
const end = TIMESTAMP.exec(interval[1]);
- const startZone = start?.[2] ?? '';
- const endZone = end?.[2] ?? '';
- if (start && end && startZone && startZone === endZone) {
- return {
- mode: 'time-range', precision: 'day', certainty: '', date: '', datetime: '',
- zone: 'local', offset: '+00:00', start: '', end: '',
- startTime: start[1], endTime: end[1],
- rangeZone: startZone === 'Z' ? 'utc' : 'offset',
- rangeOffset: startZone === 'Z' ? '+00:00' : startZone, raw,
- };
+ if (start && end && (start[2] ?? '') === (end[2] ?? '')) {
+ return { ...blank, mode: 'time-range', startTime: start[1], endTime: end[1], ...clock(start[2]) };
}
}
- return {
- mode: raw ? 'advanced' : 'date', precision: 'day', certainty: '', date: '',
- datetime: '', zone: 'local', offset: '+00:00', start: '', end: '',
- startTime: '', endTime: '', rangeZone: 'utc', rangeOffset: '+00:00', raw,
- };
+ return { ...blank, mode: raw ? 'advanced' : 'date' };
}
function timestampWithSeconds(value) {
return /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/.test(value) ? `${value}:00` : value;
}
+/** A wall time on the state's clock. A zone is written as the offset it keeps at that
+ * very time, so the stored value is an ordinary zoned timestamp. */
+function onClock(time, state) {
+ const wall = timestampWithSeconds(time);
+ if (state.zone === 'UTC') return `${wall}Z`;
+ if (state.zone) return `${wall}${offsetAt(wall, state.zone)}`;
+ return `${wall}${state.offset ?? ''}`;
+}
+
export function writeTemporalInput(state) {
if (state.mode === 'date') return state.date ? `${state.date}${state.certainty}` : '';
if (state.mode === 'range') return state.start && state.end ? `${state.start}/${state.end}` : '';
if (state.mode === 'time-range') {
if (!state.startTime || !state.endTime) return '';
- const zone = state.rangeZone === 'utc' ? 'Z' : state.rangeOffset;
- return `${timestampWithSeconds(state.startTime)}${zone}/${timestampWithSeconds(state.endTime)}${zone}`;
+ return `${onClock(state.startTime, state)}/${onClock(state.endTime, state)}`;
}
if (state.mode === 'advanced') return state.raw ?? '';
- if (!state.datetime) return '';
- const zone = state.zone === 'utc' ? 'Z' : state.zone === 'offset' ? state.offset : '';
- return `${timestampWithSeconds(state.datetime)}${zone}`;
+ return state.datetime ? onClock(state.datetime, state) : '';
}
diff --git a/frontend/src/lib/temporalInput.test.js b/frontend/src/lib/temporalInput.test.js
index c3732e5..51d0034 100644
--- a/frontend/src/lib/temporalInput.test.js
+++ b/frontend/src/lib/temporalInput.test.js
@@ -24,7 +24,7 @@ describe('the temporal input adapter', () => {
it('adds the seconds required by the backend profile', () => {
expect(writeTemporalInput({
- mode: 'timestamp', datetime: '2026-08-11T18:40', zone: 'utc', offset: '+00:00',
+ mode: 'timestamp', datetime: '2026-08-11T18:40', zone: 'UTC', offset: '',
})).toBe('2026-08-11T18:40:00Z');
});
@@ -35,6 +35,22 @@ describe('the temporal input adapter', () => {
expect(writeTemporalInput(state)).toBe('circa late summer');
});
+ it('writes a zone as the offset it keeps at that time', () => {
+ const state = { ...readTemporalInput('2026-08-11T17:05:00'), zone: 'Europe/Kyiv' };
+ expect(writeTemporalInput(state)).toBe('2026-08-11T17:05:00+03:00');
+ expect(writeTemporalInput({ ...state, datetime: '2026-01-11T17:05' })).toBe('2026-01-11T17:05:00+02:00');
+ // each end of a range keeps the offset in force at its own time
+ const range = { ...readTemporalInput('2026-03-28T12:00:00Z/2026-03-30T12:00:00Z'), zone: 'Europe/Kyiv' };
+ expect(writeTemporalInput(range)).toBe('2026-03-28T12:00:00+02:00/2026-03-30T12:00:00+03:00');
+ });
+
+ it('reads the clock a stored time writes, and none when it writes none', () => {
+ expect(readTemporalInput('2026-08-11T16:40:00Z')).toMatchObject({ zone: 'UTC', offset: '' });
+ expect(readTemporalInput('2026-08-11T18:40:00+02:00')).toMatchObject({ zone: '', offset: '+02:00' });
+ expect(readTemporalInput('2026-08-11T18:40:00')).toMatchObject({ zone: '', offset: '' });
+ expect(readTemporalInput('2026-08-11T10:00:00/2026-08-11T11:00:00')).toMatchObject({ mode: 'time-range', zone: '' });
+ });
+
it('documents every supported family with a pattern and an example', () => {
expect(TEMPORAL_SYNTAX.map(({ meaning }) => meaning)).toEqual([
'Year', 'Month', 'Day', 'Local time', 'UTC time', 'UTC offset',
diff --git a/frontend/src/lib/textFold.js b/frontend/src/lib/textFold.js
new file mode 100644
index 0000000..b092dc8
--- /dev/null
+++ b/frontend/src/lib/textFold.js
@@ -0,0 +1,44 @@
+/**
+ * How a search compares text: without case, and without the marks a reader skips.
+ *
+ * The browser half of `engine/textfold.py`. A case small enough for one page is
+ * searched here, a larger one on the server, and a term must answer the same on
+ * either side of that line; `tests/fixtures/fold_cases.json` holds both to one list.
+ *
+ * Marks go on a Latin, Greek or Cyrillic letter, Arabic harakat and the tatweel go,
+ * Hebrew points go. A Devanagari sign or a dakuten is part of its letter and stays,
+ * and punctuation is never touched.
+ */
+
+const MARK = /\p{Mn}/u;
+
+/** Case differences `toLowerCase` leaves that a reader does not see. */
+const SAME_LETTER = /[ßς]/g;
+const LETTER = { ß: 'ss', ς: 'σ' };
+
+const skippedOn = (base) => base <= 0x052f || (base >= 0x1e00 && base <= 0x1fff);
+const skipped = (mark) => (mark >= 0x064b && mark <= 0x065f) || mark === 0x0670
+ || (mark >= 0x0591 && mark <= 0x05c7);
+
+/** `text` as a search compares it. */
+export function foldText(text) {
+ const lowered = String(text ?? '').toLowerCase().replace(SAME_LETTER, (letter) => LETTER[letter]);
+ let out = '';
+ let base = 0;
+ for (const char of lowered.normalize('NFD')) {
+ const code = char.codePointAt(0);
+ if (MARK.test(char)) {
+ if (!(skippedOn(base) || skipped(code))) out += char;
+ continue;
+ }
+ if (code === 0x0640) continue; // the tatweel, which only stretches a word
+ base = code;
+ out += char;
+ }
+ return out.normalize('NFC');
+}
+
+/** The words of a search box, folded, blanks dropped. */
+export function foldTerms(query) {
+ return foldText(String(query ?? '').trim()).split(/\s+/).filter(Boolean);
+}
diff --git a/frontend/src/lib/textFold.test.js b/frontend/src/lib/textFold.test.js
new file mode 100644
index 0000000..3c22adc
--- /dev/null
+++ b/frontend/src/lib/textFold.test.js
@@ -0,0 +1,23 @@
+import { describe, expect, it } from 'vitest';
+import { readFileSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+import { dirname, join } from 'node:path';
+import { foldTerms, foldText } from './textFold.js';
+
+const here = dirname(fileURLToPath(import.meta.url));
+const { cases } = JSON.parse(
+ readFileSync(join(here, '../../../tests/fixtures/fold_cases.json'), 'utf8')
+);
+
+describe('search folding', () => {
+ it.each(cases)('folds %j as the server does', (text, folded) => {
+ expect(foldText(text)).toBe(folded);
+ expect(foldText(folded)).toBe(folded);
+ });
+
+ it('splits a search box into folded words', () => {
+ expect(foldTerms(' Café Москва ')).toEqual(['cafe', 'москва']);
+ expect(foldTerms('')).toEqual([]);
+ expect(foldTerms(null)).toEqual([]);
+ });
+});
diff --git a/frontend/src/lib/timeline.js b/frontend/src/lib/timeline.js
index 6753b53..8485baa 100644
--- a/frontend/src/lib/timeline.js
+++ b/frontend/src/lib/timeline.js
@@ -388,23 +388,42 @@ export function timeAtRatio(from, to, ratio) {
return isoInstant(Math.round(milliseconds / SECOND) * SECOND);
}
-export function dateAtRatio(from, to, ratio) {
+export function dateAtRatio(from, to, ratio, tz = null) {
const instant = timeAtRatio(from, to, ratio);
- return instant ? instant.slice(0, 10) : '';
+ if (!instant) return '';
+ if (!tz) return instant.slice(0, 10);
+ // A day stated in a zone is that zone's day: the pointer's instant is read on
+ // its calendar, or dragging an edge near midnight would land a day off.
+ const { year, month, day } = zonedFields(new Date(instant).getTime(), tz);
+ return `${String(year).padStart(4, '0')}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
}
+/** A calendar year on average, for choosing a precision; nothing is dated with it. */
+const YEAR = 365.2425 * DAY;
+
+/**
+ * The date a click or a drag on the axis proposes, as precise as the window can mean.
+ *
+ * A pointer lands on a pixel, and a pixel is worth a few minutes on a day's axis and a
+ * week on a decade's. So the proposal is cut to what the analyst could have been
+ * pointing at: a zoned time under three days, a day up to about a year, a month up to
+ * twelve years, a year beyond. A drag gives the range between two such values, and a
+ * drag too short to be one is a click.
+ */
export function draftWhen(from, to, startRatio, endRatio) {
const window = windowMillis(from, to);
if (!window) return '';
const low = Math.min(startRatio, endRatio);
const high = Math.max(startRatio, endRatio);
+ const click = high - low < .004;
if (window.span <= 3 * DAY) {
const start = timeAtRatio(from, to, low);
const end = timeAtRatio(from, to, high);
- return high - low < .004 ? start : `${start}/${end}`;
+ return click ? start : `${start}/${end}`;
}
- const a = dateAtRatio(from, to, low);
- const b = dateAtRatio(from, to, high);
+ const cut = window.span <= 400 * DAY ? 10 : window.span <= 12 * YEAR ? 7 : 4;
+ const a = timeAtRatio(from, to, low).slice(0, cut);
+ const b = timeAtRatio(from, to, click ? low : high).slice(0, cut);
if (!a || !b) return '';
return a === b ? a : `${a}/${b}`;
}
@@ -505,12 +524,20 @@ function dateLabel(raw) {
return `${Number(match[3])} ${month} ${year}`;
}
-function timestampLabel(raw) {
+function timestampLabel(raw, tz = null) {
const match = TIMESTAMP_TOKEN.exec(raw);
if (!match) return raw;
const date = `${Number(match[3])} ${MONTHS[Number(match[2]) - 1]} ${match[1]}`;
- const fraction = match[7] ? `.${match[7]}` : '';
- const zone = match[8] === 'Z' ? ' UTC' : match[8] ? ` UTC${match[8]}` : ' local time';
+ // A camera writes its clock to the microsecond, and `17:07:16.000000` is six zeros
+ // nobody reads beside a date. Kept to the millisecond when it says something.
+ const milli = (match[7] ?? '').slice(0, 3);
+ const fraction = /[1-9]/.test(milli) ? `.${milli}` : '';
+ // A time with no offset of its own reads on the clock of the zone it was stated
+ // in, when there is one; without it the words say nothing is known. An offset
+ // written for a named zone says both, since the name is what was picked.
+ const zone = match[8] === 'Z' ? ' UTC'
+ : match[8] ? (tz ? ` ${tz} (UTC${match[8]})` : ` UTC${match[8]}`)
+ : tz ? ` ${tz}` : ' local time';
return `${date}, ${match[4]}:${match[5]}:${match[6]}${fraction}${zone}`;
}
@@ -561,14 +588,37 @@ export function changeInterval(first, second) {
return validateTemporalValue(raw).valid ? raw : '';
}
-export function formatTemporalValue(raw) {
+/**
+ * The clock a row's value is read on, in words for the Timeline's facts. A day
+ * stated in no zone spans UTC's day, which is what the case has always done and
+ * what the analyst could not see; saying so is what lets them correct it.
+ */
+export function temporalZoneWords(item) {
+ if (item?.tz) return item.tz;
+ switch (item?.zone) {
+ case 'date-only': return 'Not stated, read as UTC days';
+ case 'utc': return 'UTC';
+ case 'offset': return 'The offset written in the value';
+ case 'local': return 'Not stated';
+ case 'mixed': return 'Mixed';
+ default: return 'Not set';
+ }
+}
+
+/**
+ * A stored value in words. `tz` is the zone it was stated in, when it was: a day
+ * then names that zone, since the 12th in Kyiv is not UTC's 12th, and a time with
+ * no offset of its own reads on that zone's clock. A value stated in no zone reads
+ * as it always has.
+ */
+export function formatTemporalValue(raw, tz = null) {
const check = validateTemporalValue(raw ?? '');
if (!raw) return { ...check, label: 'Undated', qualifiers: [] };
if (!check.valid) return { ...check, label: raw, qualifiers: [] };
const parts = raw.split('/');
- const label = parts.length === 2
- ? `${DATE_TOKEN.test(parts[0]) ? dateLabel(parts[0]) : timestampLabel(parts[0])} to ${DATE_TOKEN.test(parts[1]) ? dateLabel(parts[1]) : timestampLabel(parts[1])}`
- : DATE_TOKEN.test(raw) ? dateLabel(raw) : timestampLabel(raw);
+ const words = (part) => (DATE_TOKEN.test(part) ? dateLabel(part) : timestampLabel(part, tz));
+ const base = parts.length === 2 ? `${words(parts[0])} to ${words(parts[1])}` : words(raw);
+ const label = tz && parts.some((part) => DATE_TOKEN.test(part)) ? `${base} (${tz})` : base;
return { ...check, label, qualifiers: qualifierLabels(raw) };
}
@@ -686,91 +736,288 @@ export function nudgeTemporalRaw(item, mode, direction) {
return ordered(parts) ? parts.join('/') : null;
}
-function itemBounds(item, window) {
+/**
+ * How an entry is drawn on a track, in screen pixels.
+ *
+ * One rule decides the shape: **a point is an instant, a bracket is a reduced date, a
+ * bar is a period, and a box is never an instant.** A date stated to the day, the month
+ * or the year covers that whole period, so once the period is wide enough to see it is
+ * drawn across it; narrower than `bracket` pixels it is as good as an instant and drawn
+ * as one, in the middle of what it covers. A mark never moves because of its neighbours
+ * or of what is selected: only its row does, and only when two marks would overlap.
+ */
+export const MARKS = {
+ top: 14,
+ row: 18,
+ bottom: 10,
+ /** The room one point takes across the axis; two points closer than this stack. */
+ column: 10,
+ dot: 8,
+ /** Between a mark and the caption beside it. */
+ gap: 5,
+ caption: 180,
+ /** What one character of the 10px caption face costs. Fixed rather than measured:
+ * the layout has to come out the same under a test and on a plate. */
+ charWidth: 5.6,
+ /** A reduced date narrower than this is drawn as a point. */
+ bracket: 6,
+ /** The narrowest a period is drawn, however short it is. */
+ bar: 2,
+ cardWidth: 220,
+ cardMin: 120,
+ cardHeight: 40,
+ cardGap: 8,
+ cardRows: 3,
+ /** A track with more marks than this in the window stays on captions. */
+ cardMax: 12,
+ /** Overflow closer than this joins one `+N`. */
+ cluster: 28,
+};
+
+function markOf(item, window, width) {
const first = new Date(item.earliest).getTime();
- const last = new Date(item.latest).getTime();
+ const last = new Date(item.latest ?? item.earliest).getTime();
if (!Number.isFinite(first) || !Number.isFinite(last)) return null;
- const left = clamp((first - window.start) / window.span);
- const right = clamp((last - window.start) / window.span);
- const midpoint = clamp(((first + last) / 2 - window.start) / window.span);
- return { left, right: Math.max(left, right), midpoint };
+ const a = ((first - window.start) / window.span) * width;
+ const b = ((Math.max(first, last) - window.start) / window.span) * width;
+ // Half-open like the window it is read against: a period ending where the window
+ // starts is not in it, and neither is one starting where it ends.
+ if (b <= 0 && a < 0) return null;
+ if (a >= width) return null;
+ const clipped = { openStart: a < 0, openEnd: b > width };
+ if (item.shape === 'interval' || b - a >= MARKS.bracket) {
+ const left = clamp(a, 0, width);
+ const right = Math.max(clamp(b, 0, width), left + MARKS.bar);
+ return { mark: item.shape === 'interval' ? 'bar' : 'bracket', left, right, x: left, ...clipped };
+ }
+ const x = clamp((a + b) / 2, 0, width);
+ return { mark: 'point', left: x, right: x, x, openStart: false, openEnd: false };
+}
+
+/** The pixels a mark keeps to itself on its row. */
+function extentOf(geo) {
+ return geo.mark === 'point'
+ ? [geo.x - MARKS.column / 2, geo.x + MARKS.column / 2]
+ : [geo.left - 1.5, geo.right + 1.5];
+}
+
+const overlaps = (a, b) => a[0] < b[1] && b[0] < a[1];
+
+function freeRow(rows, extent, ignore = null) {
+ for (let row = 0; ; row += 1) {
+ const taken = rows[row];
+ if (!taken || !taken.some((one) => one.id !== ignore && overlaps(one.extent, extent))) return row;
+ }
+}
+
+function byTime(a, b) {
+ return String(a.earliest).localeCompare(String(b.earliest))
+ || String(a.id).localeCompare(String(b.id));
}
-function pointWidth(item) {
- const date = formatTemporalValue(item.raw).label;
- return clamp(Math.max(String(item.label ?? '').length * 5.45, date.length * 5.1) + 40, 82, 230);
+/** How wide a caption is, at the caption face's own metric. */
+export function captionWidth(text) {
+ return Math.min(MARKS.caption, Math.ceil([...String(text ?? '')].length * MARKS.charWidth) + 4);
}
-/** Pack the rendered geometry, not just the instant anchoring each item. */
-export function layoutTimelineItems(items, from, to, axisWidth = 1000, maxItemRows = 6) {
+function captionFor(entry, width) {
+ const { geo } = entry;
+ const room = captionWidth(entry.item.label);
+ if (!String(entry.item.label ?? '').trim()) return [];
+ const half = geo.mark === 'point' ? MARKS.dot / 2 : 0;
+ const tries = [];
+ // Inside a period its name may run the period's length: the room is its own.
+ const whole = Math.ceil([...String(entry.item.label)].length * MARKS.charWidth) + 4;
+ const inside = Math.min(whole, geo.right - geo.left - 16);
+ if (geo.mark !== 'point' && inside >= room) {
+ tries.push({ side: 'inside', from: geo.left + 6, room: inside });
+ }
+ tries.push({ side: 'right', from: geo.right + half + MARKS.gap, room });
+ tries.push({ side: 'left', from: geo.left - half - MARKS.gap - room, room });
+ return tries
+ .filter((one) => one.from >= 0 && one.from + one.room <= width)
+ .map((one) => ({ ...one, extent: [one.from, one.from + one.room], width: one.room }));
+}
+
+/**
+ * Cards hang under the marks when a track has the room: few enough marks, each card
+ * at most `cardWidth` wide, none of them overlapping, and no stem crossing another
+ * mark or card on its way down. Decided for the whole track at once, so a track reads
+ * one way.
+ */
+function placeCards(placed, rowsTaken, width) {
+ if (!placed.length || placed.length > MARKS.cardMax) return null;
+ const cardRows = [];
+ const cards = new Map();
+ const anchored = [...placed].sort((a, b) => a.geo.x - b.geo.x || byTime(a.item, b.item));
+ for (const entry of anchored) {
+ const { geo, item, row } = entry;
+ const anchor = geo.mark === 'point' ? geo.x : geo.left + Math.min(8, (geo.right - geo.left) / 2);
+ // The stem runs down from the mark, so every mark under this one in its rows must
+ // leave that line clear.
+ for (let below = row + 1; below < rowsTaken.length; below += 1) {
+ if ((rowsTaken[below] ?? []).some((one) => one.id !== item.id
+ && one.extent[0] <= anchor && anchor <= one.extent[1])) return null;
+ }
+ const thumb = item.category === 'media' && item.thumb;
+ // The card holds the name and, under it, the date as written in the 9px mono face.
+ const said = Math.ceil(formatTemporalValue(item.raw ?? '').label.length * 5.5);
+ const wide = clamp(
+ Math.max(captionWidth(item.label), said) + 20 + (thumb ? 38 : 0),
+ MARKS.cardMin,
+ MARKS.cardWidth
+ );
+ const left = clamp(anchor - 14, 0, Math.max(0, width - wide));
+ const extent = [left - MARKS.cardGap / 2, left + wide + MARKS.cardGap / 2];
+ let chosen = -1;
+ for (let cardRow = 0; cardRow < MARKS.cardRows; cardRow += 1) {
+ const taken = cardRows[cardRow] ?? [];
+ if (taken.some((one) => overlaps(one, extent))) continue;
+ // A stem down to a lower row passes the cards above it.
+ const crossed = cardRows.slice(0, cardRow).some((row) =>
+ row.some((one) => one[0] <= anchor && anchor <= one[1]));
+ if (crossed) continue;
+ chosen = cardRow;
+ break;
+ }
+ if (chosen === -1) return null;
+ (cardRows[chosen] ??= []).push(extent);
+ cards.set(item.id, { row: chosen, left, width: wide, anchor });
+ }
+ return { cards, rows: cardRows.length };
+}
+
+/**
+ * Lay a track's entries out against an axis `axisWidth` pixels wide.
+ *
+ * Marks first, in a stable order (pinned, then time), each on the first row where it
+ * overlaps no other mark: points stack down in their column, brackets and bars take
+ * the first row free across their whole span. Past `maxItemRows` an entry joins a
+ * `+N` instead, unless it is pinned. Captions come second, in the order selected,
+ * pinned, time: each tries the right of its mark, then the left (a period first tries
+ * inside itself), and is left out when every side would cover something already
+ * there. The mark stays either way.
+ */
+export function layoutTimelineItems(items, from, to, axisWidth = 1000, maxItemRows = 6, options = {}) {
const window = windowMillis(from, to);
- if (!window) return { items: [], clusters: [], rows: 1 };
+ const empty = {
+ items: [], clusters: [], rows: 1, cards: false, cardRows: 0, labelled: 0,
+ height: MARKS.top + MARKS.row + MARKS.bottom,
+ };
+ if (!window) return empty;
const width = Math.max(320, axisWidth);
- const gap = 7 / width;
- const lanes = [];
+ const { selectedId = null } = options;
+ const entries = [];
+ for (const item of items) {
+ const geo = markOf(item, window, width);
+ if (geo) entries.push({ item, geo });
+ }
+ entries.sort((a, b) =>
+ Number(Boolean(b.item.pinned)) - Number(Boolean(a.item.pinned))
+ || Number(a.geo.mark !== 'point') - Number(b.geo.mark !== 'point')
+ || byTime(a.item, b.item));
+
+ const rowsTaken = [];
const placed = [];
- const hidden = new Map();
- const sorted = [...items].sort((a, b) =>
- Number(Boolean(b.pinned)) - Number(Boolean(a.pinned))
- || String(a.earliest).localeCompare(String(b.earliest))
- || String(a.id).localeCompare(String(b.id))
- );
- for (const item of sorted) {
- const bounds = itemBounds(item, window);
- if (!bounds) continue;
- const interval = item.shape === 'interval';
- const left = interval ? bounds.left : bounds.midpoint;
- const displayWidth = interval
- ? Math.max(28, (bounds.right - bounds.left) * width)
- : pointWidth(item);
- const endAligned = !interval && bounds.midpoint > 0.82;
- const visualLeft = interval ? left : endAligned
- ? left - (displayWidth - 8) / width
- : left - 8 / width;
- const visualRight = interval ? left + displayWidth / width : endAligned
- ? left + 8 / width
- : left + (displayWidth - 8) / width;
- let lane = lanes.findIndex((end) => end + gap < visualLeft);
- if (lane === -1 && (lanes.length < maxItemRows || item.pinned)) {
- lane = lanes.length;
- lanes.push(visualRight);
- } else if (lane !== -1) {
- lanes[lane] = visualRight;
- } else {
- const bucket = Math.floor(clamp(bounds.midpoint, 0, 0.9999) * width / 88);
- const group = hidden.get(bucket) ?? { count: 0, items: [], midpoint: bounds.midpoint };
- group.count += 1;
- group.items.push(item);
- group.midpoint = (group.midpoint * (group.count - 1) + bounds.midpoint) / group.count;
- hidden.set(bucket, group);
+ const overflow = [];
+ for (const entry of entries) {
+ const extent = extentOf(entry.geo);
+ const row = freeRow(rowsTaken, extent);
+ if (row >= maxItemRows && !entry.item.pinned) {
+ overflow.push(entry);
continue;
}
- placed.push({
- ...item,
- lane,
- left: left * 100,
- width: (displayWidth / width) * 100,
- displayWidth,
- endAligned,
- haloLeft: bounds.left * 100,
- haloWidth: Math.max(0, (bounds.right - bounds.left) * 100),
- });
+ (rowsTaken[row] ??= []).push({ id: entry.item.id, extent });
+ placed.push({ ...entry, row });
+ }
+
+ const groups = [];
+ for (const entry of [...overflow].sort((a, b) => a.geo.x - b.geo.x || byTime(a.item, b.item))) {
+ const at = entry.geo.mark === 'point' ? entry.geo.x : (entry.geo.left + entry.geo.right) / 2;
+ const group = groups.find((one) => Math.abs(one.at - at) < MARKS.cluster);
+ if (group) {
+ group.items.push(entry.item);
+ group.at = (group.at * (group.items.length - 1) + at) / group.items.length;
+ } else groups.push({ at, items: [entry.item] });
}
- const clusters = [...hidden.entries()].map(([bucket, group]) => ({
- id: `cluster:${bucket}`,
- lane: Math.max(maxItemRows, lanes.length),
- left: group.midpoint * 100,
- count: group.count,
- items: group.items,
- earliest: group.items[0]?.earliest ?? '',
+ const markRows = Math.max(1, rowsTaken.length);
+ const clusters = groups.map((group, index) => ({
+ id: `cluster:${index}:${group.items[0].id}`,
+ row: markRows,
+ left: (group.at / width) * 100,
+ count: group.items.length,
+ items: [...group.items].sort(byTime),
+ earliest: [...group.items].sort(byTime)[0]?.earliest ?? '',
}));
+ const rows = markRows + (clusters.length ? 1 : 0);
+
+ const carded = clusters.length ? null : placeCards(placed, rowsTaken, width);
+ const captions = new Map();
+ if (!carded) {
+ const taken = rowsTaken.map((row) => [...row]);
+ const order = [...placed].sort((a, b) =>
+ Number(b.item.id === selectedId) - Number(a.item.id === selectedId)
+ || Number(Boolean(b.item.pinned)) - Number(Boolean(a.item.pinned))
+ || byTime(a.item, b.item));
+ for (const entry of order) {
+ const row = taken[entry.row];
+ const fit = captionFor(entry, width).find((one) =>
+ !row.some((other) => other.id !== entry.item.id && overlaps(other.extent, one.extent)));
+ if (!fit) continue;
+ row.push({ id: `${entry.item.id}:caption`, extent: fit.extent });
+ captions.set(entry.item.id, fit);
+ }
+ }
+
+ const laid = [...placed].sort((a, b) => byTime(a.item, b.item)).map(({ item, geo, row }) => {
+ const box = geo.mark === 'point'
+ ? { from: geo.x - MARKS.column / 2, to: geo.x + MARKS.column / 2 }
+ : { from: geo.left, to: geo.right };
+ const caption = captions.get(item.id);
+ const card = carded?.cards.get(item.id);
+ return {
+ ...item,
+ mark: geo.mark,
+ row,
+ /** Where the instant, or the start of the span, falls: a percentage of the axis. */
+ left: (geo.x / width) * 100,
+ /** How much of the axis the mark covers: nothing for a point. */
+ width: geo.mark === 'point' ? 0 : ((geo.right - geo.left) / width) * 100,
+ openStart: geo.openStart,
+ openEnd: geo.openEnd,
+ caption: caption
+ ? { side: caption.side, offset: caption.from - box.from, width: caption.width, left: caption.from }
+ : null,
+ card: card
+ ? {
+ row: card.row,
+ offset: card.left - box.from,
+ width: card.width,
+ left: card.left,
+ stem: card.anchor - box.from,
+ anchor: card.anchor,
+ }
+ : null,
+ };
+ });
+ const cardRows = carded?.rows ?? 0;
+ const marksHeight = MARKS.top + rows * MARKS.row;
return {
- items: placed,
+ items: laid,
clusters,
- rows: Math.max(1, lanes.length + (clusters.length ? 1 : 0)),
+ rows,
+ cards: Boolean(carded),
+ cardRows,
+ labelled: laid.filter((item) => item.caption || item.card).length,
+ height: marksHeight + (cardRows ? 6 + cardRows * (MARKS.cardHeight + 6) : 0) + MARKS.bottom,
};
}
+/** The top of a card row under a track's marks, in pixels from the top of the track. */
+export function cardTop(layout, row) {
+ return MARKS.top + layout.rows * MARKS.row + 6 + row * (MARKS.cardHeight + 6);
+}
+
const TICK_STEPS = [
['second', 1, SECOND], ['second', 5, 5 * SECOND], ['second', 10, 10 * SECOND],
['second', 30, 30 * SECOND], ['minute', 1, MINUTE], ['minute', 5, 5 * MINUTE],
diff --git a/frontend/src/lib/timeline.test.js b/frontend/src/lib/timeline.test.js
index c2bc860..4c01604 100644
--- a/frontend/src/lib/timeline.test.js
+++ b/frontend/src/lib/timeline.test.js
@@ -21,6 +21,7 @@ import {
formatSpan,
formatSpanRange,
formatTemporalValue,
+ temporalZoneWords,
initialWindow,
UTC,
inputWindowValue,
@@ -97,6 +98,8 @@ describe('timeline window', () => {
it('creates exact timestamps when the visible window is close enough', () => {
expect(dateAtRatio('2026-08-01', '2026-08-10', 0)).toBe('2026-08-01');
+ // 23:00 UTC on the 1st is already the 2nd in Kyiv.
+ expect(dateAtRatio('2026-08-01T23:00:00Z', '2026-08-02T01:00:00Z', 0, 'Europe/Kyiv')).toBe('2026-08-02');
expect(timeAtRatio('2026-06-23T00:00:00Z', '2026-06-24T00:00:00Z', .39999997))
.toBe('2026-06-23T09:36:00Z');
expect(draftWhen('2026-08-11T18:00:00Z', '2026-08-11T19:00:00Z', .5, .5))
@@ -105,6 +108,27 @@ describe('timeline window', () => {
.toBe('2026-08-11T18:15:00Z/2026-08-11T18:45:00Z');
expect(draftWhen('2026-08-01', '2026-08-10', .1, .8)).toBe('2026-08-02/2026-08-09');
});
+
+ it('proposes a date as precise as the window it was pointed at', () => {
+ const at = (from, span) => new Date(Date.parse(from) + span).toISOString();
+ const start = '2026-01-01T00:00:00Z';
+ // three days is still read to the second, a second more is read to the day
+ expect(draftWhen(start, at(start, 3 * DAY), .5, .5)).toBe('2026-01-02T12:00:00Z');
+ expect(draftWhen(start, at(start, 3 * DAY + 1000), .5, .5)).toBe('2026-01-02');
+ // up to four hundred days a day, then a month
+ expect(draftWhen(start, at(start, 400 * DAY), .5, .5)).toBe('2026-07-20');
+ expect(draftWhen(start, at(start, 401 * DAY), .5, .5)).toBe('2026-07');
+ // up to twelve years a month, then a year
+ expect(draftWhen(start, at(start, 12 * 365.2425 * DAY), .5, .5)).toBe('2032-01');
+ expect(draftWhen(start, at(start, 13 * 365.2425 * DAY), .5, .5)).toBe('2032');
+ // a drag gives a range at the same precision, and one inside a single period is it
+ expect(draftWhen(start, at(start, 2 * 365 * DAY), .1, .6)).toBe('2026-03/2027-03');
+ expect(draftWhen(start, at(start, 40 * 365.2425 * DAY), .1, .6)).toBe('2029/2049');
+ expect(draftWhen(start, at(start, 2 * 365 * DAY), .5, .505)).toBe('2027-01');
+ for (const value of ['2032-01', '2032', '2026-03/2027-03', '2029/2049']) {
+ expect(validateTemporalValue(value).valid, value).toBe(true);
+ }
+ });
});
describe('temporal reading', () => {
@@ -118,6 +142,32 @@ describe('temporal reading', () => {
.toBe('11 Aug 2026 to 14 Aug 2026');
});
+ it('reads a camera clock to the millisecond at most, and not at all when it is zeros', () => {
+ expect(formatTemporalValue('2023-06-22T17:07:16.000000Z').label).toBe('22 Jun 2023, 17:07:16 UTC');
+ expect(formatTemporalValue('2023-06-22T17:07:16.250000Z').label).toBe('22 Jun 2023, 17:07:16.250 UTC');
+ expect(formatTemporalValue('2023-06-22T17:07:16.1Z').label).toBe('22 Jun 2023, 17:07:16.1 UTC');
+ });
+
+ it('names the zone a value was stated in, and says when none was', () => {
+ expect(formatTemporalValue('2024-03-12', 'Europe/Kyiv').label).toBe('12 Mar 2024 (Europe/Kyiv)');
+ expect(formatTemporalValue('2024-03-12/2024-03-14', 'Asia/Tokyo').label)
+ .toBe('12 Mar 2024 to 14 Mar 2024 (Asia/Tokyo)');
+ expect(formatTemporalValue('2024-07-12T14:30:00', 'Europe/Kyiv').label)
+ .toBe('12 Jul 2024, 14:30:00 Europe/Kyiv');
+ expect(formatTemporalValue('2024-07-12T14:30:00').label).toBe('12 Jul 2024, 14:30:00 local time');
+ // A time that says where it stands keeps its own offset.
+ expect(formatTemporalValue('2024-07-12T14:30:00Z', 'Europe/Kyiv').label).toBe('12 Jul 2024, 14:30:00 UTC');
+ // An offset written for a picked zone names the zone and keeps the offset.
+ expect(formatTemporalValue('2024-07-12T14:30:00+03:00', 'Europe/Kyiv').label)
+ .toBe('12 Jul 2024, 14:30:00 Europe/Kyiv (UTC+03:00)');
+ expect(formatTemporalValue('2024-07-12T14:30:00+03:00').label).toBe('12 Jul 2024, 14:30:00 UTC+03:00');
+
+ expect(temporalZoneWords({ zone: 'date-only', tz: 'Europe/Kyiv' })).toBe('Europe/Kyiv');
+ expect(temporalZoneWords({ zone: 'date-only' })).toBe('Not stated, read as UTC days');
+ expect(temporalZoneWords({ zone: 'local' })).toBe('Not stated');
+ expect(temporalZoneWords({})).toBe('Not set');
+ });
+
it('validates the same supported families before save', () => {
for (const raw of ['2026', '2026-08~', '2026-08-11?', '2026-08-11T18:40:00Z', '2026-08/2026-10', '2026-08-11T10:00:00Z/2026-08-11T11:00:00Z']) {
expect(validateTemporalValue(raw).valid, raw).toBe(true);
@@ -132,41 +182,157 @@ describe('timeline layout', () => {
const point = (id, earliest, latest, shape = 'instant', label = id) => ({
id, earliest, latest, shape, label, raw: earliest.slice(0, 10),
});
+ const instant = (id, at, label = id) => point(id, at, new Date(Date.parse(at) + 1000).toISOString(), 'instant', label);
+ const one = (items, from = '2026-08-01', to = '2026-08-10', width = 1000, rows = 6, options) =>
+ layoutTimelineItems(items, from, to, width, rows, options);
+ // Two entries stacked at the far end: a stem would cross one, so the track stays on
+ // captions and a test can read them.
+ const crowd = [instant('z1', '2026-08-10T20:00:00Z'), instant('z2', '2026-08-10T20:00:00Z')];
+ const captioned = (items, options) =>
+ one([...items, ...crowd], undefined, undefined, 1000, 6, options).items
+ .filter((item) => !item.id.startsWith('z'));
+
+ it('puts an exact instant on its pixel, at either end of the window and in between', () => {
+ // A stamp to the second covers that second; the point sits in its middle, which is
+ // a thousandth of a pixel from the instant itself on a ten-day axis.
+ const start = Date.parse('2026-08-01T00:00:00Z');
+ const span = 10 * 86_400_000;
+ for (const at of ['2026-08-01T00:00:00Z', '2026-08-06T00:00:00Z', '2026-08-10T23:59:59Z']) {
+ const [item] = one([instant('a', at)]).items;
+ expect(item.mark).toBe('point');
+ expect(item.left).toBeCloseTo(((Date.parse(at) + 500 - start) / span) * 100, 9);
+ expect(item.width).toBe(0);
+ }
+ });
- it('packs the rendered label width instead of a fixed axis fraction', () => {
- const layout = layoutTimelineItems([
- point('a', '2026-08-02T00:00:00Z', '2026-08-03T00:00:00Z', 'instant', 'A long checkpoint observation'),
- point('b', '2026-08-02T12:00:00Z', '2026-08-03T00:00:00Z', 'instant', 'Another long checkpoint observation'),
- point('c', '2026-08-05T00:00:00Z', '2026-08-08T00:00:00Z', 'interval', 'Road closure'),
- ], '2026-08-01', '2026-08-10', 1000);
- expect(layout.items.map((item) => item.lane)).toEqual([0, 1, 0]);
- expect(layout.items[0].displayWidth).toBeGreaterThan(150);
- expect(layout.items[0].haloWidth).toBeCloseTo(10, 3);
- expect(layout.items[2].displayWidth).toBeGreaterThan(250);
+ it('never flips a mark to the other side of its date near the end of the window', () => {
+ const late = captioned([instant('late', '2026-08-10T12:00:00Z', 'Last convoy')])[0];
+ expect(late.left).toBeCloseTo(95, 2);
+ expect(late).not.toHaveProperty('endAligned');
+ // its caption goes where there is room, and the mark stays put
+ expect(late.caption.side).toBe('left');
});
- it('collapses overflow into a clear count', () => {
- const entries = Array.from({ length: 10 }, (_, index) =>
- point(`same-${index}`, '2026-08-02T00:00:00Z', '2026-08-03T00:00:00Z')
- );
- const layout = layoutTimelineItems(entries, '2026-08-01', '2026-08-10', 800, 3);
+ it('draws a reduced date across the whole period it covers', () => {
+ const [day] = one([point('day', '2026-08-03T00:00:00Z', '2026-08-04T00:00:00Z')]).items;
+ expect(day.mark).toBe('bracket');
+ expect(day.left).toBeCloseTo(20, 5);
+ expect(day.width).toBeCloseTo(10, 5);
+ });
+
+ it('draws a reduced date as a point once its period is narrower than a few pixels', () => {
+ // A day over a year of axis is under three pixels: as good as an instant.
+ const [day] = one([point('day', '2026-03-10T00:00:00Z', '2026-03-11T00:00:00Z')],
+ '2026-01-01', '2026-12-31').items;
+ expect(day.mark).toBe('point');
+ expect(day.left).toBeCloseTo(((Date.parse('2026-03-10T12:00:00Z') - Date.parse('2026-01-01'))
+ / (Date.parse('2027-01-01') - Date.parse('2026-01-01'))) * 100, 5);
+ });
+
+ it('draws a short period at its true length, never widened to a box', () => {
+ const [bar] = one([point('p', '2026-08-02T00:00:00Z', '2026-08-02T06:00:00Z', 'interval')]).items;
+ expect(bar.mark).toBe('bar');
+ expect(bar.width).toBeCloseTo(2.5, 5);
+ const [sliver] = one([point('s', '2026-08-02T00:00:00Z', '2026-08-02T00:00:10Z', 'interval')]).items;
+ expect(sliver.mark).toBe('bar');
+ expect(sliver.width).toBeCloseTo(0.2, 5); // the 2px floor, and no more
+ });
+
+ it('stacks points that would overlap, pinned first, and never moves one sideways', () => {
+ const layout = one([
+ instant('b', '2026-08-02T00:00:00Z'),
+ instant('a', '2026-08-02T00:00:00Z'),
+ { ...instant('c', '2026-08-02T00:00:00Z'), pinned: true },
+ ]);
+ const rows = Object.fromEntries(layout.items.map((item) => [item.id, item.row]));
+ expect(rows).toEqual({ c: 0, a: 1, b: 2 });
+ expect(new Set(layout.items.map((item) => item.left)).size).toBe(1);
+ });
+
+ it('gives a period the first row free across its whole span', () => {
+ const layout = one([
+ instant('x', '2026-08-03T00:00:00Z'),
+ point('span', '2026-08-02T00:00:00Z', '2026-08-06T00:00:00Z', 'interval'),
+ point('later', '2026-08-08T00:00:00Z', '2026-08-09T00:00:00Z', 'interval'),
+ ]);
+ const rows = Object.fromEntries(layout.items.map((item) => [item.id, item.row]));
+ expect(rows).toEqual({ x: 0, span: 1, later: 0 });
+ });
+
+ it('counts past the ceiling, and a pinned entry escapes it', () => {
+ const entries = Array.from({ length: 10 }, (_, index) => instant(`same-${index}`, '2026-08-02T00:00:00Z'));
+ const layout = one(entries, '2026-08-01', '2026-08-10', 800, 3);
expect(layout.items).toHaveLength(3);
expect(layout.clusters).toHaveLength(1);
expect(layout.clusters[0].count).toBe(7);
+ expect(layout.clusters[0].row).toBe(3);
expect(layout.rows).toBe(4);
- });
- it('keeps pinned entries visible when a dense track is packed', () => {
- const entries = Array.from({ length: 9 }, (_, index) => ({
- ...point(`same-${index}`, '2026-08-02T00:00:00Z', '2026-08-03T00:00:00Z'),
- pinned: index === 8,
- }));
- const layout = layoutTimelineItems(entries, '2026-08-01', '2026-08-10', 800, 3);
- expect(layout.items.some((item) => item.id === 'same-8')).toBe(true);
- expect(layout.clusters.flatMap((cluster) => cluster.items).some((item) => item.id === 'same-8'))
+ const pinned = entries.map((entry, index) => ({ ...entry, pinned: index === 8 }));
+ const kept = one(pinned, '2026-08-01', '2026-08-10', 800, 3);
+ expect(kept.items.some((item) => item.id === 'same-8')).toBe(true);
+ expect(kept.clusters.flatMap((cluster) => cluster.items).some((item) => item.id === 'same-8'))
.toBe(false);
});
+ it('captions a mark only where the caption covers nothing else', () => {
+ const [a, b] = captioned([
+ instant('a', '2026-08-02T00:00:00Z', 'A long checkpoint observation'),
+ instant('b', '2026-08-02T06:00:00Z', 'Another long checkpoint observation'),
+ ]);
+ expect(a.row).toBe(0);
+ expect(b.row).toBe(0); // 25px apart: two marks side by side, not stacked
+ expect(a.caption).toBeNull(); // no room on either side of the first
+ expect(b.caption.side).toBe('right');
+ });
+
+ it('captions the selected entry first, and the same way on every render', () => {
+ // b's right is blocked by c, and its left is where a's caption goes, until b is
+ // the one being read.
+ const items = [
+ instant('a', '2026-08-02T00:00:00Z', 'A long checkpoint observation'),
+ instant('b', '2026-08-04T00:00:00Z', 'Another long checkpoint observation'),
+ instant('c', '2026-08-05T00:00:00Z', 'Gate'),
+ ];
+ const plain = Object.fromEntries(captioned(items).map((item) => [item.id, item.caption?.side ?? null]));
+ expect(plain).toEqual({ a: 'right', b: null, c: 'right' });
+ const read = Object.fromEntries(captioned(items, { selectedId: 'b' }).map((item) => [item.id, item.caption?.side ?? null]));
+ expect(read).toEqual({ a: null, b: 'left', c: 'right' });
+ expect(captioned(items)).toEqual(captioned(items));
+ });
+
+ it('writes a period\'s name inside it when it fits, beside it when not', () => {
+ const [wide] = captioned([point('w', '2026-08-02T00:00:00Z', '2026-08-06T00:00:00Z', 'interval', 'Road closure')]);
+ expect(wide.caption.side).toBe('inside');
+ const [narrow] = captioned([point('n', '2026-08-02T00:00:00Z', '2026-08-02T03:00:00Z', 'interval', 'Road closure')]);
+ expect(narrow.caption.side).toBe('right');
+ });
+
+ it('hangs cards under a track only when every card fits', () => {
+ const few = one([
+ instant('a', '2026-08-02T00:00:00Z', 'Convoy crossed the bridge'),
+ { ...instant('m', '2026-08-06T00:00:00Z', 'VID_0312'), category: 'media', thumb: '.thumbs/v.jpg' },
+ ]);
+ expect(few.cards).toBe(true);
+ expect(few.items.every((item) => item.card && !item.caption)).toBe(true);
+ expect(few.items[1].card.width).toBeGreaterThan(few.items[0].card.width - 60);
+ expect(few.height).toBeGreaterThan(one([]).height + 40);
+
+ const many = one(Array.from({ length: 13 }, (_, index) =>
+ instant(`e${index}`, `2026-08-0${1 + (index % 9)}T0${index % 10}:00:00Z`)));
+ expect(many.cards).toBe(false);
+ // a stacked column would run a stem through the mark under it
+ const stacked = one([instant('x', '2026-08-02T00:00:00Z'), instant('y', '2026-08-02T00:00:00Z')]);
+ expect(stacked.cards).toBe(false);
+ });
+
+ it('leaves out what lies outside the window rather than piling it on the edge', () => {
+ const layout = one([instant('before', '2026-07-20T00:00:00Z'), instant('in', '2026-08-05T00:00:00Z')]);
+ expect(layout.items.map((item) => item.id)).toEqual(['in']);
+ const [open] = one([point('long', '2026-07-01T00:00:00Z', '2026-08-03T00:00:00Z', 'interval')]).items;
+ expect(open).toMatchObject({ mark: 'bar', left: 0, openStart: true, openEnd: false });
+ });
+
it('targets a useful number of major ticks and adds context', () => {
const short = axisTicks('2026-08-01T00:00:00Z', '2026-08-04T00:00:00Z', 1000);
const medium = axisTicks('2026-06-10T00:00:00Z', '2026-08-03T00:00:00Z', 1000);
diff --git a/frontend/src/lib/timelineCopy.js b/frontend/src/lib/timelineCopy.js
new file mode 100644
index 0000000..402094e
--- /dev/null
+++ b/frontend/src/lib/timelineCopy.js
@@ -0,0 +1,104 @@
+/**
+ * The window's chronology as text, for a report, a ticket or a spreadsheet.
+ *
+ * The axis is read with the eyes and the list with the pointer; neither goes into a
+ * message. This turns the same entries into the two things that do: a Markdown table
+ * for the Notebook or a ticket, and the tab-separated block a spreadsheet reads back as
+ * columns. Both writers are the Sheet's own (`toMarkdown`, `toBlock`), so a pipe or a
+ * newline in a statement is escaped the one way the app already escapes it.
+ *
+ * What is copied is the window, not the page on screen: every page of every track,
+ * without the axis's spread sampling, up to the ceiling a snapshot already holds.
+ */
+
+import { toMarkdown } from './sheetExport.js';
+import { toBlock } from './sheetClipboard.js';
+import { formatTemporalValue } from './timeline.js';
+import { timelineTrackQuery } from './timelineTracks.js';
+
+/** The most entries one copy carries, the same as a Timeline snapshot. */
+export const COPY_LIMIT = 5000;
+
+/** The spreadsheet columns, named for a reader who never saw the app. */
+export const CHRONOLOGY_COLUMNS = [
+ 'date_as_written', 'time_zone', 'earliest_utc', 'latest_utc', 'statement',
+ 'subjects', 'places', 'sources', 'confidence', 'status',
+];
+
+const names = (entries) => (entries ?? []).map((entry) => entry.label || entry.id).join('; ');
+
+/** The dated entries, once each, in the order they happened. */
+export function chronologyRows(items = []) {
+ const unique = new Map();
+ for (const item of items) if (item?.earliest && !unique.has(item.id)) unique.set(item.id, item);
+ return [...unique.values()]
+ .sort((a, b) => String(a.earliest).localeCompare(String(b.earliest))
+ || String(a.id).localeCompare(String(b.id)))
+ .map((item) => ({
+ id: item.id,
+ raw: item.raw ?? '',
+ // The zone the date was stated in: without it a day written as the 12th
+ // cannot be told from UTC's 12th by someone reading the sheet alone.
+ zone: item.tz ?? '',
+ reading: formatTemporalValue(item.raw ?? '', item.tz).label,
+ earliest: item.earliest ?? '',
+ latest: item.latest ?? '',
+ statement: item.label ?? '',
+ subjects: names(item.subject_entities),
+ places: names(item.place_entities),
+ sources: names(item.source_entities),
+ confidence: item.confidence ?? '',
+ status: item.status ?? '',
+ }));
+}
+
+/** A block to paste into a spreadsheet: a header row, then one row per entry. */
+export function chronologyBlock(rows) {
+ return toBlock([
+ CHRONOLOGY_COLUMNS,
+ ...rows.map((row) => [
+ row.raw, row.zone, row.earliest, row.latest, row.statement,
+ row.subjects, row.places, row.sources, row.confidence, row.status,
+ ]),
+ ]);
+}
+
+/** A Markdown table, with the lines that say where it came from quoted above it. */
+export function chronologyMarkdown(rows, said = []) {
+ return toMarkdown({
+ columns: ['Date', 'Statement', 'Subjects', 'Places', 'Sources', 'Confidence'],
+ rows: rows.map((row) => [
+ row.reading, row.statement, row.subjects, row.places, row.sources, row.confidence,
+ ]),
+ }, said);
+}
+
+/**
+ * Every dated entry the tracks hold in the window, page after page.
+ *
+ * `get` is the API's own reader, handed in so this stays testable without a server.
+ * Answers the entries and whether the ceiling cut them.
+ */
+export async function readChronology(get, { caseId, tracks = [], from, to, entityId, limit = COPY_LIMIT }) {
+ const seen = new Map();
+ for (const track of tracks) {
+ let cursor = null;
+ do {
+ const params = new URLSearchParams({ include_undated: 'false', limit: '200' });
+ for (const category of track.categories) params.append('category', category);
+ if (from) params.set('from', from);
+ if (to) params.set('to', to);
+ if (entityId) params.set('entity', entityId);
+ if (cursor) params.set('cursor', cursor);
+ params.set('track', timelineTrackQuery(track));
+ const page = await get(`/api/cases/${caseId}/timeline?${params}`);
+ for (const item of page?.items ?? []) {
+ if (seen.has(item.id)) continue;
+ if (seen.size >= limit) return { items: [...seen.values()], truncated: true };
+ seen.set(item.id, item);
+ }
+ cursor = page?.next_cursor ?? null;
+ } while (cursor);
+ }
+ return { items: [...seen.values()], truncated: false };
+}
diff --git a/frontend/src/lib/timelineCopy.test.js b/frontend/src/lib/timelineCopy.test.js
new file mode 100644
index 0000000..56146a0
--- /dev/null
+++ b/frontend/src/lib/timelineCopy.test.js
@@ -0,0 +1,109 @@
+import { describe, expect, it } from 'vitest';
+import {
+ CHRONOLOGY_COLUMNS,
+ COPY_LIMIT,
+ chronologyBlock,
+ chronologyMarkdown,
+ chronologyRows,
+ readChronology,
+} from './timelineCopy.js';
+import { parseBlock } from './sheetClipboard.js';
+
+const entry = (id, earliest, extra = {}) => ({
+ id,
+ label: `Entry ${id}`,
+ raw: earliest.slice(0, 10),
+ earliest,
+ latest: earliest,
+ category: 'statement',
+ ...extra,
+});
+
+describe('copying the chronology', () => {
+ it('lists each dated entry once, in the order it happened', () => {
+ const rows = chronologyRows([
+ entry('b', '2026-08-02T00:00:00Z'),
+ entry('a', '2026-08-01T00:00:00Z'),
+ entry('b', '2026-08-02T00:00:00Z'),
+ { id: 'u', label: 'Undated', raw: null, earliest: null },
+ ]);
+ expect(rows.map((row) => row.id)).toEqual(['a', 'b']);
+ });
+
+ it('writes the spreadsheet columns a reader who never saw the app can read', () => {
+ const [row] = chronologyRows([entry('a', '2026-08-11T14:05:00Z', {
+ raw: '2026-08-11T17:05:00+03:00',
+ latest: '2026-08-11T14:05:01Z',
+ label: 'Convoy crossed the "east" bridge',
+ subject_entities: [{ id: 'v', label: 'MV Aurora' }, { id: 'o', label: 'Northwind' }],
+ place_entities: [{ id: 'p', label: 'East bridge' }],
+ source_entities: [{ id: 's', label: 'VID_0312' }],
+ confidence: 'probable',
+ status: 'confirmed',
+ })]);
+ const table = parseBlock(chronologyBlock([row]));
+ expect(table[0]).toEqual(CHRONOLOGY_COLUMNS);
+ expect(table[1]).toEqual([
+ // as written, with its own offset; the bounds stay in UTC whatever the axis reads
+ '2026-08-11T17:05:00+03:00', '', '2026-08-11T14:05:00Z', '2026-08-11T14:05:01Z',
+ 'Convoy crossed the "east" bridge', 'MV Aurora; Northwind', 'East bridge', 'VID_0312',
+ 'probable', 'confirmed',
+ ]);
+ });
+
+ it('names the zone a day was stated in, beside the day and in its reading', () => {
+ const [row] = chronologyRows([entry('a', '2024-03-11T22:00:00Z', {
+ raw: '2024-03-12', tz: 'Europe/Kyiv', latest: '2024-03-12T22:00:00Z',
+ })]);
+ expect(parseBlock(chronologyBlock([row]))[1].slice(0, 4)).toEqual([
+ '2024-03-12', 'Europe/Kyiv', '2024-03-11T22:00:00Z', '2024-03-12T22:00:00Z',
+ ]);
+ expect(row.reading).toBe('12 Mar 2024 (Europe/Kyiv)');
+ });
+
+ it('writes a Markdown table that reads the date and says where it came from', () => {
+ const rows = chronologyRows([entry('a', '2026-08-03T00:00:00Z', { raw: '2026-08', label: 'Recruitment | announced' })]);
+ const text = chronologyMarkdown(rows, ['Harbour · Timeline — 1 of 1 rows']);
+ expect(text).toBe([
+ '> Harbour · Timeline — 1 of 1 rows',
+ '',
+ '| Date | Statement | Subjects | Places | Sources | Confidence |',
+ '| --- | --- | --- | --- | --- | --- |',
+ '| Aug 2026 | Recruitment \\| announced | | | | |',
+ '',
+ ].join('\n'));
+ });
+
+ it('reads every page of every track, once, up to the ceiling', async () => {
+ const asked = [];
+ const pages = {
+ events: [
+ { items: [entry('a', '2026-08-01T00:00:00Z'), entry('b', '2026-08-02T00:00:00Z')], next_cursor: 'c1' },
+ { items: [entry('c', '2026-08-03T00:00:00Z')], next_cursor: null },
+ ],
+ media: [{ items: [entry('b', '2026-08-02T00:00:00Z'), entry('m', '2026-08-04T00:00:00Z')], next_cursor: null }],
+ };
+ const get = async (url) => {
+ const params = new URL(url, 'http://x').searchParams;
+ asked.push(params);
+ const track = JSON.parse(params.get('track')).label;
+ return pages[track][params.get('cursor') ? 1 : 0];
+ };
+ const tracks = [
+ { id: 'events', categories: ['statement'], query: { label: 'events' }, hidden: ['gone'] },
+ { id: 'media', categories: ['media'], query: { label: 'media' }, hidden: [] },
+ ];
+ const read = await readChronology(get, { caseId: 'c', tracks, from: '2026-08-01', to: '2026-08-10' });
+ expect(read.items.map((item) => item.id)).toEqual(['a', 'b', 'c', 'm']);
+ expect(read.truncated).toBe(false);
+ // the whole window, never the axis's spread sample, and what a track hides stays hidden
+ expect(asked.every((params) => !params.has('spread') && params.get('include_undated') === 'false')).toBe(true);
+ expect(JSON.parse(asked[0].get('track')).hidden).toEqual(['gone']);
+ expect(asked[1].get('cursor')).toBe('c1');
+
+ const capped = await readChronology(get, { caseId: 'c', tracks, limit: 2 });
+ expect(capped).toMatchObject({ truncated: true });
+ expect(capped.items).toHaveLength(2);
+ expect(COPY_LIMIT).toBe(5000);
+ });
+});
diff --git a/frontend/src/lib/timelineFit.js b/frontend/src/lib/timelineFit.js
new file mode 100644
index 0000000..1a3437d
--- /dev/null
+++ b/frontend/src/lib/timelineFit.js
@@ -0,0 +1,87 @@
+/**
+ * What the axis can print without two names on the same pixels.
+ *
+ * Ticks and bands are chosen by span, and their names are as wide as their words. At
+ * the edge of a window, or where a day's name meets the hour beside it, two of them
+ * landed on each other ("22 Jun20:00"), and a band cut by the window's edge showed half
+ * a date ("21 Jun 20"). A name that does not fit is shortened or left out; the line it
+ * labels stays.
+ *
+ * Widths are estimated from the monospace sizes the axis is drawn in, which is exact
+ * enough to keep names apart without measuring text in the browser.
+ */
+
+const width = (label, char) => String(label ?? '').length * char;
+
+/**
+ * The ruler's ticks, each name kept only if it clears the one before it.
+ *
+ * `ticks` carry `left` in percent. A name is drawn to the right of its line, and to the
+ * left of it past `endAt` percent, so the last one stays inside the ruler.
+ */
+export function fitTicks(ticks, rulerWidth, { char = 6.1, gap = 8, endAt = 94 } = {}) {
+ let reach = -Infinity;
+ return ticks.map((tick) => {
+ if (!tick.label) return tick;
+ const x = (tick.left / 100) * rulerWidth;
+ const size = width(tick.label, char);
+ const [start, end] = tick.left > endAt ? [x - 5 - size, x - 5] : [x + 5, x + 5 + size];
+ if (start < reach + gap) return { ...tick, label: '' };
+ reach = end;
+ return tick;
+ });
+}
+
+/**
+ * The day, month or year bands over the ruler, each named only if the name fits.
+ *
+ * A band too narrow for `22 Jun 2023` says `22 Jun`, since the next band names the year,
+ * and one too narrow for that says nothing.
+ */
+export function fitBands(bands, rulerWidth, { char = 5.5, padding = 14 } = {}) {
+ return bands.map((band) => {
+ const room = (band.width / 100) * rulerWidth - padding;
+ if (width(band.label, char) <= room) return band;
+ const short = String(band.label ?? '').replace(/\s\d{4}$/, '');
+ return { ...band, label: short !== band.label && width(short, char) <= room ? short : '' };
+ });
+}
+
+/**
+ * The overview's period names, each kept only if it clears the one before it.
+ *
+ * `densityTicks` names one slot in every few and lets the name run over its
+ * neighbours, centred under its own slot (the two outermost lean inward), so what can
+ * collide is two names, not a name and its slot.
+ */
+export function fitSlots(slots, stripWidth, { char = 5, gap = 6 } = {}) {
+ let reach = -Infinity;
+ return slots.map((slot) => {
+ if (!slot.label) return slot;
+ const size = width(slot.label, char);
+ const left = (slot.left / 100) * stripWidth;
+ const right = left + (slot.width / 100) * stripWidth;
+ const middle = (left + right) / 2;
+ // A centred name wider than its box is not centred: the line overflows from the
+ // box's start edge, so that is where it is measured from.
+ const [start, end] = slot.anchor === 'end' ? [right - size, right]
+ : slot.anchor === 'start' || size > right - left ? [left, left + size]
+ : [middle - size / 2, middle + size / 2];
+ if (start < reach + gap) return { ...slot, label: '' };
+ reach = end;
+ return slot;
+ });
+}
+
+/**
+ * Whether the whole-case strip has anything to show: only once the window leaves part
+ * of the case out. A window that holds every dated entry is its own overview, and the
+ * strip then drew the same dots a second time above them.
+ */
+export function overviewNeeded(extent, window) {
+ if (!extent?.from || !window) return false;
+ const first = Date.parse(extent.from);
+ const last = Date.parse(extent.to ?? extent.from);
+ if (!Number.isFinite(first) || !Number.isFinite(last)) return false;
+ return first < window.start || last > window.end;
+}
diff --git a/frontend/src/lib/timelineFit.test.js b/frontend/src/lib/timelineFit.test.js
new file mode 100644
index 0000000..b38f5d2
--- /dev/null
+++ b/frontend/src/lib/timelineFit.test.js
@@ -0,0 +1,53 @@
+import { describe, expect, it } from 'vitest';
+import { fitBands, fitSlots, fitTicks, overviewNeeded } from './timelineFit.js';
+
+describe('names that fit the axis', () => {
+ it('leaves out a tick name that would land on the one before', () => {
+ const ticks = [
+ { at: 1, left: 10, label: '12:00' },
+ { at: 2, left: 88, label: '21:00' },
+ // past 94% the name hangs to the left of its line, onto 21:00
+ { at: 3, left: 96, label: '00:00' },
+ ];
+ expect(fitTicks(ticks, 800).map((tick) => tick.label)).toEqual(['12:00', '21:00', '']);
+ // on a wide ruler the same three are far enough apart
+ expect(fitTicks(ticks, 4000).map((tick) => tick.label)).toEqual(['12:00', '21:00', '00:00']);
+ // the tick itself stays, only its name goes
+ expect(fitTicks(ticks, 800)).toHaveLength(3);
+ });
+
+ it('shortens a band cut by the window, then drops its name', () => {
+ const bands = [
+ { left: 0, width: 5, label: '21 Jun 2023' },
+ { left: 5, width: 31, label: '22 Jun 2023' },
+ { left: 36, width: 2, label: '23 Jun 2023' },
+ ];
+ expect(fitBands(bands, 1000).map((band) => band.label)).toEqual(['21 Jun', '22 Jun 2023', '']);
+ });
+
+ it('leaves out an overview name that would run into the one before', () => {
+ // the strip read "17:00 · 22 Jun20:00"
+ const slots = [
+ { key: 'a', left: 0, width: 5, label: '17:00 · 22 Jun', anchor: 'start' },
+ { key: 'b', left: 5, width: 5, label: '20:00' },
+ { key: 'c', left: 50, width: 5, label: '02:00' },
+ { key: 'd', left: 55, width: 5, label: '' },
+ ];
+ expect(fitSlots(slots, 800).map((slot) => slot.label)).toEqual(['17:00 · 22 Jun', '', '02:00', '']);
+ // a name may run past its own narrow slot as long as it clears its neighbours
+ const days = Array.from({ length: 31 }, (_, index) => ({
+ key: String(index), left: index * 3.2, width: 3.2, label: index % 7 === 0 ? `${index + 1} Mar` : '',
+ }));
+ expect(fitSlots(days, 800).filter((slot) => slot.label)).toHaveLength(5);
+ });
+
+ it('shows the whole-case strip only once the window leaves part of the case out', () => {
+ const extent = { from: '2023-06-22T17:07:16Z', to: '2023-06-23T00:00:00Z' };
+ const all = { start: Date.parse('2023-06-21T00:00:00Z'), end: Date.parse('2023-06-25T00:00:00Z') };
+ const zoomed = { start: Date.parse('2023-06-22T12:00:00Z'), end: Date.parse('2023-06-22T20:00:00Z') };
+ expect(overviewNeeded(extent, all)).toBe(false);
+ expect(overviewNeeded(extent, zoomed)).toBe(true);
+ expect(overviewNeeded(null, all)).toBe(false);
+ expect(overviewNeeded(extent, null)).toBe(false);
+ });
+});
diff --git a/frontend/src/lib/timelinePlate.js b/frontend/src/lib/timelinePlate.js
index 06b954f..53386ef 100644
--- a/frontend/src/lib/timelinePlate.js
+++ b/frontend/src/lib/timelinePlate.js
@@ -12,15 +12,15 @@
* would reserve the wrong gaps — the plate has to be the same page whatever window it was
* exported from.
*
- * Two deliberate differences from the screen:
+ * It draws what the screen draws: a point for an instant, a bracket across the period
+ * a reduced date covers, a bar for a period, and a caption only where the layout found
+ * it room. Two deliberate differences from the screen:
*
* - **The window is the reading.** A Timeline plate is its saved window, never a
* viewport: the axis is what the analyst chose to look at.
- * - **An entry carries its name, not its date.** On screen the date is written beside
- * the label because a pixel cannot be read precisely. A plate has a ruler above every
- * lane and draws the precision it holds — a point, a bar, a dashed edge for an
- * approximation, a hairline for the span a reduced date covers — so the words would be
- * the one thing on the page repeating what the drawing already says.
+ * - **Nobody can hover a page.** Where the layout left captions out, the plate lists the
+ * window's entries under the drawing, date as written beside each, and says so in its
+ * header, so a reader holds every name the screen would have shown on demand.
*/
import {
@@ -33,6 +33,7 @@ import {
svgRect,
svgText,
} from './plate.js';
+import { MARKS, cardTop, formatTemporalValue } from './timeline.js';
import { TRACK_COLORS } from './timelineTracks.js';
/** The plate's own axis geometry, in SVG user units. */
@@ -42,9 +43,14 @@ export const TIMELINE_PLATE = {
right: 16,
ruler: 38,
trackHead: 17,
- lane: 24,
+ /** One row of marks, the same 18 units as the screen's pixels. */
+ lane: MARKS.row,
trackGap: 12,
marker: 4,
+ /** The chronology under the drawing, when captions were left out. */
+ listHead: 30,
+ listRow: 15,
+ listDate: 190,
/** Roughly what one character of the 10px label face costs. Fixed rather than
* measured: a plate has to come out the same under a test. */
charWidth: 5.4,
@@ -121,10 +127,15 @@ export function timelineDrawing({
const atPercent = (percent) => plotLeft + (Number(percent) || 0) * plotWidth / 100;
// Every track's height first, so the gridlines can run the whole way down.
- const rows = tracks.map((track) => (track.collapsed ? 0 : Math.max(1, track.layout?.rows ?? 1)));
+ const heights = tracks.map((track) => {
+ if (track.collapsed) return 0;
+ const layout = track.layout ?? {};
+ const rows = Math.max(1, layout.rows ?? 1);
+ const cards = layout.cardRows ?? 0;
+ return rows * geometry.lane + (cards ? 6 + cards * (MARKS.cardHeight + 6) : 0);
+ });
const height = tracks.reduce(
- (total, _track, index) =>
- total + geometry.trackHead + rows[index] * geometry.lane + geometry.trackGap,
+ (total, _track, index) => total + geometry.trackHead + heights[index] + geometry.trackGap,
geometry.ruler,
);
@@ -172,6 +183,8 @@ export function timelineDrawing({
// -- the tracks -----------------------------------------------------------
let top = geometry.ruler;
let entries = 0;
+ let labelled = 0;
+ const listed = new Map();
tracks.forEach((track, index) => {
const colour = trackColour(track);
const head = top + geometry.trackHead;
@@ -193,69 +206,70 @@ export function timelineDrawing({
}
if (!track.collapsed) {
+ for (const item of [...drawn, ...clusters.flatMap((cluster) => cluster.items ?? [])]) {
+ if (!listed.has(item.id)) listed.set(item.id, { item, track: track.label });
+ }
for (const item of drawn) {
- const laneTop = head + item.lane * geometry.lane;
- const middle = laneTop + geometry.lane / 2;
+ const middle = head + item.row * geometry.lane + geometry.lane / 2;
const x = atPercent(item.left);
- const interval = item.shape === 'interval';
- // Held inside the axis: a bar carries a minimum width of its own, so one that
- // starts at the very end of the window would otherwise cross the ruler it is
- // being read against.
- const span = Math.max(1.5, Math.min((Number(item.width) || 0) * plotWidth / 100, plotRight - x));
- // The span a reduced date covers, drawn as the hairline it is on screen: the
- // entry is somewhere in here, and the plate must not claim a point instead.
- if (!interval && item.haloWidth > 0) {
- const haloLeft = atPercent(item.haloLeft);
+ const span = Math.max(MARKS.bar, Math.min((Number(item.width) || 0) * plotWidth / 100, plotRight - x));
+ const hollow = item.status === 'suggested';
+ if (item.mark === 'bar') {
parts.push(svgRect({
- x: haloLeft,
- y: middle + 7,
- width: Math.max(1, Math.min((Number(item.haloWidth) || 0) * plotWidth / 100, plotRight - haloLeft)),
- height: 3,
- fill: colour,
- opacity: 0.35,
+ x, y: middle - 4, width: span, height: 8, radius: 2,
+ fill: colour, opacity: hollow ? 0.08 : 0.3, stroke: colour, strokeWidth: 1,
+ dash: item.approximate ? '4 3' : (hollow ? '1.5 2' : undefined),
}));
- }
- if (interval) {
+ } else if (item.mark === 'bracket') {
+ // The whole period a reduced date covers, as the thin line it is on screen:
+ // the entry is somewhere in here, and the plate must not claim a point.
parts.push(svgRect({
- x, y: middle - 6, width: span, height: 12, radius: 3,
- fill: colour, opacity: 0.22, stroke: colour, strokeWidth: 1,
- dash: item.approximate ? '4 3' : undefined,
+ x, y: middle - 1, width: span, height: 2, fill: colour, opacity: hollow ? 0.5 : 0.9,
}));
+ const stop = item.approximate ? '2 2' : undefined;
+ if (!item.openStart) parts.push(svgLine({ x1: x, y1: middle - 4, x2: x, y2: middle + 4, stroke: colour, width: 2, dash: stop }));
+ if (!item.openEnd) parts.push(svgLine({ x1: x + span, y1: middle - 4, x2: x + span, y2: middle + 4, stroke: colour, width: 2, dash: stop }));
} else {
parts.push(svgCircle({
x, y: middle, r: geometry.marker,
- fill: item.status === 'suggested' ? PLATE_COLOURS.paper : colour,
+ fill: hollow ? PLATE_COLOURS.paper : colour,
stroke: colour,
strokeWidth: 1.4,
dash: item.approximate ? '2 2' : undefined,
}));
}
- // The lane packing reserved this entry a box, in these same units, and that box
- // is why the lane below it is empty. A label is cut to it rather than to the far
- // edge of the page, since the room out there is where the next entry stands.
- const reserved = interval || !Number.isFinite(item.displayWidth)
- ? Infinity
- : Math.max(0, item.displayWidth - geometry.marker - 6);
- // An entry the packing pushed against the right edge is labelled leftwards, the
- // way the screen labels it, so its name has somewhere to go.
- const anchor = !interval && item.endAligned ? 'end' : undefined;
- const edge = anchor
- ? x - geometry.marker - 5
- : (interval ? x + span + 6 : x + geometry.marker + 5);
- const label = fitLabel(
- item.label,
- Math.min(anchor ? edge - plotLeft : plotRight - edge, reserved),
- );
- if (label) {
- parts.push(svgText(label, {
- x: edge, y: middle + 3.5, size: geometry.labelSize, anchor,
- fill: item.confidence === 'refuted' ? PLATE_COLOURS.hint : PLATE_COLOURS.ink,
+ const ink = item.confidence === 'refuted' ? PLATE_COLOURS.hint : PLATE_COLOURS.ink;
+ if (item.caption) {
+ labelled += 1;
+ const from = plotLeft + item.caption.left;
+ const text = fitLabel(item.label, item.caption.width);
+ if (text) {
+ const right = item.caption.side === 'left';
+ parts.push(svgText(text, {
+ x: right ? from + item.caption.width : from,
+ y: middle + 3.5, size: geometry.labelSize, anchor: right ? 'end' : undefined, fill: ink,
+ }));
+ }
+ } else if (item.card) {
+ labelled += 1;
+ const cardY = head + cardTop(track.layout, item.card.row) - MARKS.top;
+ const anchor = plotLeft + item.card.anchor;
+ parts.push(svgLine({ x1: anchor, y1: middle + 4, x2: anchor, y2: cardY, stroke: colour }));
+ parts.push(svgRect({
+ x: plotLeft + item.card.left, y: cardY, width: item.card.width, height: MARKS.cardHeight,
+ radius: 5, fill: PLATE_COLOURS.paper, stroke: colour, strokeWidth: 1,
+ }));
+ parts.push(svgText(fitLabel(item.label, item.card.width - 16), {
+ x: plotLeft + item.card.left + 8, y: cardY + 16, size: geometry.labelSize, weight: '600', fill: ink,
+ }));
+ parts.push(svgText(fitLabel(formatTemporalValue(item.raw, item.tz).label, item.card.width - 16), {
+ x: plotLeft + item.card.left + 8, y: cardY + 30, size: 9, fill: PLATE_COLOURS.hint,
}));
}
}
// What the lane could not hold, counted rather than dropped silently.
for (const cluster of clusters) {
- const laneTop = head + cluster.lane * geometry.lane;
+ const laneTop = head + cluster.row * geometry.lane;
parts.push(svgText(`+${cluster.count}`, {
x: atPercent(cluster.left), y: laneTop + geometry.lane / 2 + 3.5,
size: 10, anchor: 'middle', fill: PLATE_COLOURS.hint,
@@ -268,17 +282,47 @@ export function timelineDrawing({
}
}
- top += geometry.trackHead + rows[index] * geometry.lane + geometry.trackGap;
+ top += geometry.trackHead + heights[index] + geometry.trackGap;
});
parts.push(svgLine({ x1: plotLeft, y1: round(height), x2: width - geometry.right, y2: round(height), stroke: PLATE_COLOURS.hint }));
+ // -- the chronology, when the drawing could not name everything ------------
+ let bottom = height;
+ const named = labelled >= listed.size;
+ if (!named) {
+ const rows = [...listed.values()].sort((a, b) =>
+ String(a.item.earliest).localeCompare(String(b.item.earliest))
+ || String(a.item.id).localeCompare(String(b.item.id)));
+ bottom += geometry.listHead;
+ parts.push(svgText('Every entry in this window', {
+ x: 8, y: bottom - 10, size: 11, weight: '600', fill: PLATE_COLOURS.ink,
+ }));
+ const statement = width - geometry.right - (8 + geometry.listDate) - geometry.names;
+ for (const { item, track } of rows) {
+ bottom += geometry.listRow;
+ parts.push(svgText(fitLabel(formatTemporalValue(item.raw, item.tz).label, geometry.listDate - 10), {
+ x: 8, y: bottom, size: 9, fill: PLATE_COLOURS.label,
+ }));
+ parts.push(svgText(fitLabel(item.label, statement), {
+ x: 8 + geometry.listDate, y: bottom, size: 10,
+ fill: item.confidence === 'refuted' ? PLATE_COLOURS.hint : PLATE_COLOURS.ink,
+ }));
+ parts.push(svgText(fitLabel(track, geometry.names - 10), {
+ x: width - geometry.right, y: bottom, size: 9, anchor: 'end', fill: PLATE_COLOURS.hint,
+ }));
+ }
+ bottom += 8;
+ }
+
return {
body: parts.filter(Boolean).join('\n'),
width,
- height: Math.round(height + 4),
+ height: Math.round(bottom + 4),
tracks: tracks.length,
entries,
+ labelled: Math.min(labelled, listed.size),
+ listed: named ? 0 : listed.size,
};
}
@@ -293,9 +337,9 @@ export function timelineLegend(tracks = []) {
}));
const strokes = [
{ label: 'an instant', shape: 'dot' },
+ { label: 'the span a reduced date covers', dash: [], width: 2 },
{ label: 'a period', dash: [], width: 8 },
{ label: 'approximate', dash: [4, 3], width: 1.4 },
- { label: 'the span a reduced date covers', dash: [], width: 2 },
];
return { families, strokes };
}
@@ -306,7 +350,8 @@ export function timelinePlate({ meta = {}, ...scene } = {}) {
const tally = [
`${drawing.tracks} track${drawing.tracks === 1 ? '' : 's'}`,
`${drawing.entries} entr${drawing.entries === 1 ? 'y' : 'ies'} in this window`,
- ].join(' · ');
+ drawing.listed ? `labels shown for ${drawing.labelled} of ${drawing.listed}; the full list follows` : '',
+ ].filter(Boolean).join(' · ');
return {
...plateDocument({ meta: { ...meta, tally }, families, strokes, drawing }),
drawing,
diff --git a/frontend/src/lib/timelinePlate.test.js b/frontend/src/lib/timelinePlate.test.js
index f46f2c4..e921aca 100644
--- a/frontend/src/lib/timelinePlate.test.js
+++ b/frontend/src/lib/timelinePlate.test.js
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest';
import { readFileSync } from 'node:fs';
-import { axisTicks, layoutTimelineItems } from './timeline.js';
+import { MARKS, axisTicks, layoutTimelineItems } from './timeline.js';
import { TRACK_COLORS } from './timelineTracks.js';
import { PLATE_COLOURS } from './plate.js';
import {
@@ -113,13 +113,21 @@ describe('serialising the timeline', () => {
});
it('draws an instant, a period and the span a reduced date covers apart', () => {
+ const layout = track().layout;
const { body } = timelineDrawing(scene());
+ expect(layout.items.map((item) => item.mark)).toEqual(['point', 'bar', 'bracket']);
expect(body).toContain('Convoy seen at the roundabout'); // a point, with its name
expect(body).toContain('Checkpoint standing');
- // the approximate period is a dashed bar, the day-only media its own hairline
+ // the approximate period is a dashed bar, the day-only media a line with two stops
expect(body).toMatch(/<rect[^>]*stroke-dasharray="4 3"/);
- expect(body).toMatch(/<rect[^>]*fill-opacity="0.35"/);
+ expect(body).toMatch(/<rect[^>]*height="2"[^>]*fill-opacity="0.9"/);
+ const bracket = layout.items[2];
+ const stops = [...body.matchAll(/<line x1="([\d.]+)" y1="[\d.]+" x2="\1" y2="[\d.]+" stroke="#1f7669" stroke-width="2"/g)];
+ expect(stops.map((stop) => Number(stop[1]))).toEqual([
+ Math.round((TIMELINE_PLATE.names + bracket.left * PLATE_PLOT / 100) * 100) / 100,
+ Math.round((TIMELINE_PLATE.names + (bracket.left + bracket.width) * PLATE_PLOT / 100) * 100) / 100,
+ ]);
});
it('marks a proposal hollow, the way every surface draws one', () => {
@@ -164,32 +172,65 @@ describe('serialising the timeline', () => {
expect(PLATE_PLOT).toBe(TIMELINE_PLATE.width - TIMELINE_PLATE.names - TIMELINE_PLATE.right);
});
- it('holds a label inside the room its lane reserved, not the room to the page edge', () => {
- // The lane packing gives every entry a box, in pixels, and that box is why the next
- // entry sits where it sits. A label written past it runs under its neighbour.
- const long = [{ ...ITEMS[0], label: 'A convoy of eleven trucks leaving the depot at dawn' }];
+ // Two entries stacked on the first day: a card's stem would cross one, so these
+ // tracks are read by their captions.
+ const crowd = ['k1', 'k2'].map((id) => ({
+ ...ITEMS[0], id, label: id, earliest: '2026-03-01T06:00:00Z', latest: '2026-03-01T06:00:00Z',
+ }));
+
+ it('holds a label inside the room the layout gave its caption, not the room to the page edge', () => {
+ // The caption was placed where it covers nothing; written past its width it would
+ // run under whatever the layout kept it clear of.
+ const long = [{ ...ITEMS[0], label: 'A convoy of eleven trucks leaving the depot at dawn, then two more at noon' }, ...crowd];
const laid = layoutTimelineItems(long, FROM, TO, PLATE_PLOT);
const { body } = timelineDrawing(scene({ tracks: [track({ items: long, layout: laid })] }));
const written = body.match(/>(A convoy[^<]*)</)[1];
+ const caption = laid.items.find((item) => item.id === 't1').caption;
expect(written).not.toBe(long[0].label);
- expect([...written].length * TIMELINE_PLATE.charWidth)
- .toBeLessThanOrEqual(laid.items[0].displayWidth);
+ expect([...written].length * TIMELINE_PLATE.charWidth).toBeLessThanOrEqual(caption.width);
});
it('labels an entry at the far right leftwards, the way the screen does', () => {
const late = [{
...ITEMS[0], id: 'late', label: 'Last convoy',
- earliest: '2026-03-29T00:00:00Z', latest: '2026-03-29T00:00:00Z',
- raw: '2026-03-29T00:00:00Z',
- }];
+ earliest: '2026-03-30T12:00:00Z', latest: '2026-03-30T12:00:00Z',
+ raw: '2026-03-30T12:00:00Z',
+ }, ...crowd];
const laid = layoutTimelineItems(late, FROM, TO, PLATE_PLOT);
const { body } = timelineDrawing(scene({ tracks: [track({ items: late, layout: laid })] }));
- expect(laid.items[0].endAligned).toBe(true);
+ expect(laid.items.find((item) => item.id === 'late').caption.side).toBe('left');
expect(body).toMatch(/<text[^>]*text-anchor="end"[^>]*>Last convoy</);
});
+ it('hangs cards from their marks when the track has the room, as the screen does', () => {
+ const laid = track().layout;
+ const { body } = timelineDrawing(scene());
+
+ expect(laid.cards).toBe(true);
+ expect(body).toContain('>4 Mar 2026, 09:00:00 UTC<');
+ expect(body).toMatch(new RegExp(`<rect[^>]*height="${MARKS.cardHeight}"`));
+ });
+
+ it('lists every entry under the drawing when some went without a caption, and says so', () => {
+ const dense = Array.from({ length: 5 }, (_, index) => ({
+ ...ITEMS[0], id: `d${index}`, label: `Convoy sighting number ${index + 1}`,
+ earliest: `2026-03-1${index}T12:00:00Z`, latest: `2026-03-1${index}T12:00:00Z`,
+ raw: `2026-03-1${index}T12:00:00Z`,
+ }));
+ const items = [...dense, ...crowd];
+ const laid = layoutTimelineItems(items, FROM, TO, PLATE_PLOT);
+ expect(laid.labelled).toBeLessThan(items.length);
+ const page = timelinePlate({ meta: { view: 'Dense' }, ...scene({ tracks: [track({ items, layout: laid })] }) });
+
+ expect(page.svg).toContain(`labels shown for ${laid.labelled} of ${items.length}; the full list follows`);
+ expect(page.svg).toContain('Every entry in this window');
+ for (const entry of dense) expect(page.svg).toContain(`>${entry.label}<`);
+ // a page whose every entry is named needs no list
+ expect(timelinePlate({ meta: { view: 'March window' }, ...scene() }).svg).not.toContain('Every entry in this window');
+ });
+
it('keeps a bar that ends with the window inside the axis', () => {
// A short period carries a minimum width of its own, so one closing on the last hour
// of the window would cross the ruler it is being read against.
@@ -200,7 +241,7 @@ describe('serialising the timeline', () => {
}];
const laid = layoutTimelineItems(tail, FROM, TO, PLATE_PLOT);
const { body } = timelineDrawing(scene({ tracks: [track({ items: tail, layout: laid })] }));
- const bar = body.match(/<rect[^>]*fill-opacity="0.22"[^>]*>/)[0];
+ const bar = body.match(/<rect[^>]*fill-opacity="0.3"[^>]*>/)[0];
const at = Number(bar.match(/ x="([\d.]+)"/)[1]);
const wide = Number(bar.match(/ width="([\d.]+)"/)[1]);
diff --git a/frontend/src/lib/timelineTracks.js b/frontend/src/lib/timelineTracks.js
index da8934c..7fa271b 100644
--- a/frontend/src/lib/timelineTracks.js
+++ b/frontend/src/lib/timelineTracks.js
@@ -20,6 +20,9 @@ export function trackTint(color) {
return index < 0 ? undefined : `var(--anno-${index + 1})`;
}
const RELATIONS = new Set(['any', 'owner', 'about', 'place', 'source']);
+/** The files a file lane draws: the sources' pictures and videos, or the imagery the
+ * app pictured from above (satellite, map screenshots, Compare, Detect). */
+const FILE_LANES = new Set(['sources', 'imagery']);
const ROLES = new Set(['occurred', 'observed', 'valid', 'unset']);
const unique = (values, allowed = null, limit = 500) => [
@@ -46,6 +49,12 @@ export function timelineTrack(value, index = 0) {
label: typeof query.label === 'string' ? query.label.slice(0, 300) : '',
relation: RELATIONS.has(query.relation) ? query.relation : 'any',
roles: unique(query.roles, ROLES, 4),
+ // The Media Library's working-files switch: frames, captures, collages and
+ // renders the case made itself stay off the track. Absent reads as off, which
+ // is what every track saved before it meant.
+ ...(query.collected_only === true ? { collected_only: true } : {}),
+ // A lane that draws each of its events as the file it dates (`fileLane`).
+ ...(FILE_LANES.has(query.as_files) ? { as_files: query.as_files } : {}),
},
color: TRACK_COLORS.includes(raw.color) ? raw.color : '',
collapsed: raw.collapsed === true,
@@ -54,13 +63,87 @@ export function timelineTrack(value, index = 0) {
};
}
+/** The kinds of file an event can put at its date. */
+const SITUATED = ['media', 'capture'];
+
+/**
+ * The Media lane: the sources' pictures and videos where the analyst dated them, and
+ * nowhere else.
+ *
+ * A file's date is the one an analyst gives it: the date typed on a proof (stated for
+ * the footage it rests on), a correction, an event about the file or citing it ("seen
+ * in" a video). Each of those is a Claim, so the lane holds the Claims tied to a file
+ * and draws each one as that file, with its name and its picture. What a file says
+ * about itself (the post's date, the camera's clock) is a clue and not a finding: it
+ * stays on the File dates track, added on purpose, and one press away when an event is
+ * added from the file. What the app pictured from above is not a source's footage, so
+ * it has a lane of its own (`imageryLane`).
+ */
+export function mediaLane() {
+ return timelineTrack({
+ id: 'files', label: 'Media', categories: ['statement'], query: { as_files: 'sources' },
+ });
+}
+
+/** The Imagery lane: satellite captures, map screenshots, Compare renders and the
+ * pictures Detect keeps, where an event dates them. Added from the track list. */
+export function imageryLane() {
+ return timelineTrack({
+ id: 'imagery', label: 'Imagery', categories: ['statement'], query: { as_files: 'imagery' },
+ });
+}
+
+/** Whether a track draws its events as the files they date. */
+export function drawsFiles(track) {
+ return FILE_LANES.has(track?.query?.as_files);
+}
+
+/**
+ * The file an event puts at its date: the one the server named (`file`, with its
+ * preview), or else the first file it is about, then the first it cites.
+ */
+export function situatedFile(item) {
+ if (item?.file?.id) return item.file;
+ for (const key of ['subject_entities', 'source_entities']) {
+ const entry = (item?.[key] ?? []).find((entity) => SITUATED.includes(entity?.type));
+ if (entry) return { id: entry.id, label: entry.label, type: entry.type };
+ }
+ return null;
+}
+
+/**
+ * What a fresh reading opens on: the files where the analyst dated them, over the
+ * events. A saved view keeps the tracks it was saved with.
+ */
export function defaultTimelineTracks() {
return [
+ mediaLane(),
timelineTrack({ id: 'events', label: 'Events', categories: ['statement'] }),
- timelineTrack({ id: 'media', label: 'Media', categories: ['media'] }, 1),
];
}
+/** The File dates preset. `collectedOnly` holds back the working files. */
+export function mediaTrack(tracks = [], { collectedOnly = true } = {}) {
+ const used = new Set(tracks.map((track) => track.id));
+ let id = 'media';
+ for (let n = 2; used.has(id); n += 1) id = `media-${n}`;
+ return timelineTrack({
+ id, label: 'File dates', categories: ['media'],
+ query: collectedOnly ? { collected_only: true } : {},
+ });
+}
+
+/** Whether a track leaves the case's working files out. */
+export function holdsBackWorkingFiles(track) {
+ return track?.categories?.includes('media') && track.query?.collected_only === true;
+}
+
+/** The same track with its working files let in. */
+export function withWorkingFiles(track) {
+ const { collected_only: _held, ...query } = track.query ?? {};
+ return { ...track, query };
+}
+
export function normalizeTimelineTracks(value) {
const raw = Array.isArray(value) ? value.slice(0, 20) : [];
const tracks = raw.length ? raw.map(timelineTrack) : defaultTimelineTracks();
@@ -85,9 +168,13 @@ export function trackPresets(types = []) {
});
return [
timelineTrack({ id: 'preset-events', label: 'Events', categories: ['statement'] }),
+ { ...mediaLane(), id: 'preset-files' },
+ { ...imageryLane(), id: 'preset-imagery' },
ofType('person'),
ofType('place', 'place'),
- timelineTrack({ id: 'preset-media', label: 'Media', categories: ['media'] }),
+ timelineTrack({
+ id: 'preset-media', label: 'File dates', categories: ['media'], query: { collected_only: true },
+ }),
timelineTrack({
id: 'preset-sources', label: 'Sources', categories: ['statement'],
query: { relation: 'source' },
@@ -190,9 +277,11 @@ export function timelineViewState(value) {
// `zone:<IANA name>` is the fourth reading, for an investigation at the other end
// of the world that the case has no saved point in yet. Validated by shape only:
// whether this machine can load the name is asked when the axis is drawn, so a
- // view made where the zone exists does not lose it on a stricter box.
+ // view made where the zone exists does not lose it on a stricter box. `case` is
+ // the zone the case's places stand in, found again wherever the view is opened.
+ // A view saved before there was a choice read UTC, and still does.
zoneChoice: typeof raw.zone_choice === 'string'
- && /^(utc|machine|place:[^\s]{1,64}|zone:[A-Za-z0-9+\-_/]{1,64})$/.test(raw.zone_choice)
+ && /^(utc|case|machine|place:[^\s]{1,64}|zone:[A-Za-z0-9+\-_/]{1,64})$/.test(raw.zone_choice)
? raw.zone_choice : 'utc',
viewMode: raw.view_mode === 'list' ? 'list' : 'plot',
groupBy: ['subject', 'type', 'place', 'source', 'role'].includes(raw.group_by)
diff --git a/frontend/src/lib/timelineTracks.test.js b/frontend/src/lib/timelineTracks.test.js
index 18906f2..a70d141 100644
--- a/frontend/src/lib/timelineTracks.test.js
+++ b/frontend/src/lib/timelineTracks.test.js
@@ -3,28 +3,73 @@ import {
TRACK_COLORS,
copyTimelineTrack,
defaultTimelineTracks,
+ drawsFiles,
+ holdsBackWorkingFiles,
+ mediaTrack,
groupedTimelineTracks,
moveTimelineTrack,
normalizeTimelineTracks,
+ situatedFile,
timelineTrack,
timelineViewState,
trackPresets,
trackTint,
+ withWorkingFiles,
} from './timelineTracks.js';
describe('Timeline tracks', () => {
- it('starts with editable event and media tracks', () => {
- expect(defaultTimelineTracks().map((track) => [track.label, track.categories])).toEqual([
- ['Events', ['statement']], ['Media', ['media']],
+ it('opens on the files where the analyst dated them, over the events', () => {
+ const tracks = defaultTimelineTracks();
+ expect(tracks.map((track) => [track.id, track.label, track.categories, drawsFiles(track)])).toEqual([
+ ['files', 'Media', ['statement'], true],
+ ['events', 'Events', ['statement'], false],
]);
+ // the Media lane is the events tied to a source's picture or video
+ expect(tracks[0].query).toMatchObject({ relation: 'any', as_files: 'sources' });
+ // what the app pictured from above, Compare and Detect among it, is a lane added on purpose
+ const imagery = trackPresets().find((preset) => preset.id === 'preset-imagery');
+ expect([imagery.label, imagery.query.as_files, drawsFiles(imagery)]).toEqual(['Imagery', 'imagery', true]);
+ // and a file's own dates are a track added on purpose
+ const fileDates = trackPresets().find((preset) => preset.id === 'preset-media');
+ expect(fileDates.label).toBe('File dates');
+ expect(holdsBackWorkingFiles(fileDates)).toBe(true);
+ // a saved reading keeps its own tracks, and one saved before the switch lets every
+ // file in; only an empty one falls back to the default
+ const saved = normalizeTimelineTracks([{ id: 'media', label: 'Media', categories: ['media'] }]);
+ expect(saved.map((track) => track.id)).toEqual(['media']);
+ expect(holdsBackWorkingFiles(saved[0])).toBe(false);
+ expect('collected_only' in saved[0].query).toBe(false);
+ expect(normalizeTimelineTracks([]).map((track) => track.id)).toEqual(['files', 'events']);
+ // the switch survives a view being saved and read back, and is off unless set
+ expect(normalizeTimelineTracks([{ id: 'x', categories: ['statement'], query: { as_files: 'imagery' } }])[0].query.as_files)
+ .toBe('imagery');
+ expect('as_files' in timelineTrack({ id: 'y' }).query).toBe(false);
+ expect('as_files' in timelineTrack({ id: 'z', query: { as_files: true } }).query).toBe(false);
+ });
+
+ it('adds the File dates track under an id the reading does not use yet', () => {
+ expect(mediaTrack([{ id: 'events' }])).toMatchObject({ id: 'media', label: 'File dates', categories: ['media'] });
+ expect(mediaTrack([...defaultTimelineTracks(), mediaTrack()]).id).toBe('media-2');
+ expect(mediaTrack([{ id: 'media' }, { id: 'media-2' }]).id).toBe('media-3');
+ expect(holdsBackWorkingFiles(mediaTrack([], { collectedOnly: false }))).toBe(false);
+ });
+
+ it('lets the working files back in without touching the rest of the question', () => {
+ const held = timelineTrack({ id: 'm', categories: ['media'], query: { relation: 'source', collected_only: true } });
+ const open = withWorkingFiles(held);
+ expect(holdsBackWorkingFiles(open)).toBe(false);
+ expect(open.query.relation).toBe('source');
+ expect(held.query.collected_only).toBe(true);
+ // the switch only means something on a track that holds files
+ expect(holdsBackWorkingFiles(timelineTrack({ categories: ['statement'], query: { collected_only: true } }))).toBe(false);
});
it('builds presets from registry labels rather than a second type vocabulary', () => {
const presets = trackPresets([{ type: 'person', label: 'Human' }, { type: 'place', label: 'Location' }]);
expect(presets.map((preset) => preset.label)).toEqual([
- 'Events', 'Human', 'Location', 'Media', 'Sources', 'Case activity',
+ 'Events', 'Media', 'Imagery', 'Human', 'Location', 'File dates', 'Sources', 'Case activity',
]);
- expect(presets[1].query.terms).toEqual({ type: 'person' });
+ expect(presets[3].query.terms).toEqual({ type: 'person' });
});
it('normalizes imported state and keeps track ids unique', () => {
@@ -62,14 +107,14 @@ describe('Timeline tracks', () => {
it('reorders and duplicates presentation without sharing arrays', () => {
const tracks = defaultTimelineTracks();
- expect(moveTimelineTrack(tracks, 0, 1).map((track) => track.label)).toEqual(['Media', 'Events']);
- const copy = copyTimelineTrack({ ...tracks[0], hidden: ['a'] }, tracks);
+ expect(moveTimelineTrack(tracks, 0, 1).map((track) => track.label)).toEqual(['Events', 'Media']);
+ const copy = copyTimelineTrack({ ...tracks[1], hidden: ['a'] }, tracks);
expect(copy.label).toBe('Events copy');
expect(copy.id).not.toBe(tracks[0].id);
});
it('groups one event into each matching subject without copying the event', () => {
- const tracks = defaultTimelineTracks().slice(0, 1);
+ const tracks = defaultTimelineTracks().slice(1);
const item = { id: 'event', subject_entities: [{ id: 'a', label: 'A' }, { id: 'b', label: 'B' }] };
const grouped = groupedTimelineTracks(tracks, { events: [item] }, 'subject');
expect(grouped.map((track) => track.label)).toEqual(['A', 'B']);
@@ -77,15 +122,15 @@ describe('Timeline tracks', () => {
});
it('keeps entries without a grouping value visible', () => {
- const tracks = defaultTimelineTracks();
+ const tracks = [mediaTrack(), ...defaultTimelineTracks().slice(1)];
const event = { id: 'event', owner_type: 'claim' };
const media = { id: 'media', owner_type: 'capture' };
expect(groupedTimelineTracks(tracks, { events: [event], media: [media] }, 'subject')
.map((track) => track.label)).toEqual(['No subject', 'No subject']);
expect(groupedTimelineTracks(tracks, { events: [event], media: [media] }, 'type')
- .map((track) => track.label)).toEqual(['claim', 'capture']);
+ .map((track) => track.label)).toEqual(['capture', 'claim']);
expect(groupedTimelineTracks(tracks, { events: [event], media: [media] }, 'type',
- (type) => type.toUpperCase()).map((track) => track.label)).toEqual(['CLAIM', 'CAPTURE']);
+ (type) => type.toUpperCase()).map((track) => track.label)).toEqual(['CAPTURE', 'CLAIM']);
});
it('leaves a track on its category colours until one is chosen', () => {
@@ -115,6 +160,8 @@ describe('Timeline tracks', () => {
expect(timelineViewState({
timezone: 'Europe/Kyiv', zone_choice: 'zone:Europe/Kyiv',
})).toMatchObject({ zoneChoice: 'zone:Europe/Kyiv' });
+ // the zone of the case's places is found again wherever the view is opened
+ expect(timelineViewState({ zone_choice: 'case' }).zoneChoice).toBe('case');
expect(timelineViewState({ zone_choice: 'zone:../../etc/passwd' }).zoneChoice).toBe('utc');
expect(timelineViewState({ zone_choice: 'zone:' }).zoneChoice).toBe('utc');
});
@@ -129,4 +176,18 @@ describe('Timeline tracks', () => {
});
expect(restored.categories).toEqual(['statement', 'media']);
});
+
+ it('names the file an event puts at its date, the one it is about first', () => {
+ const about = { id: 'm1', label: 'clip.mp4', type: 'media' };
+ const cited = { id: 'c1', label: 'Sentinel-2 scene', type: 'capture' };
+ const proof = { id: 'p1', label: 'Bridge proof', type: 'proof' };
+ expect(situatedFile({ subject_entities: [about], source_entities: [cited] })).toEqual(about);
+ // a proof's date is about the footage and cites the proof: the footage is the file
+ expect(situatedFile({ subject_entities: [about], source_entities: [proof] })).toEqual(about);
+ expect(situatedFile({ subject_entities: [{ id: 'x', type: 'person' }], source_entities: [cited] })).toEqual(cited);
+ expect(situatedFile({ subject_entities: [], source_entities: [proof] })).toBeNull();
+ // what the server named wins, with its preview
+ expect(situatedFile({ file: { id: 'm2', label: 'IMG', thumb: 't.jpg' }, subject_entities: [about] }))
+ .toEqual({ id: 'm2', label: 'IMG', thumb: 't.jpg' });
+ });
});
diff --git a/frontend/src/lib/workspaces.js b/frontend/src/lib/workspaces.js
index 7806d8e..6b1599b 100644
--- a/frontend/src/lib/workspaces.js
+++ b/frontend/src/lib/workspaces.js
@@ -9,9 +9,13 @@
* new rail entries.
*
* `case` is a workspace like any other — tabs, deep links, its own remembered
- * sidebar — but it is not on the rail. The rail reads as a sequence of stages,
- * and the case is not a stage: it is what every stage files into. It hangs off
- * the case switcher in the topbar instead, beside the name of the case it opens.
+ * sidebar — and sits on the rail under the four stages, a rule apart from them:
+ * the case is not a stage but what every stage files into, and a door into it
+ * from the topbar was one nobody took.
+ *
+ * The Timeline is its first tab, so `#case` and a first visit land where events are
+ * noted and read; the Board, the index of who and what, is the next one. `#board`
+ * is still a tab of its own, and the tool id stays `board` in every stored view.
*/
import { splitHash } from './hash.js';
@@ -19,7 +23,7 @@ export const CASE_WORKSPACE = {
id: 'case',
label: 'Case',
icon: 'graph',
- tools: ['board', 'graph', 'timeline', 'sheet'],
+ tools: ['timeline', 'board', 'graph', 'sheet'],
};
/**
diff --git a/frontend/src/lib/workspaces.test.js b/frontend/src/lib/workspaces.test.js
index 73d7318..7f5a63a 100644
--- a/frontend/src/lib/workspaces.test.js
+++ b/frontend/src/lib/workspaces.test.js
@@ -113,8 +113,10 @@ describe('toolFromHash', () => {
expect(toolFromHash('#collect', ALL_TOOLS)).toBe('media');
expect(toolFromHash('#compose', ALL_TOOLS)).toBe('proof');
// off the rail, still a workspace: #case and #home have to keep resolving
- expect(toolFromHash('#case', ALL_TOOLS)).toBe('board');
- expect(toolFromHash('#case/timeline', ALL_TOOLS)).toBe('timeline');
+ // the case opens on its Timeline, and its Board keeps a link of its own
+ expect(toolFromHash('#case', ALL_TOOLS)).toBe('timeline');
+ expect(toolFromHash('#case/board', ALL_TOOLS)).toBe('board');
+ expect(toolFromHash('#board', ALL_TOOLS)).toBe('board');
expect(toolFromHash('#home', ALL_TOOLS)).toBe('overview');
expect(toolFromHash('#home/guide', ALL_TOOLS)).toBe('guide');
});
diff --git a/frontend/src/tools/Board.groups.render.test.js b/frontend/src/tools/Board.groups.render.test.js
new file mode 100644
index 0000000..2af2d99
--- /dev/null
+++ b/frontend/src/tools/Board.groups.render.test.js
@@ -0,0 +1,255 @@
+// @vitest-environment happy-dom
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { flushSync, mount, unmount } from 'svelte';
+
+/**
+ * The Board read as groups, driven the way an analyst reads it: who and what first,
+ * the material folded under it, each group paging on its own answer.
+ */
+
+const TYPES = [
+ { type: 'person', label: 'Person', family: 'actor', hint: 'somebody', attrs: [], manual: true },
+ { type: 'organization', label: 'Organization', family: 'actor', hint: 'a group', attrs: [], manual: true },
+ { type: 'place', label: 'Place', family: 'place', hint: 'somewhere', attrs: [] },
+ { type: 'media', label: 'Media', family: 'collected', hint: 'a file', attrs: [] },
+ { type: 'capture', label: 'Capture', family: 'collected', hint: 'a map image', attrs: [] },
+ { type: 'claim', label: 'Claim', family: 'claim', hint: 'what is said', attrs: [], manual: true },
+];
+
+let ROWS = [];
+const row = (id, type, label, extra = {}) => ({
+ id, type, label, attrs: {}, provenance: { at: '2026-08-01T00:00:00Z', status: 'confirmed' }, ...extra,
+});
+
+function withSubjects() {
+ ROWS = [
+ row('p1', 'person', 'Witness'),
+ row('o1', 'organization', '4th brigade'),
+ row('pl1', 'place', 'Crossroads'),
+ row('m1', 'media', 'VID_0312'),
+ row('c1', 'capture', 'S2 11/03'),
+ row('k1', 'claim', 'Column seen', { attrs: { when: '2026-03-12' } }),
+ ];
+}
+function filesOnly() {
+ ROWS = [row('m1', 'media', 'VID_0312'), row('c1', 'capture', 'S2 11/03')];
+}
+
+const summary = () => ({
+ total: ROWS.length,
+ by_type: Object.fromEntries(
+ [...new Set(ROWS.map((r) => r.type))].map((t) => [t, ROWS.filter((r) => r.type === t).length])
+ ),
+ by_status: { suggested: 2 },
+ by_folder: {},
+ by_source: {},
+ unlinked: 0,
+ lacks: { source: 1, assessment: 0 },
+});
+
+const asked = [];
+const get = vi.fn(async (url) => {
+ if (url.includes('/entity-types')) return TYPES;
+ if (url.includes('/relation-types')) return [];
+ if (url.includes('/confidence-levels')) return [];
+ if (url.includes('/catalog/summary')) return summary();
+ if (url.includes('/catalog/entities')) {
+ const params = new URL(url, 'http://x').searchParams;
+ asked.push(params);
+ const q = (params.get('q') ?? '').toLowerCase();
+ const matched = ROWS.filter((r) => !q || r.label.toLowerCase().includes(q));
+ if (params.get('counts') === 'type') {
+ const byType = {};
+ for (const r of matched) byType[r.type] = (byType[r.type] ?? 0) + 1;
+ return { items: matched.slice(0, 1), total: matched.length, next_cursor: null, by_type: byType };
+ }
+ const types = (params.get('type') ?? '').split(',').filter(Boolean);
+ const items = matched.filter((r) => !types.length || types.includes(r.type));
+ return { items, total: items.length, next_cursor: null };
+ }
+ if (url.includes('/catalog/attributes')) return { attrs: [] };
+ if (url.includes('/analysis-views')) return { views: [] };
+ return {};
+});
+const post = vi.fn(async (url, body) => {
+ if (url.includes('/catalog/events')) {
+ return {
+ range: { from: '2026-03-01T00:00:00.000000Z', to: '2026-04-01T00:00:00.000000Z' },
+ rows: Object.fromEntries(
+ body.ids.map((id) => [
+ id,
+ id === 'o1'
+ ? {
+ events: 5, first: '2026-03-11T00:00:00.000000Z', last: '2026-03-20T00:00:00.000000Z',
+ sources: 2, places: 1, buckets: [0, 0, 0, 0, 2, 1, 1, 0, 0, 1, 0, 0],
+ }
+ : { events: 0, first: null, last: null, sources: 0, places: 0, buckets: Array(12).fill(0) },
+ ])
+ ),
+ };
+ }
+ return {};
+});
+vi.mock('../lib/api.js', () => ({
+ api: { get, post, del: vi.fn(), patch: vi.fn(), put: vi.fn() },
+ ApiError: Error,
+}));
+
+const toast = vi.fn();
+const uiState = { tool: 'board', openBoardEntity: null, drawInGraph: null, openGraphEntity: null };
+vi.mock('../lib/state.svelte.js', async () => {
+ const { caseState } = await import('../components/views.fixture.svelte.js');
+ return {
+ caseState,
+ reloadCase: vi.fn(async () => {}),
+ toast,
+ uiState,
+ registerCaseChangeGuard: () => () => {},
+ };
+});
+vi.mock('../components/EntityDetails.svelte', async () => await import('../components/Modal.svelte'));
+
+const { default: Board } = await import('./Board.svelte');
+const { openAnalysisCase } = await import('../lib/analysisSearch.svelte.js');
+
+let live = null;
+let target = null;
+
+async function settle() {
+ for (let index = 0; index < 20; index += 1) {
+ await Promise.resolve();
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ }
+ flushSync();
+}
+
+async function open() {
+ target = document.createElement('div');
+ document.body.append(target);
+ live = mount(Board, { target });
+ flushSync();
+ await settle();
+ return target;
+}
+
+const groups = () =>
+ [...target.querySelectorAll('section.group')].map((section) => ({
+ title: section.querySelector('.title')?.textContent.trim(),
+ count: section.querySelector('.count')?.textContent.trim(),
+ open: section.querySelector('button.fold')?.getAttribute('aria-expanded') === 'true',
+ rows: [...section.querySelectorAll('tbody tr .name')].map((name) => name.textContent.trim()),
+ section,
+ }));
+const group = (title) => groups().find((entry) => entry.title === title);
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ asked.length = 0;
+ localStorage.clear();
+ // The question outlives a mount, as it does between tabs: each test starts on none.
+ openAnalysisCase(null);
+ withSubjects();
+});
+
+afterEach(() => {
+ if (live) unmount(live);
+ live = null;
+ target?.remove();
+});
+
+describe('the groups', () => {
+ it('reads who and what first, the material folded under it', async () => {
+ await open();
+ expect(groups().map((entry) => [entry.title, entry.count, entry.open])).toEqual([
+ ['People & organizations', '2', true],
+ ['Places', '1', true],
+ ['Events', '1', false],
+ ['Files', '2', false],
+ ]);
+ expect(group('People & organizations').rows).toEqual(['Witness', '4th brigade']);
+ // folded, a group says what is inside it, and reads nothing
+ expect(group('Files').section.querySelector('.types').textContent).toContain('Capture, Media');
+ expect(asked.some((params) => params.get('type') === 'capture,media')).toBe(false);
+ });
+
+ it('reads a folded group when it is opened, and remembers the fold for the case', async () => {
+ await open();
+ group('Files').section.querySelector('button.fold').click();
+ flushSync();
+ await settle();
+ expect(group('Files').open).toBe(true);
+ expect(group('Files').rows).toEqual(['VID_0312', 'S2 11/03']);
+ expect(JSON.parse(localStorage.getItem('azimut:board-layout:case-a')).folds).toEqual({ collected: true });
+ });
+
+ it('says what the events say about each subject row', async () => {
+ await open();
+ const brigade = [...target.querySelectorAll('tr')].find((tr) => tr.textContent.includes('4th brigade'));
+ expect(brigade.querySelector('td.n').textContent.trim()).toBe('5');
+ expect(brigade.querySelector('td.span').textContent.trim()).toBe('11–19 Mar 2026');
+ expect(brigade.querySelector('svg.sparkline')).not.toBeNull();
+ const witness = [...target.querySelectorAll('tr')].find((tr) => tr.textContent.includes('Witness'));
+ expect(witness.querySelector('td.n').textContent.trim()).toBe('—');
+ // one read for the page of subject rows, never one per row
+ const reads = post.mock.calls.filter(([url]) => url.includes('/catalog/events'));
+ expect(reads).toHaveLength(1);
+ expect(reads[0][1].ids.sort()).toEqual(['o1', 'p1', 'pl1']);
+ });
+
+ it('orders the subjects most noted first, and the material newest first', async () => {
+ await open();
+ group('Files').section.querySelector('button.fold').click();
+ flushSync();
+ await settle();
+ const order = (types) => asked.find((params) => params.get('type') === types && !params.get('counts'))?.get('order');
+ expect(order('organization,person')).toBe('-events');
+ expect(order('place')).toBe('-events');
+ expect(order('capture,media')).toBe('-created');
+ });
+
+ it('opens every group holding an answer under a question', async () => {
+ await open();
+ const search = target.querySelector('input[placeholder="Search the case…"]');
+ search.value = 'vid';
+ search.dispatchEvent(new Event('input', { bubbles: true }));
+ flushSync();
+ await new Promise((resolve) => setTimeout(resolve, 320));
+ await settle();
+ expect(groups().map((entry) => [entry.title, entry.open])).toEqual([['Files', true]]);
+ expect(group('Files').rows).toEqual(['VID_0312']);
+ });
+
+ it('shows the waiting questions, priced, and asks one on a click', async () => {
+ await open();
+ const line = target.querySelector('.waiting-line');
+ expect(line.textContent).toContain('2 to review');
+ expect(line.textContent).toContain('1 event without a source');
+ [...line.querySelectorAll('button')].find((b) => b.textContent.includes('to review')).click();
+ flushSync();
+ await settle();
+ expect(asked.some((params) => params.get('status') === 'suggested')).toBe(true);
+ });
+
+ it('lays out one flat table under Group: None, and keeps that choice', async () => {
+ await open();
+ const select = [...target.querySelectorAll('label.pick-one')]
+ .find((label) => label.textContent.includes('Group'))
+ .querySelector('select');
+ select.value = 'none';
+ select.dispatchEvent(new Event('change', { bubbles: true }));
+ flushSync();
+ await settle();
+ expect(target.querySelector('section.group')).toBeNull();
+ expect(target.querySelectorAll('.table tbody tr')).toHaveLength(ROWS.length);
+ expect(JSON.parse(localStorage.getItem('azimut:board-layout:case-a')).group).toBe('none');
+ });
+});
+
+describe('a case of files only', () => {
+ it('opens its files, and says how the index fills', async () => {
+ filesOnly();
+ await open();
+ expect(target.querySelector('.no-subjects').textContent).toContain('No people, places or things yet.');
+ expect(groups().map((entry) => [entry.title, entry.open])).toEqual([['Files', true]]);
+ });
+});
diff --git a/frontend/src/tools/Board.render.test.js b/frontend/src/tools/Board.render.test.js
index 2562970..f505f15 100644
--- a/frontend/src/tools/Board.render.test.js
+++ b/frontend/src/tools/Board.render.test.js
@@ -123,6 +123,9 @@ async function press(label, root = document.body) {
beforeEach(() => {
vi.clearAllMocks();
+ // These drive the flat table, the one the grouped Board keeps under Group: None
+ // (`Board.groups.render.test.js` drives the groups).
+ localStorage.setItem('azimut:board-layout:case-a', JSON.stringify({ group: 'none' }));
});
afterEach(() => {
@@ -290,32 +293,15 @@ describe('deleting what is ticked', () => {
});
});
-describe('filing a claim from a row', () => {
- const claimPress = (label) =>
- [...target.querySelectorAll('.table tbody tr')]
- .find((row) => row.textContent.includes(label))
- ?.querySelector('td.go button[aria-label^="File a claim"]');
-
- it('says, per row, where the entity would sit on the claim', async () => {
+describe('adding an event about a row', () => {
+ it('is Details’ to offer, not a press on every row', async () => {
+ // One place to add an event about an entity, the top of its Details, where the
+ // line has room; a quote button on every row was the same act a second time.
await open();
- expect(claimPress('Quai sud').title).toBe('File a claim placed here');
- expect(claimPress('Clip').title).toBe('File a claim that rests on this');
- expect(claimPress('Witness').title).toBe('File a claim about this');
- });
-
- it('opens the form on that row without opening the row', async () => {
- await open();
- claimPress('Quai sud').click();
- flushSync();
- await settle();
-
- const form = document.querySelector('.quick-claim');
- expect(form).not.toBeNull();
- expect(form.querySelector('textarea').value).toBe('Seen at Quai sud');
- // The row's Details stay shut: the press is the claim's, not the row's.
- expect(document.querySelectorAll('[role="dialog"]')).toHaveLength(1);
-
- await press('Cancel', form);
- expect(document.querySelector('.quick-claim')).toBeNull();
+ const presses = [...target.querySelectorAll('.table tbody td.go button')].map(
+ (button) => button.getAttribute('aria-label')
+ );
+ expect(presses.length).toBe(ROWS.length);
+ expect(presses.every((label) => label.startsWith('Show '))).toBe(true);
});
});
diff --git a/frontend/src/tools/Board.svelte b/frontend/src/tools/Board.svelte
index 9149e8e..9689937 100644
--- a/frontend/src/tools/Board.svelte
+++ b/frontend/src/tools/Board.svelte
@@ -1,22 +1,29 @@
<script>
/**
- * The case as its graph: every entity the case holds, filtered, sorted and opened.
+ * The case as an index: who, what and where, then the material it is built from.
*
* Until this existed the vocabulary was reachable only through the API. A case
- * could hold a `person`, a `claim` or an `account` — the registry declared them,
- * the relation verbs accepted them — but no screen created one, so a bookmark had
- * nothing to be related *to* and a statement had nowhere to be read. That is what
- * this tool is: create the hand-made types, list what the case holds, and open any
- * row in the same Details panel every other surface uses.
+ * could hold a `person`, a `claim` or an `account`, the registry declared them and
+ * the relation verbs accepted them, but no screen created one. That is what this
+ * tool is: create the hand-made types, list what the case holds, and read any row
+ * in the same Details every other surface uses.
*
- * Bounded like every other list here (docs/STORAGE_AND_PERFORMANCE.md): one page
- * off the catalog endpoint, filters applied server-side, "Show more" for the rest.
- * A case that fits one page filters in memory, so typing costs no request.
+ * **Grouped by family, never hidden.** A case is mostly files, and one table of
+ * everything answered "what is in the database" rather than "who is this about".
+ * So the rows fall into groups (`lib/boardGroups.js`): people, identifiers, places
+ * and things open first, each saying how many events name it and when; the events,
+ * files and work fold underneath, one click from the tool that reads them. The
+ * question is still the one Board and Graph share, so a count, a total or a drawing
+ * never depends on which groups are open. "Group: None" is the flat table, and a
+ * view saved before the groups opens that way.
*
- * One view, a table. Two views of the same rows only asked which one was the real
- * one. The graph is what comes next, and that is a different question, not a
- * different rendering of this list.
- */
+ * **Details beside the list** when there is room for both, so reading five people is
+ * five presses of an arrow key rather than five modals opened and closed.
+ *
+ * Bounded like every other list here (docs/STORAGE_AND_PERFORMANCE.md): one count
+ * of the answer per type, one page per open group, one events read per page of rows.
+ * A folded group reads nothing.
+ */
import { untrack } from 'svelte';
import { api } from '../lib/api.js';
import {
@@ -50,6 +57,7 @@
import { deletedToast, deleteEntities, entityDeletePrompt } from '../lib/trash.js';
import { toggleCheck } from '../lib/gridSelect.js';
import {
+ askQuestion,
chipsOf,
clearAxis,
emptyFilter,
@@ -85,19 +93,36 @@
import PasteDialog from '../components/PasteDialog.svelte';
import SnapshotDetails from '../components/SnapshotDetails.svelte';
import ViewSwitch from '../components/ViewSwitch.svelte';
- import QuickClaim, { claimSeat } from '../components/QuickClaim.svelte';
- import { claimActionTitle } from '../lib/quickClaim.js';
+ import BoardGroup from './board/BoardGroup.svelte';
import { loadRelationTypes } from '../lib/relations.svelte.js';
+ import { fetchEventRows } from '../lib/catalog.js';
+ import { offerNote } from '../lib/noteHere.svelte.js';
+ import {
+ BOARD_GROUPS,
+ GROUPINGS,
+ GROUP_SORTS,
+ boardGroup,
+ groupCounts,
+ groupOfType,
+ groupOpen,
+ holdsSubjects,
+ loadLayout,
+ saveLayout,
+ viewLayout,
+ waitingOf,
+ } from '../lib/boardGroups.js';
const PAGE = 100;
+ /** A group's page: enough to read a group at a glance, small enough that the next
+ * group is one scroll away. */
+ const GROUP_PAGE = 40;
+ /** Below this width Details opens over the list rather than beside it. */
+ const DOCK_WIDTH = 1100;
loadEntityTypes();
- // The row's claim press is offered where the verb registry gives the entity a seat.
+ // Details beside a row offers an event where the verb registry gives it a seat.
loadRelationTypes();
- /** The row a claim is being filed from, while its form is open. */
- let claimFor = $state(null);
-
/**
* The question being asked of the case, as one value (`lib/entityFilter.js`).
*
@@ -210,13 +235,372 @@
* a small case searching in memory — there the server was never told the term, so
* its count would answer a wider question than the one on screen. */
const matchCount = $derived(
- pl.serverMode || !filter.q.trim() ? pl.total : matching.length
+ grouped
+ ? groupedTotal
+ : pl.serverMode || !filter.q.trim()
+ ? pl.total
+ : matching.length
);
/** What the answer is a part of. The **whole case**, always: a proportion is the
* information a count carries, and a denominator that shrinks with the numerator
* carries none. */
const caseTotal = $derived(summary?.total ?? pl.total);
+ // ── the groups ───────────────────────────────────────────────────────────────
+ /** How this analyst lays the Board out for this case: grouped or flat, the sort,
+ * the folds. Kept in this browser (`lib/boardGroups.js`). A Board view states its
+ * own grouping and sort, which hold while it is open. */
+ let layout = $state(loadLayout(null));
+ let viewShape = $state(null); // { group, sort } while a Board view is open
+ const shape = $derived(viewShape ?? { group: layout.group, sort: layout.sort });
+ const grouped = $derived(shape.group === 'kind' && !totalling);
+
+ /** Folds made under the current question, forgotten when it changes: a question
+ * opens every group that holds an answer, and a fold made while reading it should
+ * not outlive it. */
+ let asked = $state({});
+ /** Groups opened for the analyst this session, by a file just imported or a row
+ * followed here, until they fold the group themselves. */
+ let revealed = $state({});
+
+ function setShape(next) {
+ if (viewShape) viewShape = { ...viewShape, ...next };
+ else {
+ layout = { ...layout, ...next };
+ saveLayout(caseState.current?.id, layout);
+ }
+ }
+
+ /** The answer counted per type, which every group reads its size from. */
+ let byType = $state(null);
+ const counts = $derived(groupCounts(byType ?? {}, entityFamily));
+ const groupedTotal = $derived(
+ Object.values(byType ?? {}).reduce((sum, n) => sum + (Number(n) || 0), 0)
+ );
+ /** Whether the case holds anything an investigation is about. A case of files only
+ * opens its files, rather than an index with nothing in it. */
+ const subjects = $derived(holdsSubjects(summary?.by_type ?? {}, entityFamily));
+
+ function isOpen(group) {
+ if (filtering) return groupOpen(group, { asked, filtering: true });
+ if (group.id in revealed) return revealed[group.id];
+ return groupOpen(group, { folds: layout.folds, subjects });
+ }
+
+ function toggleGroup(group) {
+ const next = !isOpen(group);
+ if (filtering) asked = { ...asked, [group.id]: next };
+ else {
+ const { [group.id]: _dropped, ...rest } = revealed;
+ revealed = rest;
+ layout = { ...layout, folds: { ...layout.folds, [group.id]: next } };
+ saveLayout(caseState.current?.id, layout);
+ }
+ if (next && !lists[group.id].items.length) loadGroup(group.id);
+ }
+
+ /** Open the group a type falls in, so what the analyst just made or followed is on
+ * screen rather than folded away. */
+ function reveal(type) {
+ if (!type) return;
+ const group = groupOfType(type, entityFamily);
+ if (filtering) asked = { ...asked, [group.id]: true };
+ else revealed = { ...revealed, [group.id]: true };
+ if (!lists[group.id].items.length) loadGroup(group.id);
+ }
+
+ /** The types each group's page asks for: the ones the answer holds in it. */
+ const groupTypes = $derived.by(() => {
+ const out = Object.fromEntries(BOARD_GROUPS.map((group) => [group.id, []]));
+ for (const [type, n] of Object.entries(byType ?? {})) {
+ if (Number(n) > 0) out[groupOfType(type, entityFamily).id].push(type);
+ }
+ for (const list of Object.values(out)) list.sort();
+ return out;
+ });
+
+ /** One bounded list per group, each paging on its own. Always a server answer:
+ * the text term is counted server-side too, and a group filtered in memory while
+ * its count came from the server could say two different numbers. */
+ const lists = Object.fromEntries(
+ BOARD_GROUPS.map((group) => [
+ group.id,
+ createPagedList({
+ fetchPage: ({ cursor }) =>
+ api.get(
+ buildCatalogQuery(caseState.current.id, {
+ cursor,
+ limit: GROUP_PAGE,
+ ...toQuery(filter, { types: groupTypes[group.id] }),
+ ...(catalogViews.snapshotId ? {} : analysisPeriodQuery(analysisSearch.period)),
+ order: groupOrder(group),
+ view: catalogViews.snapshotId || undefined,
+ })
+ ),
+ }),
+ ])
+ );
+
+ /** "Most noted" orders the subjects; the material under them reads newest first,
+ * since a file is sought by when it came in rather than by how often it is cited. */
+ function groupOrder(group) {
+ return group.kind === 'material' && shape.sort === '-events' ? '-created' : shape.sort;
+ }
+
+ function loadGroup(id) {
+ if (!caseState.current?.id) return;
+ const list = lists[id];
+ if (!groupTypes[id]?.length) {
+ list.clear();
+ return;
+ }
+ untrack(() => void list.reload().catch(() => {}));
+ }
+
+ /**
+ * Count the answer, then read the open groups that hold some of it.
+ *
+ * One request says how much each group holds; a group then asks for its own page
+ * only if it is open and not empty. Asked again on every change to the question, the
+ * sort or the case, and a quarter second after a keystroke, which is the paged
+ * list's own delay for the same box.
+ */
+ let countedAsk = '';
+ let countedQ = '';
+ let countSeq = 0;
+ $effect(() => {
+ const id = caseState.current?.id;
+ if (!id || !grouped) return;
+ const period = catalogViews.snapshotId ? null : analysisPeriodQuery(analysisSearch.period);
+ const query = toQuery(filter, { types: wantedTypes });
+ const ask = JSON.stringify([
+ id, caseState.rev, query, period, shape.sort, catalogViews.snapshotId,
+ ]);
+ if (ask === countedAsk) return;
+ const typing = countedAsk !== '' && filter.q !== countedQ;
+ const mine = ++countSeq;
+ const timer = setTimeout(async () => {
+ countedAsk = ask;
+ countedQ = filter.q;
+ try {
+ const page = await api.get(
+ buildCatalogQuery(id, {
+ limit: 1,
+ counts: 'type',
+ ...query,
+ ...(period ?? {}),
+ view: catalogViews.snapshotId || undefined,
+ })
+ );
+ if (mine !== countSeq || caseState.current?.id !== id) return;
+ byType = page.by_type ?? {};
+ for (const group of BOARD_GROUPS) {
+ if (counts[group.id] && isOpen(group)) loadGroup(group.id);
+ else lists[group.id].clear();
+ }
+ } catch {
+ if (mine === countSeq) countedAsk = '';
+ }
+ }, typing ? 250 : 0);
+ return () => clearTimeout(timer);
+ });
+
+ // A new question opens every group that answers it, whatever was folded under the
+ // last one.
+ $effect(() => {
+ JSON.stringify(filter);
+ JSON.stringify(analysisSearch.period);
+ untrack(() => (asked = {}));
+ });
+
+ /** The groups on screen, with their rows, in reading order. */
+ const shownGroups = $derived(
+ BOARD_GROUPS.filter((group) => counts[group.id] > 0).map((group) => ({
+ group,
+ open: isOpen(group),
+ list: lists[group.id],
+ }))
+ );
+ /** Every row the groups show, in the order they show them: what a tick range, the
+ * selection bar and the arrow keys walk. */
+ const groupedRows = $derived(
+ shownGroups.filter((entry) => entry.open).flatMap((entry) => entry.list.items)
+ );
+
+ /**
+ * What the events say about the subject rows on screen: one read per page of rows,
+ * refreshed with the case. A snapshot is a frozen reading and asks nothing of the
+ * live case, so its rows draw without it.
+ */
+ let events = $state({});
+ let eventsRev = -1;
+ let eventsCase = null;
+ $effect(() => {
+ const id = caseState.current?.id;
+ const rev = caseState.rev;
+ const frozen = Boolean(catalogViews.snapshotId);
+ const ids = shownGroups
+ .filter((entry) => entry.open && entry.group.kind === 'subject')
+ .flatMap((entry) => entry.list.items.map((entity) => entity.id));
+ if (!id || !grouped || frozen) {
+ if (Object.keys(untrack(() => events)).length) events = {};
+ return;
+ }
+ const fresh = rev !== eventsRev || id !== eventsCase;
+ const held = fresh ? {} : untrack(() => events);
+ const missing = ids.filter((one) => !(one in held));
+ if (!missing.length) return;
+ eventsRev = rev;
+ eventsCase = id;
+ fetchEventRows(id, missing)
+ .then((body) => {
+ if (caseState.current?.id !== id || caseState.rev !== rev) return;
+ events = { ...(fresh ? {} : events), ...(body?.rows ?? {}) };
+ })
+ .catch(() => {});
+ });
+
+ function openRow(entity) {
+ if (snapshotReading) snapshotOpen = entity;
+ else requestOpen(entity.id);
+ }
+
+ /** Change the open row, asking first when Details holds edits Save has not taken:
+ * an arrow key is too easy a way to throw a half-typed field away. */
+ let pendingOpen = null;
+ function requestOpen(id) {
+ if (id === openId) return;
+ if (dirty && openId) {
+ pendingOpen = id;
+ discarding = true;
+ return;
+ }
+ openId = id;
+ }
+
+ // The row Details is open on is what the topbar's Add event seats here.
+ $effect(() => {
+ const id = openId ?? snapshotOpen?.id ?? null;
+ const entity = id && !snapshotReading ? shownRows.find((row) => row.id === id) ?? null : null;
+ offerNote('board', entity);
+ });
+
+ function showInGraph(entity) {
+ uiState.openGraphEntity = entity.id;
+ uiState.tool = 'graph';
+ }
+
+ const thumbUrl = (thumb) =>
+ thumb.startsWith('data:') ? thumb : fileUrl(caseState.current.id, thumb);
+
+ /** The waiting questions, priced: shown while nothing is being asked, since a
+ * question already on the bar is the one being read. */
+ const waiting = $derived(
+ !filtering && !snapshotReading && !totalling ? waitingOf(summary) : []
+ );
+
+ // ── Details beside the list ─────────────────────────────────────────────────
+ let measuredWidth = $state(0);
+ /** The width the Board last had on screen. A hidden tab measures nothing, and
+ * reading that as a narrow window would turn Details beside the list into a modal
+ * over whichever tool the analyst moved to. */
+ let toolWidth = $state(0);
+ $effect(() => {
+ if (measuredWidth > 0) toolWidth = measuredWidth;
+ });
+ /** Beside the list or over it is decided when Details opens, and kept until it
+ * closes: switching on a resize would remount it, and a remount throws away the
+ * fields being typed and the dialog opened from it. */
+ let dockedWhenOpened = $state(null);
+ $effect(() => {
+ if (!openId && !snapshotOpen) {
+ dockedWhenOpened = null;
+ return;
+ }
+ if (dockedWhenOpened === null) dockedWhenOpened = untrack(() => toolWidth >= DOCK_WIDTH);
+ });
+ const docked = $derived(dockedWhenOpened ?? toolWidth >= DOCK_WIDTH);
+ const FICHE_KEY = 'azimut:boardDetailsW';
+ const FICHE_MIN = 420;
+ let ficheWidth = $state(readFicheWidth());
+ function readFicheWidth() {
+ try {
+ const stored = Number(localStorage.getItem(FICHE_KEY));
+ return Number.isFinite(stored) && stored >= FICHE_MIN ? stored : 560;
+ } catch {
+ return 560;
+ }
+ }
+ /** Never so wide that the list beside it stops being a list. */
+ const ficheShown = $derived(
+ Math.round(
+ Math.min(
+ Math.max(FICHE_MIN, Math.min(ficheWidth, 900, toolWidth - 480)),
+ // a window narrowed while it is open: Details keeps the room there is
+ toolWidth || Infinity
+ )
+ )
+ );
+ function startResize(e) {
+ e.preventDefault();
+ const startX = e.clientX;
+ const startWidth = ficheShown;
+ const move = (ev) => (ficheWidth = Math.max(FICHE_MIN, startWidth + (startX - ev.clientX)));
+ const up = () => {
+ window.removeEventListener('pointermove', move);
+ window.removeEventListener('pointerup', up);
+ try {
+ localStorage.setItem(FICHE_KEY, String(Math.round(ficheWidth)));
+ } catch {
+ /* the width holds for the session */
+ }
+ };
+ window.addEventListener('pointermove', move);
+ window.addEventListener('pointerup', up);
+ }
+ function nudgeFiche(e) {
+ if (e.key !== 'ArrowLeft' && e.key !== 'ArrowRight') return;
+ e.preventDefault();
+ ficheWidth = ficheShown + (e.key === 'ArrowLeft' ? 24 : -24);
+ try {
+ localStorage.setItem(FICHE_KEY, String(Math.round(ficheWidth)));
+ } catch {
+ /* the width holds for the session */
+ }
+ }
+
+ /** The arrow keys walk the rows, and with Details open beside the list they carry
+ * it along: reading five people is five presses rather than five modals. */
+ let bodyElement = $state();
+ function walkRows(e) {
+ if (e.key !== 'ArrowDown' && e.key !== 'ArrowUp') return;
+ const row = e.target;
+ if (!(row instanceof HTMLElement) || row.tagName !== 'TR') return;
+ const all = [...(bodyElement?.querySelectorAll('tbody tr[tabindex]') ?? [])];
+ const next = all[all.indexOf(row) + (e.key === 'ArrowDown' ? 1 : -1)];
+ if (!next) return;
+ e.preventDefault();
+ next.focus();
+ if (docked && (openId || snapshotOpen)) next.click();
+ }
+
+ /** Escape closes Details beside the list, unless it is closing something inside
+ * it first (a menu, a field being typed in). */
+ function escapeFiche(e) {
+ if (e.key !== 'Escape' || !docked || (!openId && !snapshotOpen)) return;
+ const target = e.target;
+ if (
+ target instanceof HTMLElement &&
+ (target.closest('input, textarea, select, [contenteditable="true"], [role="listbox"], [role="menu"]'))
+ ) {
+ return;
+ }
+ if (e.defaultPrevented) return;
+ e.preventDefault();
+ if (snapshotOpen) snapshotOpen = null;
+ else closeDetails();
+ }
+
/**
* The same question, added up instead of listed.
*
@@ -414,18 +798,20 @@
* more* is what says the rest is still out there.
*/
const ticked = $derived(new Set(selected));
+ /** The rows on screen, grouped or flat, in the order they are shown. */
+ const shownRows = $derived(grouped ? groupedRows : rows);
/** The ticked rows themselves, in the order the table is showing them. It is what
* the bar counts and what Delete sends, so the number on screen is never a row
* the table has since stopped showing. */
- const chosen = $derived(rows.filter((entity) => ticked.has(entity.id)));
- const allTicked = $derived(rows.length > 0 && chosen.length === rows.length);
+ const chosen = $derived(shownRows.filter((entity) => ticked.has(entity.id)));
+ const allTicked = $derived(shownRows.length > 0 && chosen.length === shownRows.length);
function tick(entity, shift) {
const result = toggleCheck(
selected,
entity.id,
{ shift },
- rows.map((row) => row.id),
+ shownRows.map((row) => row.id),
anchor
);
selected = result.selected;
@@ -433,7 +819,7 @@
}
function tickAll(on) {
- selected = on ? rows.map((row) => row.id) : [];
+ selected = on ? shownRows.map((row) => row.id) : [];
anchor = null;
}
@@ -451,6 +837,7 @@
JSON.stringify(analysisSearch.period);
totalling;
snapshotReading;
+ shape.group;
untrack(untickAll);
});
@@ -491,19 +878,25 @@
pl.clear();
summary = null;
loadedFor = null;
+ byType = null;
return;
}
if (loadedFor !== id) {
loadedFor = id;
pl.clear();
+ for (const list of Object.values(lists)) list.clear();
+ byType = null;
// The question travels with the case, not with the tab: reopening Azimut on a
- // case lands on what was being asked of it.
+ // case lands on what was being asked of it. So does the way it was laid out.
openAnalysisCase(id);
filter = normalizeFilter(analysisSearch.filter);
+ layout = loadLayout(id);
+ revealed = {};
fieldsWanted = false;
facetState = 'unasked';
}
- void pl.reload();
+ // The flat table reads its own page; the groups read theirs off the count.
+ if (!grouped) void pl.reload();
api
.get(`/api/cases/${id}/catalog/summary`)
.then((s) => {
@@ -546,7 +939,7 @@
setAnalysisFilter(caseState.current?.id, filter);
// The text term is the paged list's own, debounced there; asking again here would
// be a second request per keystroke.
- if (!first && caseState.current?.id) void pl.reload();
+ if (!first && caseState.current?.id && !untrack(() => grouped)) void pl.reload();
});
/**
@@ -628,13 +1021,13 @@
/** Start from what the analyst is already looking at: the chosen type, or the
* first type of the chosen family. Opening on "Person" while the family chip
* says Identifier is the menu ignoring the question just asked. */
- function startCreate() {
+ function startCreate(type = '') {
if (snapshotReading) return;
const wanted = creatableTypes().filter(
(entry) => !filter.families.length || filter.families.includes(entry.family)
);
draft = {
- type: onlyType || wanted[0]?.type || creatableTypes()[0]?.type || '',
+ type: type || onlyType || wanted[0]?.type || creatableTypes()[0]?.type || '',
label: '',
notes: '',
attrs: {},
@@ -724,9 +1117,11 @@
'warn'
);
}
- // One file opens where the analyst can say what it is; a batch does not, since
- // a panel over the list would be about whichever one happened to land last.
- if (files.length === 1 && last) openId = last;
+ // What was filed shows in its group. One file opens where the analyst can say
+ // what it is; a batch does not, since Details would be about whichever one
+ // happened to land last.
+ if (added || duplicates) reveal('media');
+ if (files.length === 1 && last) requestOpen(last);
} finally {
importing = false;
}
@@ -770,12 +1165,14 @@
// The same bytes twice is not an error and not a second row: the case keeps
// the one it has, and saying so is what stops the analyst pasting again.
if (result.duplicate) toast('Already in the case (same SHA-256)', 'warn');
- openId = result.entity.id;
+ reveal(result.entity.type ?? 'media');
+ requestOpen(result.entity.id);
} else {
const entity = await createBookmark(caseId, { ...values, url: payload.url });
pasted = null;
await reloadCase();
- openId = entity.id;
+ reveal(entity.type ?? 'bookmark');
+ requestOpen(entity.id);
}
} catch (e) {
toast(e.message, 'danger');
@@ -785,6 +1182,7 @@
}
function closeDetails() {
+ pendingOpen = null;
if (dirty) discarding = true;
else openId = null;
}
@@ -799,8 +1197,19 @@
snapshotOpen = catalogViews.activeView?.spec?.snapshot?.entities?.find(
(entity) => entity.id === id
) ?? null;
+ reveal(snapshotOpen?.type);
} else {
- openId = id;
+ requestOpen(id);
+ // Its group opens too, so the row followed here is on screen beside its Details.
+ const caseId = caseState.current?.id;
+ if (caseId) {
+ api
+ .get(`/api/cases/${caseId}/entities/${id}/chain`)
+ .then((chain) => {
+ if (caseState.current?.id === caseId) reveal(chain?.entity?.type);
+ })
+ .catch(() => {});
+ }
}
});
@@ -868,7 +1277,9 @@
terms: toGraphQuery(filter, { types: wantedTypes }),
label: said,
},
- board: { order, sortKey, sortDesc },
+ // The grouping and its sort travel with the view: a Board view reopens laid out
+ // the way it was saved.
+ board: { order, sortKey, sortDesc, group: shape.group, groupSort: shape.sort },
timeline: analysisPeriodSpec(analysisSearch.period),
};
}
@@ -886,6 +1297,8 @@
const board = view.spec?.board ?? {};
sortKey = typeof board.sortKey === 'string' ? board.sortKey : '';
sortDesc = board.sortDesc === true;
+ // A view saved before the groups states none, and opens flat as it was saved.
+ viewShape = viewLayout(board);
}
let appliedViewId = null;
@@ -893,6 +1306,7 @@
const view = catalogViews.activeView;
if (!view) {
appliedViewId = null;
+ viewShape = null;
return;
}
if (view.surface !== 'board' || view.id === appliedViewId) return;
@@ -911,17 +1325,22 @@
}
const savedFilter = normalizeFilter(view.spec?.query?.filter);
const savedBoard = view.spec?.board ?? {};
+ const savedShape = viewLayout(savedBoard);
const current = JSON.stringify({
filter: normalizeFilter(filter),
period: normalizeAnalysisPeriod(analysisSearch.period),
sortKey,
sortDesc,
+ group: shape.group,
+ groupSort: shape.sort,
});
const saved = JSON.stringify({
filter: savedFilter,
period: normalizeAnalysisPeriod(view.spec?.timeline),
sortKey: typeof savedBoard.sortKey === 'string' ? savedBoard.sortKey : '',
sortDesc: savedBoard.sortDesc === true,
+ group: savedShape.group,
+ groupSort: savedShape.sort,
});
if (observedLiveView !== view.id) {
observedLiveView = view.id;
@@ -935,6 +1354,7 @@
function leaveAnalysisReading() {
appliedViewId = null;
+ viewShape = null;
openId = null;
snapshotOpen = null;
filter = normalizeFilter(analysisSearch.filter);
@@ -955,10 +1375,10 @@
};
</script>
-<div class="tool">
+<div class="tool" bind:clientWidth={measuredWidth}>
<div class="tool-header">
<h2>Board</h2>
- <span class="sub">Everything this case holds</span>
+ <span class="sub">{grouped ? 'People, places and things first' : 'Everything this case holds'}</span>
<div class="spacer"></div>
<AnalysisViews
surface="board"
@@ -984,7 +1404,7 @@
e.currentTarget.value = '';
}}
/>
- <button class="btn btn-primary" onclick={startCreate} disabled={!caseState.current || snapshotReading}>
+ <button class="btn btn-primary" onclick={() => startCreate()} disabled={!caseState.current || snapshotReading}>
<Icon name="plus" size={14} /> New entity
</button>
</div>
@@ -1036,6 +1456,38 @@
{caseTotal} in this case
{/if}
</span>
+ <!-- How the rows are laid out: grouped by what they are, and in which order
+ across the case, or the one flat table. Neither changes the answer. -->
+ {#if caseState.current && !totalling}
+ <span class="layout">
+ {#if grouped}
+ <label class="pick-one" title="How each group is ordered, across the whole case">
+ <span>Sort</span>
+ <select
+ class="select"
+ value={shape.sort}
+ onchange={(e) => setShape({ sort: e.currentTarget.value })}
+ >
+ {#each GROUP_SORTS as option (option.id)}
+ <option value={option.id} title={option.hint}>{option.label}</option>
+ {/each}
+ </select>
+ </label>
+ {/if}
+ <label class="pick-one" title="Group the rows by what they are, or show one table">
+ <span>Group</span>
+ <select
+ class="select"
+ value={shape.group}
+ onchange={(e) => setShape({ group: e.currentTarget.value })}
+ >
+ {#each GROUPINGS as option (option.id)}
+ <option value={option.id} title={option.hint}>{option.label}</option>
+ {/each}
+ </select>
+ </label>
+ </span>
+ {/if}
<!-- How this screen renders the answer, in the control Files and the Media Library
already use for the same job. What a single subject comes to is read where
that subject is, in its own Details; this one reads several at once, ranked. -->
@@ -1046,6 +1498,21 @@
/>
</p>
+ <!-- The Board's standing questions, priced, while nothing else is being asked:
+ what is waiting on the analyst, one click from the rows it counts. -->
+ {#if waiting.length}
+ <p class="waiting-line">
+ <span class="lead-in">Waiting</span>
+ {#each waiting as item (item.id)}
+ <button
+ class="as-link"
+ title="Show them"
+ onclick={() => (filter = askQuestion(filter, item.id))}
+ ><strong>{item.count}</strong> {item.words}</button>
+ {/each}
+ </p>
+ {/if}
+
<!-- What the ticks come to, and the one thing they are for. Outside the scrolling
body so a selection made at the top of eight hundred rows is still actionable
at the bottom of them. -->
@@ -1063,9 +1530,13 @@
`dragleave` is guarded on the container itself: the event fires for every
child the pointer crosses, so an unguarded handler flickers the overlay off
halfway across the table. -->
+ <!-- svelte-ignore a11y_no_static_element_interactions -->
+ <div class="split" onkeydown={escapeFiche}>
+ <!-- svelte-ignore a11y_no_static_element_interactions -->
<div
class="body"
- role="presentation"
+ bind:this={bodyElement}
+ onkeydown={walkRows}
ondragover={(e) => {
if (!caseState.current || snapshotReading) return;
e.preventDefault();
@@ -1119,18 +1590,19 @@
{@const sure = confidenceLine(row, claimReads)}
<tr
tabindex="0"
- onclick={() => (openId = row.id)}
+ class:current={openId === row.id}
+ onclick={() => requestOpen(row.id)}
onkeydown={(e) => {
if (e.target !== e.currentTarget) return;
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
- openId = row.id;
+ requestOpen(row.id);
}
}}
>
<td>
<Icon name={entityIcon(row)} size={12} />
- <span class="name">{row.label}</span>
+ <span class="name" dir="auto">{row.label}</span>
<span class="dim">{entityLabel(row.type)}</span>
</td>
<td>
@@ -1152,6 +1624,53 @@
</tbody>
</table>
{/if}
+ {:else if grouped}
+ {#if byType && !groupedTotal}
+ <p class="empty">{filtering ? 'Nothing matches.' : 'Nothing filed in this case yet.'}</p>
+ {:else}
+ {#if byType && !filtering && !subjects && !snapshotReading}
+ <!-- A case of files only: nothing to index yet, and the way one arrives. -->
+ <div class="no-subjects">
+ <strong>No people, places or things yet.</strong>
+ <span>Name one with @ when you add an event, or</span>
+ <button class="as-link" onclick={() => startCreate()}>create one</button>
+ </div>
+ {/if}
+ {#each shownGroups as entry, index (entry.group.id)}
+ {#if index > 0 && entry.group.kind === 'material' && shownGroups[index - 1].group.kind === 'subject'}
+ <div class="divider" role="presentation"></div>
+ {/if}
+ <BoardGroup
+ group={entry.group}
+ count={counts[entry.group.id]}
+ open={entry.open}
+ rows={entry.list.items}
+ types={groupTypes[entry.group.id]}
+ loading={entry.list.loading}
+ hasMore={entry.list.hasMore}
+ {events}
+ currentId={openId ?? snapshotOpen?.id ?? null}
+ {ticked}
+ {busyId}
+ readOnly={snapshotReading}
+ query={filter.q}
+ creatable={creatableTypes().filter((type) => entry.group.families.includes(type.family))}
+ {matchReasons}
+ {thumbUrl}
+ {folderName}
+ {created}
+ ontoggle={() => toggleGroup(entry.group)}
+ onopen={openRow}
+ ontick={tick}
+ onconfirm={confirmEntity}
+ ondismiss={dismissEntity}
+ ongraph={showInGraph}
+ oncreate={(type) => startCreate(type)}
+ onreads={(tool) => (uiState.tool = tool)}
+ onmore={() => entry.list.loadMore()}
+ />
+ {/each}
+ {/if}
{:else if !rows.length && !pl.loading}
<p class="empty">{filtering ? 'Nothing matches.' : 'Nothing filed in this case yet.'}</p>
{:else}
@@ -1207,19 +1726,17 @@
<tr
class:suggested={isSuggested(entity)}
class:busy={busyId === entity.id}
+ class:current={(openId ?? snapshotOpen?.id) === entity.id}
+ data-row-id={entity.id}
tabindex="0"
- onclick={() => {
- if (snapshotReading) snapshotOpen = entity;
- else openId = entity.id;
- }}
+ onclick={() => openRow(entity)}
onkeydown={(e) => {
// only the row's own key press: Enter on the confirm button inside
// it is that button's, and would otherwise open Details as well
if (e.target !== e.currentTarget) return;
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
- if (snapshotReading) snapshotOpen = entity;
- else openId = entity.id;
+ openRow(entity);
}
}}
>
@@ -1242,21 +1759,14 @@
{/if}
<td>
{#if entity.thumb}
- <img
- class="entity-thumb"
- src={entity.thumb.startsWith('data:')
- ? entity.thumb
- : fileUrl(caseState.current.id, entity.thumb)}
- alt=""
- loading="lazy"
- />
+ <img class="entity-thumb" src={thumbUrl(entity.thumb)} alt="" loading="lazy" />
{:else}
<Icon name={entityIcon(entity)} size={12} />
{/if}
- <span class="name">{entity.label}</span>
+ <span class="name" dir="auto">{entity.label}</span>
{#if filter.q.trim() && matchReasons(entity)[0]}
{@const match = matchReasons(entity)[0]}
- <span class="match-reason" title={match.value}>
+ <span class="match-reason" title={match.value} dir="auto">
{match.label}: {match.value}
</span>
{/if}
@@ -1290,35 +1800,20 @@
<td title={entityHint(entity.type)}>{entityLabel(entity.type)}</td>
<td class="dim">{folderName(entity)}</td>
<td class="dim mono">{created(entity)}</td>
- {#each columns as column (column.key)}<td class="dim">{cell(entity, column)}</td>{/each}
+ {#each columns as column (column.key)}<td class="dim" dir="auto">{cell(entity, column)}</td>{/each}
<!-- The row's one way out of the table. A list is good at narrowing and
says nothing about how things join up, so the question a row most
often raises is the one only the drawing answers. Quiet until the
row is under the pointer, like the review clicks beside it. -->
<td class="go">
{#if !snapshotReading}
- {@const seat = claimSeat(entity)}
- {#if seat}
- <button
- class="btn btn-ghost btn-sm act"
- aria-label="File a claim from {entity.label}"
- title={claimActionTitle(seat.slot)}
- onclick={(e) => {
- e.stopPropagation();
- claimFor = entity;
- }}
- >
- <Icon name="quote" size={13} />
- </button>
- {/if}
<button
class="btn btn-ghost btn-sm act"
aria-label="Show {entity.label} in the graph"
title="Show it in the graph, with what it is connected to"
onclick={(e) => {
e.stopPropagation();
- uiState.openGraphEntity = entity.id;
- uiState.tool = 'graph';
+ showInGraph(entity);
}}
>
<Icon name="graph" size={13} />
@@ -1333,7 +1828,7 @@
<!-- Paging belongs to the list. The addition is bounded server-side and says so on
its own line, so a "Show more" under it would offer to lengthen a total. -->
- {#if pl.hasMore && !totalling}
+ {#if pl.hasMore && !totalling && !grouped}
<div class="more">
<!-- A sort the store could not answer runs over what is loaded, so it says
so while there is more: an alphabet over the first hundred of eight
@@ -1351,6 +1846,60 @@
</div>
{/if}
</div>
+
+ <!-- Details beside the list, when there is room for both: the row stays in view
+ while it is read, and the arrow keys walk from one to the next. -->
+ {#if docked && ((openId && !snapshotReading) || (snapshotOpen && snapshotReading))}
+ <!-- svelte-ignore a11y_no_noninteractive_tabindex -->
+ <!-- svelte-ignore a11y_no_noninteractive_element_interactions -->
+ <div
+ class="grip"
+ role="separator"
+ aria-orientation="vertical"
+ aria-label="Resize Details"
+ aria-valuemin={FICHE_MIN}
+ aria-valuemax="900"
+ aria-valuenow={ficheShown}
+ tabindex="0"
+ title="Drag to resize"
+ onpointerdown={startResize}
+ onkeydown={nudgeFiche}
+ ></div>
+ <aside class="fiche" style="width: {ficheShown}px" aria-label="Details">
+ <div class="fiche-bar">
+ <span class="fiche-title">{snapshotReading ? 'Snapshot details' : 'Details'}</span>
+ <span class="fiche-keys">↑ ↓ next row · Esc close</span>
+ <button
+ class="btn btn-ghost btn-sm"
+ aria-label="Close Details"
+ title="Close (Esc)"
+ onclick={() => (snapshotReading ? (snapshotOpen = null) : closeDetails())}
+ >
+ <Icon name="x" size={14} />
+ </button>
+ </div>
+ <div class="fiche-body">
+ {#if snapshotReading}
+ <SnapshotDetails
+ caseId={caseState.current?.id}
+ entity={snapshotOpen}
+ entities={catalogViews.activeView?.spec?.snapshot?.entities ?? []}
+ links={catalogViews.activeView?.spec?.snapshot?.links ?? []}
+ />
+ {:else}
+ <!-- The tab stays as the rows change, so walking five people on their
+ Connections tab reads five sets of connections. -->
+ <EntityDetails
+ entityId={openId}
+ bind:dirty
+ onclose={() => (openId = null)}
+ ondeleted={() => (openId = null)}
+ />
+ {/if}
+ </div>
+ </aside>
+ {/if}
+ </div>
</div>
{#if draft}
@@ -1360,13 +1909,15 @@
startType={draft.type}
ontwin={(entity) => {
draft = null;
- openId = entity.id;
+ reveal(entity.type);
+ requestOpen(entity.id);
}}
oncreated={(entity) => {
draft = null;
- // Create it, then open it: a claim exists in order to be pointed at things, so
- // landing on its own Details with the relation picker is the next gesture.
- openId = entity.id;
+ // Create it, then open it in its group: a new subject exists in order to be
+ // pointed at, so its own Details is where the next gesture is.
+ reveal(entity.type);
+ requestOpen(entity.id);
}}
onclose={() => (draft = null)}
/>
@@ -1382,18 +1933,7 @@
/>
{/if}
-{#if claimFor}
- <Modal title="New claim" onclose={() => (claimFor = null)} width="560px">
- <QuickClaim
- caseId={caseState.current.id}
- entity={claimFor}
- onsaved={() => (claimFor = null)}
- oncancel={() => (claimFor = null)}
- />
- </Modal>
-{/if}
-
-{#if openId && !snapshotReading}
+{#if openId && !snapshotReading && !docked && uiState.tool === 'board'}
<!-- Escape and the backdrop both close a modal, and the panel's fields wait for
Save: closing over unsaved edits threw them away without a word. The ask is
only raised when there is something to lose. -->
@@ -1409,9 +1949,10 @@
</Modal>
{/if}
-{#if snapshotOpen && snapshotReading}
+{#if snapshotOpen && snapshotReading && !docked && uiState.tool === 'board'}
<Modal title="Snapshot details" onclose={() => (snapshotOpen = null)} width="640px">
<SnapshotDetails
+ caseId={caseState.current?.id}
entity={snapshotOpen}
entities={catalogViews.activeView?.spec?.snapshot?.entities ?? []}
links={catalogViews.activeView?.spec?.snapshot?.links ?? []}
@@ -1441,8 +1982,16 @@
message="This item has edits that Save has not taken."
confirmLabel="Discard"
icon="alert"
- onconfirm={() => { discarding = false; dirty = false; openId = null; }}
- oncancel={() => (discarding = false)}
+ onconfirm={() => {
+ discarding = false;
+ dirty = false;
+ openId = pendingOpen;
+ pendingOpen = null;
+ }}
+ oncancel={() => {
+ discarding = false;
+ pendingOpen = null;
+ }}
/>
{/if}
@@ -1508,16 +2057,146 @@
.picked .drop:hover {
color: var(--danger);
}
- /* The one scrolling region. `.tool` is a full-height flex column, so the body
+ /* The list and Details beside it. `.tool` is a full-height flex column, so the row
needs min-height:0 or the table pushes the column taller than the viewport and
nothing scrolls at all. */
+ .split {
+ display: flex;
+ flex: 1;
+ min-height: 0;
+ }
+ /* The list's own scrolling region. */
.body {
position: relative;
flex: 1;
+ min-width: 0;
min-height: 0;
overflow: auto;
padding: 0 16px 16px;
}
+ /* Details beside the list: its own scroll, its own edge, resized from the rule. */
+ .grip {
+ position: relative;
+ flex: 0 0 5px;
+ margin-left: -2px;
+ cursor: col-resize;
+ border-left: 1px solid var(--border);
+ }
+ .grip:hover,
+ .grip:focus-visible {
+ border-left-color: var(--accent);
+ outline: none;
+ }
+ .fiche {
+ display: flex;
+ flex-direction: column;
+ flex-shrink: 0;
+ min-height: 0;
+ background: var(--bg-1);
+ }
+ .fiche-bar {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 6px 10px 6px 16px;
+ border-bottom: 1px solid var(--border);
+ }
+ .fiche-title {
+ color: var(--text-3);
+ font-size: var(--fs-xs);
+ font-weight: 600;
+ letter-spacing: 0.02em;
+ text-transform: uppercase;
+ }
+ .fiche-keys {
+ margin-left: auto;
+ color: var(--text-3);
+ font-size: var(--fs-xs);
+ }
+ .fiche-body {
+ flex: 1;
+ min-height: 0;
+ overflow: auto;
+ padding: 12px 16px 16px;
+ }
+ /* Grouping and sort sit with the switch they share a job with, quiet until used. */
+ .layout {
+ display: inline-flex;
+ align-items: center;
+ gap: 10px;
+ }
+ .pick-one {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ color: var(--text-3);
+ font-size: var(--fs-xs);
+ }
+ .pick-one .select {
+ width: auto;
+ min-height: 0;
+ padding: 2px 22px 2px 6px;
+ font-size: var(--fs-xs);
+ }
+ /* What is waiting on the analyst, one line under the count. */
+ .waiting-line {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: 4px 14px;
+ margin: 0;
+ padding: 0 16px 8px;
+ color: var(--text-3);
+ font-size: var(--fs-xs);
+ }
+ .waiting-line .lead-in {
+ color: var(--text-3);
+ font-weight: 600;
+ }
+ .waiting-line .as-link {
+ padding: 0;
+ border: 0;
+ background: none;
+ color: var(--text-2);
+ font: inherit;
+ cursor: pointer;
+ }
+ .waiting-line .as-link strong {
+ color: var(--accent);
+ font-weight: 600;
+ }
+ .waiting-line .as-link:hover {
+ color: var(--text-1);
+ }
+ /* A case holding files only: the line that says how the index fills. */
+ .no-subjects {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: baseline;
+ gap: 6px;
+ margin: 10px 0 14px;
+ padding: 12px 14px;
+ border: 1px dashed var(--border-strong);
+ border-radius: var(--r-md);
+ color: var(--text-3);
+ font-size: var(--fs-sm);
+ }
+ .no-subjects strong {
+ color: var(--text-1);
+ font-weight: 600;
+ }
+ .no-subjects .as-link {
+ padding: 0;
+ border: 0;
+ background: none;
+ color: var(--accent);
+ font: inherit;
+ cursor: pointer;
+ }
+ /* Between what the case is about and what it is built from. */
+ .divider {
+ height: 14px;
+ }
.drop-overlay {
position: absolute;
inset: 0;
@@ -1536,7 +2215,7 @@
gap: 8px;
padding: 22px 30px;
border: 1px dashed var(--accent);
- border-radius: var(--r);
+ border-radius: var(--r-md);
color: var(--text-2);
font-size: var(--fs-sm);
}
@@ -1620,6 +2299,14 @@
.table tbody tr.busy {
opacity: 0.5;
}
+ /* The row whose Details are open beside the list. */
+ .table tbody tr.current td {
+ background: var(--accent-soft);
+ color: var(--text-1);
+ }
+ .table tbody tr.current {
+ border-left-color: var(--accent);
+ }
/* the two review clicks, quiet until the row is under the pointer or focused */
.review {
display: inline-flex;
@@ -1725,13 +2412,10 @@
.tally .sure {
display: block;
margin-top: 2px;
- font-size: var(--fs-xs);
- }
- .tally .note {
color: var(--text-3);
+ font-size: var(--fs-xs);
}
.tally .sure {
- color: var(--text-3);
font-style: italic;
}
.tally td .dim {
diff --git a/frontend/src/tools/Board.test.js b/frontend/src/tools/Board.test.js
index 7570086..b244f2b 100644
--- a/frontend/src/tools/Board.test.js
+++ b/frontend/src/tools/Board.test.js
@@ -24,8 +24,8 @@ describe('the board is what makes the vocabulary reachable', () => {
expect(source).toContain('width="640px"');
});
- it('opens what it just created, since a claim exists to be pointed at things', () => {
- expect(source).toContain('openId = entity.id;');
+ it('opens what it just created in its group, since a subject exists to be pointed at', () => {
+ expect(source).toMatch(/oncreated=\{\(entity\) => \{[\s\S]{0,300}reveal\(entity\.type\);\s*requestOpen\(entity\.id\);/);
});
it('opens any row in the one Details panel every other surface uses', () => {
@@ -40,8 +40,8 @@ describe('the board is what makes the vocabulary reachable', () => {
it('uses the primary photo when an entity has one', () => {
expect(source).toContain('{#if entity.thumb}');
- expect(source).toContain("entity.thumb.startsWith('data:')");
- expect(source).toContain('fileUrl(caseState.current.id, entity.thumb)');
+ expect(source).toContain("thumb.startsWith('data:') ? thumb : fileUrl(caseState.current.id, thumb)");
+ expect(source).toContain('<img class="entity-thumb" src={thumbUrl(entity.thumb)}');
expect(source).toContain('{:else}\n <Icon name={entityIcon(entity)}');
});
});
@@ -94,9 +94,11 @@ describe('bounded loading', () => {
});
it('counts a memory-filtered page itself, since the server never heard the term', () => {
- expect(source).toContain(
- "pl.serverMode || !filter.q.trim() ? pl.total : matching.length"
+ expect(source).toMatch(
+ /pl\.serverMode \|\| !filter\.q\.trim\(\)\s*\? pl\.total\s*: matching\.length/
);
+ // grouped, the count is the server's, since every group reads its page from it
+ expect(source).toContain('grouped\n ? groupedTotal');
});
it('hands the term to the list, which is what searches past one page', () => {
@@ -195,7 +197,7 @@ describe('one table, and it scrolls', () => {
it('is the tool shell, so the rows scroll instead of the page growing', () => {
// `.tool` is a full-height flex column; a body without min-height:0 pushes the
// column past the viewport and nothing scrolls at all
- expect(source).toContain('<div class="tool">');
+ expect(source).toContain('<div class="tool" bind:clientWidth={measuredWidth}>');
expect(source).toContain('.body {');
expect(source).toMatch(/\.body \{[^}]*min-height: 0;/);
expect(source).toMatch(/\.body \{[^}]*overflow: auto;/);
@@ -298,7 +300,7 @@ describe('creating one', () => {
expect(source).toContain(
'(entry) => !filter.families.length || filter.families.includes(entry.family)'
);
- expect(source).toContain('type: onlyType || wanted[0]?.type');
+ expect(source).toContain('type: type || onlyType || wanted[0]?.type');
});
it('names the first column after the chosen type, as the create form does', () => {
@@ -310,8 +312,7 @@ describe('creating one', () => {
it('offers the row this case already holds under the same identifier', () => {
// the warning itself lives in the shared dialog; what the Board owns is where the
// offer lands — the existing row, opened
- expect(source).toContain('ontwin={(entity) => {');
- expect(source).toContain('openId = entity.id;');
+ expect(source).toMatch(/ontwin=\{\(entity\) => \{[\s\S]{0,120}requestOpen\(entity\.id\);/);
});
it('asks before a close would throw away an unsaved field', () => {
@@ -326,7 +327,7 @@ describe('a frozen analysis snapshot', () => {
expect(source).toContain('const snapshotReading = $derived(Boolean(catalogViews.snapshotId))');
expect(source).toContain('disabled={!caseState.current || importing || snapshotReading}');
expect(source).toContain('disabled={snapshotReading}');
- expect(source).toContain('{#if openId && !snapshotReading}');
+ expect(source).toContain("{#if openId && !snapshotReading && !docked && uiState.tool === 'board'}");
expect(source).toContain('{#if !snapshotReading}<span class="review">');
expect(source).toContain('<Modal title="Snapshot details"');
expect(source).toContain('<SnapshotDetails');
@@ -355,7 +356,9 @@ describe('taking a file into the case', () => {
});
it('opens one file where the analyst can say what it is, and a batch nowhere', () => {
- expect(source).toContain('if (files.length === 1 && last) openId = last;');
+ expect(source).toContain('if (files.length === 1 && last) requestOpen(last);');
+ // and what was filed shows in its group rather than folded away
+ expect(source).toContain("if (added || duplicates) reveal('media');");
});
});
@@ -415,7 +418,7 @@ describe('a row reaches the drawing', () => {
});
it('keeps that click off the row it sits on', () => {
- expect(source).toMatch(/e\.stopPropagation\(\);\s*uiState\.openGraphEntity/);
+ expect(source).toMatch(/e\.stopPropagation\(\);\s*showInGraph\(entity\);/);
});
it('stays quiet until the row is under the pointer, like the review clicks', () => {
@@ -491,11 +494,11 @@ describe('adding the statements up', () => {
});
it('offers no Show more under a bounded total', () => {
- expect(source).toContain('{#if pl.hasMore && !totalling}');
+ expect(source).toContain('{#if pl.hasMore && !totalling && !grouped}');
});
it('opens the subject a row stands for', () => {
- expect(source).toContain('onclick={() => (openId = row.id)}');
+ expect(source).toContain('onclick={() => requestOpen(row.id)}');
});
});
@@ -505,8 +508,8 @@ describe('Ctrl+V on the table', () => {
expect(source).toContain("import PasteDialog from '../components/PasteDialog.svelte'");
expect(source).toContain("resolvePaste('board', payload)");
// opened, not just filed: the next gesture is relating it to what prompted it
- expect(source).toContain('openId = result.entity.id;');
- expect(source).toContain('openId = entity.id;');
+ expect(source).toContain('requestOpen(result.entity.id);');
+ expect(source).toContain("reveal(entity.type ?? 'bookmark');");
});
it('only answers while it is the tool on screen', () => {
@@ -532,7 +535,8 @@ describe('several rows at once', () => {
it('measures a shift-run over the rows on screen, with the shared selection math', () => {
expect(source).toContain("import { toggleCheck } from '../lib/gridSelect.js'");
- expect(source).toContain('rows.map((row) => row.id)');
+ expect(source).toContain('shownRows.map((row) => row.id)');
+ expect(source).toContain('const shownRows = $derived(grouped ? groupedRows : rows);');
});
it('drops the ticks when the question they were made in changes', () => {
@@ -547,10 +551,67 @@ describe('several rows at once', () => {
});
});
-describe('filing a claim from a row', () => {
- it('offers it only where the verb registry gives the row a seat', () => {
- expect(source).toContain('{@const seat = claimSeat(entity)}');
- expect(source).toContain('title={claimActionTitle(seat.slot)}');
+describe('the groups', () => {
+ it('reads the case by family, from one count of the answer per type', () => {
+ expect(source).toContain("import BoardGroup from './board/BoardGroup.svelte';");
+ expect(source).toContain("counts: 'type',");
+ expect(source).toContain('byType = page.by_type ?? {};');
+ // a group reads its own page only when it is open and holds part of the answer
+ expect(source).toContain('if (counts[group.id] && isOpen(group)) loadGroup(group.id);');
+ });
+
+ it('keeps the question the one Board and Graph share', () => {
+ // no preset in the filter: the groups lay the answer out, they never narrow it
+ expect(source).not.toMatch(/['"]Subjects['"]/);
+ expect(source).toContain('...toQuery(filter, { types: groupTypes[group.id] }),');
+ });
+
+ it('reads the events of the subject rows once per page, never per row', () => {
+ expect(source).toContain("import { fetchEventRows } from '../lib/catalog.js';");
+ expect(source).toContain("entry.open && entry.group.kind === 'subject'");
+ expect(source).toContain('fetchEventRows(id, missing)');
+ });
+
+ it('keeps the layout per case and lets a saved view state its own', () => {
+ expect(source).toContain('layout = loadLayout(id);');
+ expect(source).toContain('board: { order, sortKey, sortDesc, group: shape.group, groupSort: shape.sort },');
+ expect(source).toContain('viewShape = viewLayout(board);');
+ });
+
+ it('opens Details beside the list when there is room, and walks it with the arrows', () => {
+ expect(source).toContain('<aside class="fiche"');
+ expect(source).toContain('onkeydown={walkRows}');
+ expect(source).toContain("if (docked && (openId || snapshotOpen)) next.click();");
+ });
+
+ it('keeps Details where it opened while the window is resized', () => {
+ // a switch on resize would remount it and throw away what was being typed
+ expect(source).toContain('if (dockedWhenOpened === null) dockedWhenOpened = untrack(() => toolWidth >= DOCK_WIDTH);');
+ expect(source).toContain('const docked = $derived(dockedWhenOpened ?? toolWidth >= DOCK_WIDTH);');
+ });
+
+ it('keeps Details beside the list while the Board is hidden', () => {
+ // a hidden tab measures no width, which must not read as a narrow window
+ expect(source).toContain('if (measuredWidth > 0) toolWidth = measuredWidth;');
+ });
+
+ it('asks before an arrow key throws half-typed fields away', () => {
+ expect(source).toContain('if (dirty && openId) {');
+ expect(source).toContain('openId = pendingOpen;');
+ });
+
+ it('offers the waiting questions while nothing else is asked', () => {
+ expect(source).toContain('!filtering && !snapshotReading && !totalling ? waitingOf(summary) : []');
+ expect(source).toContain('onclick={() => (filter = askQuestion(filter, item.id))}');
+ });
+
+ it('says how a case of files only fills its index', () => {
+ expect(source).toContain('No people, places or things yet.');
+ });
+
+ it('leaves adding an event to Details, with no press on each row', () => {
+ expect(source).not.toContain('claimSeat');
+ expect(source).not.toContain('File a claim');
expect(source).toContain('loadRelationTypes();');
});
});
diff --git a/frontend/src/tools/Collage.render.svelte.test.js b/frontend/src/tools/Collage.render.svelte.test.js
index fd50cf1..587d95c 100644
--- a/frontend/src/tools/Collage.render.svelte.test.js
+++ b/frontend/src/tools/Collage.render.svelte.test.js
@@ -39,7 +39,11 @@ 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() } }));
+const put = vi.fn(async () => ({}));
+vi.mock('../lib/api.js', () => ({ api: { get, post, put, patch: vi.fn(), del: vi.fn() } }));
+// happy-dom has no 2D canvas, so the preview's pixels are stood in for.
+const renderCollageThumb = vi.fn(async () => new Blob(['png'], { type: 'image/png' }));
+vi.mock('../lib/collageThumb.js', () => ({ renderCollageThumb }));
// Reactive, so a change made elsewhere in the case can reach the open collage.
const caseState = $state({ current: { id: 'case-a', folders: [] }, rev: 0 });
@@ -78,6 +82,8 @@ beforeEach(() => {
media = MEDIA;
works = [];
post.mockClear();
+ put.mockClear();
+ renderCollageThumb.mockClear();
toast.mockClear();
uiState.openCollage = null;
// A picture "loads" as soon as it is asked for, with a size to lay out.
@@ -91,10 +97,11 @@ beforeEach(() => {
globalThis.ResizeObserver ??= class { observe() {} disconnect() {} };
});
-afterEach(() => {
+afterEach(async () => {
if (live) unmount(live);
live = null;
target?.remove();
+ await settle(); // a preview sent on the way out lands before the next test counts
vi.unstubAllGlobals();
});
@@ -291,3 +298,252 @@ describe('frames from Inspect', () => {
expect(target.querySelector('.group').textContent).toContain('No frames left here.');
});
});
+
+describe('the list', () => {
+ const previewPuts = () => put.mock.calls.filter(([path]) => path.endsWith('/thumb'));
+ // The preview waits for the layout to settle past the save.
+ const afterPreview = () => settle(1700);
+
+ it('shows each collage as a card with its preview, or its outline until it has one', async () => {
+ collages = [
+ { name: 'Strip', title: 'Strip', pieces: 1, thumb: '.collages/Strip.webp', thumb_v: 7, filed: true },
+ { name: 'Wall', title: 'Wall', pieces: 2, filed: false,
+ outline: { width: 100, height: 50, quads: [[[0, 0], [50, 0], [50, 50], [0, 50]], [[50, 0], [100, 0], [100, 50], [50, 50]]] } },
+ ];
+ await start();
+
+ const [strip, wall] = target.querySelectorAll('.card');
+ expect(strip.querySelector('img').getAttribute('src')).toBe('/files/case-a/.collages/Strip.webp?v=7');
+ expect(wall.querySelectorAll('svg polygon')).toHaveLength(2);
+ // Only the one whose picture is in the case carries the mark.
+ expect(strip.querySelector('.filed')).not.toBeNull();
+ expect(wall.querySelector('.filed')).toBeNull();
+ });
+
+ it('files a preview once a placed piece has settled', async () => {
+ await start();
+ button('New collage').click();
+ await settle();
+ button('Images').click();
+ flushSync();
+ target.querySelector('.picker .thumb').click();
+ await settle(20);
+ await afterQuiet();
+ await afterPreview();
+
+ expect(previewPuts()).toHaveLength(1);
+ const [path, body] = previewPuts()[0];
+ expect(path).toBe('/api/cases/case-a/collages/Collage%201/thumb');
+ expect(body).toBeInstanceOf(FormData);
+ const [nodes] = renderCollageThumb.mock.calls[0];
+ expect(nodes).toHaveLength(1);
+ expect(nodes[0].quad).toHaveLength(4);
+ });
+
+ it('draws nothing again for a collage reopened as it was', async () => {
+ collages = [{ name: 'Strip', title: 'Strip', pieces: 1, thumb: '.collages/Strip.webp', thumb_v: 1 }];
+ saved.Strip = {
+ name: 'Strip', title: 'Strip',
+ spec: { width: 800, height: 400, transparent: true, nodes: [piece('media/roof.png')] },
+ };
+ await start();
+ button('Strip').click();
+ await settle(20);
+ await afterPreview();
+
+ expect(previewPuts()).toHaveLength(0);
+ });
+
+ it('draws one for a collage that has none yet, once its pieces are in', async () => {
+ collages = [{ name: 'Strip', title: 'Strip', pieces: 1, outline: null }];
+ saved.Strip = {
+ name: 'Strip', title: 'Strip',
+ spec: { width: 800, height: 400, transparent: true, nodes: [piece('media/roof.png')] },
+ };
+ await start();
+ button('Strip').click();
+ await settle(20);
+ await afterPreview();
+
+ expect(previewPuts().map(([path]) => path)).toEqual(['/api/cases/case-a/collages/Strip/thumb']);
+ });
+});
+
+describe('finding and leaving a collage', () => {
+ const typeInto = (input, value) => {
+ input.value = value;
+ input.dispatchEvent(new Event('input', { bubbles: true }));
+ flushSync();
+ };
+ const titles = () => [...target.querySelectorAll('.card .row-title')].map((el) => el.textContent);
+
+ it('narrows the list to the names holding every word, whatever their accents', async () => {
+ collages = [
+ { name: 'Façade est', title: 'Façade est', pieces: 2 },
+ { name: 'Harbour strip', title: 'Harbour strip', pieces: 1 },
+ { name: 'Facade west', title: 'Facade west', pieces: 1 },
+ ];
+ await start();
+ const search = target.querySelector('input[aria-label="Search collages…"]');
+
+ typeInto(search, 'FACADE');
+ expect(titles()).toEqual(['Façade est', 'Facade west']);
+ typeInto(search, 'façade west');
+ expect(titles()).toEqual(['Facade west']);
+ typeInto(search, 'quay');
+ expect(titles()).toEqual([]);
+ expect(target.textContent).toContain('No collage has “quay” in its name.');
+ });
+
+ it('offers no search over a single collage', async () => {
+ collages = [{ name: 'Strip', title: 'Strip', pieces: 1 }];
+ await start();
+
+ expect(target.querySelector('input[aria-label="Search collages…"]')).toBeNull();
+ });
+
+ it('saves what is pending and goes back to the list on Close', async () => {
+ await start();
+ button('New collage').click();
+ await settle();
+ button('Images').click();
+ flushSync();
+ target.querySelector('.picker .thumb').click();
+ await settle(20);
+ expect(collagePosts()).toHaveLength(0); // still waiting on the autosave
+
+ collages = [{ name: 'Collage 1', title: 'Collage 1', pieces: 1 }];
+ button('Close').click();
+ await settle(20);
+
+ expect(collagePosts()).toHaveLength(1);
+ expect(target.querySelector('.tool-header')).toBeNull();
+ expect(titles()).toEqual(['Collage 1']);
+ });
+
+ it('lets a rename typed just before Close land first', async () => {
+ 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')] },
+ };
+ let answer;
+ post.mockImplementationOnce((_path, body) => new Promise((resolve) => (answer = () => resolve({ name: body.title, title: body.title }))));
+ await start();
+ button('Strip').click();
+ await settle(20);
+
+ const input = target.querySelector('input[aria-label="Collage name"]');
+ typeInto(input, 'Harbour');
+ input.dispatchEvent(new FocusEvent('blur'));
+ button('Close').click();
+ await settle(20);
+ expect(target.querySelector('.tool-header')).not.toBeNull(); // waiting on the rename
+
+ answer();
+ await settle(20);
+ expect(collagePosts().map(([, body]) => body.title)).toEqual(['Harbour']);
+ expect(target.querySelector('.tool-header')).toBeNull();
+ });
+
+ it('stays open when the last save fails', async () => {
+ post.mockImplementationOnce(async () => {
+ throw new Error('disk full');
+ });
+ await start();
+ button('New collage').click();
+ await settle();
+ button('Images').click();
+ flushSync();
+ target.querySelector('.picker .thumb').click();
+ await settle(20);
+
+ button('Close').click();
+ await settle(20);
+
+ expect(target.querySelector('.tool-header')).not.toBeNull();
+ expect(toast).toHaveBeenCalledWith('The collage could not be saved, so it stays open', 'warn');
+ });
+});
+
+describe('the piece picker', () => {
+ const clip = { name: 'Convoy clip', title: 'Convoy clip', source: 'media/clip.mp4', frames: 2, kind: 'video' };
+ const roof = { name: 'Roof', title: 'Roof', source: 'media/roof.png', frames: 1, kind: 'image' };
+ const heads = () => [...target.querySelectorAll('.group-head .name')].map((el) => el.textContent);
+ const typeInto = (input, value) => {
+ input.value = value;
+ input.dispatchEvent(new Event('input', { bubbles: true }));
+ flushSync();
+ };
+
+ async function openNew() {
+ await start();
+ button('New collage').click();
+ await settle();
+ }
+
+ it('shows each file by its own thumbnail, in the order last worked on', async () => {
+ works = [roof, clip];
+ await openNew();
+
+ expect(heads()).toEqual(['Roof', 'Convoy clip']);
+ const [first, second] = target.querySelectorAll('.group-head .file');
+ expect(first.querySelector('img').getAttribute('src')).toBe('/files/case-a/media/.thumbs/r.jpg');
+ expect(second.querySelector('img')).toBeNull(); // no thumbnail cached: its kind stands in
+ });
+
+ it('narrows the files, then the images, to the words typed', async () => {
+ works = [roof, clip];
+ await openNew();
+ const search = target.querySelector('.picker input[aria-label="Search…"]');
+
+ typeInto(search, 'convoy');
+ expect(heads()).toEqual(['Convoy clip']);
+ typeInto(search, 'quay');
+ expect(target.querySelector('.picker').textContent).toContain('No file named “quay”.');
+
+ button('Images').click();
+ flushSync();
+ typeInto(search, 'ROOF');
+ expect(target.querySelectorAll('.picker .thumbs .thumb')).toHaveLength(1);
+ });
+
+ it('keeps one file unfolded at a time', async () => {
+ works = [roof, clip];
+ await openNew();
+ const [roofHead, clipHead] = target.querySelectorAll('.group-head');
+
+ roofHead.click();
+ flushSync();
+ clipHead.click();
+ flushSync();
+
+ expect(roofHead.getAttribute('aria-expanded')).toBe('false');
+ expect(clipHead.getAttribute('aria-expanded')).toBe('true');
+ });
+});
+
+describe('the export', () => {
+ it('says its size, and composes at the piece’s own resolution', async () => {
+ collages = [{ name: 'Strip', title: 'Strip', pieces: 1 }];
+ // a 1920×1080 piece shown at 800×450
+ saved.Strip = {
+ name: 'Strip', title: 'Strip',
+ spec: { width: 1600, height: 800, transparent: true, nodes: [{
+ ...piece('media/roof.png'), w: 1920, h: 1080, quad: [[100, 50], [900, 50], [900, 500], [100, 500]],
+ }] },
+ };
+ await start();
+ button('Strip').click();
+ await settle(20);
+
+ expect(target.textContent).toContain('Exports at 1920 × 1080 px.');
+ expect(target.querySelector('input[aria-label="Canvas width in pixels"]')).toBeNull();
+
+ [...document.querySelectorAll('.save .btn-primary')][0].click();
+ await settle(20);
+ const [, body] = post.mock.calls.find(([path]) => path.endsWith('/inspect/compose'));
+ expect(body).toMatchObject({ width: 1920, height: 1080 });
+ expect(body.nodes[0].quad).toEqual([[0, 0], [1920, 0], [1920, 1080], [0, 1080]]);
+ });
+});
diff --git a/frontend/src/tools/Collage.svelte b/frontend/src/tools/Collage.svelte
index b4bef66..27a4dcf 100644
--- a/frontend/src/tools/Collage.svelte
+++ b/frontend/src/tools/Collage.svelte
@@ -3,7 +3,7 @@
import { fileUrl } from '../lib/fileUrl.js';
import { caseState, uiState, reloadCase, toast } from '../lib/state.svelte.js';
import {
- uid, initialQuad, quadFromCropRect, collageBounds, COLLAGE_DEFAULT_SIZE,
+ uid, initialQuad, quadFromCropRect, exportFrame, COLLAGE_DEFAULT_SIZE,
} from '../lib/inspect.js';
import {
workState, collageSpec, collageSignature, missingPieces, isFiled,
@@ -12,11 +12,15 @@
import { createAutosave } from '../lib/autosave.svelte.js';
import { createHistory } from '../lib/history.js';
import { deletedToast } from '../lib/trash.js';
+ import { renderCollageThumb } from '../lib/collageThumb.js';
+ import { foldTerms, foldText } from '../lib/textFold.js';
import Icon from '../components/Icon.svelte';
import Modal from '../components/Modal.svelte';
import ConfirmDialog from '../components/ConfirmDialog.svelte';
+ import SearchInput from '../components/SearchInput.svelte';
import CollageCanvas from './inspect/CollageCanvas.svelte';
import CollageMenu from './inspect/CollageMenu.svelte';
+ import CollagePreview from './inspect/CollagePreview.svelte';
import PiecePicker from './inspect/PiecePicker.svelte';
import PieceCropModal from './inspect/PieceCropModal.svelte';
import SaveToCase from './inspect/SaveToCase.svelte';
@@ -37,13 +41,27 @@
let selectedIds = $state([]);
let cropPieceNode = $state(null);
let opening = $state(false);
+ let query = $state('');
+
+ // The list, narrowed by the search box: every word has to be in the name.
+ const shownCollages = $derived.by(() => {
+ const terms = foldTerms(query);
+ if (!terms.length) return collages;
+ return collages.filter((row) => {
+ const title = foldText(row.title);
+ return terms.every((term) => title.includes(term));
+ });
+ });
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 })));
+ const fileThumbs = $derived(new Map(mediaList.map((m) => [m.path, m.thumbnail])));
+ const pickerWorks = $derived(
+ works.map((w) => ({ ...w, title: fileTitles.get(w.source) ?? w.title, thumb: fileThumbs.get(w.source) ?? null }))
+ );
// The open collage. `name` is the file it is saved under, absent until the
// first piece makes it worth filing.
@@ -71,6 +89,11 @@
const exportedPath = $derived(
isFiled(doc.exported, collageSignature(doc), mediaPaths) ? doc.exported.path : null
);
+ // What the export will be, said beside the button that makes it.
+ const output = $derived(doc.nodes.length ? exportFrame(doc.nodes) : null);
+ const outputHint = $derived(
+ output ? `Exports at ${output.width} × ${output.height} px${output.capped ? ', the size limit' : ''}.` : ''
+ );
// -- saving as it is made -----------------------------------------------------
let savedSignature = $state(null);
@@ -120,6 +143,56 @@
return 'saved';
});
+ // -- the list's preview -------------------------------------------------------------
+ // Drawn here from the pieces already on screen, once every piece is in and the
+ // layout has settled, and filed beside the collage (engine/inspectwork.py). What
+ // it was last drawn from is kept, so reopening an unchanged collage sends nothing.
+ let thumbDrawnFrom = null;
+ let thumbTimer = null;
+ const thumbKey = () => JSON.stringify(doc.nodes.map((n) => [n.save, n.quad, !!n.missing]));
+ const piecesIn = () => doc.nodes.length > 0 && doc.nodes.every((n) => n.url || n.missing);
+
+ /** Draw and file the preview now. Takes its own copy, so the collage can close meanwhile. */
+ function sendThumb() {
+ clearTimeout(thumbTimer);
+ thumbTimer = null;
+ if (!doc.open || !doc.name || !piecesIn()) return null;
+ const key = thumbKey();
+ if (key === thumbDrawnFrom) return null;
+ const { caseId, name } = doc;
+ const nodes = doc.nodes.map((n) => ({
+ id: n.id, quad: n.quad.map(([x, y]) => [x, y]), url: n.url, w: n.w, h: n.h, missing: !!n.missing,
+ }));
+ thumbDrawnFrom = key;
+ return renderCollageThumb(nodes)
+ .then((blob) => {
+ if (!blob) return;
+ const form = new FormData();
+ form.append('file', blob, 'preview.png');
+ return api.put(`/api/cases/${caseId}/collages/${encodeURIComponent(name)}/thumb`, form);
+ })
+ .then(() => {
+ const shown = listOpen || !doc.open;
+ if (shown && caseState.current?.id === caseId) refreshList(caseId);
+ })
+ .catch(() => {
+ // A preview is a convenience: the list falls back to the outline, and the
+ // next change draws it again.
+ if (thumbDrawnFrom === key) thumbDrawnFrom = null;
+ });
+ }
+
+ $effect(() => {
+ const key = thumbKey();
+ const ready = doc.open && !!doc.name && !opening && piecesIn();
+ if (!ready || key === thumbDrawnFrom) return;
+ clearTimeout(thumbTimer);
+ thumbTimer = setTimeout(sendThumb, 1500);
+ });
+ $effect(() => () => {
+ if (thumbTimer) sendThumb();
+ });
+
// -- undo / redo ------------------------------------------------------------------
// Snapshots of the layout. A drag moves quads continuously; the debounced
// capture collapses it into one entry.
@@ -275,9 +348,14 @@
// -- opening ----------------------------------------------------------------------
function closeDoc() {
- docRun += 1;
- for (const url of blobs) URL.revokeObjectURL(url);
+ // A preview still waiting is drawn from the pieces as they are, so their
+ // pixels are let go only once it has them.
+ const drawing = thumbTimer ? sendThumb() : null;
+ const urls = [...blobs];
blobs.clear();
+ Promise.resolve(drawing).finally(() => urls.forEach((url) => URL.revokeObjectURL(url)));
+ thumbDrawnFrom = null;
+ docRun += 1;
Object.assign(doc, {
open: false, caseId: null, name: null, title: '', ...COLLAGE_DEFAULT_SIZE,
background: '#12141c', transparent: true, nodes: [], exported: null,
@@ -323,9 +401,13 @@
background: spec.background ?? '#12141c',
transparent: spec.transparent ?? true,
exported: spec.exported ?? null,
- nodes: (spec.nodes ?? []).map((n) => ({ ...n, url: null, baseUrl: null })),
+ // Marked lost up front, so the preview key reads as it did when last drawn.
+ nodes: (spec.nodes ?? []).map((n) => ({
+ ...n, url: null, baseUrl: null, missing: !mediaPaths.has(n.save?.path),
+ })),
});
savedSignature = signature();
+ if (collages.find((c) => c.name === saved.name)?.thumb) thumbDrawnFrom = thumbKey();
anchorHistory();
renderPieces(run);
} catch (e) {
@@ -459,7 +541,14 @@
titleField = doc.title;
});
- async function commitTitle() {
+ // A rename typed and left by clicking Close is still on its way when Close runs.
+ let renaming = null;
+ function commitTitle() {
+ renaming = renameTo().finally(() => (renaming = null));
+ return renaming;
+ }
+
+ async function renameTo() {
const next = titleField.trim();
if (!next || next === doc.title) {
titleField = doc.title;
@@ -493,18 +582,35 @@
}
}
+ // -- back to the list ---------------------------------------------------------------
+ // Everything is saved as it is made, so closing only waits for the last write. A
+ // write that failed keeps the collage open, where the header says so.
+ async function closeCollage() {
+ await renaming;
+ await autosave.flush();
+ if (autosave.state.status === 'error') {
+ toast('The collage could not be saved, so it stays open', 'warn');
+ return;
+ }
+ closeDoc();
+ query = '';
+ await refreshList();
+ }
+
// -- 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]) }));
+ // Always a transparent PNG of just the pieces, trimmed to their bounds and at
+ // the sharpest piece's own resolution, however small it sits on the canvas.
+ const f = exportFrame(doc.nodes);
+ const nodes = doc.nodes.map((n) => ({
+ src: n.save, quad: n.quad.map(([x, y]) => [(x - f.minX) * f.scale, (y - f.minY) * f.scale]),
+ }));
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,
+ width: f.width, height: f.height, background: null, nodes, folder, label: name, notes: note,
});
if (res?.item?.path) doc.exported = { path: res.item.path, signature: signatureNow };
await reloadCase();
@@ -544,24 +650,55 @@
<svelte:window onkeydown={onWindowKeydown} {onpagehide} />
-{#snippet list()}
+{#snippet filedMark(row)}
+ {#if row.filed}
+ <span class="filed" title="Its picture is in the case"><Icon name="check" size={10} /></span>
+ {/if}
+{/snippet}
+
+{#snippet list(grid = false)}
{#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>
+ <div class={grid ? 'cards' : 'rows'}>
+ {#each shownCollages as row (row.name)}
+ {@const meta = `${row.pieces} piece${row.pieces === 1 ? '' : 's'}${when(row.updated_at) ? ` · ${when(row.updated_at)}` : ''}`}
+ {#if grid}
+ <div class="card" class:current={row.name === doc.name}>
+ <button class="card-open" onclick={() => openCollage(row.name)}>
+ <span class="card-preview"><CollagePreview {row} caseId={caseState.current?.id} iconSize={28} /></span>
+ <span class="card-foot">
+ <span class="row-title">{row.title}</span>
+ {@render filedMark(row)}
+ </span>
+ <span class="row-meta">{meta}</span>
+ </button>
+ <button class="btn btn-ghost btn-xs card-delete" onclick={() => (deleting = row)} aria-label="Delete collage" title="Delete collage">
+ <Icon name="trash" size={14} />
+ </button>
+ </div>
+ {:else}
+ <div class="row" class:current={row.name === doc.name}>
+ <button class="row-open" onclick={() => openCollage(row.name)}>
+ <span class="row-preview"><CollagePreview {row} caseId={caseState.current?.id} iconSize={15} /></span>
+ <span class="row-title">{row.title}</span>
+ {@render filedMark(row)}
+ <span class="row-meta">{meta}</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>
+ {/if}
{/each}
</div>
+ {#if !shownCollages.length}
+ <p class="hint">No collage has “{query.trim()}” in its name.</p>
+ {/if}
+ {/if}
+{/snippet}
+
+{#snippet search()}
+ {#if collages.length > 1}
+ <SearchInput bind:value={query} placeholder="Search collages…" width="100%" />
{/if}
{/snippet}
@@ -591,12 +728,15 @@
<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">
+ <button class="btn btn-sm" onclick={() => { query = ''; 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>
+ <button class="btn btn-ghost btn-sm" onclick={closeCollage} title="Save and go back to the list">
+ <Icon name="x" size={14} /> Close
+ </button>
</div>
{/if}
@@ -618,7 +758,8 @@
{#if opening}
<span class="spinner" aria-label="Opening"></span>
{:else}
- {@render list()}
+ {@render search()}
+ {@render list(true)}
{/if}
</div>
</div>
@@ -641,7 +782,7 @@
/>
</div>
<div class="section">
- <CollageMenu collage={doc} bind:selectedIds {requestCrop} {renderPiece} />
+ <CollageMenu collage={doc} bind:selectedIds {requestCrop} {renderPiece} {fileTitles} />
</div>
<div class="section">
<SaveToCase
@@ -653,7 +794,7 @@
: 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."
+ hint={outputHint}
bind:folder={exportFolder}
onsave={exportCollage}
/>
@@ -673,7 +814,10 @@
{#if listOpen}
<Modal title="Collages" width="480px" onclose={() => (listOpen = false)}>
{#if collages.length}
- {@render list()}
+ <div class="modal-list">
+ {@render search()}
+ {@render list()}
+ </div>
{:else}
<p class="hint">No collage saved in this case yet.</p>
{/if}
@@ -781,7 +925,7 @@
align-items: center;
gap: 10px;
min-width: 0;
- padding: 9px 11px;
+ padding: 6px 11px 6px 6px;
text-align: left;
border: 1px solid var(--border);
border-radius: var(--r-md);
@@ -807,6 +951,85 @@
font-size: var(--fs-xs);
white-space: nowrap;
}
+ .modal-list {
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+ }
+ .row-preview {
+ flex-shrink: 0;
+ width: 56px;
+ height: 38px;
+ border-radius: var(--r-sm);
+ overflow: hidden;
+ }
+ /* The start page has the room to show what each collage holds. */
+ .cards {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
+ gap: 12px;
+ }
+ .card {
+ position: relative;
+ }
+ .card-open {
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ width: 100%;
+ height: 100%;
+ padding: 0 0 9px;
+ text-align: left;
+ border: 1px solid var(--border);
+ border-radius: var(--r-md);
+ background: var(--bg-2);
+ color: var(--text-2);
+ overflow: hidden;
+ }
+ .card-open:hover,
+ .card.current .card-open {
+ border-color: var(--accent);
+ }
+ .card-preview {
+ display: block;
+ aspect-ratio: 16 / 10;
+ min-height: 0;
+ border-bottom: 1px solid var(--border);
+ margin-bottom: 4px;
+ }
+ .card-foot {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ min-width: 0;
+ padding: 0 10px;
+ }
+ .card-open .row-meta {
+ padding: 0 10px;
+ }
+ .card-delete {
+ position: absolute;
+ top: 6px;
+ right: 6px;
+ background: var(--bg-1);
+ opacity: 0;
+ }
+ .card:hover .card-delete,
+ .card-delete:focus-visible {
+ opacity: 1;
+ }
+ /* Its picture is in the case: a small mark, since the list is about the layouts. */
+ .filed {
+ flex-shrink: 0;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 15px;
+ height: 15px;
+ border-radius: 50%;
+ background: var(--ok-soft);
+ color: var(--ok);
+ }
.spinner {
align-self: center;
width: 24px;
diff --git a/frontend/src/tools/Compare.note.test.js b/frontend/src/tools/Compare.note.test.js
new file mode 100644
index 0000000..a29b06e
--- /dev/null
+++ b/frontend/src/tools/Compare.note.test.js
@@ -0,0 +1,14 @@
+import { readFileSync } from 'node:fs';
+import { describe, expect, it } from 'vitest';
+
+/** What Compare hands the topbar's Add event: the pair's dates, read when it opens. */
+const source = readFileSync(new URL('./Compare.svelte', import.meta.url), 'utf8');
+
+describe('Add event over Compare', () => {
+ it('offers each picture’s day and the span between them, one press each', () => {
+ expect(source).toContain("offerNote('compare', null, {");
+ expect(source).toContain('const { a: first, b: second } = pictureDates();');
+ expect(source).toContain('return pairOffers(side(first), side(second), {');
+ expect(source).toContain("onDestroy(() => withdrawNote('compare'));");
+ });
+});
diff --git a/frontend/src/tools/Compare.svelte b/frontend/src/tools/Compare.svelte
index dc44e01..fc0fcf8 100644
--- a/frontend/src/tools/Compare.svelte
+++ b/frontend/src/tools/Compare.svelte
@@ -7,7 +7,7 @@
* analyst swap either side, then changes only how that pair is read. The provider, Wayback release and Sentinel-2 day belong to each
* MapSurface; the camera is the one shared fact.
*/
- import { onMount, tick, untrack } from 'svelte';
+ import { onDestroy, onMount, tick, untrack } from 'svelte';
import { api } from '../lib/api.js';
import {
caseState,
@@ -99,6 +99,8 @@
import { SENTINEL_ID, variantId } from '../lib/sentinel.js';
import { WAYBACK_ID, releaseYearBefore, waybackId } from '../lib/wayback.js';
import { RADAR_ID, radarId } from '../lib/radar.js';
+ import { offerNote, pairOffers, withdrawNote } from '../lib/noteHere.svelte.js';
+ import { changeInterval, formatTemporalValue } from '../lib/timeline.js';
import Icon from '../components/Icon.svelte';
import Compass from '../components/Compass.svelte';
import TurnGuide from '../components/TurnGuide.svelte';
@@ -109,6 +111,7 @@
import ModeControl from './compare/ModeControl.svelte';
import SourceCard from './compare/SourceCard.svelte';
import DifferenceBar from './compare/DifferenceBar.svelte';
+ import DifferencePanel from './compare/DifferencePanel.svelte';
import { fromDifference } from '../lib/map/analyzerRules.js';
import PassStrip from './compare/PassStrip.svelte';
import EvolutionPicker from './compare/EvolutionPicker.svelte';
@@ -225,6 +228,9 @@
let copernicus = $state(null);
// Highlights laid over whichever view mode is on, never a layout of their own.
let difference = $state(false);
+ // Its settings, docked on the stage's right edge; closed whenever Difference comes on.
+ let differenceOpen = $state(false);
+ const differenceDocked = $derived(both && difference && differenceOpen);
/** The surface the shared controls act on. */
const primeEngine = $derived(a.engine ?? b.engine);
@@ -883,6 +889,7 @@
return;
}
difference = on;
+ differenceOpen = false;
if (!on) return;
if (!changeStatus.methods.includes(changeOptions.method)) changeOptions.method = changeStatus.methods[0];
// Turning it on by hand asks for a reading, bands included. Queued behind
@@ -1083,6 +1090,7 @@
mode = compareMode(spec.mode);
// Difference used to be a mode of its own, laid over the pair side by side.
difference = spec.difference === true || spec.mode === 'change';
+ differenceOpen = false;
// A reopened session reads nothing it has not been asked to, bands included.
changeReadScope = '';
divider = percentage(spec.divider, DEFAULT_DIVIDER);
@@ -1955,12 +1963,35 @@
return { a: a.surface?.provenance?.() ?? {}, b: b.surface?.provenance?.() ?? {} };
}
+ // What the topbar's Add event offers here: each picture's day, and the span
+ // between them, read when the bar opens.
+ offerNote('compare', null, {
+ dates: () => {
+ const { a: first, b: second } = pictureDates();
+ const side = (picture) =>
+ picture.imageryWhen ? { value: picture.imageryWhen, exact: picture.imageryExact } : null;
+ return pairOffers(side(first), side(second), {
+ interval: changeInterval,
+ label: (value) => formatTemporalValue(value).label,
+ });
+ },
+ });
+ onDestroy(() => withdrawNote('compare'));
+
/** 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 });
}
+ /** Keep the colours visible in this comparison while the GIF is quantized. */
+ function gifKeepColours({ signed = false } = {}) {
+ return gifColours(annotations, {
+ signed,
+ changePalette: difference ? changeSettings(changeOptions).palette : null,
+ });
+ }
+
async function saveWorkingPreview(caseId, name) {
const form = new FormData();
// The saved image files the date of each picture it shows, as a capture does.
@@ -1974,7 +2005,7 @@
form.append('image_b', frameB, 'comparison-b.png');
form.append('format', 'blink');
form.append('interval', String(blinkInterval));
- form.append('keep', gifColours(annotations));
+ form.append('keep', gifKeepColours());
} else {
form.append('image_a', await comparisonBlob(), 'comparison.png');
form.append('format', 'png');
@@ -2010,7 +2041,7 @@
if (imageB) form.append('image_b', imageB, 'comparison-b.png');
form.append('format', format);
form.append('interval', String(blinkInterval));
- if (format !== 'png') form.append('keep', gifColours(annotations, { signed: signExport }));
+ if (format !== 'png') form.append('keep', gifKeepColours({ signed: signExport }));
form.append('filename', exportName());
form.append('spec', JSON.stringify(sessionSpec()));
for (const [field, value] of pictureDateFields(pictureDates())) form.append(field, value);
@@ -2068,7 +2099,7 @@
form.append('image_b', frameB, 'comparison-b.png');
form.append('animation', animation);
form.append('interval', String(blinkInterval));
- form.append('keep', gifColours(annotations, { signed: signExport }));
+ form.append('keep', gifKeepColours({ signed: signExport }));
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);
@@ -2401,6 +2432,7 @@
class:capturing={grabbing}
class:capture-a={captureSide === 'a'}
class:capture-b={captureSide === 'b'}
+ class:docked={differenceDocked}
style:--divider={`${divider}%`}
style:--opacity={opacity / 100}
style:--change-opacity={changeOpacity / 100}
@@ -2685,6 +2717,11 @@
{:else if changeCounts}<em>{changeShare(changeCounts)}% highlighted</em>{/if}
</div>
{/if}
+ {#if differenceDocked}
+ <DifferencePanel bind:settings={changeOptions} status={changeStatus} result={changeResult}
+ reading={changeState} error={changeError} onrun={() => refreshChangeAssist()} onzone={visitZone}
+ onanalyzer={saveAsAnalyzer} onclose={() => (differenceOpen = false)} />
+ {/if}
</div>
{#if both && stripOpen && archive}
@@ -2701,9 +2738,8 @@
<div class="mode-footer">
<ModeControl {mode} bind:divider bind:opacity bind:blinkB bind:blinkPaused bind:blinkInterval />
{#if difference}
- <DifferenceBar bind:settings={changeOptions} status={changeStatus} result={changeResult}
- reading={changeState} error={changeError}
- onrun={() => refreshChangeAssist()} onzone={visitZone} onanalyzer={saveAsAnalyzer} />
+ <DifferenceBar bind:settings={changeOptions} bind:open={differenceOpen} status={changeStatus}
+ reading={changeState} onrun={() => refreshChangeAssist()} />
{/if}
</div>
{/if}
@@ -3061,9 +3097,9 @@
.source-add:hover { color: var(--text-1); border-color: var(--accent); }
/* Lifted off the imagery, which can be as dark as the chips themselves. */
.source-bar :global(.cmp-glass) { box-shadow: var(--shadow-1); }
- .view-col { display: flex; flex-direction: column; align-items: flex-end; gap: 6px; margin-left: auto; pointer-events: none; }
+ .view-col { display: flex; flex-direction: column; align-items: flex-end; gap: 6px; max-width: 100%; margin-left: auto; pointer-events: none; }
.view-col > * { pointer-events: auto; }
- .search-chip { display: flex; width: min(280px, 24vw); padding: 4px; }
+ .search-chip { display: flex; width: min(280px, 24vw); max-width: 100%; padding: 4px; }
.search-chip :global(.place-search) { flex: 1; }
.camera-chip { display: flex; align-items: center; gap: 4px; padding: 0 0 0 8px; }
/* one frame for the pair; a turned camera still rings the compass in amber */
@@ -3073,8 +3109,7 @@
/* The dock is drawn for the map; in the header row its segments stand on
the row itself, not on a second frame. */
.tool-header :global(.mode-dock) { padding: 0; border: 0; background: transparent; box-shadow: none; }
- /* Above the stage, which keeps its map layers to itself (see .compare-stage),
- so the Difference panel opening upward lies over the highlights. */
+ /* Above the stage, which keeps its map layers to itself (see .compare-stage). */
.mode-footer { position: relative; z-index: 1; display: flex; flex-wrap: wrap; justify-content: center; align-items: center; gap: 8px; padding: 6px; background: var(--bg-1); }
.presets { display: flex; justify-content: center; gap: 8px; padding: 8px; }
.locked small { color: var(--accent); }
@@ -3118,6 +3153,7 @@
A and B is one line down the whole tool. */
.stage-column { display: flex; flex-direction: column; flex: 1; min-width: 0; min-height: 0; }
.compare-stage {
+ --difference-dock: clamp(290px, 24vw, 340px);
position: relative;
flex: 1;
min-height: 0;
@@ -3206,6 +3242,14 @@
font-size: 10px;
backdrop-filter: blur(6px);
}
+ /* Difference's settings dock on the right edge under the cards' row, so
+ what rides that corner steps aside rather than hiding under them, leaving
+ B's zoom buttons their column. */
+ .compare-stage.docked .view-col {
+ max-width: calc(100% - var(--difference-dock) - 48px);
+ margin-right: calc(var(--difference-dock) + 8px);
+ }
+ .compare-stage.docked .change-legend { right: calc(var(--difference-dock) + 20px); }
.change-legend span { display: flex; align-items: center; gap: 4px; }
.change-legend i { width: 9px; height: 9px; border-radius: 2px; }
.change-legend .gain { background: var(--gain); }
diff --git a/frontend/src/tools/Detect.svelte b/frontend/src/tools/Detect.svelte
index 56b78fc..789ba3e 100644
--- a/frontend/src/tools/Detect.svelte
+++ b/frontend/src/tools/Detect.svelte
@@ -22,7 +22,6 @@
import { blinkable } from '../lib/map/detectReview.js';
import { ADVISED_MAXCC } from '../lib/map/detectWhen.js';
import { DEFAULT_MAXCC } from '../lib/sentinel.js';
- import { insideBounds } from '../lib/map/analyzerRules.js';
import { DEFAULT_BLINK_INTERVAL } from '../lib/map/compare.js';
import { createImageryState } from './satellite/state/imagery.svelte.js';
import { createSentinelState } from './satellite/state/sentinel.svelte.js';
@@ -49,9 +48,11 @@
import AnalysisOverlay from './detect/AnalysisOverlay.svelte';
import DetectAreas from './detect/DetectAreas.svelte';
import DetectPanel from './detect/DetectPanel.svelte';
+ import CheckBench from './detect/CheckBench.svelte';
import CheckMarks from './detect/CheckMarks.svelte';
import RuleLayers from './detect/RuleLayers.svelte';
import RuleProbe from './detect/RuleProbe.svelte';
+ import SecondPass from './detect/SecondPass.svelte';
import './mapdock.css';
const SENTINEL = 'sentinel2';
@@ -68,6 +69,8 @@
let providerId = $state('esri-world-imagery');
let chosenBasemap = $state('esri-world-imagery');
let collapsed = $state(false);
+ let dockWidth = $state(380);
+ let savedDockWidth = $state(380);
let toolEl = $state(null);
let fullscreen = $state(false);
let overlays = $state(['boundaries', 'placenames']);
@@ -110,15 +113,21 @@
let drawing = $state('select');
let selectedZone = $state(null);
let layers = $state([]);
+ let focusedRunId = $state(null);
+ // Reviewing a run temporarily isolates it. The saved eye states stay intact
+ // and return as soon as the review closes.
+ const visibleRunLayers = $derived(focusedRunId
+ ? layers.filter((layer) => layer.id === focusedRunId).map((layer) => ({ ...layer, visible: true }))
+ : layers);
let showZones = $state(true);
let selectedResult = $state(null);
let areaGroups = $state([]);
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.
+ // An analyzer of your own being built (AnalyzerBuilder): the bench it keeps
+ // (lib/map/bench.svelte.js), which says what the map shows. 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
@@ -129,15 +138,36 @@
layersAsked = true;
untrack(() => s2.loadLayers(false, true));
});
- // While a check is open the map shows what the rules keep inside its frame only:
- // the check judges that ground, and paint past the frame read as it being off.
- const previewLayer = $derived(builder?.preview?.ready ? [{
+ // What the last test found, outlined and pinned on the ground it judged.
+ const previewLayer = $derived(builder?.detail ? [{
id: 'builder-preview', visible: true,
- input: { recipe: { colour: builder.colour, style: builder.style } },
- results: builder.preview.candidates
- .filter((row) => !builder.ground || insideBounds(row.coordinates, builder.ground.bounds))
- .map((row) => ({ ...row, review: 'new', phenomenon: builder.phenomenon })),
+ input: { recipe: { colour: builder.recipe.colour, style: builder.recipe.style } },
+ results: builder.detail.candidates.map((row) => ({ ...row, review: 'new', phenomenon: builder.recipe.phenomenon })),
}] : []);
+ const paintedRules = $derived(builder ? builder.recipe.rules.map((_, i) => builder.painted(i)) : []);
+ /** The pin the reading card was opened on, if it was opened on one. */
+ const probedPin = $derived.by(() => {
+ const at = builder?.probe?.pin;
+ const mark = at === null || at === undefined ? null : builder.marks[at];
+ return mark ? { number: at + 1, expect: mark.expect } : null;
+ });
+ // The passes the bench asks for go under the pins: the before pass (or the
+ // only one) on this map, the after pass on a second one laid over it.
+ $effect(() => {
+ const intent = builder?.imagery;
+ if (!intent) return;
+ untrack(() => {
+ if (intent.mode === 'basemap') leavePass();
+ else showDate(intent.mode === 'swipe' ? intent.a : intent.b);
+ });
+ });
+ const building = $derived(!!builder);
+ $effect(() => {
+ if (!building) return;
+ return () => untrack(() => leavePass());
+ });
+ let secondEngine = $state(null);
+ let secondElement = $state(null);
$effect(() => { manualTool = manual?.kind === 'polygon' ? 'polygon' : 'select'; });
// The ruler: measures drawn over the map, one armed at a time.
@@ -188,6 +218,7 @@
const mapDate = $derived(s2.date || '');
const passChip = $derived(providerId === RADAR_ID ? passLabel(s1.pass) : mapDate);
let passCloud = $state(null);
+ let passContext = $state(null);
const cloudyPass = $derived(providerId !== RADAR_ID && passCloud > ADVISED_MAXCC);
/**
* What Detect needs before a run can fetch anything: a Copernicus key, which
@@ -199,12 +230,16 @@
onMount(() => {
let gone = false;
+ const fitDock = () => (dockWidth = clampDock(savedDockWidth));
+ window.addEventListener('resize', fitDock);
void (async () => {
imagery.refreshUsage();
await prefsReady;
if (gone) return;
const saved = prefs.detectView;
collapsed = saved?.collapsed ?? false;
+ savedDockWidth = Math.max(300, Math.min(720, saved?.width ?? 380));
+ fitDock();
chosenBasemap = saved?.basemap && !PASSES.includes(saved.basemap) ? saved.basemap : 'esri-world-imagery';
providerId = chosenBasemap;
// Only the layers still offered: a retired one (Labels) would be sent back
@@ -225,16 +260,24 @@
if (gone) return;
if (!imagery.find(providerId)) providerId = 'esri-world-imagery';
})();
- return () => { gone = true; };
+ return () => { gone = true; window.removeEventListener('resize', fitDock); };
});
+ function dockMaximum() {
+ const available = toolEl?.clientWidth || window.innerWidth;
+ return Math.max(300, Math.min(720, available - 320));
+ }
+ function clampDock(width) { return Math.max(300, Math.min(dockMaximum(), Math.round(width))); }
+ function commitDockWidth() { savedDockWidth = dockWidth; }
+
$effect(() => {
if (!PASSES.includes(providerId)) chosenBasemap = providerId;
});
let lastPrefs = '';
$effect(() => {
if (!prefsLoaded) return;
- const value = { collapsed, basemap: chosenBasemap, overlays: [...overlays], saved: savedVisible };
+ const value = { collapsed, width: savedDockWidth, basemap: chosenBasemap,
+ overlays: [...overlays], saved: savedVisible };
const key = JSON.stringify(value);
if (!lastPrefs) { lastPrefs = key; return; }
if (key === lastPrefs) return;
@@ -245,6 +288,7 @@
$effect(() => {
collapsed;
fullscreen;
+ dockWidth;
void tick().then(() => engine?.resize());
});
@@ -262,19 +306,23 @@
let rotating = $state(null);
$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);
+ const surfaces = [[engine, element], ...(secondEngine && secondElement ? [[secondEngine, secondElement]] : [])];
+ const releases = surfaces.map(([surfaceEngine, surface]) => {
+ const down = (event) =>
+ turnFromPress(surfaceEngine, event, {
+ onPivot: (point) => (rotating = point),
+ onEnd: () => (rotating = null),
+ });
+ surface.addEventListener('mousedown', down, true);
+ return () => surface.removeEventListener('mousedown', down, true);
+ });
+ return () => releases.forEach((release) => release());
});
function onKey(event) {
if (uiState.tool !== 'detect') return;
// held down, the turn keeps going
if (turnFromKey(engine, event)) return;
+ if (event.key === 'Escape' && builder?.escape()) { event.preventDefault(); return; }
if (event.repeat || event.ctrlKey || event.metaKey || event.altKey
|| event.target?.closest?.('input, textarea, select, [contenteditable="true"]')) return;
if (event.key === ']') collapsed = !collapsed;
@@ -284,6 +332,13 @@
event.preventDefault();
}
+ /** A click on either map: a candidate to add, a pin to drop, or a point to read the rules at. */
+ function onMapClick({ lon, lat }) {
+ if (manual?.kind === 'point') void panel?.addManual({ type: 'Point', coordinates: [lon, lat] });
+ else if (builder?.pinning && !measuring) builder.dropPin({ lon, lat });
+ else if (builder && !measuring) void builder.probeAt({ lon, lat });
+ }
+
function armMeasure() {
drawing = 'select';
manual = null;
@@ -418,6 +473,7 @@
function leavePass() {
blinking = false;
readingPass = false;
+ passContext = null;
providerId = chosenBasemap;
}
@@ -526,8 +582,10 @@
* drop a cloudier tile and leave the map black. Its cloud, when the lookup
* knows it, rides on the chip.
*/
- function showDate({ provider, date, time, layer, cloud = null }) {
+ function showDate({ provider, date, time, layer, cloud = null, area = null, side = '' }) {
if (!date) { leavePass(); return; }
+ passContext = area && side ? { name: area.name, side } : null;
+ if (area) frame([area]);
passCloud = provider === RADAR_ID || !Number.isFinite(cloud) ? null : cloud;
if (provider === RADAR_ID) {
// A radar pass is shown by the radar basemap, once Settings has its layer.
@@ -585,38 +643,22 @@
/>
</div>
<div class="map-choices">
- <ImageryChip {imagery} bind:providerId {s2} {wayback} {s1} {shown} />
+ <!-- The passes under an analyzer being built are its check's (the console), so the provider is not offered. -->
+ {#if !builder}<ImageryChip {imagery} bind:providerId {s2} {wayback} {s1} {shown} />{/if}
<div class="layer-picker cmp-glass">
<MapLayers rows={layerRows} bind:open={layersOpen} />
</div>
- {#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}
+ <!-- While an analyzer is built, the console over the map holds its passes. -->
+ {#if blinkPair && !builder}
<!-- 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}
+ {:else if readingPass && !builder}
+ <button class="pass-chip cmp-glass" title="Return to your basemap" aria-label="Leave pass imagery" onclick={leavePass}>
+ {#if passContext}<strong>{passContext.name} · {passContext.side?.toUpperCase()}</strong>{/if}{passChip}
{#if cloudyPass}<span class="cloudy" title="Ground under cloud is left out of a run">{Math.round(passCloud)}% cloud</span>{/if}
<Icon name="x" size={12} /></button>
{/if}
@@ -652,11 +694,7 @@
resetToHome={false}
imperial={prefs.units === 'imperial'}
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 });
- }}
+ onclick={onMapClick}
controlsTop={108}
{alternate}
alternateOn={showingA}
@@ -664,25 +702,33 @@
onviewsettled={onSettled}
oncontextmenu={onMapContextMenu}
/>
+ {#if builder?.split}
+ <SecondPass {imagery} primary={engine} source={builder.imagery.b} {view} {bearing} {home} {overlays}
+ imperial={prefs.units === 'imperial'} armed={measuring ? 'measuring' : builder.pinning ? 'selecting' : null}
+ divider={builder.divider} bind:engine={secondEngine} bind:element={secondElement}
+ onsplit={(percent) => builder.setDivider(percent)} onclick={onMapClick} oncontextmenu={onMapContextMenu}
+ onusage={() => imagery.refreshUsage()} />
+ {/if}
{#if builder}
- <RuleLayers {engine} {element} preview={builder.preview} shown={builder.shown} hover={builder.hover}
- colours={builder.colours} within={builder.ground?.bounds ?? null} />
+ <RuleLayers {engine} {element} detail={builder.detail} rules={builder.recipe.rules} shown={paintedRules}
+ hover={builder.hovered} colours={builder.colours} split={builder.split} divider={builder.divider} stale={builder.stale} />
{#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] });
+ const row = builder.detail.candidates.find((candidate) => candidate.id === id);
+ if (row) void builder.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}
+ <CheckMarks {engine} pins={builder.pins} armed={!!builder.pinning} selected={builder.probe?.pin ?? null}
+ onpick={(index) => builder.probePin(index)} />
{#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} />
+ <RuleProbe {engine} probe={builder.probe} rules={builder.recipe.rules} colours={builder.colours} single={builder.single}
+ width={element?.clientWidth ?? 0} height={(element?.clientHeight ?? 0) - builder.reach} onclose={() => builder.closeProbe()}
+ onmark={(expect) => builder.markProbe(expect)} pin={probedPin}
+ onturn={() => { builder.flipPin(builder.probe.pin); builder.closeProbe(); }}
+ onremove={() => { builder.removePin(builder.probe.pin); builder.closeProbe(); }} />
{/if}
- {:else if savedVisible && !bare && layers.some((layer) => layer.visible)}
- <AnalysisOverlay {engine} {layers} selected={selectedResult} active={!manual}
+ {:else if !bare && (focusedRunId || savedVisible) && visibleRunLayers.some((layer) => layer.visible)}
+ <AnalysisOverlay {engine} layers={visibleRunLayers} selected={selectedResult} active={!manual}
onpick={(run, result) => panel?.pick(run, result)} />
{/if}
{#if areaGroups.length && !manual && !bare && !builder}
@@ -727,6 +773,9 @@
{#if rotating}
<TurnGuide x={rotating.x} y={rotating.y} />
{/if}
+ {#if builder}
+ <CheckBench bench={builder} />
+ {/if}
{#if needs}
<div class="need-over">
<CopernicusNeeded need={needs} tool="Detect" />
@@ -737,11 +786,6 @@
<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>
@@ -752,6 +796,10 @@
<DetectPanel
bind:this={panel}
bind:collapsed
+ {dockWidth}
+ maxDockWidth={dockMaximum}
+ onwidth={(value) => (dockWidth = clampDock(value))}
+ onwidthend={commitDockWidth}
{fullscreen}
onfullscreen={switchFullscreen}
bind:manual
@@ -760,6 +808,7 @@
bind:drawing
bind:selectedZone
bind:layers
+ bind:focusedRunId
bind:showZones
bind:selectedResult
bind:areaGroups
@@ -776,9 +825,7 @@
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))}
/>
@@ -802,12 +849,6 @@
.layer-picker :global(.layers) { min-width: 190px; margin-top: 8px; }
.ruler { position: absolute; top: 66px; left: 12px; z-index: 650; display: flex; padding: 2px; }
.blink-chip { padding: 2px 2px 2px 4px; }
- .bench-bar { gap: 4px; padding: 2px 2px 2px 4px; }
- .bench-bar .cmp-letter { cursor: pointer; }
- .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); }
.pass-chip .cloudy { color: var(--warn, #e2a03f); }
diff --git a/frontend/src/tools/Files.svelte b/frontend/src/tools/Files.svelte
index ca8e5bd..1a8bdf0 100644
--- a/frontend/src/tools/Files.svelte
+++ b/frontend/src/tools/Files.svelte
@@ -8,6 +8,7 @@
* The tree and the filing routing are the sidebar's own (lib/folderTree.js,
* lib/filing.js); the selection math is pure and unit-tested (lib/gridSelect.js).
*/
+ import { onDestroy } from 'svelte';
import { api } from '../lib/api.js';
import { fileUrl } from '../lib/fileUrl.js';
import { caseState, reloadCase, toast, uiState } from '../lib/state.svelte.js';
@@ -32,6 +33,7 @@
restoreGroup,
} from '../lib/trash.js';
import { createPagedList } from '../lib/pagedList.svelte.js';
+ import { offerNote, withdrawNote } from '../lib/noteHere.svelte.js';
import Icon from '../components/Icon.svelte';
import SearchInput from '../components/SearchInput.svelte';
import Modal from '../components/Modal.svelte';
@@ -322,6 +324,13 @@
anchor = null;
});
+ // What is open or alone-selected here is what the topbar's Add event seats.
+ $effect(() => {
+ const id = infoEntityId ?? (selected.length === 1 ? selected[0] : null);
+ offerNote('files', curEntities.find((e) => e.id === id) ?? null);
+ });
+ onDestroy(() => withdrawNote('files'));
+
function onTileClick(e, id) {
const r = toggleSelection(selected, id, { shift: e.shiftKey, meta: e.metaKey || e.ctrlKey }, entityOrder, anchor);
selected = r.selected;
diff --git a/frontend/src/tools/Files.test.js b/frontend/src/tools/Files.test.js
index d612995..a0591b2 100644
--- a/frontend/src/tools/Files.test.js
+++ b/frontend/src/tools/Files.test.js
@@ -196,3 +196,10 @@ describe('Files — acting on what the view actually shows', () => {
expect(source).not.toContain('const ents = confirmed.filter((e) => ids.includes(e.id));');
});
});
+
+describe('Files offers what is open to the Add event bar', () => {
+ it('publishes under its own tool id and withdraws on unmount', () => {
+ expect(source).toMatch(/offerNote\(\s*'files',/);
+ expect(source).toContain("onDestroy(() => withdrawNote('files'))");
+ });
+});
diff --git a/frontend/src/tools/Graph.svelte b/frontend/src/tools/Graph.svelte
index 7d84eea..2db5c2d 100644
--- a/frontend/src/tools/Graph.svelte
+++ b/frontend/src/tools/Graph.svelte
@@ -58,7 +58,8 @@
within,
zoomAround,
} from '../lib/graphViewport.js';
- import { tick, untrack } from 'svelte';
+ import { onDestroy, tick, untrack } from 'svelte';
+ import { offerNote, withdrawNote } from '../lib/noteHere.svelte.js';
import { api } from '../lib/api.js';
import {
analysisSearch,
@@ -139,6 +140,8 @@
ringsAround,
shortLabel,
} from '../lib/graph.js';
+ import { bidiIsolate } from '../lib/bidi.js';
+ import { foldText } from '../lib/textFold.js';
import { createHistory } from '../lib/history.js';
import { createBookmark } from '../lib/bookmarks.js';
import { windowWords } from '../lib/timeline.js';
@@ -151,7 +154,7 @@
import AnalysisPeriodBar from '../components/AnalysisPeriodBar.svelte';
import FilterBar from '../components/FilterBar.svelte';
import Modal from '../components/Modal.svelte';
- import QuickClaim, { claimSeat } from '../components/QuickClaim.svelte';
+ import EntryLine, { claimSeat } from '../components/EntryLine.svelte';
import { claimActionTitle } from '../lib/quickClaim.js';
import ConfirmDialog from '../components/ConfirmDialog.svelte';
import EntityCreate from '../components/EntityCreate.svelte';
@@ -601,6 +604,11 @@
const bends = $derived(parallelBends(edges));
const byId = $derived(new Map(nodes.map((node) => [node.id, node])));
const chosen = $derived(selected ? (byId.get(selected) ?? null) : null);
+ // The node open or selected here is what the topbar's Add event seats.
+ $effect(() => {
+ offerNote('graph', byId.get(openId ?? selected) ?? null);
+ });
+ onDestroy(() => withdrawNote('graph'));
const edgeById = $derived(new Map(edges.map((link) => [link.id, link])));
const chosenEdge = $derived(chosenLink ? (edgeById.get(chosenLink) ?? null) : null);
const snapshotReading = $derived(Boolean(catalogViews.snapshotId || payload?.snapshot));
@@ -908,11 +916,11 @@
* canvas is the reading.
*/
const found = $derived.by(() => {
- const term = find.trim().toLowerCase();
+ const term = foldText(find.trim());
const hit = new Set();
if (!term) return hit;
for (const node of nodes) {
- if (String(node.label).toLowerCase().includes(term)) hit.add(node.id);
+ if (foldText(node.label).includes(term)) hit.add(node.id);
}
return hit;
});
@@ -925,13 +933,13 @@
* first, so the obvious answer is the first one.
*/
const matches = $derived.by(() => {
- const term = find.trim().toLowerCase();
+ const term = foldText(find.trim());
if (!term) return [];
// Over what the case **sent**, not over what is drawn, so a folded node is found
// where it is rather than reported missing and fetched again. It says it is
// folded, and picking it gives its fold back.
return sentNodes
- .filter((node) => String(node.label).toLowerCase().includes(term))
+ .filter((node) => foldText(node.label).includes(term))
.sort((a, b) => b.degree - a.degree)
.slice(0, 8);
});
@@ -2945,7 +2953,7 @@
y: node.y + nodeRadius(data.degree) + 5,
width: 140,
align: 'center',
- text: shortLabel(data.label),
+ text: bidiIsolate(shortLabel(data.label)),
fontSize: 11,
fontFamily: fontStack,
listening: false,
@@ -5152,7 +5160,7 @@
drawing where the strips below describe one node in it. -->
<div class="from-board">
<Icon name="sliders" size={13} />
- <span>{fromBoard.label || 'A question from the Board'}</span>
+ <span>{fromBoard.label || 'A question from the case'}</span>
<button
class="as-link"
onclick={() => {
@@ -5791,7 +5799,7 @@
{#if seat}
<li>
<button onclick={() => chose((id) => (claimFor = byId.get(id) ?? null))} title={claimActionTitle(seat.slot)}>
- Add claim…
+ Add event…
</button>
</li>
{/if}
@@ -5927,8 +5935,8 @@
{/if}
{#if claimFor && !snapshotReading}
- <Modal title="New claim" onclose={() => (claimFor = null)} width="560px">
- <QuickClaim
+ <Modal title="Add event" onclose={() => (claimFor = null)} width="640px">
+ <EntryLine
caseId={caseState.current.id}
entity={claimFor}
onsaved={() => (claimFor = null)}
@@ -5956,6 +5964,7 @@
{#if snapshotOpen && snapshotReading}
<Modal title="Snapshot details" onclose={() => (snapshotOpen = null)} width="640px">
<SnapshotDetails
+ caseId={caseState.current?.id}
entity={snapshotOpen}
entities={catalogViews.activeView?.spec?.snapshot?.entities ?? []}
links={catalogViews.activeView?.spec?.snapshot?.links ?? []}
diff --git a/frontend/src/tools/Graph.test.js b/frontend/src/tools/Graph.test.js
index c6b03e8..7e259e6 100644
--- a/frontend/src/tools/Graph.test.js
+++ b/frontend/src/tools/Graph.test.js
@@ -381,7 +381,7 @@ describe('the interaction', () => {
// The teleport this guards: `rebuild` ends in `restyle`, which reads the
// selection — so the rebuild effect tracked hover, and every mouseover threw
// the view back to its starting transform.
- expect(source).toContain("import { tick, untrack } from 'svelte'");
+ expect(source).toContain("import { onDestroy, tick, untrack } from 'svelte'");
expect(source).toMatch(/void height;\s*untrack\(rebuild\);/);
});
@@ -1896,7 +1896,7 @@ describe('a question handed over by the Board', () => {
it('is announced over the drawing, with one press back to the case', () => {
// a picture that silently answers somebody else's question looks broken
expect(source).toContain('{#if fromBoard}');
- expect(source).toContain("fromBoard.label || 'A question from the Board'");
+ expect(source).toContain("fromBoard.label || 'A question from the case'");
expect(source).toContain('Show the whole case');
});
@@ -2138,11 +2138,18 @@ describe('filing a claim from a node', () => {
expect(source).toContain('{@const seat = claimSeat(at)}');
expect(source).toContain('chose((id) => (claimFor = byId.get(id) ?? null))');
expect(source).toContain('title={claimActionTitle(seat.slot)}');
- expect(source).toContain('Add claim…');
+ expect(source).toContain('Add event…');
});
it('opens the same form as Details and the Board, never over a snapshot', () => {
- expect(source).toContain("import QuickClaim, { claimSeat } from '../components/QuickClaim.svelte';");
+ expect(source).toContain("import EntryLine, { claimSeat } from '../components/EntryLine.svelte';");
expect(source).toContain('{#if claimFor && !snapshotReading}');
});
});
+
+describe('Graph offers what is open to the Add event bar', () => {
+ it('publishes under its own tool id and withdraws on unmount', () => {
+ expect(source).toMatch(/offerNote\(\s*'graph',/);
+ expect(source).toContain("onDestroy(() => withdrawNote('graph'))");
+ });
+});
diff --git a/frontend/src/tools/Inspector.svelte b/frontend/src/tools/Inspector.svelte
index 0d1f489..f8dbf58 100644
--- a/frontend/src/tools/Inspector.svelte
+++ b/frontend/src/tools/Inspector.svelte
@@ -1,4 +1,5 @@
<script>
+ import { onDestroy } from 'svelte';
import { api } from '../lib/api.js';
import { fileUrl } from '../lib/fileUrl.js';
import { caseState, uiState, reloadCase, toast } from '../lib/state.svelte.js';
@@ -12,6 +13,7 @@
import { createAutosave } from '../lib/autosave.svelte.js';
import { deletedToast } from '../lib/trash.js';
import { openInReverseSearch } from '../lib/navigate.js';
+ import { offerNote, withdrawNote } from '../lib/noteHere.svelte.js';
import Icon from '../components/Icon.svelte';
import Modal from '../components/Modal.svelte';
import ConfirmDialog from '../components/ConfirmDialog.svelte';
@@ -65,6 +67,18 @@
const videoFilters = $derived(filters.filter((f) => VIDEO_ADJUST_IDS.includes(f.id)));
const isVideo = $derived(work.source?.kind === 'video');
+
+ // The file open here is what the topbar's Add event seats.
+ $effect(() => {
+ const s = work.source;
+ offerNote(
+ 'inspect',
+ s?.entity_id
+ ? { id: s.entity_id, label: s.title ?? s.filename, type: 'media', attrs: { path: s.path, kind: s.kind } }
+ : null,
+ );
+ });
+ onDestroy(() => withdrawNote('inspect'));
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: '' });
diff --git a/frontend/src/tools/Inspector.test.js b/frontend/src/tools/Inspector.test.js
index c90f84c..636ae82 100644
--- a/frontend/src/tools/Inspector.test.js
+++ b/frontend/src/tools/Inspector.test.js
@@ -69,3 +69,10 @@ describe('Inspect — words', () => {
expect(markup).not.toContain('Discard');
});
});
+
+describe('Inspector offers what is open to the Add event bar', () => {
+ it('publishes under its own tool id and withdraws on unmount', () => {
+ expect(source).toMatch(/offerNote\(\s*'inspect',/);
+ expect(source).toContain("onDestroy(() => withdrawNote('inspect'))");
+ });
+});
diff --git a/frontend/src/tools/MediaLibrary.svelte b/frontend/src/tools/MediaLibrary.svelte
index 0c4e9b2..f2a7f86 100644
--- a/frontend/src/tools/MediaLibrary.svelte
+++ b/frontend/src/tools/MediaLibrary.svelte
@@ -1,7 +1,9 @@
<script>
+ import { onDestroy } from 'svelte';
import { api } from '../lib/api.js';
import { fileUrl } from '../lib/fileUrl.js';
import { lookupEntity } from '../lib/catalog.js';
+ import { offerNote, withdrawNote } from '../lib/noteHere.svelte.js';
import { buildMediaQuery } from '../lib/mediaQuery.js';
import { createPagedList } from '../lib/pagedList.svelte.js';
import { pollWhile } from '../lib/poll.js';
@@ -282,6 +284,19 @@
}
let infoItem = $state(null); // the media row behind the details modal, for Export
+ // What is open here is what the topbar's Add event seats: the picture in the
+ // lightbox, else the file whose Details are open.
+ $effect(() => {
+ const row = lightboxItem?.entity_id ? lightboxItem : infoEntityId && infoItem ? infoItem : null;
+ const id = row === infoItem ? infoEntityId : row?.entity_id;
+ offerNote(
+ 'media',
+ row && id
+ ? { id, label: row.title ?? row.filename, type: 'media', attrs: { path: row.path, kind: row.kind } }
+ : null,
+ );
+ });
+ onDestroy(() => withdrawNote('media'));
// Where a media copy lands, app-wide and remembered. Empty = the case folder.
let exportDir = $state('');
let exportPicker = $state(false);
diff --git a/frontend/src/tools/MediaLibrary.test.js b/frontend/src/tools/MediaLibrary.test.js
index dfa0b23..d954f90 100644
--- a/frontend/src/tools/MediaLibrary.test.js
+++ b/frontend/src/tools/MediaLibrary.test.js
@@ -503,3 +503,10 @@ describe('Media Library — broken thumbnails', () => {
expect(source).not.toContain('next.delete(path);');
});
});
+
+describe('MediaLibrary offers what is open to the Add event bar', () => {
+ it('publishes under its own tool id and withdraws on unmount', () => {
+ expect(source).toMatch(/offerNote\(\s*'media',/);
+ expect(source).toContain("onDestroy(() => withdrawNote('media'))");
+ });
+});
diff --git a/frontend/src/tools/Notebook.svelte b/frontend/src/tools/Notebook.svelte
index 8ed831d..dcc7376 100644
--- a/frontend/src/tools/Notebook.svelte
+++ b/frontend/src/tools/Notebook.svelte
@@ -1,6 +1,9 @@
<script>
+ import { onDestroy } from 'svelte';
import { api } from '../lib/api.js';
import { fetchAllEntities } from '../lib/catalog.js';
+ import { offerNote, withdrawNote } from '../lib/noteHere.svelte.js';
+ import { foldText } from '../lib/textFold.js';
import { caseState, uiState, toast, reloadCase } from '../lib/state.svelte.js';
import { entityReference, markdownHtml, remoteImageUrls } from '../lib/markdown.js';
import { drawMermaidDiagrams } from '../lib/mermaid.js';
@@ -79,6 +82,23 @@
// the case-open payload. Mention autocomplete inherently spans every entity, so
// it fetches the whole slice, but server-side and re-read on any change.
let graphEntities = $state([]);
+ let referenceRedirects = $state({});
+ $effect(() => {
+ const cid = caseState.current?.id;
+ caseState.rev;
+ const ids = [...new Set([...text.matchAll(/\[\[entity:([A-Za-z0-9_-]+)\|/g)].map((match) => match[1]))];
+ referenceRedirects = {};
+ if (!cid || !ids.length) return;
+ let live = true;
+ const batches = [];
+ for (let offset = 0; offset < ids.length; offset += 2000) {
+ batches.push(api.post(`/api/cases/${cid}/entities/redirects`, { ids: ids.slice(offset, offset + 2000) }));
+ }
+ Promise.all(batches).then((results) => {
+ if (live) referenceRedirects = Object.assign({}, ...results.map((result) => result.redirects));
+ }).catch(() => {});
+ return () => { live = false; };
+ });
$effect(() => {
const id = caseState.current?.id;
caseState.rev;
@@ -110,14 +130,19 @@
].filter((choice) => matchesTerms(`${choice.label} ${choice.folder}`, exportQuery)));
const referenceEntities = $derived(graphEntities
.filter((entity) => entity.provenance?.status !== 'suggested')
- .filter((entity) => `${entity.label} ${entity.type}`.toLowerCase().includes(referenceQuery.trim().toLowerCase()))
+ .filter((entity) => foldText(`${entity.label} ${entity.type}`).includes(foldText(referenceQuery.trim())))
.sort((a, b) => a.label.localeCompare(b.label)));
const caseMedia = $derived(graphEntities
.filter((entity) => (entity.type === 'media' || entity.type === 'capture') && entity.attrs?.path)
- .filter((entity) => `${entity.label} ${entity.attrs?.kind ?? ''}`.toLowerCase().includes(mediaQuery.trim().toLowerCase()))
+ .filter((entity) => foldText(`${entity.label} ${entity.attrs?.kind ?? ''}`).includes(foldText(mediaQuery.trim())))
.sort((a, b) => a.label.localeCompare(b.label)));
const activeTab = $derived(tabs.find((tab) => tab.id === activeId) ?? tabs[0] ?? null);
const noteId = $derived(activeTab?.noteId ?? null);
+ // The filed note open here is what the topbar's Add event seats; the case notes offer nothing.
+ $effect(() => {
+ offerNote('notebook', noteEntities.find((entity) => entity.id === noteId) ?? null);
+ });
+ onDestroy(() => withdrawNote('notebook'));
const title = $derived(noteId
? noteEntities.find((entity) => entity.id === noteId)?.label ?? 'Note'
: 'Case Notes');
@@ -126,7 +151,7 @@
: `/api/cases/${caseState.current?.id}/notes`);
const key = $derived(caseState.current?.id ? `${caseState.current.id}:${noteId ?? 'case'}` : '');
const preview = $derived(markdownHtml(text, {
- entities: graphEntities, caseId: caseState.current?.id ?? '',
+ entities: graphEntities, caseId: caseState.current?.id ?? '', redirects: referenceRedirects,
}));
const remoteImages = $derived(remoteImageUrls(text));
const saving = $derived(pendingSaves > 0);
diff --git a/frontend/src/tools/Notebook.test.js b/frontend/src/tools/Notebook.test.js
index 9cc8090..9d276e8 100644
--- a/frontend/src/tools/Notebook.test.js
+++ b/frontend/src/tools/Notebook.test.js
@@ -95,3 +95,10 @@ describe('Notebook — the debounced save and the export', () => {
expect(notebook).toMatch(/function cancelPendingSave\(\) \{[\s\S]*?pendingSave = null;/);
});
});
+
+describe('Notebook offers what is open to the Add event bar', () => {
+ it('publishes under its own tool id and withdraws on unmount', () => {
+ expect(source).toMatch(/offerNote\(\s*'notebook',/);
+ expect(source).toContain("onDestroy(() => withdrawNote('notebook'))");
+ });
+});
diff --git a/frontend/src/tools/Overview.render.test.js b/frontend/src/tools/Overview.render.test.js
index 3a2e688..a75d8a5 100644
--- a/frontend/src/tools/Overview.render.test.js
+++ b/frontend/src/tools/Overview.render.test.js
@@ -302,6 +302,8 @@ describe('with a case open', () => {
await pressRow('No date yet');
expect(setAnalysisFilter).not.toHaveBeenCalled();
expect(uiState.tool).toBe('timeline');
+ // and lands on the queue it counted, rather than on the axis
+ expect(uiState.timelineQueue).toBe('undated');
});
it('prefers the list stamp, which is recomputed off the database', async () => {
diff --git a/frontend/src/tools/Overview.svelte b/frontend/src/tools/Overview.svelte
index 82c3ef1..d72c879 100644
--- a/frontend/src/tools/Overview.svelte
+++ b/frontend/src/tools/Overview.svelte
@@ -96,7 +96,9 @@
async function load(id) {
const [counts, dates, newest, lately, points] = await Promise.allSettled([
api.get(`/api/cases/${id}/catalog/summary`),
- api.get(`/api/cases/${id}/timeline?limit=1`),
+ // Claims only: the Timeline this lands on opens on them, and a file's dates are
+ // never "waiting for a date".
+ api.get(`/api/cases/${id}/timeline?limit=1&category=statement`),
api.get(buildCatalogQuery(id, { limit: RECENT, order: '-created' })),
api.get(buildCatalogQuery(id, { limit: 1, since: weekAgo() })),
api.get(`/api/cases/${id}/satellite/media`),
@@ -142,9 +144,10 @@
uiState.tool = 'board';
}
- /** Hand a waiting row to whichever surface answers it. */
+ /** Hand a waiting row to whichever surface answers it, landed on what it counted. */
function ask(row) {
if (row.surface === 'timeline') {
+ uiState.timelineQueue = row.id;
uiState.tool = 'timeline';
return;
}
diff --git a/frontend/src/tools/PostComposer.defaultTemplate.render.test.js b/frontend/src/tools/PostComposer.defaultTemplate.render.test.js
new file mode 100644
index 0000000..f6bba29
--- /dev/null
+++ b/frontend/src/tools/PostComposer.defaultTemplate.render.test.js
@@ -0,0 +1,238 @@
+// @vitest-environment happy-dom
+/**
+ * The Post composer and the template a new post starts with, actually mounted.
+ *
+ * The rule is about timing more than layout: the template can be there before
+ * the composer, arrive after it, or be taken off by the analyst, and each of
+ * those has to leave the draft as the analyst would expect to find it.
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { flushSync, mount, unmount } from 'svelte';
+
+vi.mock('konva', () => ({ default: {} }));
+
+vi.mock('../lib/api.js', () => ({
+ api: {
+ get: vi.fn(async () => []),
+ put: vi.fn(async () => ({})),
+ post: vi.fn(async () => ({})),
+ del: vi.fn(async () => ({})),
+ },
+}));
+
+const { caseState, postDraftState, prefs, templatesState, uiState } = await import('../lib/state.svelte.js');
+const { default: PostComposer } = await import('./PostComposer.svelte');
+
+const HOUSE = {
+ id: 'po_1',
+ name: 'House style',
+ data: { mention: '@House', body: '#coordinates\n#mention', mediaEnabled: true, extraTweets: [] },
+};
+const OTHER = {
+ id: 'po_2',
+ name: 'Other style',
+ data: { mention: '', body: '#place', mediaEnabled: true, extraTweets: [] },
+};
+
+let target;
+let app;
+
+const mountComposer = () => {
+ target = document.createElement('div');
+ document.body.append(target);
+ app = mount(PostComposer, { target });
+ flushSync();
+};
+const settle = async () => {
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ flushSync();
+};
+const chip = () => target.querySelector('.tpl-loaded-name')?.textContent.trim() ?? null;
+const removeButton = () => target.querySelector('.tpl-remove');
+const description = () => target.querySelector('#pc-desc');
+const mentionField = () => target.querySelector('input[placeholder="@GeoConfirmed"]');
+const toasts = () => uiState.toasts.map((t) => t.message);
+
+beforeEach(() => {
+ prefs.postTemplate = '';
+ prefs.postMention = '@GeoConfirmed';
+ templatesState.post = [];
+ uiState.toasts.splice(0);
+ caseState.current = null;
+});
+
+afterEach(() => {
+ if (app) unmount(app);
+ target?.remove();
+ app = null;
+ prefs.postTemplate = '';
+ templatesState.post = [];
+ caseState.current = null;
+ uiState.toasts.splice(0);
+});
+
+describe('a blank composer', () => {
+ it('starts on the default template, without a toast', () => {
+ templatesState.post = [HOUSE, OTHER];
+ prefs.postTemplate = 'po_1';
+ mountComposer();
+
+ expect(chip()).toBe('House style');
+ expect(toasts()).toEqual([]);
+ expect(mentionField().value).toBe('@House'); // the template set it
+ });
+
+ it('starts classic when no default is set', () => {
+ templatesState.post = [HOUSE];
+ mountComposer();
+ expect(chip()).toBeNull();
+ expect(target.querySelector('#pc-tpl')).not.toBeNull(); // the picker, still offered
+ });
+
+ it('starts classic when the default names a template that is gone', () => {
+ templatesState.post = [OTHER];
+ prefs.postTemplate = 'po_gone';
+ mountComposer();
+ expect(chip()).toBeNull();
+ });
+
+ it('picks the template up when it arrives after the composer', async () => {
+ mountComposer();
+ expect(chip()).toBeNull();
+
+ prefs.postTemplate = 'po_1';
+ flushSync();
+ expect(chip()).toBeNull(); // the preference is here, the template is not yet
+ templatesState.post = [HOUSE];
+ await settle();
+
+ expect(chip()).toBe('House style');
+ expect(toasts()).toEqual([]);
+ });
+
+ it('follows a change of the default while it is still blank', async () => {
+ mountComposer();
+ templatesState.post = [HOUSE, OTHER];
+ prefs.postTemplate = 'po_2';
+ await settle();
+ expect(chip()).toBe('Other style');
+ });
+});
+
+describe('Remove', () => {
+ it('goes back to the classic layout and stays there', async () => {
+ templatesState.post = [HOUSE];
+ prefs.postTemplate = 'po_1';
+ mountComposer();
+ expect(mentionField().value).toBe('@House');
+
+ removeButton().click();
+ await settle();
+
+ expect(chip()).toBeNull();
+ expect(mentionField().value).toBe('@GeoConfirmed');
+ expect(target.querySelector('#pc-tpl')).not.toBeNull();
+ // changing what the effect reads must not put the template back
+ templatesState.post = [HOUSE, OTHER];
+ await settle();
+ expect(chip()).toBeNull();
+ });
+
+ it('does not make an empty composer look as if it held a post', async () => {
+ templatesState.post = [HOUSE];
+ prefs.postTemplate = 'po_1';
+ mountComposer();
+ removeButton().click();
+ await settle();
+
+ expect(postDraftState.fields).toBeNull();
+ expect([...target.querySelectorAll('.head-actions button')].map((b) => b.textContent.trim()))
+ .not.toContain('Discard');
+ });
+
+ it('is undone by the next blank draft, which starts on the default again', async () => {
+ templatesState.post = [HOUSE];
+ prefs.postTemplate = 'po_1';
+ caseState.current = { id: 'case-1', folders: [], entities: [] };
+ mountComposer();
+ await settle();
+ removeButton().click();
+ await settle();
+ expect(chip()).toBeNull();
+
+ caseState.current = { id: 'case-2', folders: [], entities: [] };
+ await settle();
+ expect(chip()).toBe('House style');
+ });
+});
+
+describe('a composer that holds a post', () => {
+ it('is left as it is when the default arrives late', async () => {
+ mountComposer();
+ description().value = 'A rooftop';
+ description().dispatchEvent(new Event('input', { bubbles: true }));
+ await settle();
+
+ templatesState.post = [HOUSE];
+ prefs.postTemplate = 'po_1';
+ await settle();
+
+ expect(chip()).toBeNull();
+ expect(description().value).toBe('A rooftop');
+ });
+
+ it('starts the next draft on the default once it is discarded', async () => {
+ templatesState.post = [HOUSE];
+ prefs.postTemplate = 'po_1';
+ mountComposer();
+ description().value = 'A rooftop';
+ description().dispatchEvent(new Event('input', { bubbles: true }));
+ await settle();
+
+ const discard = [...target.querySelectorAll('.head-actions button')]
+ .find((b) => b.textContent.trim() === 'Discard');
+ discard.click();
+ flushSync();
+ const confirm = [...document.querySelectorAll('[role="alertdialog"] button')]
+ .find((b) => b.textContent.trim() !== 'Cancel');
+ confirm.click();
+ await settle();
+
+ expect(description().value).toBe('');
+ expect(chip()).toBe('House style');
+ });
+});
+
+describe('the draft the template editor previews with', () => {
+ it('is nothing while the composer is empty', () => {
+ mountComposer();
+ expect(postDraftState.fields).toBeNull();
+ });
+
+ it('carries what the tokens stand for once the composer holds a post', async () => {
+ mountComposer();
+ description().value = 'A rooftop';
+ description().dispatchEvent(new Event('input', { bubbles: true }));
+ await settle();
+
+ expect(postDraftState.fields).toMatchObject({
+ description: 'A rooftop',
+ mention: '@GeoConfirmed',
+ place: '',
+ source: '',
+ date: '',
+ });
+ });
+
+ it('lets go when the composer goes', async () => {
+ mountComposer();
+ description().value = 'A rooftop';
+ description().dispatchEvent(new Event('input', { bubbles: true }));
+ await settle();
+ expect(postDraftState.fields).not.toBeNull();
+
+ unmount(app);
+ app = null;
+ expect(postDraftState.fields).toBeNull();
+ });
+});
diff --git a/frontend/src/tools/PostComposer.svelte b/frontend/src/tools/PostComposer.svelte
index d36c162..29175bf 100644
--- a/frontend/src/tools/PostComposer.svelte
+++ b/frontend/src/tools/PostComposer.svelte
@@ -1,9 +1,10 @@
<script>
+ import { untrack } from 'svelte';
import { api } from '../lib/api.js';
import { fileUrl } from '../lib/fileUrl.js';
import { fetchAllEntities, lookupEntity, fetchDerivation } from '../lib/catalog.js';
import { caseState, uiState, toast, reloadCase, prefs, updatesState } from '../lib/state.svelte.js';
- import { templatesState } from '../lib/state.svelte.js';
+ import { templatesState, postDraftState } from '../lib/state.svelte.js';
import { createNote } from '../lib/notes.js';
import { openNotebook } from '../lib/navigate.js';
import { deletedToast, RESTORABLE } from '../lib/trash.js';
@@ -19,7 +20,7 @@
normalizePostMediaPickerTarget, postMediaForType, renumberMediaTweetText, retargetMediaTweetText,
normalizePostTarget, POST_TARGETS, postCharacterCount, postComposeUrl, postReportMarkdown,
postTarget, templateUsesPostField, togglePostMedia, pointLines,
- handoffThread, postHandoffUrl,
+ handoffThread, postHandoffUrl, postDate,
} from '../lib/post.js';
import { extensionOutdated, extensionVersion, handOffPost } from '../lib/extBridge.js';
import { bidiSafe } from '../lib/bidi.js';
@@ -43,6 +44,13 @@
/** The Source box grows with what it holds, up to four lines: a proof read from a
* thread carries an address per post, and one row would hide all but the first. */
const sourceRows = $derived(Math.min(4, Math.max(1, source.split('\n').length)));
+ // The date the proof states, as the post carries it (lib/post.postDate). Only a
+ // template holding `#date` shows the field, so the classic thread never grows a
+ // date line nobody asked for.
+ let date = $state('');
+ // Set when the attached proof was read and states no date, so the empty field
+ // says why rather than looking forgotten.
+ let proofUndated = $state(false);
let proofPng = $state(null);
let proofVer = $state(0); // cache-buster: bumped whenever proofPng is (re)assigned
let tweet1 = $state('');
@@ -230,6 +238,8 @@
description = p.description?.trim()
? p.description.trim()
: (isDefaultName(p.title, 'proof') ? '' : (p.title ?? ''));
+ date = postDate(p.when, p.whenZone);
+ proofUndated = !date;
const proofSourceUrl = p.source ?? p.sources?.[0] ?? '';
source = proofSourceUrl;
setProof(p.png ?? null);
@@ -301,6 +311,7 @@
coordsText,
mention,
source,
+ date,
});
}
@@ -339,7 +350,9 @@
};
}
- function applyPostTemplate(t) {
+ // `quiet` is a blank composer starting on the default template: no toast, and
+ // nothing to rebuild since the draft holds no facts yet.
+ function applyPostTemplate(t, { quiet = false } = {}) {
// first apply snapshots the current structure; re-applying keeps that
// original, so Discard always returns to the pre-template layout.
const prev = appliedPostTemplate?.prev ?? snapshotPostStructure();
@@ -349,10 +362,24 @@
mediaEnabled = norm.mediaEnabled;
extraTweets = norm.extraTweets.map((e) => ({ id: ++extraSeq, ...e }));
appliedPostTemplate = { name: t.name, prev };
+ if (quiet) return;
if (!tweet1Edited) regenerate();
toast(`Template loaded: ${t.name}`, 'ok', 1400);
}
+ // A blank composer starts on the template chosen in Settings → Templates. One
+ // whose template was since deleted just starts classic. Remove opts this draft
+ // out, so the effect below never puts back what was taken off; the next blank
+ // draft starts on it again.
+ let defaultDeclined = false;
+
+ const defaultTemplate = () => templatesState.post.find((x) => x.id === prefs.postTemplate);
+
+ function startFromDefaultTemplate() {
+ const t = defaultTemplate();
+ if (t) applyPostTemplate(t, { quiet: true });
+ }
+
function applyPostFromSelect(e) {
const t = templatesState.post.find((x) => x.id === e.target.value);
e.target.value = '';
@@ -374,7 +401,8 @@
mediaTextIncludesPrefix: e.mediaTextIncludesPrefix === true,
}));
appliedPostTemplate = null;
- if (!tweet1Edited) regenerate();
+ defaultDeclined = true;
+ if (!tweet1Edited && tweet1.trim()) regenerate();
toast('Template removed', 'ok', 1200);
}
@@ -614,6 +642,10 @@
// Its sentence, once the spec is here. The picker row carries a filename
// and a thumbnail, so the title above was only ever a stand-in for this.
if (blank && spec.description?.trim()) description = spec.description.trim();
+ // The zone the date was stated in travels beside it, so a time reads on the
+ // clock of the place and a day stays that place's day.
+ date = postDate(spec.when, spec.whenZoneStated ?? spec.whenZone);
+ proofUndated = !date;
const src = proofSource(spec);
if (src) source = src;
await preloadProofMedia(item.png, src);
@@ -709,6 +741,7 @@
place,
mention,
source,
+ date,
proofPng,
tweet1,
tweet1Edited,
@@ -810,6 +843,8 @@
place = s.place ?? '';
mention = s.mention ?? prefs.postMention;
source = s.source ?? '';
+ date = typeof s.date === 'string' ? s.date : '';
+ proofUndated = false;
setProof(s.proofPng ?? null);
mediaEnabled = s.mediaEnabled ?? true;
mediaType = s.mediaType ?? 'none';
@@ -869,6 +904,8 @@
place = '';
mention = prefs.postMention;
source = '';
+ date = '';
+ proofUndated = false;
setProof(null);
tweet1 = '';
tweet1Edited = false;
@@ -882,12 +919,14 @@
draftName = null;
postName = freshPostName();
appliedPostTemplate = null;
+ defaultDeclined = false;
discardConfirm = false;
+ startFromDefaultTemplate();
}
const hasContent = $derived(
- !!(draftName || description.trim() || coordsText.trim() || mediaPaths.length || proofPng ||
- extraTweets.length || tweet1.trim())
+ !!(draftName || description.trim() || coordsText.trim() || date.trim() || mediaPaths.length ||
+ proofPng || extraTweets.length || tweet1.trim())
);
// Preferences can arrive after this tool mounts. A blank composer follows the
@@ -896,6 +935,26 @@
if (!hasContent) target = normalizePostTarget(prefs.postTarget);
});
+ // Templates and preferences can land after this tool mounts, so a blank
+ // composer picks the default template up when they do.
+ $effect(() => {
+ if (hasContent || appliedPostTemplate || defaultDeclined) return;
+ const t = defaultTemplate();
+ if (t) untrack(() => applyPostTemplate(t, { quiet: true }));
+ });
+
+ // The live draft, mirrored for Settings → Templates so a layout can be tried on
+ // the post that is open. Content only, and nothing while the composer is empty.
+ $effect(() => {
+ postDraftState.fields = hasContent
+ ? {
+ place, plusCode: geo?.plus_code, description, lat: geo?.lat, lon: geo?.lon,
+ coordsText, mention, source, date,
+ }
+ : null;
+ return () => (postDraftState.fields = null);
+ });
+
function reportAttachmentPaths() {
return [
proofPng,
@@ -1079,22 +1138,22 @@
{/if}
<div class="head-actions">
{#if caseState.current}
- <button class="btn btn-ghost btn-sm" onclick={openDraftList} title="Reopen a saved draft">
+ <button class="btn btn-sm" onclick={openDraftList} title="Reopen a saved draft">
<Icon name="folderOpen" size={14} /> Open
</button>
{/if}
{#if hasContent}
- <button class="btn btn-ghost btn-sm" onclick={() => (discardConfirm = true)} title="Clear this draft">
+ <button class="btn btn-sm" onclick={() => (discardConfirm = true)} title="Clear this draft">
<Icon name="reset" size={14} /> Discard
</button>
{/if}
- <button class="btn btn-ghost btn-sm" onclick={saveDraft} disabled={saving || !postName.trim()} title="Keep this thread to reopen and edit here">
+ <button class="btn btn-sm" onclick={saveDraft} disabled={saving || !postName.trim()} title="Keep this thread to reopen and edit here">
<Icon name="save" size={14} /> {draftName ? 'Save draft' : 'Save as draft'}
</button>
- <button class="btn btn-ghost btn-sm" onclick={openSaveReport} disabled={!hasContent || reportSaving} title="Write the finding up as a Notebook note">
+ <button class="btn btn-ok btn-sm" onclick={openSaveReport} disabled={!hasContent || reportSaving} title="Write the finding up as a Notebook note">
<Icon name="file" size={14} /> Save report
</button>
- <button class="btn btn-primary btn-sm" onclick={publish} disabled={!tweet1.trim()} title={`Copy posts and open ${targetInfo.label}`}>
+ <button class="btn btn-info btn-sm" onclick={publish} disabled={!tweet1.trim()} title={`Copy posts and open ${targetInfo.label}`}>
<Icon name="post" size={14} /> Publish on {targetInfo.label}
</button>
</div>
@@ -1182,6 +1241,23 @@
/>
</div>
+ {#if templateUsesPostField(body, 'date')}
+ <div class="field">
+ <label class="label" for="pc-date">Date</label>
+ <input
+ id="pc-date"
+ class="input"
+ placeholder="2025-10-24 14:30 UTC+3"
+ bind:value={date}
+ oninput={() => (proofUndated = false)}
+ onchange={regenerate}
+ />
+ {#if proofUndated && !date.trim()}
+ <p class="field-note">This proof has no date. Leave it empty and the line drops.</p>
+ {/if}
+ </div>
+ {/if}
+
<div
class="field"
class:template-disabled={fieldDisabledByTemplate('coordinates')}
@@ -1782,7 +1858,7 @@
.head-actions {
margin-left: auto;
display: flex;
- gap: 8px;
+ gap: 10px;
flex-shrink: 0;
}
@@ -1850,6 +1926,7 @@
color: var(--text-3);
line-height: 1.4;
}
+ .field-note { margin: 4px 0 0; font-size: var(--fs-xs); color: var(--text-3); }
.field.template-disabled {
opacity: 0.48;
cursor: not-allowed;
diff --git a/frontend/src/tools/PostComposer.test.js b/frontend/src/tools/PostComposer.test.js
index 091b84d..ef33227 100644
--- a/frontend/src/tools/PostComposer.test.js
+++ b/frontend/src/tools/PostComposer.test.js
@@ -219,3 +219,24 @@ describe('Post Composer — the sentence the proof carries', () => {
expect(source).toContain("if (blank && spec.description?.trim()) description = spec.description.trim();");
});
});
+
+describe('the date a proof states', () => {
+ it('shows a Date field only when the template holds #date', () => {
+ const field = source.slice(source.indexOf("{#if templateUsesPostField(body, 'date')}"));
+ expect(field).toContain('id="pc-date"');
+ expect(field).toContain('This proof has no date. Leave it empty and the line drops.');
+ });
+
+ it('reads it from the proof with the clock it was stated on', () => {
+ expect(source).toContain('date = postDate(spec.when, spec.whenZoneStated ?? spec.whenZone);');
+ expect(source).toContain('date = postDate(p.when, p.whenZone);');
+ });
+
+ it('keeps it with the draft and clears it with a fresh one', () => {
+ const snap = source.slice(source.indexOf('function snapshot()'), source.indexOf('function snapshot()') + 400);
+ expect(snap).toContain('date,');
+ expect(source).toContain("date = typeof s.date === 'string' ? s.date : '';");
+ const reset = source.slice(source.indexOf('function resetDraft()'));
+ expect(reset.slice(0, reset.indexOf('}\n'))).toContain("date = '';");
+ });
+});
diff --git a/frontend/src/tools/ProofComposer.svelte b/frontend/src/tools/ProofComposer.svelte
index 959db59..573efeb 100644
--- a/frontend/src/tools/ProofComposer.svelte
+++ b/frontend/src/tools/ProofComposer.svelte
@@ -1,5 +1,6 @@
<script>
- import { onMount, untrack } from 'svelte';
+ import { onDestroy, onMount, untrack } from 'svelte';
+ import { offerNote, withdrawNote } from '../lib/noteHere.svelte.js';
import { fileUrl } from '../lib/fileUrl.js';
import Konva from 'konva';
import { api } from '../lib/api.js';
@@ -10,11 +11,13 @@
// Reading a typed pair back into a point: the one parser the app has, and the
// one a coordinate row is written in (decimal, hemispheres, or DMS).
import { parseLatLon } from '../lib/sheetRoles.js';
+ import { zoneAt } from '../lib/localZone.js';
import { caseState, uiState, ensureCase, reloadCase, toast, prefs, fmtCoords } from '../lib/state.svelte.js';
import { templatesState } from '../lib/state.svelte.js';
import Icon from '../components/Icon.svelte';
import Modal from '../components/Modal.svelte';
import DateField from '../components/DateField.svelte';
+ import ClockField from '../components/ClockField.svelte';
import SearchInput from '../components/SearchInput.svelte';
import FolderBrowser from '../components/FolderBrowser.svelte';
import ConfirmDialog from '../components/ConfirmDialog.svelte';
@@ -125,6 +128,8 @@
// post is written from. '' → the panels answer for the date, nothing for the
// sentence.
when: '',
+ // The zone the date is read in: null is the first point's, resolved on save.
+ whenZone: null,
description: '',
// Case files the proof rests on without composing them, brought in from a stated
// source address. They join the chain on save, and the point with it.
@@ -162,6 +167,46 @@
// Saved proof slug, or null before the first save.
let savedName = $state(null);
let dirty = $state(false);
+
+ // ---- the clock the date is read on ---------------------------------------
+ // The first point is the conclusion, and footage is read on the clock of the
+ // place it shows, so that point's zone is the default. It is looked up only
+ // while a date is set, from the bundled boundaries (no network).
+ let pointZone = $state('');
+ const zonePointKey = $derived.by(() => {
+ if (!proof.when.trim()) return '';
+ const typed = String(specPoints(proof)[0]?.coords ?? '').trim();
+ if (typed) return typed;
+ const auto = autoCoords(proof.panels ?? []);
+ return auto ? `${auto.lat}, ${auto.lon}` : '';
+ });
+ $effect(() => {
+ const key = zonePointKey;
+ if (!key) {
+ pointZone = '';
+ return;
+ }
+ let live = true;
+ const timer = setTimeout(async () => {
+ try {
+ const where = parseLatLon(key) ?? (await api.post('/api/geo/parse', { text: key }));
+ const zone = await zoneAt({ lat: Number(where.lat), lon: Number(where.lon) });
+ if (live) pointZone = zone;
+ } catch {
+ if (live) pointZone = '';
+ }
+ }, 250);
+ return () => {
+ live = false;
+ clearTimeout(timer);
+ };
+ });
+ /** The clock the date reads on: the analyst's pick, else the point's, else UTC. A
+ * pick of the point's own row goes back to following the point. */
+ function pickClock(zone, { here }) {
+ proof.whenZone = here ? null : zone;
+ dirty = true;
+ }
// The document as it stands on disk, so an undo that walks all the way back
// to it can say the proof is saved again. null until a save or an open has
// put something there to match.
@@ -194,6 +239,12 @@
// reload elsewhere.
let proofEntities = $state([]);
let presentPaths = $state(new Set());
+ // The saved proof open here is what the topbar's Add event seats; an unsaved one offers nothing.
+ $effect(() => {
+ const spec = savedName ? specPath('proof', savedName) : null;
+ offerNote('proof', proofEntities.find((e) => e.attrs?.[specAttr('proof')] === spec) ?? null);
+ });
+ onDestroy(() => withdrawNote('proof'));
$effect(() => {
const id = caseState.current?.id;
caseState.rev;
@@ -376,6 +427,7 @@
proof.footerText = spec.footerText !== false;
proof.sources = statedSources(spec.sources ?? spec.source ?? null);
proof.when = typeof spec.when === 'string' ? spec.when : '';
+ proof.whenZone = typeof spec.whenZone === 'string' && spec.whenZone ? spec.whenZone : null;
proof.description = typeof spec.description === 'string' ? spec.description : '';
proof.material = normalizeMaterial(spec.material);
proof.captionSize = style.captionSize;
@@ -689,6 +741,7 @@
proof.points = [blankPoint()];
proof.sources = null;
proof.when = '';
+ proof.whenZone = null;
proof.description = '';
proof.material = [];
proof.captionSize = CAPTION_SIZE;
@@ -3836,6 +3889,9 @@
title: result.title,
// What the post is written from, when the proof carries one.
description: proof.description,
+ // The date and the clock the save read it on, for a post template with #date.
+ when: proof.when,
+ whenZone: result.when_zone ?? null,
// every point, one per line: the post cites the first and carries the rest
coordsText: coordsPostLines(proofCoordsLines(proof, prefs.coordFormat)).join('\n'),
source: displayedSource,
@@ -3946,6 +4002,7 @@
// sentence edited from Details opens here as the case's answer rather than as
// the copy this file was written with.
proof.when = typeof spec.when === 'string' ? spec.when : '';
+ proof.whenZone = typeof spec.whenZone === 'string' && spec.whenZone ? spec.whenZone : null;
proof.description = typeof spec.description === 'string' ? spec.description : '';
proof.material = normalizeMaterial(spec.material);
proof.captionSize = style.captionSize;
@@ -4750,9 +4807,27 @@
label="Date the material was taken"
placeholder="dd/mm/yyyy · Oct 2025 · ~2025"
calendar
+ zone={proof.whenZone || pointZone || null}
value={proof.when}
onchange={(value) => { proof.when = value; dirty = true; }}
/>
+ <!-- Which clock the date is read on. A day is that place's day, so the
+ default follows the first point and is named here rather than
+ assumed: without it the Timeline would put Kyiv's 12th on UTC's. -->
+ {#if proof.when.trim()}
+ <div class="when-zone">
+ <span class="when-zone-label">Clock</span>
+ <ClockField
+ value={proof.when}
+ clock={{ zone: proof.whenZone || pointZone || 'UTC', fixed: '' }}
+ here={pointZone ? [{ zone: pointZone, place: 'the point' }] : []}
+ onpick={pickClock}
+ />
+ {#if !proof.whenZone && !pointZone}
+ <p class="when-zone-note">No point yet, so the day is read in UTC.</p>
+ {/if}
+ </div>
+ {/if}
</div>
<ProofLayersPanel
@@ -5380,6 +5455,9 @@
padding: 12px;
}
.meta-field { margin-bottom: 10px; }
+ .when-zone { margin-top: 6px; display: grid; grid-template-columns: auto 1fr; align-items: center; gap: 4px 8px; }
+ .when-zone-label { font-size: var(--fs-xs); color: var(--text-3); }
+ .when-zone-note { grid-column: 2; margin: 0; font-size: var(--fs-xs); color: var(--text-3); }
.meta-head {
display: flex;
align-items: center;
diff --git a/frontend/src/tools/ProofComposer.test.js b/frontend/src/tools/ProofComposer.test.js
index 3b299e4..ae422ac 100644
--- a/frontend/src/tools/ProofComposer.test.js
+++ b/frontend/src/tools/ProofComposer.test.js
@@ -1272,6 +1272,24 @@ describe('Proof Composer — what the proof says about itself', () => {
it('hands the description to the post it opens', () => {
expect(source).toContain('description: proof.description,');
});
+
+ it('names the clock a date is read on, the first point\'s unless another is picked', () => {
+ const clock = side.slice(side.indexOf('<DateField'));
+ expect(clock).toContain('{#if proof.when.trim()}');
+ expect(clock).toContain("clock={{ zone: proof.whenZone || pointZone || 'UTC', fixed: '' }}");
+ expect(clock).toContain("here={pointZone ? [{ zone: pointZone, place: 'the point' }] : []}");
+ expect(clock).toContain('zone={proof.whenZone || pointZone || null}');
+ expect(clock).toContain('No point yet, so the day is read in UTC.');
+ // the point's own row goes back to following the point
+ expect(bodyOfFn('pickClock')).toContain('proof.whenZone = here ? null : zone;');
+ expect(source).toContain("await zoneAt({ lat: Number(where.lat), lon: Number(where.lon) })");
+ expect(bodyOfFn('resetDoc')).toContain('proof.whenZone = null;');
+ });
+
+ it('hands the date and its clock to the post it opens', () => {
+ expect(source).toContain('when: proof.when,');
+ expect(source).toContain('whenZone: result.when_zone ?? null,');
+ });
});
describe('Proof Composer — dating the material', () => {
@@ -1384,3 +1402,10 @@ describe('Proof Composer — numbered markers and blur boxes', () => {
expect(source).toContain('showStroke={!solidIconOnly && !strokeless}');
});
});
+
+describe('ProofComposer offers what is open to the Add event bar', () => {
+ it('publishes under its own tool id and withdraws on unmount', () => {
+ expect(source).toMatch(/offerNote\(\s*'proof',/);
+ expect(source).toContain("onDestroy(() => withdrawNote('proof'))");
+ });
+});
diff --git a/frontend/src/tools/Satellite.svelte b/frontend/src/tools/Satellite.svelte
index 7b572cd..ff6af34 100644
--- a/frontend/src/tools/Satellite.svelte
+++ b/frontend/src/tools/Satellite.svelte
@@ -1,5 +1,5 @@
<script>
- import { onMount, tick, untrack } from 'svelte';
+ import { onDestroy, onMount, tick, untrack } from 'svelte';
// The map is lib/map's: the engine, its layers, what is drawn on them and the
// drag gestures. Nothing in this file knows which engine that is — and the
// map itself is a surface (satellite/MapSurface.svelte), which is what lets a
@@ -38,6 +38,7 @@
import { assignFolder } from '../lib/filing.js';
import { saveRelation } from '../lib/relations.svelte.js';
import { openComparison, openEntity, openMapAt } from '../lib/navigate.js';
+ import { offerNote, withdrawNote } from '../lib/noteHere.svelte.js';
import { deletedToast, RESTORABLE } from '../lib/trash.js';
import { extensionVersion, mapLinkRelay, onActivated } from '../lib/extBridge.js';
import { SENTINEL_ID } from '../lib/sentinel.js';
@@ -2046,9 +2047,25 @@
else detailsEntityId = null;
}
+ let detailsTitle = '';
+
+ // The saved place open here, in its dialog or its Details, is what the topbar's
+ // Add event seats.
+ $effect(() => {
+ const id = placeModal?.id ?? detailsEntityId;
+ offerNote(
+ 'satellite',
+ id
+ ? { id, label: placeModal?.title ?? detailsTitle, type: 'place', attrs: {} }
+ : null,
+ );
+ });
+ onDestroy(() => withdrawNote('satellite'));
+
function openPlaceDetails() {
detailsDirty = false; // a fresh panel, whatever the last one was left holding
detailsEntityId = placeModal?.id ?? null;
+ detailsTitle = placeModal?.title ?? '';
placeModal = null;
}
@@ -2584,12 +2601,16 @@
<AddedLayers
rows={addedLayers.rows}
busy={addedLayers.busy}
+ refreshing={addedLayers.refreshing}
+ opened={addedLayers.justAdded}
bind:open={addedLayers.open}
search={addedLayers.search}
ontoggle={(row) => addedLayers.toggle(caseState.current?.id, row)}
oncategory={(row, name) =>
addedLayers.toggleCategory(caseState.current?.id, row, name)}
onrefresh={(row) => addedLayers.refresh(caseState.current?.id, row)}
+ onrefreshall={() => addedLayers.refreshAll(caseState.current?.id)}
+ onreorder={(names) => addedLayers.reorder(caseState.current?.id, names)}
onremove={(row) => (removingLayer = row)}
onpick={(row, hit) => addedLayers.pick(caseState.current?.id, row, hit)}
dates={addedLayers.dates}
diff --git a/frontend/src/tools/Satellite.test.js b/frontend/src/tools/Satellite.test.js
index bc1453b..ad29d98 100644
--- a/frontend/src/tools/Satellite.test.js
+++ b/frontend/src/tools/Satellite.test.js
@@ -902,3 +902,10 @@ describe('the right-click menu', () => {
expect(lookup.slice(0, 600)).toContain('if (mine !== pointLookupSeq || !pointMenu) return;');
});
});
+
+describe('Satellite offers what is open to the Add event bar', () => {
+ it('publishes under its own tool id and withdraws on unmount', () => {
+ expect(source).toMatch(/offerNote\(\s*'satellite',/);
+ expect(source).toContain("onDestroy(() => withdrawNote('satellite'))");
+ });
+});
diff --git a/frontend/src/tools/Settings.render.test.js b/frontend/src/tools/Settings.render.test.js
index ebaef2f..e6e7eae 100644
--- a/frontend/src/tools/Settings.render.test.js
+++ b/frontend/src/tools/Settings.render.test.js
@@ -10,6 +10,8 @@
*/
import { describe, expect, it, afterEach, beforeEach, vi } from 'vitest';
import { flushSync, mount, unmount } from 'svelte';
+import { api } from '../lib/api.js';
+import { prefs, templatesState } from '../lib/state.svelte.js';
// The template editors reach Konva through the composer; nothing here draws.
vi.mock('konva', () => ({ default: {} }));
@@ -55,6 +57,7 @@ function settingsBlob() {
home_view: { lat: 48.85, lon: 2.29, zoom: 12 },
post_mention: '',
post_target: 'x',
+ post_template: '',
update_check_on_start: true,
proof_place_auto: true,
};
@@ -176,3 +179,129 @@ describe('each section', () => {
expect(text).toContain('Report an issue');
});
});
+
+describe('post templates', () => {
+ const CLASSIC = {
+ id: 'po_1', name: 'Classic', data: { mention: '@House', body: '#place\n#mention', mediaEnabled: true, extraTweets: [] },
+ };
+ const SHORT = {
+ id: 'po_2', name: 'Short', data: { mention: '', body: '#coordinates', mediaEnabled: false, extraTweets: [{ text: 'Thread' }] },
+ };
+ const settle = () => new Promise((resolve) => setTimeout(resolve, 0));
+ const click = (el) => {
+ el.click();
+ flushSync();
+ };
+ const row = (name) =>
+ [...pane().querySelectorAll('.tpl-row')].find((r) => r.querySelector('.tpl-name').textContent === name);
+ const inRow = (name, text) =>
+ [...row(name).querySelectorAll('button')].find((b) => b.textContent.trim() === text);
+ const editor = () => document.querySelector('.tpl-modal');
+ const startFrom = () => editor().querySelector('.starters');
+
+ beforeEach(async () => {
+ // the shell asked for the templates and the settings as it mounted
+ await settle();
+ templatesState.post = [CLASSIC, SHORT];
+ api.put.mockImplementation(async (path, patch) => ({ ...settingsBlob(), ...patch }));
+ api.put.mockClear();
+ api.post.mockClear();
+ api.del.mockClear();
+ rail()[TABS.indexOf('templates')].click();
+ flushSync();
+ });
+
+ afterEach(() => {
+ if (editor()) click(editor().querySelector('.btn-ghost:not(.btn-sm)')); // Cancel
+ api.put.mockImplementation(async () => settingsBlob());
+ templatesState.proof = [];
+ templatesState.post = [];
+ prefs.postTemplate = '';
+ });
+
+ it('offers starting layouts for a new template, and not for one that exists', () => {
+ click(pane().querySelectorAll('.group')[1].querySelector(':scope > button'));
+ expect(startFrom()).not.toBeNull();
+ click(editor().querySelector('.btn-ghost:not(.btn-sm)')); // Cancel
+
+ click(inRow('Classic', 'Edit'));
+ expect(editor()).not.toBeNull();
+ expect(startFrom()).toBeNull();
+ });
+
+ it('opens a copy of a template under its own name, to be saved as a new one', async () => {
+ click(inRow('Short', 'Duplicate'));
+
+ expect(editor().querySelector('.tpl-title').value).toBe('Short copy');
+ expect(editor().querySelector('textarea.body').value).toBe('#coordinates');
+ expect(startFrom()).toBeNull(); // a copy is not a blank start
+ expect(api.post).not.toHaveBeenCalled(); // nothing is stored until Save
+
+ click([...editor().querySelectorAll('button')].find((b) => b.textContent.includes('Save template')));
+ await settle();
+ expect(api.post).toHaveBeenCalledWith('/api/templates/post', {
+ id: null,
+ name: 'Short copy',
+ data: SHORT.data,
+ });
+ });
+
+ it('leaves the original alone when the copy is edited and dropped', async () => {
+ click(inRow('Classic', 'Duplicate'));
+ const body = editor().querySelector('textarea.body');
+ body.value = 'changed';
+ body.dispatchEvent(new Event('input', { bubbles: true }));
+ await settle(); // the textarea binding reads its value back one tick later
+ click(editor().querySelector('.btn-ghost:not(.btn-sm)'));
+
+ expect(editor()).toBeNull();
+ expect(CLASSIC.data.body).toBe('#place\n#mention');
+ });
+
+ it('keeps a copied name inside the length a template may have', () => {
+ templatesState.post = [{ ...CLASSIC, name: 'n'.repeat(120) }];
+ flushSync();
+ click(inRow('n'.repeat(120), 'Duplicate'));
+ expect(editor().querySelector('.tpl-title').value).toBe('n'.repeat(120));
+ });
+
+ it('saves the template new posts start with, and shows it', async () => {
+ row('Short').querySelector('button[aria-pressed]').click();
+ await settle();
+ flushSync();
+ expect(api.put).toHaveBeenCalledWith('/api/settings/prefs', { post_template: 'po_2' });
+ expect(prefs.postTemplate).toBe('po_2');
+ expect(row('Short').querySelector('.tpl-tag').textContent).toBe('Default');
+ expect(row('Classic').querySelector('.tpl-tag')).toBeNull();
+
+ row('Short').querySelector('button[aria-pressed]').click();
+ await settle();
+ flushSync();
+ expect(api.put).toHaveBeenLastCalledWith('/api/settings/prefs', { post_template: '' });
+ expect(prefs.postTemplate).toBe('');
+ });
+
+ it('forgets the default when that template is deleted', async () => {
+ prefs.postTemplate = 'po_2';
+ flushSync();
+ click(row('Short').querySelector('button[title="Delete"]'));
+ click([...document.querySelectorAll('[role="alertdialog"] button')].find((b) => b.textContent.trim() === 'Delete'));
+ await settle();
+
+ expect(api.del).toHaveBeenCalledWith('/api/templates/post/po_2');
+ expect(api.put).toHaveBeenCalledWith('/api/settings/prefs', { post_template: '' });
+ expect(prefs.postTemplate).toBe('');
+ });
+
+ it('keeps the default when another template is deleted', async () => {
+ prefs.postTemplate = 'po_2';
+ flushSync();
+ click(row('Classic').querySelector('button[title="Delete"]'));
+ click([...document.querySelectorAll('[role="alertdialog"] button')].find((b) => b.textContent.trim() === 'Delete'));
+ await settle();
+
+ expect(api.del).toHaveBeenCalledWith('/api/templates/post/po_1');
+ expect(api.put).not.toHaveBeenCalled();
+ expect(prefs.postTemplate).toBe('po_2');
+ });
+});
diff --git a/frontend/src/tools/Settings.svelte b/frontend/src/tools/Settings.svelte
index 6cc8552..833e295 100644
--- a/frontend/src/tools/Settings.svelte
+++ b/frontend/src/tools/Settings.svelte
@@ -712,7 +712,9 @@
// ---- reusable templates (proof house style + post thread) ----------------
// One editor draft at a time. `editing` = { kind, id|null, name, data }; a
- // fresh id is null until first save. Content-free presets, workspace-level.
+ // fresh id is null until first save, and `fresh` marks a blank new template
+ // (a duplicate has no id either, yet is not one). Content-free presets,
+ // workspace-level.
let editing = $state(null);
let savingTpl = $state(false);
let deleteTpl = $state(null); // { kind, id, name } pending confirmation
@@ -722,7 +724,7 @@
}
function newTemplate(kind) {
- editing = { kind, id: null, name: '', data: freshTemplate(kind) };
+ editing = { kind, id: null, name: '', data: freshTemplate(kind), fresh: true };
}
function editTemplate(kind, rec) {
@@ -732,6 +734,17 @@
editing = { kind, id: rec.id, name: rec.name, data: JSON.parse(JSON.stringify(rec.data)) };
}
+ // A copy opens unsaved under a new name, so the original is never touched and
+ // Cancel leaves nothing behind. The server's per-kind cap answers on save.
+ function duplicateTemplate(kind, rec) {
+ editing = {
+ kind,
+ id: null,
+ name: `${rec.name} copy`.slice(0, 120),
+ data: JSON.parse(JSON.stringify(rec.data)),
+ };
+ }
+
function cancelEdit() {
editing = null;
}
@@ -764,6 +777,7 @@
try {
await deleteTemplate(t.kind, t.id);
if (editing?.kind === t.kind && editing?.id === t.id) editing = null;
+ if (t.kind === 'post' && prefs.postTemplate === t.id) await savePrefs({ post_template: '' });
toast(`Deleted "${t.name}"`, 'info');
} catch (e) {
toast(e.message, 'danger');
@@ -958,7 +972,7 @@
{/if}
{#if tab === 'templates'}
- <TemplatesTab {newTemplate} {editTemplate} bind:deleteTpl />
+ <TemplatesTab {newTemplate} {editTemplate} {duplicateTemplate} {savePrefs} bind:deleteTpl />
{/if}
</div>
</div>
@@ -989,7 +1003,7 @@
{#if editing.kind === 'proof'}
<ProofTemplateEditor bind:data={editing.data} />
{:else}
- <PostTemplateEditor bind:data={editing.data} />
+ <PostTemplateEditor bind:data={editing.data} fresh={editing.fresh === true} />
{/if}
</div>
<div class="tpl-modal-foot">
diff --git a/frontend/src/tools/Timeline.svelte b/frontend/src/tools/Timeline.svelte
index 36aabbc..6532ca6 100644
--- a/frontend/src/tools/Timeline.svelte
+++ b/frontend/src/tools/Timeline.svelte
@@ -1,6 +1,6 @@
<script>
/** A windowed UTC axis over the case's derived temporal projection. */
- import { untrack } from 'svelte';
+ import { tick, untrack } from 'svelte';
import { api } from '../lib/api.js';
import {
openAnalysisCase,
@@ -12,6 +12,7 @@
import { caseState, reloadCase, toast, uiState } from '../lib/state.svelte.js';
import { entityLabel, entityTypes, loadEntityTypes } from '../lib/entityTypes.svelte.js';
import {
+ MARKS,
TIMELINE_CATEGORIES,
UTC,
WINDOW_SPANS,
@@ -21,10 +22,12 @@
axisTicks,
bucketWindow,
canDragTemporal,
+ cardTop,
dateAtRatio,
describePair,
draftWhen,
formatTemporalValue,
+ temporalZoneWords,
initialWindow,
inputWindowValue,
isoInstant,
@@ -48,8 +51,8 @@
windowMillis,
windowWords,
zoneAbbreviation,
+ zoneWords,
zonedFields,
- zonedStamp,
zoomWindow,
} from '../lib/timeline.js';
import {
@@ -61,15 +64,31 @@
timelineTrack,
timelineTrackQuery,
timelineViewState,
+ holdsBackWorkingFiles,
+ drawsFiles,
+ situatedFile,
+ mediaTrack,
+ withWorkingFiles,
trackPresets,
trackTint,
} from '../lib/timelineTracks.js';
+ import { chronologyBlock, chronologyMarkdown, chronologyRows, readChronology } from '../lib/timelineCopy.js';
+ import { provenance } from '../lib/sheetExport.js';
+ import { fileUrl } from '../lib/fileUrl.js';
+ import { caseZone, clockReading, rememberClock, rememberedClock } from '../lib/caseClock.js';
+ import { fitBands, fitSlots, fitTicks, overviewNeeded } from '../lib/timelineFit.js';
import { plateFilename } from '../lib/plate.js';
import { PLATE_PLOT, timelinePlate } from '../lib/timelinePlate.js';
import AnalysisViews from '../components/AnalysisViews.svelte';
import PlateExport from '../components/PlateExport.svelte';
import ConfirmDialog from '../components/ConfirmDialog.svelte';
import EntityDetails from '../components/EntityDetails.svelte';
+ import MediaPreview from '../components/MediaPreview.svelte';
+ import DateField from '../components/DateField.svelte';
+ import ClockField from '../components/ClockField.svelte';
+ import { clockOf, isTimed, settleClock, writesOwnClock } from '../lib/clock.js';
+ import { noteAxisZone } from '../lib/caseAxis.svelte.js';
+ import EntryLine from '../components/EntryLine.svelte';
import Icon from '../components/Icon.svelte';
import Modal from '../components/Modal.svelte';
import TemporalClaimEditor from '../components/TemporalClaimEditor.svelte';
@@ -82,8 +101,10 @@
let trackPages = $state({});
let groupBy = $state('none');
let trackEditor = $state(null);
- let trackMenu = $state(false);
- let trackMenuElement = $state(null);
+ /** The bar's `⋯`: tracks, grouping, the period handed to another tool, the legend and
+ * full screen. Asked for rarely, so kept out of the way of the axis. */
+ let moreMenu = $state(false);
+ let moreElement = $state(null);
let draggedTrack = null;
let selectedTrackId = $state(null);
let from = $state('');
@@ -108,23 +129,26 @@
*/
let against = $state(null);
/**
- * Which clock the axis is *read* on: `utc`, `machine`, or `place:<id>` for the
- * local time at a point the case has saved.
+ * Which clock the axis is *read* on: `case`, `utc`, `machine`, `zone:<IANA>`, or
+ * `place:<id>` for the local time at a point the case has saved.
*
* The case is stored in UTC and stays there (`lib/timeline.js`): this moves the
- * ticks and their words, nothing else. UTC is the default because it is the one
- * reading that means the same thing on every machine — and it is the wrong reading
- * for the work, because an investigator argues in the local time of the *event*,
- * and checking a 19:40 timestamp against a clock in the analyst's own country is
- * how an hour goes missing.
+ * ticks and their words, nothing else. It opens on `case`, the zone most of the
+ * case's places stand in (`lib/caseClock.js`), because an investigator argues in the
+ * local time of the *event*: checking a 19:40 timestamp against UTC, or against a
+ * clock in the analyst's own country, is how an hour goes missing. A case with no
+ * placed point reads UTC, the one reading that means the same thing everywhere. The
+ * clock picked is kept per case.
*
- * A saved point is that reading, and it is the only one that can carry the daylight
- * ribbon with it: a band of day and night needs coordinates, so it arrives with the
- * zone rather than being a second control.
+ * A saved point is the same reading narrowed to one place, and the only one that can
+ * carry the daylight ribbon with it: a band of day and night needs coordinates, so it
+ * arrives with the zone rather than being a second control.
*/
- let zoneChoice = $state('utc');
+ let zoneChoice = $state('case');
/** The case's saved points, for that menu. Bounded like every other list here. */
let places = $state([]);
+ /** The zone most of those points stand in, `{ zone, count, of }`, or null. */
+ let caseClock = $state(null);
/** `{ zone, day, civil, truncated }` for the chosen point over the visible window. */
let daylight = $state(null);
let daylightLoading = $state(false);
@@ -132,15 +156,72 @@
let editor = $state(null);
let detailsId = $state(null);
let entityFilter = $state(null);
+ /** The entity the reading was scoped from, whole, so the entry line can seat it.
+ * A saved view only keeps the scope's id and label, and then nothing is seated. */
+ let scopedEntity = $state(null);
+ /** A file the line was asked for from (its entry picked, then Add pressed), seated
+ * with its own dates offered one press each. It follows the pick: another entry
+ * picked, and the line goes back to the one it had. */
+ let lineFile = $state(null);
+ const lineEntity = $derived(
+ scopedEntity && scopedEntity.id === entityFilter?.id ? scopedEntity : lineFile
+ );
+ let entryLine = $state(null);
+ // The topbar's Add event, pressed on the Timeline, is its own line under the axis,
+ // about the file whose entry is picked when there is one.
+ let lineFocusSeen = uiState.timelineLineFocus;
+ $effect(() => {
+ const asked = uiState.timelineLineFocus;
+ if (asked === lineFocusSeen) return;
+ lineFocusSeen = asked;
+ if (!snapshotReading) untrack(() => focusLine());
+ });
+
+ /** Go to the line, seated on the picked entry's file if it has one. */
+ function focusLine() {
+ const file = previewEntity;
+ lineFile = file ? { id: file.id, label: file.label, type: file.type, attrs: file.attrs ?? {} } : null;
+ void tick().then(() => entryLine?.focus());
+ }
+
+ // Another entry picked, and a file seated for the last one lets go of the line.
+ $effect(() => {
+ const picked = previewEntity?.id ?? null;
+ untrack(() => {
+ if (lineFile && lineFile.id !== picked) lineFile = null;
+ });
+ });
let viewMode = $state('plot');
let expandedTracks = $state({});
let toolElement = $state(null);
let fullscreen = $state(false);
- let legendElement = $state(null);
- let legendOpen = $state(false);
let rangeElement = $state(null);
let rangeMenu = $state(false);
let plotElement = $state(null);
+ let axisCardElement = $state(null);
+ let listPane = $state(null);
+ /** The entry under the pointer, on the axis or in the list: the other one lights it. */
+ let hovered = $state(null);
+ /**
+ * How much of the room below the overview the axis takes; the list has the rest.
+ *
+ * The two are one reading, so both are always there. `view_mode` from a saved view
+ * says which of them it favours, and dragging the bar between them moves it for now
+ * without rewriting what the view says.
+ */
+ const SHARES = { plot: 0.62, list: 0.28 };
+ let axisShare = $state(SHARES.plot);
+ let chronologyHeight = $state(0);
+ let overviewHeight = $state(0);
+ let splitting = null;
+ let copyMenu = $state(false);
+ let copyMenuElement = $state(null);
+ let copying = $state(false);
+ /** How many file dates the tracks leave out, said when nothing is on the axis. */
+ let fileDates = $state(0);
+ let undatedOpen = $state(true);
+ let undatedElement = $state(null);
+ let landOnUndated = $state(false);
let plotWidth = $state(1000);
let overviewWidth = $state(800);
let tooltip = $state(null);
@@ -169,18 +250,29 @@
const minorTicks = $derived(axisMinorTicks(from, to, plotWidth, zone));
const bands = $derived(axisBands(from, to, plotWidth, zone));
const nowLeft = $derived(nowPosition(from, to));
+ /**
+ * An event on the Media lane, drawn as the file it dates: the file's name and its
+ * picture, where the analyst put it. The row stays the event's, so picking it opens
+ * the event and moving it moves the event's date (`drawsFiles`).
+ */
+ function asFile(item) {
+ const file = situatedFile(item);
+ return file ? { ...item, label: file.label || item.label, thumb: file.thumb ?? '', statement: item.label, asFile: true } : item;
+ }
const baseTrackItems = $derived(Object.fromEntries(
trackSpecs.map((track) => [
track.id,
(trackPages[track.id]?.items ?? [])
.filter((item) => !track.hidden.includes(item.id))
- .map((item) => ({ ...item, pinned: track.pinned.includes(item.id) })),
+ .map((item) => ({ ...(drawsFiles(track) ? asFile(item) : item), pinned: track.pinned.includes(item.id) })),
])
));
const visibleItems = $derived.by(() => {
const unique = new Map();
for (const rows of Object.values(baseTrackItems)) {
- for (const item of rows) unique.set(item.id, item);
+ // The list reads an event as its sentence: a row drawn as its file on the Media
+ // lane gives way to the same row on any other lane.
+ for (const item of rows) if (!unique.has(item.id) || unique.get(item.id).asFile) unique.set(item.id, item);
}
return [...unique.values()];
});
@@ -214,8 +306,12 @@
* packs lanes by the room a label takes in pixels: it is the width that decides which
* entries collide, how many lanes a track needs and what ends up in a `+n`. The screen
* asks at the width it measured, the export at the plate's own.
+ *
+ * The selected entry is captioned first on screen, so the one being read is never the
+ * one left without its name. A plate is not being read by anyone yet, so it asks for
+ * no selection and comes out the same whatever was clicked.
*/
- function buildTracks(axisWidth) {
+ function buildTracks(axisWidth, selectedId = null) {
return groupedTimelineTracks(trackSpecs, baseTrackItems, groupBy, entityLabel).map((track) => {
const baseId = track.parentId ?? track.id;
const expanded = Boolean(expandedTracks[baseId]);
@@ -225,16 +321,13 @@
total: groupBy === 'none' ? (trackPages[baseId]?.total ?? track.items.length) : track.items.length,
layout: layoutTimelineItems(
track.items.filter((item) => item.earliest), from, to, axisWidth,
- expanded ? PAGE : 6
+ expanded ? PAGE : 6, { selectedId }
),
};
});
}
- const tracks = $derived(buildTracks(plotWidth));
+ const tracks = $derived(buildTracks(plotWidth, selected?.id ?? null));
const density = $derived(layoutDensityBuckets(overview, extent));
- const overviewUnit = $derived(
- { 13: 'Hour', 10: 'Day', 7: 'Month' }[overview[0]?.start?.length] ?? 'Year'
- );
/**
* The date scale under the minimap: one slot per period, named under its own bar.
*
@@ -243,7 +336,13 @@
* wide one half empty.
*/
const overviewTicks = $derived(densityTicks(overview, extent, overviewWidth));
- const selectedReading = $derived(formatTemporalValue(selected?.raw ?? ''));
+ const selectedReading = $derived(formatTemporalValue(selected?.raw ?? '', selected?.tz));
+ /** Whether an entry names an instant, which can be read on the axis's clock. A day
+ * has no hour, and printing 00:00 in another zone would invent one. */
+ function instantOnClock(item) {
+ return zone !== UTC && Boolean(item?.earliest) && ['second', 'subsecond'].includes(item?.precision);
+ }
+ const onClock = $derived(instantOnClock(selected));
const selectedTrack = $derived(trackSpecs.find((track) => track.id === selectedTrackId) ?? null);
const inspectorConnections = $derived.by(() => {
const grouped = { about: [], at: [], cites: [] };
@@ -258,9 +357,62 @@
}
return grouped;
});
+ /**
+ * The file an entry is about, shown at the top of the inspector: the file itself
+ * for a file's date, then the file an event is about, then the first one it cites.
+ * Seeing it is what a click on a dated file is most often for, and it used to cost
+ * Details, then the file. `about` comes first because a proof's date is stated
+ * *about* the footage and *cites* the proof: the video is what was dated.
+ */
+ const PREVIEWS = new Set(['media', 'capture']);
+ const previewEntity = $derived.by(() => {
+ if (!selected) return null;
+ const own = inspectorChain?.entity;
+ if (own?.id === selected.owner_id && PREVIEWS.has(own.type)) return own;
+ const out = (inspectorChain?.relations ?? []).filter(
+ (row) => row.direction === 'out' && PREVIEWS.has(row.entity?.type)
+ );
+ const file = out.find((row) => row.link?.type === 'about') ?? out.find((row) => row.link?.type === 'cites');
+ return file?.entity ?? null;
+ });
+ /** The picture the row already carried, drawn before the file is known. */
+ const previewThumb = $derived(selected?.category === 'media' ? selected.thumb ?? '' : '');
+
+ /** What the list reads: the dated entries the window holds, the same page as the axis. */
+ const windowItems = $derived(axisWindow
+ ? dated.filter((item) => Date.parse(item.earliest) < axisWindow.end
+ && Date.parse(item.latest ?? item.earliest) >= axisWindow.start)
+ : dated);
+ /** The whole-case strip, only once the window leaves part of the case out
+ * (`lib/timelineFit.js`). Under the axis, so the axis does not move when it comes. */
+ const overviewShown = $derived(overviewNeeded(extent, axisWindow));
+ const overviewRoom = $derived(overviewShown ? overviewHeight : 0);
+ // The strip's height comes out of the list, not the axis: the lanes being read keep
+ // their room when the window is zoomed and the strip arrives.
+ const axisMax = $derived(Math.max(150, Math.round((chronologyHeight - 130) * axisShare)));
+ /** Names on the ruler and the strip, each kept only where it fits. */
+ const tickNames = $derived(fitTicks(ticks, plotWidth));
+ const bandNames = $derived(fitBands(bands, plotWidth));
+ const overviewNames = $derived(fitSlots(overviewTicks, overviewWidth));
+ /**
+ * The list's link columns, only those some entry of the window fills: three empty
+ * columns under `Subjects · Places · Sources` were most of a file date's row.
+ */
+ const listColumns = $derived({
+ subjects: windowItems.some((item) => item.subject_entities?.length),
+ places: windowItems.some((item) => item.place_entities?.length),
+ sources: windowItems.some((item) => item.source_entities?.length),
+ });
+ const listTemplate = $derived([
+ '150px', 'minmax(200px, 3fr)',
+ ...(listColumns.subjects ? ['minmax(70px, 1.1fr)'] : []),
+ ...(listColumns.places ? ['minmax(60px, .9fr)'] : []),
+ ...(listColumns.sources ? ['minmax(70px, 1.1fr)'] : []),
+ 'minmax(90px, auto)',
+ ].join(' '));
const listGroups = $derived.by(() => {
const groups = new Map();
- for (const item of [...dated].sort((a, b) => String(a.earliest).localeCompare(String(b.earliest)))) {
+ for (const item of [...windowItems].sort((a, b) => String(a.earliest).localeCompare(String(b.earliest)))) {
const date = new Date(item.earliest);
// Grouped by the month the reading falls in, so the list and the axis agree
// about which month an entry near a midnight belongs to.
@@ -295,6 +447,7 @@
);
const zone = $derived.by(() => {
if (frozenZone && knownZone(frozenZone)) return frozenZone;
+ if (zoneChoice === 'case') return caseClock && knownZone(caseClock.zone) ? caseClock.zone : UTC;
if (zoneChoice === 'machine') return knownZone(localZone) ? localZone : UTC;
// A zone named outright: the investigation is at the other end of the world and
// the case has no saved point there yet. It carries no coordinates, so it labels
@@ -307,6 +460,10 @@
const named = daylight?.zone?.name;
return named && knownZone(named) ? named : UTC;
});
+ // A date typed anywhere in the case opens on the clock the axis reads on.
+ $effect(() => {
+ if (!snapshotReading) noteAxisZone(caseState.current?.id, zone);
+ });
/** What one tick is worth, and which clock is being read. */
const zoneWord = $derived(
zone === UTC ? 'UTC' : zoneAbbreviation(zone, axisWindow?.start ?? 0)
@@ -324,10 +481,6 @@
const twilightBands = $derived(
sunPlace && !daylight?.truncated ? ribbonBands(daylight?.civil ?? [], from, to) : []
);
- const scaleLabel = $derived.by(() => {
- const unit = axisScale(from, to, plotWidth);
- return unit ? `${unit} · ${zoneWord}` : zoneWord;
- });
/** The machine's own zone is offered rather than assumed: it is a legitimate
* reading of a working day and a poor default. */
const localZone = machineZone();
@@ -345,7 +498,71 @@
return () => observer.disconnect();
});
- $effect(() => trackMenu ? closeOnOutsidePointer(trackMenuElement, () => (trackMenu = false)) : undefined);
+ $effect(() => moreMenu ? closeOnOutsidePointer(moreElement, () => (moreMenu = false)) : undefined);
+ $effect(() => copyMenu ? closeOnOutsidePointer(copyMenuElement, () => (copyMenu = false)) : undefined);
+
+ // A saved view's mode says which half it favours; applying one moves the bar there.
+ $effect(() => {
+ axisShare = SHARES[viewMode] ?? SHARES.plot;
+ });
+
+ // Nothing on these tracks: say how many dates the files carry that they leave out,
+ // from one bounded read, so the empty axis is not mistaken for an empty case. With
+ // a Media track that holds back working files and an empty axis, every file date
+ // left is one of those.
+ const mediaTracks = $derived(trackSpecs.filter((track) => track.categories.includes('media')));
+ const workingFilesHeld = $derived(mediaTracks.length > 0 && mediaTracks.every(holdsBackWorkingFiles));
+ $effect(() => {
+ const caseId = caseState.current?.id;
+ const empty = !extent?.from && !loading;
+ const open = mediaTracks.length > 0 && !workingFilesHeld;
+ void caseState.rev;
+ if (!caseId || !empty || open || snapshotReading) {
+ fileDates = 0;
+ return;
+ }
+ let live = true;
+ api.get(`/api/cases/${caseId}/timeline?category=media&include_undated=false&limit=1`)
+ .then((page) => { if (live) fileDates = Number(page?.total ?? 0); })
+ .catch(() => { if (live) fileDates = 0; });
+ return () => { live = false; };
+ });
+
+ // The Overview's "No date yet" lands on the queue it counted, open. A Claim opened
+ // from elsewhere lands on its own entry in the queue that holds it.
+ $effect(() => {
+ const asked = uiState.timelineQueue;
+ if (!asked) return;
+ uiState.timelineQueue = null;
+ const queue = typeof asked === 'string' ? asked : asked.queue;
+ if (queue === 'undated') {
+ undatedOpen = true;
+ landOnUndated = true;
+ }
+ if (typeof asked === 'object' && asked.itemId) handOverSelection(asked.itemId, false, asked.item);
+ });
+
+ $effect(() => {
+ if (!landOnUndated || loading) return;
+ const queue = undatedElement;
+ if (!queue) {
+ // Given up only once the tracks have answered and hold nothing undated.
+ if (Object.keys(trackPages).length && !undatedTotal) landOnUndated = false;
+ return;
+ }
+ landOnUndated = false;
+ // After the axis and the list have taken their measured room, and after the second
+ // read the window's first setting starts: landing before it would scroll to where
+ // the queue was, not to where it ends up.
+ requestAnimationFrame(() => requestAnimationFrame(() => {
+ if (loading) {
+ landOnUndated = true;
+ return;
+ }
+ queue.scrollIntoView({ block: 'start' });
+ queue.querySelector('.holding-list button')?.focus({ preventScroll: true });
+ }));
+ });
$effect(() => rangeMenu ? closeOnOutsidePointer(rangeElement, () => (rangeMenu = false)) : undefined);
$effect(() => {
@@ -355,7 +572,6 @@
return () => document.removeEventListener('fullscreenchange', changed);
});
- $effect(() => legendOpen ? closeOnOutsidePointer(legendElement, () => (legendOpen = false)) : undefined);
$effect(() => itemMenu ? closeOnOutsidePointer(itemMenuElement, () => (itemMenu = null)) : undefined);
function overviewQuery(track, { densityBucket = 'year' } = {}) {
@@ -672,7 +888,7 @@
items = [];
trackSpecs = defaultTimelineTracks();
groupBy = 'none';
- zoneChoice = 'utc';
+ zoneChoice = rememberedClock(caseState.current?.id);
from = '';
to = '';
entityFilter = null;
@@ -737,7 +953,8 @@
trackSpecs = defaultTimelineTracks();
trackPages = {};
groupBy = 'none';
- zoneChoice = 'utc';
+ zoneChoice = rememberedClock(caseId);
+ caseClock = null;
selected = null;
pendingSelection = null;
cursor = null;
@@ -792,7 +1009,22 @@
/** A point no longer in the case cannot go on labelling the axis. */
$effect(() => {
- if (zoneChoice.startsWith('place:') && places.length && !sunPlace) zoneChoice = 'utc';
+ if (zoneChoice.startsWith('place:') && places.length && !sunPlace) zoneChoice = 'case';
+ });
+
+ /** Where the case is: the zone its points stand in, read once they are listed. */
+ $effect(() => {
+ const caseId = caseState.current?.id;
+ const points = places;
+ if (!caseId || !points.length) {
+ caseClock = null;
+ return;
+ }
+ let live = true;
+ caseZone(points)
+ .then((found) => { if (live && caseState.current?.id === caseId) caseClock = found; })
+ .catch(() => { if (live) caseClock = null; });
+ return () => { live = false; };
});
/**
@@ -839,10 +1071,37 @@
* given — no load follows, and a selection waiting for one would never arrive. What
* is already drawn answers in that case.
*/
- function handOverSelection(itemId) {
+ /**
+ * A row handed over from elsewhere is a file's date or a filing more often than one
+ * would think — Details' Time tab, a mark on the map. The track that holds such a row
+ * is added before it is looked for, or the hand-over would land on nothing, and a
+ * working file is let back onto the Media track that holds them back: a frame of the
+ * person the reading is about is not the person, so the focus does not bring it.
+ */
+ function ensureTrackFor(itemId, producedHere = false) {
+ const category = String(itemId ?? '').startsWith('temporal:media:') ? 'media'
+ : String(itemId ?? '').startsWith('temporal:activity:') ? 'case_activity'
+ : null;
+ if (!category || snapshotReading) return;
+ const holding = trackSpecs.filter((track) => track.categories.includes(category));
+ if (category === 'media' && producedHere && holding.length && holding.every(holdsBackWorkingFiles)) {
+ trackSpecs = trackSpecs.map((track) => (track.id === holding[0].id ? withWorkingFiles(track) : track));
+ return;
+ }
+ if (holding.length) return;
+ trackSpecs = [
+ ...trackSpecs,
+ category === 'media'
+ ? mediaTrack(trackSpecs, { collectedOnly: !producedHere })
+ : timelineTrack({ id: 'activity', label: 'Case activity', categories: ['case_activity'] }, trackSpecs.length),
+ ];
+ }
+
+ function handOverSelection(itemId, producedHere = false, fallback = null) {
+ ensureTrackFor(itemId, producedHere);
const held = itemId ? items.find((item) => item.id === itemId) : null;
selected = held ?? selected;
- pendingSelection = itemId && !held ? { id: itemId } : null;
+ pendingSelection = itemId && !held ? { id: itemId, ...(fallback ? { fallback } : {}) } : null;
}
$effect(() => {
@@ -852,15 +1111,18 @@
if (!windowMillis(range.from, range.to)) return;
from = range.from;
to = range.to;
- handOverSelection(range.itemId);
+ handOverSelection(range.itemId, false, range.item);
});
$effect(() => {
const focus = uiState.timelineFocus;
if (!focus) return;
entityFilter = { id: focus.entityId, label: focus.entityLabel || 'Selected entity' };
+ scopedEntity = focus.entityType
+ ? { id: focus.entityId, label: focus.entityLabel, type: focus.entityType, attrs: focus.entityAttrs ?? {} }
+ : null;
selected = null;
- handOverSelection(focus.itemId);
+ handOverSelection(focus.itemId, focus.producedHere === true);
from = '';
to = '';
uiState.timelineFocus = null;
@@ -959,7 +1221,8 @@
.map((category) => TIMELINE_CATEGORIES.find((entry) => entry.id === category)?.short ?? category)
.join(' · ');
const asked = track.query?.label?.trim();
- return [track.label, [words, asked || 'the whole case'].join(' · ')].join('\n');
+ const held = holdsBackWorkingFiles(track) ? 'working files held back' : '';
+ return [track.label, [words, asked || 'the whole case', held].filter(Boolean).join(' · ')].join('\n');
}
/** A span asked for by name. Absolute where a zoom step is relative: "Week" is the
@@ -972,11 +1235,14 @@
expandedTracks = { ...expandedTracks, [id]: expanded };
}
+ /** What a file lane holds, said where it is added. */
+ const FILE_LANE_NOTES = { sources: 'your files, where dated', imagery: 'satellite · Compare · Detect' };
+
function addPreset(preset) {
const duplicate = copyTimelineTrack(preset, trackSpecs);
const used = trackSpecs.some((track) => track.label.toLocaleLowerCase() === preset.label.toLocaleLowerCase());
trackSpecs = [...trackSpecs, { ...duplicate, label: used ? duplicate.label : preset.label }];
- trackMenu = false;
+ moreMenu = false;
}
function saveTrack(track) {
@@ -1066,7 +1332,9 @@
* *while* reading one entry — a "compare" button would be a state to enter, leave
* and forget you were in. Ctrl-clicking the held entry again lets it go.
*/
- function selectItem(item, trackId = null, event = null) {
+ function selectItem(picked, trackId = null, event = null) {
+ // A file on the Media lane is its event: the panel reads the event, the file on top.
+ const item = picked?.asFile ? pageItems.find((row) => row.id === picked.id) ?? picked : picked;
if ((event?.ctrlKey || event?.metaKey) && selected && selected.id !== item.id) {
against = against?.id === item.id ? null : item;
return;
@@ -1150,7 +1418,7 @@
function drawStart(event, trackId) {
const track = trackSpecs.find((entry) => entry.id === trackId);
if (
- snapshotReading || !track?.categories.includes('statement') ||
+ snapshotReading || !track?.categories.includes('statement') || drawsFiles(track) ||
event.button !== 0 || event.target.closest('button')
) return;
const rect = event.currentTarget.getBoundingClientRect();
@@ -1159,8 +1427,54 @@
event.currentTarget.setPointerCapture(event.pointerId);
}
+ /** A date offered from the axis goes to the entry line, which is where the rest
+ * of the entry is written. */
+ function offerDate(when) {
+ if (snapshotReading) return;
+ entryLine?.offer(when);
+ }
+
function createFromKeyboard() {
- openEditor(null, draftWhen(from, to, .5, .5));
+ offerDate(draftWhen(from, to, .5, .5));
+ }
+
+ /**
+ * Where a line just added went, said when it is not where the analyst is looking:
+ * a reading with no Events track, a date outside the window, or no date at all.
+ */
+ function lineAdded(saved, { undo }) {
+ const row = saved.temporal;
+ pendingSelection = row ? { id: row.id, fallback: row } : null;
+ const statements = trackSpecs.some((track) => track.categories.includes('statement'));
+ if (!statements) {
+ toast('Added · not in the tracks shown', 'ok', 8000, {
+ label: 'Show',
+ onClick: () => {
+ const events = defaultTimelineTracks()[0];
+ trackSpecs = [...trackSpecs, { ...copyTimelineTrack(events, trackSpecs), label: events.label }];
+ },
+ });
+ return;
+ }
+ if (row && !row.earliest) {
+ toast('Added · in Undated', 'ok', 8000, { label: 'Show', onClick: () => { undatedOpen = true; undatedElement?.scrollIntoView?.({ block: 'nearest' }); } });
+ return;
+ }
+ const start = Date.parse(row?.earliest ?? '');
+ const end = Date.parse(row?.latest ?? row?.earliest ?? '');
+ if (axisWindow && Number.isFinite(start) && (start >= axisWindow.end || end < axisWindow.start)) {
+ toast('Added · outside this window', 'ok', 8000, {
+ label: 'Go there',
+ onClick: () => {
+ const half = axisWindow.span / 2;
+ const middle = (start + Math.max(start, end)) / 2;
+ from = isoInstant(middle - half);
+ to = isoInstant(middle + half);
+ },
+ });
+ return;
+ }
+ toast('Added', 'ok', 8000, { label: 'Undo', onClick: undo });
}
/** The instants the minimap spans — the bars', so a drag lands where it looks. */
@@ -1249,7 +1563,7 @@
if (drawing?.pointer === event.pointerId) {
const draft = drawing;
drawing = null;
- openEditor(null, draftWhen(from, to, draft.start, draft.end));
+ offerDate(draftWhen(from, to, draft.start, draft.end));
return;
}
if (!moving || moving.pointer !== event.pointerId) return;
@@ -1263,7 +1577,7 @@
} else {
const value = edit.item.raw.includes('T')
? timeAtRatio(from, to, ratio)
- : dateAtRatio(from, to, ratio);
+ : dateAtRatio(from, to, ratio, edit.item.tz);
raw = resizeTemporalRaw(edit.item, edit.mode, value);
}
if (raw && raw !== edit.item.raw) pendingEdit = { item: edit.item, raw };
@@ -1291,17 +1605,56 @@
if (raw && raw !== item.raw) pendingEdit = { item, raw };
}
+ /** A date being changed from the inspector, until it is saved or given up. `picked`
+ * is a clock chosen here, `undefined` while the entry keeps its own. */
+ let dateEditing = $state(null); // { id, value, picked }
+ const dateSettled = $derived(
+ dateEditing
+ ? settleClock(dateEditing.value, {
+ picked: dateEditing.picked,
+ stated: selected?.tz ?? null,
+ // an entry on no known clock stays on none until one is picked
+ fallback: clockOf(selected?.raw, selected?.tz).zone,
+ })
+ : null
+ );
+ const dateEditReady = $derived(
+ Boolean(dateEditing?.value) &&
+ formatTemporalValue(dateEditing.value).valid &&
+ (dateSettled.raw !== (selected?.raw ?? '') || dateSettled.zone !== (selected?.tz ?? null))
+ );
+ function startDateEdit() {
+ if (!selected || snapshotReading) return;
+ dateEditing = { id: selected.id, value: selected.raw ?? '', picked: undefined };
+ }
+ // Through the same old → new confirmation a drag on the axis asks.
+ function saveDateEdit() {
+ if (!dateEditReady) return;
+ pendingEdit = { item: selected, raw: dateSettled.raw, zone: dateSettled.zone };
+ }
+ $effect(() => {
+ const id = selected?.id ?? null;
+ untrack(() => {
+ if (dateEditing && dateEditing.id !== id) dateEditing = null;
+ });
+ });
+
async function confirmDirectEdit() {
if (!pendingEdit || directSaving) return;
directSaving = true;
try {
await api.patch(
`/api/cases/${caseState.current.id}/timeline/claims/${pendingEdit.item.owner_id}`,
- { when: pendingEdit.raw }
+ {
+ when: pendingEdit.raw,
+ // a drag moves the date on the clock it has; the inspector can change the clock
+ ...(pendingEdit.zone !== undefined ? { when_zone: pendingEdit.zone } : {}),
+ }
);
pendingEdit = null;
+ dateEditing = null;
await reloadCase();
- toast('Claim updated', 'ok', 1600);
+ toast('Date updated', 'ok', 1600);
} catch (error) {
toast(error.message, 'danger');
} finally {
@@ -1309,6 +1662,9 @@
}
}
+ /** What the picked entry is, in the words the tracks use. */
+ const HEADINGS = { statement: 'Event', media: 'File date', case_activity: 'Case activity' };
+
function categoryName(item) {
return TIMELINE_CATEGORIES.find((entry) => entry.id === item.category)?.label ?? item.category;
}
@@ -1320,13 +1676,15 @@
}
function showItemTooltip(event, item) {
- const reading = formatTemporalValue(item.raw ?? '');
+ const reading = formatTemporalValue(item.raw ?? '', item.tz);
tooltip = {
x: Math.min(window.innerWidth - 286, event.clientX + 12),
y: Math.min(window.innerHeight - 132, event.clientY + 12),
title: item.label,
date: reading.label,
- detail: [categoryName(item), item.time_role, item.confidence].filter(Boolean).join(' · '),
+ // a file on the Media lane says which event dated it
+ detail: item.asFile ? item.statement : [categoryName(item), item.time_role, item.confidence].filter(Boolean).join(' · '),
+ sentence: item.asFile === true,
};
}
@@ -1335,6 +1693,206 @@
showItemTooltip({ clientX: rect.right, clientY: rect.top }, item);
}
+ /**
+ * A line from the entry up to the ruler, and on the ruler the date as it was written.
+ *
+ * A mark is exactly where its date is, and this is what lets that be read without
+ * counting ticks: an instant gets one line, a reduced date or a period one at each
+ * end of what it covers.
+ */
+ let guide = $state(null);
+ function showGuide(element, item) {
+ const card = axisCardElement?.getBoundingClientRect();
+ const ruler = plotElement?.getBoundingClientRect();
+ if (!card || !ruler || !element) return;
+ const mark = element.getBoundingClientRect();
+ const middle = mark.left + mark.width / 2;
+ const lines = item.mark === 'point' ? [middle] : [mark.left, mark.right];
+ // The card scrolls under its sticky ruler, and the guide is drawn in what scrolls.
+ const down = axisCardElement.scrollTop;
+ const across = axisCardElement.scrollLeft;
+ guide = {
+ id: item.id,
+ lines: lines.map((x) => x - card.left + across),
+ top: ruler.bottom - card.top + down,
+ height: Math.max(0, mark.top + mark.height / 2 - ruler.bottom),
+ at: Math.min(Math.max(middle, ruler.left + 90), ruler.right - 90) - card.left + across,
+ label: formatTemporalValue(item.raw ?? '', item.tz).label,
+ };
+ }
+
+ function leaveMark(item) {
+ tooltip = null;
+ if (guide?.id === item.id) guide = null;
+ if (hovered === item.id) hovered = null;
+ }
+
+ function enterMark(event, item) {
+ hovered = item.id;
+ showGuide(event.currentTarget, item);
+ }
+
+ /** The row of an entry, found by its id rather than by a selector built from it. */
+ function rowOf(id) {
+ return [...(listPane?.querySelectorAll('[data-row]') ?? [])].find((row) => row.dataset.row === id);
+ }
+
+ function markOf(id) {
+ return [...(axisCardElement?.querySelectorAll('[data-mark]') ?? [])].find((mark) => mark.dataset.mark === id);
+ }
+
+ /** A mark picked on the axis brings its row into the list, without moving the axis. */
+ async function revealRow(id) {
+ await tick();
+ rowOf(id)?.scrollIntoView({ block: 'nearest' });
+ }
+
+ function hoverRow(item) {
+ hovered = item.id;
+ const laid = tracks.flatMap((track) => track.layout.items).find((entry) => entry.id === item.id);
+ const mark = laid ? markOf(item.id) : null;
+ if (mark) showGuide(mark, laid);
+ }
+
+ function leaveRow(item) {
+ if (hovered === item.id) hovered = null;
+ if (guide?.id === item.id) guide = null;
+ }
+
+ function rowKey(event, item) {
+ if (event.key === 'Enter' || event.key === ' ') {
+ event.preventDefault();
+ selectItem(item, null, event);
+ return;
+ }
+ if (!['ArrowDown', 'ArrowUp'].includes(event.key)) return;
+ event.preventDefault();
+ const rows = [...(listPane?.querySelectorAll('[data-row]') ?? [])];
+ const index = rows.indexOf(event.currentTarget);
+ rows[index + (event.key === 'ArrowDown' ? 1 : -1)]?.focus();
+ }
+
+ const names = (entries) => (entries ?? []).map((entry) => entry.label || entry.id).join(', ');
+
+ /**
+ * What a row still waits for, said as words beside it rather than as a colour.
+ *
+ * Only a Claim is asked for a source and an assessment: a proof is its own source,
+ * and a file's date is not an assessment anybody made.
+ */
+ function rowFlags(item) {
+ const flags = [];
+ if (item.status === 'suggested') flags.push({ id: 'suggested', label: 'suggested' });
+ if (item.confidence) flags.push({ id: item.confidence === 'refuted' ? 'refuted' : 'assessed', label: item.confidence });
+ if (item.kind === 'claim') {
+ if (!item.source_entities?.length && !item.sources?.length) flags.push({ id: 'unsourced', label: 'no source' });
+ if (!item.confidence) flags.push({ id: 'unassessed', label: 'not assessed' });
+ }
+ return flags;
+ }
+
+ function splitStart(event) {
+ if (event.button !== 0) return;
+ event.preventDefault();
+ splitting = {
+ pointer: event.pointerId,
+ top: axisCardElement?.getBoundingClientRect().top ?? 0,
+ room: Math.max(1, chronologyHeight - overviewRoom - 70),
+ };
+ event.currentTarget.setPointerCapture?.(event.pointerId);
+ }
+
+ function splitMove(event) {
+ if (splitting?.pointer !== event.pointerId) return;
+ axisShare = Math.min(.85, Math.max(.15, (event.clientY - splitting.top) / splitting.room));
+ }
+
+ function splitEnd(event) {
+ if (splitting?.pointer === event.pointerId) splitting = null;
+ }
+
+ function splitKey(event) {
+ const step = { ArrowUp: -.05, ArrowDown: .05 }[event.key];
+ if (step === undefined && !['Home', 'End'].includes(event.key)) return;
+ event.preventDefault();
+ if (event.key === 'Home') axisShare = .15;
+ else if (event.key === 'End') axisShare = .85;
+ else axisShare = Math.min(.85, Math.max(.15, axisShare + step));
+ }
+
+ function setViewMode(mode) {
+ viewMode = mode;
+ axisShare = SHARES[mode];
+ }
+
+ /** What the empty axis counted, put on it: the working files let back onto the
+ * Media track that held them, or a Media track that holds every file. */
+ function showFileDates() {
+ trackSpecs = workingFilesHeld
+ ? trackSpecs.map((track) => (track.id === mediaTracks[0].id ? withWorkingFiles(track) : track))
+ : [...trackSpecs, mediaTrack(trackSpecs, { collectedOnly: false })];
+ }
+
+ /**
+ * The window's chronology on the clipboard, as a table for a report or a block for a
+ * spreadsheet. A frozen reading copies what it froze and asks nothing of the case.
+ */
+ async function copyChronology(kind) {
+ copyMenu = false;
+ const caseId = caseState.current?.id;
+ if (!caseId || copying) return;
+ copying = true;
+ try {
+ const read = snapshotReading
+ ? { items: windowItems, truncated: false }
+ : await readChronology((url) => api.get(url), {
+ caseId, tracks: trackSpecs, from, to, entityId: entityFilter?.id,
+ });
+ const rows = chronologyRows(read.items);
+ const text = kind === 'markdown'
+ ? chronologyMarkdown(rows, provenance({
+ caseName: caseState.current?.name ?? '',
+ sheet: timelineViews.activeView?.name || 'Timeline',
+ filter: [trackSpecs.map((track) => track.label).join(', '), windowWords(from, to, zone), zoneWord]
+ .filter(Boolean).join(' · '),
+ at: new Date().toISOString(),
+ }))
+ : chronologyBlock(rows);
+ await navigator.clipboard.writeText(text);
+ const count = `${rows.length} ${rows.length === 1 ? 'entry' : 'entries'}`;
+ toast(read.truncated ? `The first ${count} copied.` : `${count} copied.`, 'ok', 1800);
+ } catch (error) {
+ toast(error?.message || 'Copying failed.', 'danger');
+ } finally {
+ copying = false;
+ }
+ }
+
+ /**
+ * The keys a mark answers to itself. Enter and Space are its own click, so they stop
+ * here rather than reaching the canvas, where they would start a new claim. Alt with
+ * an arrow walks to the entry before or after it on the same track; every other key
+ * goes on to the canvas, which pans and zooms as it always has.
+ */
+ function markKey(event, track, item) {
+ if (event.key === 'Enter' || event.key === ' ') {
+ event.stopPropagation();
+ return;
+ }
+ if (!event.altKey || !['ArrowLeft', 'ArrowRight'].includes(event.key)) return;
+ event.preventDefault();
+ event.stopPropagation();
+ const order = [...track.layout.items].sort((a, b) =>
+ String(a.earliest).localeCompare(String(b.earliest)) || String(a.id).localeCompare(String(b.id)));
+ const index = order.findIndex((entry) => entry.id === item.id);
+ const next = order[index + (event.key === 'ArrowLeft' ? -1 : 1)];
+ if (!next) return;
+ const canvas = event.currentTarget.closest('.track-canvas');
+ const target = [...(canvas?.querySelectorAll('[data-mark]') ?? [])]
+ .find((element) => element.dataset.mark === next.id);
+ target?.focus();
+ }
+
function showBucketTooltip(event, bucket) {
const parts = TIMELINE_CATEGORIES
.map((category) => bucket.categories?.[category.id] ? `${category.short} ${bucket.categories[category.id]}` : '')
@@ -1354,29 +1912,39 @@
<svelte:window
onpointermove={pointerMove}
onpointerup={pointerUp}
- onkeydown={(event) => { if (event.key === 'Escape' && itemMenu) itemMenu = null; }}
+ onkeydown={(event) => {
+ if (event.key !== 'Escape') return;
+ if (itemMenu) itemMenu = null;
+ else if (moreMenu) moreMenu = false;
+ else if (rangeMenu) rangeMenu = false;
+ }}
/>
<div class="timeline-tool" class:fullscreen bind:this={toolElement}>
- <header class="timeline-head">
- <!-- Titled the way every other tool is (`app.css .tool-header`): the name, then
- one clause saying what is on screen. It used to carry a second title over the
- first in accent capitals, which said the same word twice. -->
- <div class="title-block">
- <h2>Timeline</h2>
- <span class="sub">{total} {total === 1 ? 'entry' : 'entries'} across tracks</span>
- </div>
+ <!-- One bar: the period, the clock it is read on, and which half gets the room. The
+ rest (tracks, grouping, the period handed to another tool, the legend, full
+ screen) is asked for rarely and waits under `⋯`. There used to be three rows of
+ controls, a title repeating the tab, and a line of mouse hints, and the first
+ entry started halfway down the screen. Adding is the line under the axis, which
+ the topbar's Add event also goes to, so the bar has no Add of its own. -->
+ <header class="timeline-bar">
+ {#if entityFilter}
+ <button class="scope-chip" disabled={snapshotReading} title="Clear entity filter" onclick={() => { entityFilter = null; from = ''; to = ''; }}>
+ <Icon name="crosshair" size={11} /><span>{entityFilter.label}</span><Icon name="x" size={10} />
+ </button>
+ {/if}
- <!-- The window, read rather than spelled out in controls. Two date boxes, four
- icons and an All button were seven things on the toolbar for one fact; the
- boundaries are typed rarely and checked constantly, so the reading is what
- stays out and the rest opens under it. Panning keeps its arrows because
- stepping through a chronology is the frequent move. -->
+ <!-- The window, read rather than spelled out in controls. The boundaries are typed
+ rarely and checked constantly, so the reading is what stays out and the rest
+ opens under it. Panning keeps its arrows: stepping through a chronology is the
+ frequent move. -->
<div class="range" bind:this={rangeElement}>
<button class="range-step" title="Earlier" aria-label="Earlier" onclick={() => pan(-.7)} disabled={!axisWindow}>
<Icon name="chevronLeft" size={15} />
</button>
- <button class="range-face" aria-expanded={rangeMenu} onclick={() => (rangeMenu = !rangeMenu)}>
+ <!-- The exact boundaries on hover: the corner of the ruler spelled them in ISO
+ beside the words already here. -->
+ <button class="range-face" aria-expanded={rangeMenu} title={`${windowInputValue(from, zone).replace('T', ' ')} to ${windowInputValue(to, zone).replace('T', ' ')} · Scroll to zoom, Shift-scroll to pan`} onclick={() => (rangeMenu = !rangeMenu)}>
{windowWords(from, to, zone)}
</button>
<button class="range-step" title="Later" aria-label="Later" onclick={() => pan(.7)} disabled={!axisWindow}>
@@ -1402,179 +1970,167 @@
{/if}
</div>
- <div class="head-actions">
- <AnalysisViews
- surface="timeline"
- capture={captureAnalysisView}
- onopen={openAnalysisView}
- onleave={leaveAnalysisReading}
- />
- <PlateExport surface="timeline" plate={capturePlate} disabled={!caseState.current} />
- <button class="btn btn-ghost fullscreen-btn" aria-pressed={fullscreen} onclick={toggleFullscreen}>{fullscreen ? 'Exit full screen' : 'Full screen'}</button>
- <button class="btn btn-primary add-event" disabled={snapshotReading} onclick={() => openEditor()}><Icon name="plus" size={13} />Add claim</button>
- </div>
- </header>
-
- <div class="filter-row">
- {#if entityFilter}
- <button class="scope-chip" disabled={snapshotReading} title="Clear entity filter" onclick={() => { entityFilter = null; from = ''; to = ''; }}>
- <Icon name="crosshair" size={11} /><span>{entityFilter.label}</span><Icon name="x" size={10} />
- </button>
- {/if}
- <div class="view-switch" aria-label="Timeline display">
- <button class:active={viewMode === 'plot'} aria-pressed={viewMode === 'plot'} onclick={() => (viewMode = 'plot')}>Plot</button>
- <button class:active={viewMode === 'list'} aria-pressed={viewMode === 'list'} onclick={() => (viewMode = 'list')}>List</button>
- </div>
<!-- Which clock the axis is read on. Presentation only: the case stores UTC, the
- queries ask in UTC, and this moves the ticks and their words. A saved point
- also brings its daylight with it, since a band of day and night needs
- coordinates and there is no sense in asking for them twice. -->
+ queries ask in UTC, and this moves the ticks and their words. It opens on the
+ zone of the case's places. A saved point also brings its daylight with it,
+ since a band of day and night needs coordinates. -->
<ZonePicker
bind:choice={zoneChoice}
{places}
+ home={caseClock}
at={axisWindow?.start ?? 0}
resolved={zone}
disabled={snapshotReading}
+ onpick={(value) => rememberClock(caseState.current?.id, value)}
/>
- <details class="legend" bind:this={legendElement} bind:open={legendOpen}>
- <summary>Legend</summary>
- <div class="legend-card">
- <strong>Date quality</strong>
- <span><i class="sample approximate"></i>Approximate date</span>
- <span><i class="sample uncertain"></i>Uncertain date</span>
- <strong>Status</strong>
- <span><i class="sample suggested"></i>Suggested status</span>
- <span><i class="sample refuted"></i>Refuted confidence</span>
- <p>Confidence and date quality are independent.</p>
- </div>
- </details>
- <span class="utc-readout">{scaleLabel} · Wheel zoom · Shift-wheel pan</span>
- </div>
- <div class="track-toolbar">
- <div class="track-add" bind:this={trackMenuElement}>
- <button class="btn btn-sm" aria-expanded={trackMenu} disabled={snapshotReading || trackSpecs.length >= 20} onclick={() => (trackMenu = !trackMenu)}>
- <Icon name="plus" size={12} /> Track
- </button>
- {#if trackMenu}
- <div class="track-menu">
- <strong>Add a track</strong>
- {#each trackPresets(entityTypes()) as preset (preset.id)}
- <button onclick={() => addPreset(preset)}><span>{preset.label}</span><small>{preset.categories.map((category) => category === 'case_activity' ? 'activity' : category).join(' · ')}</small></button>
- {/each}
- <button class="custom" onclick={() => { trackEditor = { mode: 'new' }; trackMenu = false; }}>
- <span>Custom</span><small>Build with Search+</small>
- </button>
- </div>
- {/if}
+ <div class="view-switch" aria-label="Timeline display">
+ <button class:active={viewMode === 'plot'} aria-pressed={viewMode === 'plot'} title="Give the axis more room" onclick={() => setViewMode('plot')}>Plot</button>
+ <button class:active={viewMode === 'list'} aria-pressed={viewMode === 'list'} title="Give the list more room" onclick={() => setViewMode('list')}>List</button>
</div>
- <label>Group by
- <select class="input input-sm" bind:value={groupBy} disabled={snapshotReading}>
- <option value="none">None</option>
- <option value="subject">Subject</option>
- <option value="type">Type</option>
- <option value="place">Place</option>
- <option value="source">Evidence</option>
- <option value="role">Time role</option>
- </select>
- </label>
- <span>{trackSpecs.length} {trackSpecs.length === 1 ? 'track' : 'tracks'}</span>
- {#if snapshotReading}<em>Frozen view</em>{/if}
-
- <!-- Asking the same period of the other three surfaces is the point of having a
- period, so the handoff stays in the open rather than under the window's
- boundaries: the window is set rarely and handed over often. It ends the track
- row instead of trailing the window, which left six controls fighting for the
- middle of the header for one fact. -->
- <div class="range-handoffs" role="group" aria-label="Open range">
- <span>Open in</span>
- <button onclick={() => openRangeIn('board')} disabled={!axisWindow}>Board</button>
- <button onclick={() => openRangeIn('graph')} disabled={!axisWindow}>Graph</button>
- <button onclick={() => openRangeIn('satellite')} disabled={!axisWindow}>Map</button>
+ {#if snapshotReading}<em class="frozen">Frozen view</em>{/if}
+
+ <div class="bar-end">
+ <AnalysisViews
+ surface="timeline"
+ capture={captureAnalysisView}
+ onopen={openAnalysisView}
+ onleave={leaveAnalysisReading}
+ />
+ <PlateExport surface="timeline" plate={capturePlate} disabled={!caseState.current} />
+ {#if fullscreen}<button class="btn btn-sm" onclick={toggleFullscreen}>Exit full screen</button>{/if}
+ <div class="more" bind:this={moreElement}>
+ <button class="btn btn-sm more-btn" aria-expanded={moreMenu} aria-label="More" title="Tracks, grouping, legend, full screen" onclick={() => (moreMenu = !moreMenu)}>
+ <Icon name="more" size={15} stroke={2.6} />
+ </button>
+ {#if moreMenu}
+ <div class="more-menu">
+ <section aria-label="Add a track">
+ <strong>Add a track</strong>
+ {#each trackPresets(entityTypes()) as preset (preset.id)}
+ <button disabled={snapshotReading || trackSpecs.length >= 20} onclick={() => addPreset(preset)}><span>{preset.label}</span><small>{FILE_LANE_NOTES[preset.query.as_files] ?? preset.categories.map((category) => category === 'case_activity' ? 'activity' : category).join(' · ')}</small></button>
+ {/each}
+ <button class="custom" disabled={snapshotReading || trackSpecs.length >= 20} onclick={() => { trackEditor = { mode: 'new' }; moreMenu = false; }}>
+ <span>Custom</span><small>Build with Search+</small>
+ </button>
+ </section>
+ <label class="more-row">Group by
+ <select class="input input-sm" bind:value={groupBy} disabled={snapshotReading}>
+ <option value="none">None</option>
+ <option value="subject">Subject</option>
+ <option value="type">Type</option>
+ <option value="place">Place</option>
+ <option value="source">Evidence</option>
+ <option value="role">Time role</option>
+ </select>
+ </label>
+ <!-- The same period asked of another tool. -->
+ <div class="more-row range-handoffs" role="group" aria-label="Open range">
+ <span>Open this period in</span>
+ <div>
+ <button onclick={() => { moreMenu = false; openRangeIn('board'); }} disabled={!axisWindow}>Board</button>
+ <button onclick={() => { moreMenu = false; openRangeIn('graph'); }} disabled={!axisWindow}>Graph</button>
+ <button onclick={() => { moreMenu = false; openRangeIn('satellite'); }} disabled={!axisWindow}>Map</button>
+ </div>
+ </div>
+ <details class="legend">
+ <summary>Legend</summary>
+ <div class="legend-card">
+ <strong>Shape</strong>
+ <span><i class="sample shape-point"></i>Instant</span>
+ <span><i class="sample shape-bracket"></i>Reduced date, across what it covers</span>
+ <span><i class="sample shape-bar"></i>Period</span>
+ <strong>Date quality</strong>
+ <span><i class="sample approximate"></i>Approximate date</span>
+ <span><i class="sample uncertain"></i>Uncertain date</span>
+ <strong>Status</strong>
+ <span><i class="sample suggested"></i>Suggested status</span>
+ <span><i class="sample refuted"></i>Refuted confidence</span>
+ <p>Confidence and date quality are independent.</p>
+ </div>
+ </details>
+ {#if !fullscreen}<button class="more-act" onclick={() => { moreMenu = false; void toggleFullscreen(); }}>Full screen</button>{/if}
+ </div>
+ {/if}
+ </div>
</div>
- </div>
+ </header>
- <div class="timeline-grid">
- <main class="chronology">
+ <div class="timeline-grid" class:inspecting={Boolean(selected)}>
+ <main class="chronology" class:blank={!caseState.current || (!extent?.from && !loading)} bind:clientHeight={chronologyHeight}>
+ <!-- The entry line, under the axis. None in a snapshot, which takes no writes. -->
+ {#snippet line()}
+ {#if caseState.current && !snapshotReading}
+ <section class="entry-host" aria-label="Add an event">
+ {#key `${caseState.current.id}:${lineEntity?.id ?? ''}`}
+ <EntryLine
+ bind:this={entryLine}
+ caseId={caseState.current.id}
+ entity={lineEntity}
+ draftKey={`timeline:${lineEntity?.id ?? ''}`}
+ announce={false}
+ onsaved={lineAdded}
+ />
+ {/key}
+ </section>
+ {/if}
+ {/snippet}
+ <!-- What still waits for a date, under the list or under an empty axis alike. -->
+ {#snippet holdings()}
+ {#if unplaced.length || unplacedTotal}
+ <details class="holding-card" open>
+ <summary><span><Icon name="alert" size={14} />Not on UTC axis</span><strong>{unplacedTotal}</strong></summary>
+ <p class="holding-note">Add a timezone or correct the value to place these entries.</p>
+ <div class="holding-list">
+ {#each unplaced as item (item.id)}
+ <button onclick={() => selectItem(item)} oncontextmenu={(event) => openItemMenu(event, item)}>
+ <span class={`category-dot ${item.category}`}></span>
+ <span><strong>{item.label}</strong><small><span class="mono">{item.raw}</span> · {unplacedReason(item)}</small></span>
+ {#if item.category === 'statement'}<Icon name="edit" size={12} />{/if}
+ </button>
+ {/each}
+ {#if unplacedTotal > unplaced.length}<p>Load more to see the remaining entries.</p>{/if}
+ </div>
+ </details>
+ {/if}
+
+ {#if undated.length || undatedTotal}
+ <details class="holding-card undated-card" bind:open={undatedOpen} bind:this={undatedElement}>
+ <summary><span><Icon name="clock" size={14} />Undated</span><strong>{undatedTotal}</strong></summary>
+ <div class="holding-list">
+ {#each undated as item (item.id)}
+ <button onclick={() => selectItem(item)} oncontextmenu={(event) => openItemMenu(event, item)}>
+ <span class={`category-dot ${item.category}`}></span>
+ <span><strong>{item.label}</strong><small>{item.parse_error || categoryName(item)}</small></span>
+ {#if item.category === 'statement'}<Icon name="edit" size={12} />{/if}
+ </button>
+ {/each}
+ {#if undatedTotal > undated.length}<p>Load more to see the remaining undated entries.</p>{/if}
+ </div>
+ </details>
+ {/if}
+ {/snippet}
{#if !caseState.current}
<div class="blank-state"><Icon name="clock" size={24} /><h2>Open a case to build its timeline.</h2></div>
{:else if !extent?.from && !loading}
<div class="blank-state">
<Icon name="clock" size={24} />
- <h2>No dated entries yet</h2>
- <p>Add a dated claim here or from an entity's Time tab.</p>
- <button class="btn btn-primary" disabled={snapshotReading} onclick={() => openEditor()}>Add first claim</button>
+ <h2>Nothing dated yet</h2>
+ <p>Date what happened on the line below, or give a proof its date.</p>
+ {#if fileDates}
+ <p class="blank-files">{fileDates} {fileDates === 1 ? 'date' : 'dates'} read from {workingFilesHeld ? 'working files' : 'files'} · <button class="text-button" onclick={showFileDates}>Show them</button></p>
+ {/if}
+ <div class="blank-line">{@render line()}</div>
</div>
+ {@render holdings()}
{:else}
- <section class="overview-card" aria-label="Timeline overview">
- <div class="overview-title">
- <span>Overview</span>
- <!-- The extent in words rather than the first and last bucket keys, which
- read as `2026-08-02T03` the moment the case is cut by the hour. -->
- <small>{extent?.from ? windowWords(extent.from, extent.to, 'UTC') : 'No dated entries'}</small>
- {#if overview.length}<small>{overviewUnit} buckets · exact counts on hover</small>{/if}
- <div class="overview-counts">
- {#if unplacedTotal}<span>{unplacedTotal} local</span>{/if}
- {#if undatedTotal}<span>{undatedTotal} undated</span>{/if}
- </div>
- {#if overviewTruncated}<small class="capped">Partial overview</small>{/if}
- </div>
- <!-- svelte-ignore a11y_no_noninteractive_tabindex -->
- <!-- svelte-ignore a11y_no_noninteractive_element_interactions -->
- <div class="density-bars" role="application" tabindex="0" aria-label="Timeline minimap" bind:clientWidth={overviewWidth} onclick={overviewRecenter} onkeydown={navigateKey}>
- {#each overviewTicks as slot (slot.key)}
- {#if slot.label && slot.left > 0}
- <span class="overview-rule" style:left={`${slot.left}%`}></span>
- {/if}
- {/each}
- {#each density as bucket (bucket.start)}
- <button
- class="density-bucket"
- aria-label={`${bucket.start}, ${bucket.count} entries`}
- style:left={`${bucket.left}%`}
- style:width={`${bucket.width}%`}
- onclick={(event) => { event.stopPropagation(); openBucket(bucket); }}
- onpointerenter={(event) => showBucketTooltip(event, bucket)}
- onpointermove={(event) => showBucketTooltip(event, bucket)}
- onpointerleave={() => (tooltip = null)}
- >
- <span class="density-stack" style:height={`${bucket.height}%`}>
- {#each TIMELINE_CATEGORIES as category (category.id)}
- {#if bucket.categories?.[category.id]}
- <i class={category.id} style:flex-grow={bucket.categories[category.id]}></i>
- {/if}
- {/each}
- </span>
- </button>
- {/each}
- <span class="density-baseline"></span>
- {#each overviewTicks as slot (slot.key)}
- {#if slot.label}
- <span
- class="overview-tick {slot.anchor}"
- style:left={`${slot.left}%`}
- style:width={`${slot.width}%`}
- >{slot.label}</span>
- {/if}
- {/each}
- <!-- What the axis is not showing, dimmed: the brush says where the window
- is, and these say what it left out. -->
- <span class="overview-shade" style:left="0" style:width={`${overviewWindow.left}%`}></span>
- <span class="overview-shade" style:left={`${overviewWindow.left + overviewWindow.width}%`} style:right="0"></span>
- <div class="overview-window" style:left={`${overviewWindow.left}%`} style:width={`${overviewWindow.width}%`}>
- <button class="overview-drag" aria-label="Move visible range" title="Move visible range" onpointerdown={(event) => beginOverview(event, 'move')} onkeydown={(event) => overviewKey(event, 'move')}></button>
- <button class="overview-handle start" aria-label="Change range start" title="Change range start" onpointerdown={(event) => beginOverview(event, 'start')} onkeydown={(event) => overviewKey(event, 'start')}></button>
- <button class="overview-handle end" aria-label="Change range end" title="Change range end" onpointerdown={(event) => beginOverview(event, 'end')} onkeydown={(event) => overviewKey(event, 'end')}></button>
- </div>
- </div>
- </section>
-
- {#if viewMode === 'plot'}
- <section class="axis-card" aria-label="Timeline axis">
+ <section class="axis-card" aria-label="Timeline axis" bind:this={axisCardElement} style:max-height={`${axisMax}px`}>
<div class="axis-row">
+ <!-- Which clock the ruler is in, in words. The window's two boundaries in
+ ISO sat here too, a second spelling of what the bar already says. -->
<div class="axis-label">
<span>{zoneWord}</span>
- <small>{windowInputValue(from, zone).replace('T', ' ')} to {windowInputValue(to, zone).replace('T', ' ')}</small>
+ {#if zone !== UTC}<small>{zoneWords(zone).place} time</small>{/if}
</div>
<!-- svelte-ignore a11y_no_noninteractive_tabindex -->
<!-- svelte-ignore a11y_no_noninteractive_element_interactions -->
@@ -1590,13 +2146,13 @@
onkeydown={navigateKey}
>
<div class="axis-bands">
- {#each bands as band (band.label + band.left)}
+ {#each bandNames as band (band.left)}
<span style:left={`${band.left}%`} style:width={`${band.width}%`}>{band.label}</span>
{/each}
</div>
{#each minorTicks as tick (tick.at)}<span class="axis-minor" style:left={`${tick.left}%`}></span>{/each}
- {#each ticks as tick (tick.at)}
- <div class="axis-tick" class:end={tick.left > 94} style:left={`${tick.left}%`}><span>{tick.label}</span></div>
+ {#each tickNames as tick (tick.at)}
+ <div class="axis-tick" class:end={tick.left > 94} style:left={`${tick.left}%`}>{#if tick.label}<span>{tick.label}</span>{/if}</div>
{/each}
{#if nowLeft !== null}<span class="now-line" style:left={`${nowLeft}%`}><small>Now</small></span>{/if}
<!-- Day and night at the chosen point, on the same scale as the
@@ -1630,15 +2186,19 @@
</p>
{/if}
+ <div class="axis-tracks" role="list">
{#each tracks as track (track.id)}
{@const baseId = track.parentId ?? track.id}
- {@const canCreate = track.categories.includes('statement') && !snapshotReading}
+ <!-- A file lane holds events tied to a file, so a click on it has no file
+ to tie a new one to: a file is dated from its proof or an event about it. -->
+ {@const canCreate = track.categories.includes('statement') && !drawsFiles(track) && !snapshotReading}
+ {@const shown = track.layout.items.length + track.layout.clusters.reduce((sum, cluster) => sum + cluster.count, 0)}
<div
class="track-row"
class:folded={track.collapsed}
role="listitem"
style:--track-tint={trackTint(track.color)}
- style:min-height={track.collapsed ? '42px' : `${Math.max(78, track.layout.rows * 46 + 28)}px`}
+ style:min-height={track.collapsed ? '42px' : `${Math.max(46, track.layout.height)}px`}
ondragover={(event) => { if (groupBy === 'none' && !snapshotReading) event.preventDefault(); }}
ondrop={() => dropTrack(baseId)}
>
@@ -1662,11 +2222,13 @@
<button class="fold-track" aria-label={`${track.collapsed ? 'Expand' : 'Fold'} ${track.label}`} title={`${track.collapsed ? 'Expand' : 'Fold'} ${track.label}`} disabled={snapshotReading} onclick={() => setTrackCollapsed(baseId, !track.collapsed)}>
<Icon name={track.collapsed ? 'chevronRight' : 'chevronDown'} size={11} />
</button>
- <span class={`category-dot ${track.categories[0]}`}></span>
+ <span class={`category-dot ${drawsFiles(track) ? 'media' : track.categories[0]}`}></span>
<!-- The hover says what the lane below is a reading of: the whole
name, then the question that filled it. -->
- <span class="track-name" title={trackTitle(track)}><strong>{track.label}</strong>{#if track.groupLabel}<em>{track.groupLabel}</em>{/if}</span>
- <small title={track.total !== track.items.length ? 'A sample across the window. Load more fills it in.' : undefined}>{track.layout.items.length + track.layout.clusters.reduce((sum, cluster) => sum + cluster.count, 0)}{#if track.total !== track.items.length} / {track.total}{/if}</small>
+ <span class="track-name" title={trackTitle(track)}><strong dir="auto">{track.label}</strong>{#if track.groupLabel}<em>{track.groupLabel}</em>{/if}</span>
+ <!-- A count only when there is one: a `0` badge on an empty lane said
+ what the empty lane already shows. -->
+ {#if shown || track.total}<small title={track.total !== track.items.length ? 'A sample across the window. Load more fills it in.' : undefined}>{shown}{#if track.total !== track.items.length} / {track.total}{/if}</small>{/if}
{#if groupBy === 'none' && !snapshotReading}
<div class="track-actions">
<button aria-label={`Edit ${track.label}`} title="Edit track" onclick={() => (trackEditor = { mode: 'edit', track })}><Icon name="edit" size={11} /></button>
@@ -1703,18 +2265,14 @@
<div class="draw-range" style:left={`${Math.min(drawing.start, drawing.end) * 100}%`} style:width={`${Math.max(.35, Math.abs(drawing.end - drawing.start) * 100)}%`}></div>
{/if}
{#each track.layout.items as item (item.id)}
- {#if item.shape !== 'interval' && item.zone === 'date-only' && item.haloWidth > 0}
- <span
- class={`precision-span ${item.category}`}
- class:chosen={selected?.id === item.id}
- style:left={`${item.haloLeft}%`}
- style:width={`${item.haloWidth}%`}
- style:top={`${item.lane * 46 + 31}px`}
- aria-hidden="true"
- ></span>
- {/if}
+ {@const editable = canDragTemporal(item) && !snapshotReading}
+ {@const markTop = MARKS.top + item.row * MARKS.row}
+ <!-- A point is an instant, a bracket a reduced date across what it
+ covers, a bar a period at its true length. The caption and the
+ card are the mark's own button, so reading one is clicking it. -->
<div
- class={`timeline-event ${item.category}`}
+ class={`timeline-event ${item.category} ${item.mark}`}
+ class:as-file={item.asFile}
class:chosen={selected?.id === item.id}
class:against={against?.id === item.id}
class:period={item.shape === 'interval'}
@@ -1723,41 +2281,63 @@
class:suggested={item.status === 'suggested'}
class:refuted={item.confidence === 'refuted'}
class:pinned={item.pinned}
- class:axis-editable={canDragTemporal(item) && !snapshotReading}
- class:end-aligned={item.endAligned}
- style:left={`${item.left}%`}
- style:width={`${item.width}%`}
- style:top={`${item.lane * 46 + 18}px`}
+ class:axis-editable={editable}
+ class:open-start={item.openStart}
+ class:open-end={item.openEnd}
+ class:guided={guide?.id === item.id}
+ class:lit={hovered === item.id}
+ style:left={item.mark === 'point' ? `calc(${item.left}% - ${MARKS.column / 2}px)` : `${item.left}%`}
+ style:width={item.mark === 'point' ? `${MARKS.column}px` : `${item.width}%`}
+ style:top={`${markTop}px`}
>
- {#if item.shape === 'interval' && canDragTemporal(item) && !snapshotReading}
+ {#if item.shape === 'interval' && editable}
<button class="resize start" aria-label="Resize start" title="Resize start" onpointerdown={(event) => beginMove(event, item, 'start')} onkeydown={(event) => keyboardEdit(event, item, 'start')}></button>
{/if}
<button
class="event-select"
- aria-label={`${item.label}, ${formatTemporalValue(item.raw).label}`}
+ data-mark={item.id}
+ aria-label={`${item.label}, ${formatTemporalValue(item.raw, item.tz).label}`}
onpointerdown={(event) => {
// Ctrl is the measure gesture, so it must not also start a drag
if (event.ctrlKey || event.metaKey) return;
- if (selected?.id === item.id && canDragTemporal(item) && !snapshotReading) beginMove(event, item);
+ if (selected?.id === item.id && editable) beginMove(event, item);
}}
- onclick={(event) => { event.stopPropagation(); selectItem(item, baseId, event); }}
+ onclick={(event) => { event.stopPropagation(); selectItem(item, baseId, event); revealRow(item.id); }}
oncontextmenu={(event) => openItemMenu(event, item, baseId)}
- onpointerenter={(event) => showItemTooltip(event, item)}
+ onpointerenter={(event) => { showItemTooltip(event, item); enterMark(event, item); }}
onpointermove={(event) => showItemTooltip(event, item)}
- onpointerleave={() => (tooltip = null)}
- onfocus={(event) => showFocusedTooltip(event, item)}
- onblur={() => (tooltip = null)}
+ onpointerleave={() => leaveMark(item)}
+ onfocus={(event) => { showFocusedTooltip(event, item); enterMark(event, item); }}
+ onblur={() => leaveMark(item)}
+ onkeydown={(event) => markKey(event, track, item)}
>
- {#if item.shape !== 'interval'}<span class="event-point"></span>{/if}
- <span class="event-text">
- <strong class="event-label">{item.label}</strong>
- <small class="event-date">{formatTemporalValue(item.raw).label}</small>
- </span>
+ <span class="event-shape" aria-hidden="true"></span>
+ {#if item.caption}
+ <span
+ class={`event-caption ${item.caption.side}`}
+ style:left={`${item.caption.offset}px`}
+ style:width={`${item.caption.width}px`}
+ dir="auto"
+ >{item.label}</span>
+ {/if}
+ {#if item.card}
+ {@const drop = cardTop(track.layout, item.card.row) - markTop}
+ <span class="card-stem" style:left={`${item.card.stem}px`} style:height={`${drop - MARKS.row / 2}px`} aria-hidden="true"></span>
+ <span class="event-card" style:left={`${item.card.offset}px`} style:top={`${drop}px`} style:width={`${item.card.width}px`}>
+ {#if (item.category === 'media' || item.asFile) && item.thumb && caseState.current?.id}
+ <img src={fileUrl(caseState.current.id, item.thumb)} alt="" loading="lazy" decoding="async" />
+ {/if}
+ <span class="card-copy">
+ <strong dir="auto">{item.label}</strong>
+ <small>{formatTemporalValue(item.raw, item.tz).label}</small>
+ </span>
+ </span>
+ {/if}
</button>
- {#if canDragTemporal(item) && !snapshotReading}
+ {#if editable}
<button class="move-grip" aria-label="Move selected date" title="Move date" onpointerdown={(event) => beginMove(event, item)} onkeydown={(event) => keyboardEdit(event, item, 'move')}><Icon name="grip" size={10} /></button>
{/if}
- {#if item.shape === 'interval' && canDragTemporal(item) && !snapshotReading}
+ {#if item.shape === 'interval' && editable}
<button class="resize end" aria-label="Resize end" title="Resize end" onpointerdown={(event) => beginMove(event, item, 'end')} onkeydown={(event) => keyboardEdit(event, item, 'end')}></button>
{/if}
</div>
@@ -1766,100 +2346,281 @@
<button
class="timeline-cluster"
style:left={`${cluster.left}%`}
- style:top={`${cluster.lane * 46 + 22}px`}
+ style:top={`${MARKS.top + cluster.row * MARKS.row}px`}
aria-label={`${cluster.count} more events near ${formatTemporalValue(cluster.earliest).label}`}
onclick={() => expandTrack(baseId)}
>+{cluster.count}</button>
{/each}
- {#if canCreate}<span class="track-hint">Click or drag to add a claim</span>{/if}
- {#if !track.layout.items.length && !track.layout.clusters.length && !canCreate}<span class="track-empty">No entries in this window</span>{/if}
+ {#if canCreate}<span class="track-hint">Click or drag to date a new entry</span>{/if}
+ {#if !track.layout.items.length && !track.layout.clusters.length && !canCreate}<span class="track-empty">{drawsFiles(track) ? 'No file dated in this window. A proof’s date or an event about a file puts it here.' : 'No entries in this window'}</span>{/if}
{:else}<span class="folded-note">Track folded</span>{/if}
</div>
</div>
{/each}
+ </div>
+ {#if guide}
+ <div class="time-guide" aria-hidden="true">
+ {#each guide.lines as x, index (index)}
+ <span class="guide-line" style:left={`${x}px`} style:top={`${guide.top}px`} style:height={`${guide.height}px`}></span>
+ {/each}
+ <span class="guide-reading" style:left={`${guide.at}px`} style:top={`${guide.top - 19}px`}>{guide.label}</span>
+ </div>
+ {/if}
</section>
- {:else}
- <section class="timeline-list" aria-label="Timeline list">
- {#each listGroups as group (group.key)}
- <h2>{group.label}<span>{group.items.length}</span></h2>
- {#each group.items as item (item.id)}
+
+ {#if overviewShown}
+ <section class="overview-card" aria-label="Timeline overview" bind:clientHeight={overviewHeight}>
+ <div class="overview-title">
+ <span>Whole case</span>
+ <!-- The extent in words rather than the first and last bucket keys, which
+ read as `2026-08-02T03` the moment the case is cut by the hour. -->
+ <small>{extent?.from ? windowWords(extent.from, extent.to, 'UTC') : 'No dated entries'}</small>
+ <div class="overview-counts">
+ {#if unplacedTotal}<span>{unplacedTotal} local</span>{/if}
+ {#if undatedTotal}<span>{undatedTotal} undated</span>{/if}
+ </div>
+ {#if overviewTruncated}<small class="capped">Partial overview</small>{/if}
+ </div>
+ <!-- svelte-ignore a11y_no_noninteractive_tabindex -->
+ <!-- svelte-ignore a11y_no_noninteractive_element_interactions -->
+ <div class="density-bars" role="application" tabindex="0" aria-label="Timeline minimap" bind:clientWidth={overviewWidth} onclick={overviewRecenter} onkeydown={navigateKey}>
+ {#each overviewTicks as slot (slot.key)}
+ {#if slot.label && slot.left > 0}
+ <span class="overview-rule" style:left={`${slot.left}%`}></span>
+ {/if}
+ {/each}
+ {#each density as bucket (bucket.start)}
<button
- class:chosen={selected?.id === item.id}
- class:against={against?.id === item.id}
- onclick={(event) => selectItem(item, null, event)}
- oncontextmenu={(event) => openItemMenu(event, item)}
+ class="density-bucket"
+ aria-label={`${bucket.start}, ${bucket.count} entries`}
+ style:left={`${bucket.left}%`}
+ style:width={`${bucket.width}%`}
+ onclick={(event) => { event.stopPropagation(); openBucket(bucket); }}
+ onpointerenter={(event) => showBucketTooltip(event, bucket)}
+ onpointermove={(event) => showBucketTooltip(event, bucket)}
+ onpointerleave={() => (tooltip = null)}
>
- <span class={`category-dot ${item.category}`}></span>
- <span class="list-copy"><strong>{item.label}</strong><small>{categoryName(item)}{#if item.time_role} · {item.time_role}{/if}{#if item.confidence} · {item.confidence}{/if}</small></span>
- <span class="list-date"><strong>{formatTemporalValue(item.raw).label}</strong><code>{item.raw}</code></span>
- <Icon name="arrowRight" size={12} />
+ <span class="density-stack" style:height={`${bucket.height}%`}>
+ {#each TIMELINE_CATEGORIES as category (category.id)}
+ {#if bucket.categories?.[category.id]}
+ <i class={category.id} style:flex-grow={bucket.categories[category.id]}></i>
+ {/if}
+ {/each}
+ </span>
</button>
{/each}
- {/each}
- </section>
- {/if}
-
- {#if unplaced.length || unplacedTotal}
- <details class="holding-card" open>
- <summary><span><Icon name="alert" size={14} />Not on UTC axis</span><strong>{unplacedTotal}</strong></summary>
- <p class="holding-note">Add a timezone or correct the value to place these entries.</p>
- <div class="holding-list">
- {#each unplaced as item (item.id)}
- <button onclick={() => selectItem(item)} oncontextmenu={(event) => openItemMenu(event, item)}>
- <span class={`category-dot ${item.category}`}></span>
- <span><strong>{item.label}</strong><small><span class="mono">{item.raw}</span> · {unplacedReason(item)}</small></span>
- {#if item.category === 'statement'}<Icon name="edit" size={12} />{/if}
- </button>
+ <span class="density-baseline"></span>
+ {#each overviewNames as slot (slot.key)}
+ {#if slot.label}
+ <span
+ class="overview-tick {slot.anchor}"
+ style:left={`${slot.left}%`}
+ style:width={`${slot.width}%`}
+ >{slot.label}</span>
+ {/if}
{/each}
- {#if unplacedTotal > unplaced.length}<p>Load more to see the remaining entries.</p>{/if}
+ <!-- What the axis is not showing, dimmed: the brush says where the window
+ is, and these say what it left out. -->
+ <span class="overview-shade" style:left="0" style:width={`${overviewWindow.left}%`}></span>
+ <span class="overview-shade" style:left={`${overviewWindow.left + overviewWindow.width}%`} style:right="0"></span>
+ <div class="overview-window" style:left={`${overviewWindow.left}%`} style:width={`${overviewWindow.width}%`}>
+ <button class="overview-drag" aria-label="Move visible range" title="Move visible range" onpointerdown={(event) => beginOverview(event, 'move')} onkeydown={(event) => overviewKey(event, 'move')}></button>
+ <button class="overview-handle start" aria-label="Change range start" title="Change range start" onpointerdown={(event) => beginOverview(event, 'start')} onkeydown={(event) => overviewKey(event, 'start')}></button>
+ <button class="overview-handle end" aria-label="Change range end" title="Change range end" onpointerdown={(event) => beginOverview(event, 'end')} onkeydown={(event) => overviewKey(event, 'end')}></button>
+ </div>
</div>
- </details>
- {/if}
+ </section>
+ {/if}
- {#if undated.length || undatedTotal}
- <details class="holding-card undated-card" open>
- <summary><span><Icon name="clock" size={14} />Undated</span><strong>{undatedTotal}</strong></summary>
- <div class="holding-list">
- {#each undated as item (item.id)}
- <button onclick={() => selectItem(item)} oncontextmenu={(event) => openItemMenu(event, item)}>
- <span class={`category-dot ${item.category}`}></span>
- <span><strong>{item.label}</strong><small>{item.parse_error || categoryName(item)}</small></span>
- {#if item.category === 'statement'}<Icon name="edit" size={12} />{/if}
- </button>
- {/each}
- {#if undatedTotal > undated.length}<p>Load more to see the remaining undated entries.</p>{/if}
- </div>
- </details>
- {/if}
+ <!-- svelte-ignore a11y_no_noninteractive_tabindex -->
+ <!-- svelte-ignore a11y_no_noninteractive_element_interactions -->
+ <div
+ class="split"
+ role="separator"
+ aria-orientation="horizontal"
+ aria-label="Share the room between the axis and the list"
+ aria-valuemin="15"
+ aria-valuemax="85"
+ aria-valuenow={Math.round(axisShare * 100)}
+ tabindex="0"
+ title="Drag to give the axis or the list more room"
+ onpointerdown={splitStart}
+ onpointermove={splitMove}
+ onpointerup={splitEnd}
+ onpointercancel={splitEnd}
+ onkeydown={splitKey}
+ ></div>
+
+ {@render line()}
+
+ <div class="reading-pane" bind:this={listPane}>
+ <section class="timeline-list" aria-label="Timeline list">
+ <header class="list-head">
+ <strong>{windowItems.length} {windowItems.length === 1 ? 'entry' : 'entries'} in this window</strong>
+ {#if cursor}<small>More below the ones loaded</small>{/if}
+ <div class="copy-menu" bind:this={copyMenuElement}>
+ <button class="btn btn-ghost btn-sm" aria-expanded={copyMenu} disabled={!windowItems.length || copying} onclick={() => (copyMenu = !copyMenu)}>
+ <Icon name="copy" size={12} /> Copy
+ </button>
+ {#if copyMenu}
+ <div class="copy-options" role="menu">
+ <button role="menuitem" onclick={() => copyChronology('markdown')}>As a Markdown table</button>
+ <button role="menuitem" onclick={() => copyChronology('block')}>For a spreadsheet</button>
+ </div>
+ {/if}
+ </div>
+ </header>
+ {#if windowItems.length}
+ <div class="list-grid" role="grid" aria-label="Chronology" aria-rowcount={windowItems.length + 1} style:--list-columns={listTemplate}>
+ <div class="list-row headings" role="row">
+ <span role="columnheader">{zone === UTC ? 'Date' : `Date · ${zoneWords(zone).place} time`}</span>
+ <span role="columnheader">Statement</span>
+ {#if listColumns.subjects}<span role="columnheader">Subjects</span>{/if}
+ {#if listColumns.places}<span role="columnheader">Places</span>{/if}
+ {#if listColumns.sources}<span role="columnheader">Sources</span>{/if}
+ <span role="columnheader"><span class="sr-only">Waiting for</span></span>
+ </div>
+ {#each listGroups as group (group.key)}
+ <div class="list-row month" role="row">
+ <span role="gridcell" aria-colspan={3 + Object.values(listColumns).filter(Boolean).length}>{group.label}<small>{group.items.length}</small></span>
+ </div>
+ {#each group.items as item (item.id)}
+ <!-- svelte-ignore a11y_no_noninteractive_element_interactions -->
+ <div
+ class="list-row entry"
+ class:chosen={selected?.id === item.id}
+ class:against={against?.id === item.id}
+ class:lit={hovered === item.id}
+ role="row"
+ tabindex="0"
+ data-row={item.id}
+ aria-selected={selected?.id === item.id}
+ onclick={(event) => selectItem(item, null, event)}
+ onkeydown={(event) => rowKey(event, item)}
+ oncontextmenu={(event) => openItemMenu(event, item)}
+ onpointerenter={() => hoverRow(item)}
+ onpointerleave={() => leaveRow(item)}
+ onfocus={() => hoverRow(item)}
+ onblur={() => leaveRow(item)}
+ >
+ <!-- An instant on the axis's clock, so the list and the ruler agree
+ about the hour; a day as it was stated, in its own zone. -->
+ <span role="gridcell" class="list-date" title={`${formatTemporalValue(item.raw, item.tz).label} · ${item.raw}`}>{instantOnClock(item) ? clockReading(item.earliest, zone, { named: false }) : formatTemporalValue(item.raw, item.tz).label}</span>
+ <span role="gridcell" class="list-copy"><span class={`category-dot ${item.category}`}></span><strong dir="auto">{item.label}</strong></span>
+ {#if listColumns.subjects}<span role="gridcell" class="list-links" dir="auto">{names(item.subject_entities)}</span>{/if}
+ {#if listColumns.places}<span role="gridcell" class="list-links" dir="auto">{names(item.place_entities)}</span>{/if}
+ {#if listColumns.sources}<span role="gridcell" class="list-links" dir="auto">{names(item.source_entities)}</span>{/if}
+ <span role="gridcell" class="list-flags">
+ {#each rowFlags(item) as flag (flag.id)}<em class={flag.id}>{flag.label}</em>{/each}
+ </span>
+ </div>
+ {/each}
+ {/each}
+ </div>
+ {:else}
+ <p class="list-empty">No dated entries in this window.</p>
+ {/if}
+ </section>
- {#if cursor}
- <button class="btn btn-ghost load-more" disabled={loading} onclick={() => loadMain({ more: true })}>
- {loading ? 'Loading…' : `Load more · ${items.length} of ${total}`}
- </button>
- {/if}
+ {@render holdings()}
+
+ {#if cursor}
+ <button class="btn btn-ghost load-more" disabled={loading} onclick={() => loadMain({ more: true })}>
+ {loading ? 'Loading…' : `Load more · ${items.length} of ${total}`}
+ </button>
+ {/if}
+ </div>
{/if}
{#if loading}<div class="loading-line"></div>{/if}
</main>
- <aside class="inspector" class:empty={!selected}>
- {#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>
+ <!-- Only while an entry is picked: with nothing to say, it held a third of the width
+ for one line asking for a pick. -->
+ {#if selected}
+ <aside class="inspector">
+ <header><span class={`category-dot ${selected.category}`}></span><span>{HEADINGS[selected.category] ?? 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">{temporalKindLabel(selected.kind)}{#if selected.time_role} · {selected.time_role}{/if}</div>
- <h2>{selected.label}</h2>
+ {#if previewEntity || previewThumb}
+ <MediaPreview
+ caseId={caseState.current?.id}
+ entity={previewEntity}
+ thumb={previewThumb}
+ label={previewEntity?.label ?? selected.label}
+ />
+ {#if previewEntity && !snapshotReading}
+ <button class="btn btn-ghost btn-sm from-file" title="Write an event on the line that cites this file, its dates one press away" onclick={focusLine}>
+ <Icon name="plus" size={12} /> Add event from this file
+ </button>
+ {/if}
+ {/if}
+ <!-- What kind of date, when the heading has not said it: `Claim` under `Event`
+ said the same thing twice. -->
+ {#if selected.kind !== 'claim' || selected.time_role}
+ <div class="item-kind">{[selected.kind !== 'claim' ? temporalKindLabel(selected.kind) : '', selected.time_role].filter(Boolean).join(' · ')}</div>
+ {/if}
+ <h2 dir="auto">{selected.label}</h2>
{#if inspectorLoading}<div class="inspector-loading">Loading details…</div>{/if}
+ <!-- The date on the clock the axis is read on, first: a camera's 17:07 UTC in
+ Sanaa is read as 20:07 there. The value as it was stated follows it. Only
+ for a value that names an instant: a date has no time of day, and printing
+ 00:00 in another zone would invent an hour the source never gave. -->
<div class="date-reading">
<Icon name="clock" size={15} />
<div>
- <strong>{selectedReading.label}</strong>{#if selected.raw}<code>{selected.raw}</code>{/if}<small>{selected.precision || 'No global position'}{#if selected.zone} · {selected.zone}{/if}</small>
- <!-- The same instant on the clock the axis is being read on. Only for a
- value that names one: a date has no time of day, and printing 00:00
- in another zone would invent an hour the source never gave. -->
- {#if zone !== UTC && selected.earliest && ['second', 'subsecond'].includes(selected.precision)}
- <small class="in-zone">{zonedStamp(selected.earliest, zone)} {zoneWord}</small>
+ {#if onClock}
+ <strong>{clockReading(selected.earliest, zone)}</strong>
+ <small class="as-stated">{selectedReading.label}</small>
+ {:else}
+ <strong>{selectedReading.label}</strong>
{/if}
</div>
</div>
+ <!-- The date is changed where it is read. Dragging the mark and the full editor
+ still do it; a picked entry just no longer hides how. A file's own date is
+ never rewritten: it is corrected by a sourced event beside it. -->
+ {#if selected.kind === 'claim' && !snapshotReading}
+ {#if dateEditing?.id === selected.id}
+ <form class="date-edit" onsubmit={(event) => { event.preventDefault(); saveDateEdit(); }}>
+ <DateField
+ id="inspector-when"
+ label="When"
+ placeholder="dd/mm/yyyy hh:mm"
+ calendar
+ value={dateEditing.value}
+ zone={dateSettled.zone}
+ onchange={(value) => (dateEditing = {
+ ...dateEditing,
+ value,
+ // a clock typed into the value itself (`14:30 UTC`) takes over
+ picked: writesOwnClock(value) ? undefined : dateEditing.picked,
+ })}
+ />
+ <ClockField
+ value={dateEditing.value}
+ clock={dateSettled.clock}
+ timed={isTimed(dateEditing.value)}
+ onpick={(zone) => (dateEditing = { ...dateEditing, picked: zone })}
+ />
+ <div class="date-edit-acts">
+ <button type="button" class="btn btn-ghost btn-sm" onclick={() => (dateEditing = null)}>Cancel</button>
+ <button type="submit" class="btn btn-primary btn-sm" disabled={!dateEditReady}>Save date</button>
+ </div>
+ </form>
+ {:else}
+ <button class="btn btn-sm date-change" onclick={startDateEdit}>
+ <Icon name="edit" size={12} /> {selected.raw ? 'Change the date' : 'Give it a date'}
+ </button>
+ {/if}
+ {:else if selected.category === 'media' && !snapshotReading}
+ <button
+ class="btn btn-sm date-change"
+ disabled={!inspectorChain?.entity}
+ title="The file keeps its own date; this files a sourced correction beside it"
+ onclick={addMediaCorrection}
+ >
+ <Icon name="edit" size={12} /> Correct this date
+ </button>
+ {/if}
<!-- What the case knows about the time between two entries. The wording is
`lib/timeline.js`: a gap printed as one number when the dates only allow
@@ -1876,8 +2637,6 @@
<small>{pairReading.detail}</small>
{#each pairReading.notes as note (note)}<small class="caveat">{note}</small>{/each}
</section>
- {:else}
- <p class="measure-hint">Ctrl-click a second entry to measure between them.</p>
{/if}
<div class="badges">
{#if selected.approximate}<span>Date: approximate</span>{/if}
@@ -1887,21 +2646,12 @@
</div>
{#if selected.parse_error}<p class="warning">{selected.parse_error}</p>{/if}
{#if selected.raw && !selected.earliest && selected.zone === 'local'}<p class="warning">Add a timezone to place this time on the UTC axis.</p>{/if}
- {#if canDragTemporal(selected) && !snapshotReading}<p class="axis-edit-help">{selected.shape === 'interval' ? 'Drag to move. Use either edge to resize.' : 'Drag the event to move it.'}</p>{/if}
- <dl class="temporal-facts">
- <div><dt>Precision</dt><dd>{selected.precision || 'Not set'}</dd></div>
- <div><dt>Timezone</dt><dd>{selected.zone || 'Not set'}</dd></div>
- <div><dt>Authority</dt><dd>{selected.authority || selected.category}</dd></div>
- {#if selected.time_role}<div><dt>Time role</dt><dd>{selected.time_role}</dd></div>{/if}
- {#if selected.status}<div><dt>Status</dt><dd>{selected.status}</dd></div>{/if}
- {#if selected.confidence}<div><dt>Confidence</dt><dd>{selected.confidence}</dd></div>{/if}
- </dl>
{#if inspectorChain?.entity?.attrs?.method}
- <section class="inspector-note"><h3>Method</h3><p>{inspectorChain.entity.attrs.method}</p></section>
+ <section class="inspector-note"><h3>Method</h3><p dir="auto">{inspectorChain.entity.attrs.method}</p></section>
{/if}
{#if inspectorChain?.entity?.attrs?.verbatim}
- <section class="inspector-note"><h3>Source wording</h3><blockquote>{inspectorChain.entity.attrs.verbatim}</blockquote></section>
+ <section class="inspector-note"><h3>Source wording</h3><blockquote dir="auto">{inspectorChain.entity.attrs.verbatim}</blockquote></section>
{/if}
{#if inspectorConnections.about.length || inspectorConnections.at.length || inspectorConnections.cites.length}
@@ -1920,6 +2670,29 @@
{/if}
</section>
{/if}
+
+ <!-- How the date is held, for whoever needs to check it: the stored value, its
+ precision and zone, who states it. Folded, since reading a chronology
+ rarely needs it and it was most of the panel. -->
+ <details class="date-more">
+ <summary>About this date</summary>
+ <div class="date-reading plain">
+ <div>
+ {#if selected.raw}<code>{selected.raw}</code>{/if}<small>{selected.precision || 'No global position'}{#if selected.tz || selected.zone} · {selected.tz || selected.zone}{/if}</small>
+ </div>
+ </div>
+ <dl class="temporal-facts">
+ <div><dt>Precision</dt><dd>{selected.precision || 'Not set'}</dd></div>
+ <div><dt>Timezone</dt><dd>{temporalZoneWords(selected)}</dd></div>
+ <div><dt>Authority</dt><dd>{selected.authority || selected.category}</dd></div>
+ {#if selected.time_role}<div><dt>Time role</dt><dd>{selected.time_role}</dd></div>{/if}
+ {#if selected.status}<div><dt>Status</dt><dd>{selected.status}</dd></div>{/if}
+ {#if selected.confidence}<div><dt>Confidence</dt><dd>{selected.confidence}</dd></div>{/if}
+ </dl>
+ {#if canDragTemporal(selected) && !snapshotReading}<p class="axis-edit-help">{selected.shape === 'interval' ? 'Drag it on the axis to move it, or either edge to resize.' : 'Drag it on the axis to move it.'}</p>{/if}
+ {#if !pairReading}<p class="measure-hint">Ctrl-click a second entry to measure between them.</p>{/if}
+ </details>
+
<!-- Both acts are about a lane: pinning keeps an entry out of that lane's
density overflow, hiding takes it out of that lane. An entry with no
place on the axis is in neither, so it is offered neither — a control
@@ -1932,17 +2705,14 @@
</section>
{/if}
</div>
+ <!-- A file's date is corrected with the button under it; the footer only opens
+ what the entry belongs to, or edits the event whole. -->
<footer>
<button class="btn btn-ghost" disabled={snapshotReading} onclick={() => (detailsId = selected.owner_id)}>Details</button>
{#if selected.category === 'statement'}<button class="btn btn-primary" disabled={snapshotReading} onclick={() => openEditor(selected)}>Edit claim</button>{/if}
- {#if selected.category === 'media'}<button class="btn btn-primary" disabled={snapshotReading || !inspectorChain?.entity} onclick={addMediaCorrection}>Add correction</button>{/if}
</footer>
- {:else}
- <!-- The tool's own clock rather than a target: nothing is being aimed at here,
- and the panel is empty until an entry is chosen. -->
- <div class="inspector-empty"><Icon name="clock" size={16} /><span>Select an entry</span></div>
- {/if}
</aside>
+ {/if}
</div>
<!-- Inside the tool, not beside it: this screen goes to full screen, and nothing
@@ -1986,12 +2756,12 @@
{#if tooltip}
<div class="timeline-tooltip" style:left={`${tooltip.x}px`} style:top={`${tooltip.y}px`} role="tooltip">
- <strong>{tooltip.title}</strong><span>{tooltip.date}</span>{#if tooltip.detail}<small>{tooltip.detail}</small>{/if}
+ <strong>{tooltip.title}</strong><span>{tooltip.date}</span>{#if tooltip.detail}<small class:sentence={tooltip.sentence}>{tooltip.detail}</small>{/if}
</div>
{/if}
{#if editor}
- <Modal title={editor.item ? 'Edit claim' : 'Add claim'} onclose={() => (editor = null)} width="660px">
+ <Modal title={editor.item ? 'Edit claim' : 'Add event'} onclose={() => (editor = null)} width="660px">
<TemporalClaimEditor
caseId={caseState.current.id}
item={editor.item}
@@ -2025,9 +2795,9 @@
{#if pendingEdit}
<ConfirmDialog
- title={pendingEdit.item.shape === 'interval' ? 'Change this period?' : 'Move this date?'}
+ title={!pendingEdit.item.raw ? 'Date this entry?' : pendingEdit.item.shape === 'interval' ? 'Change this period?' : 'Move this date?'}
message={pendingEdit.item.label}
- detail={`${pendingEdit.item.raw} → ${pendingEdit.raw}`}
+ detail={`${pendingEdit.item.raw ? formatTemporalValue(pendingEdit.item.raw, pendingEdit.item.tz).label : 'Undated'} → ${formatTemporalValue(pendingEdit.raw, pendingEdit.zone === undefined ? pendingEdit.item.tz : pendingEdit.zone).label}`}
confirmLabel="Update date"
icon="clock"
busy={directSaving}
@@ -2045,18 +2815,15 @@
background: var(--bg-0);
color: var(--text-1);
}
- .timeline-head { display: grid; grid-template-columns: minmax(160px, 1fr) auto minmax(160px, 1fr); align-items: center; gap: 18px; padding: 12px 24px 10px; }
- /* The house header: name, then one clause. `app.css .tool-header` spells the same
- two rules, and this screen keeps its own only because the head is a three-column
- grid with the range controls in the middle. */
- .title-block { min-width: 0; display: flex; align-items: baseline; gap: 10px; }
- .title-block h2 { font-size: var(--fs-lg); font-weight: 600; letter-spacing: -0.01em; }
- .title-block .sub { overflow: hidden; color: var(--text-3); font-size: var(--fs-sm); text-overflow: ellipsis; white-space: nowrap; }
- /* The middle column carries the window and nothing else. One segmented group: step
- back, the window itself, step on. */
- .range { position: relative; display: flex; align-items: center; justify-self: center; }
+ /* The one bar: the period, its clock and the split, then Views, Export and `⋯` at the
+ end. One row of controls where there were three. */
+ .timeline-bar { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; padding: 10px 24px; border-bottom: 1px solid var(--border); }
+ .bar-end { margin-left: auto; display: flex; align-items: center; gap: 5px; }
+ .frozen { color: var(--accent); font-size: 10px; font-style: normal; }
+ /* One segmented group: step back, the window itself, step on. */
+ .range { position: relative; display: flex; align-items: center; }
.range-step, .range-face {
- height: 30px; border: 1px solid var(--border); background: var(--bg-2);
+ height: 28px; border: 1px solid var(--border); background: var(--bg-2);
color: var(--text-2); cursor: pointer;
}
.range-step { width: 28px; display: grid; place-items: center; padding: 0; }
@@ -2066,10 +2833,9 @@
.range-step:hover, .range-face:hover, .range-face[aria-expanded='true'] { border-color: var(--border-strong); color: var(--text-1); }
.range-step:disabled { opacity: .4; cursor: default; }
.range-menu {
- position: absolute; z-index: 80; top: calc(100% + 6px); left: 50%; width: 244px;
+ position: absolute; z-index: 80; top: calc(100% + 6px); left: 0; width: 244px;
display: grid; gap: 9px; padding: 11px; border: 1px solid var(--border-strong);
border-radius: var(--r-md); background: var(--bg-1); box-shadow: var(--shadow-2);
- transform: translateX(-50%);
}
.range-menu label { display: grid; gap: 4px; color: var(--text-3); font-size: var(--fs-xs); }
.range-spans { display: flex; flex-wrap: wrap; gap: 4px; padding-top: 9px; border-top: 1px solid var(--border); }
@@ -2077,10 +2843,8 @@
flex: 1 1 30%; padding: 5px 0; border: 1px solid var(--border); border-radius: var(--r-sm);
background: var(--bg-2); color: var(--text-2); font-size: var(--fs-xs); cursor: pointer;
}
- /* Ends the track row: the label in the row's own small grey, the three surfaces
- welded into one segmented control so they read as one choice. */
- .range-handoffs { margin-left: auto; flex: 0 0 auto; display: flex; align-items: center; }
- .range-handoffs > span { margin-right: 8px; color: var(--text-3); font-size: 10px; }
+ /* The three tools welded into one segmented control, so they read as one choice. */
+ .range-handoffs > div { display: flex; }
.range-handoffs button {
height: 24px;
padding: 0 10px;
@@ -2097,15 +2861,26 @@
.range-handoffs button:disabled { opacity: .4; cursor: default; }
.range-spans button:hover { border-color: var(--border-strong); color: var(--text-1); }
.range-spans button:disabled { opacity: .4; cursor: default; }
- .head-actions { justify-self: end; display: flex; align-items: center; gap: 5px; }
- /* One height across the row. Views and Export come from shared components and are
- `btn-sm`, the tool's own two are not, and four buttons of two heights read as a
- mistake. Stated from the same tokens a plain `.btn` is built from — its text plus
- its padding and rule — rather than as a number that would drift from them. */
- .head-actions :global(.btn) { min-height: calc(var(--fs-sm) * 1.5 + 12px); }
- .add-event { justify-self: end; }
.timeline-tool:fullscreen { width: 100vw; height: 100vh; }
- .filter-row { min-height: 42px; display: flex; align-items: center; gap: 8px; padding: 0 24px 10px; border-bottom: 1px solid color-mix(in srgb, var(--border) 75%, transparent); }
+ /* What `⋯` holds, grouped the way it is asked for: a track to add, how lanes split,
+ the period handed on, what the marks mean, the whole screen. */
+ .more { position: relative; }
+ .more-btn { display: grid; place-items: center; width: 30px; padding: 0; }
+ .more-menu {
+ position: absolute; z-index: 70; top: calc(100% + 5px); right: 0; width: 264px;
+ max-height: min(70vh, 560px); overflow: auto; display: grid; gap: 4px; padding: 7px;
+ border: 1px solid var(--border-strong); border-radius: var(--r-md); background: var(--bg-1);
+ box-shadow: var(--shadow-2);
+ }
+ .more-menu > section { display: grid; padding-bottom: 5px; border-bottom: 1px solid var(--border); }
+ .more-menu > section > strong { padding: 5px 7px 5px; color: var(--text-3); font-size: 9px; letter-spacing: .07em; text-transform: uppercase; }
+ .more-menu > section > button, .more-act { display: flex; justify-content: space-between; gap: 8px; padding: 7px; border: 0; border-radius: var(--r-sm); background: none; color: var(--text-2); font-size: var(--fs-xs); text-align: left; cursor: pointer; }
+ .more-menu > section > button:hover:not(:disabled), .more-act:hover { background: var(--bg-2); color: var(--text-1); }
+ .more-menu > section > button:disabled { opacity: .45; cursor: default; }
+ .more-menu > section > button small { color: var(--text-3); font-size: 9px; }
+ .more-menu .custom { margin-top: 3px; border-top: 1px solid var(--border); border-radius: 0 0 var(--r-sm) var(--r-sm); }
+ .more-row { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 5px 7px; color: var(--text-3); font-size: 10px; }
+ .more-row select { width: 118px; }
.category-dot { width: 7px; height: 7px; flex: 0 0 auto; border-radius: 50%; background: var(--text-3); }
/* `--track-tint` is the colour the analyst gave this track, set on its row. Unset
everywhere else, so the category keeps its own colour and the legend stays true. */
@@ -2117,10 +2892,9 @@
.view-switch { display: flex; padding: 2px; border: 1px solid var(--border); border-radius: var(--r-sm); background: var(--bg-1); }
.view-switch button { padding: 3px 7px; border: 0; border-radius: 2px; background: none; color: var(--text-3); font-size: 10px; cursor: pointer; }
.view-switch button.active { background: var(--bg-3); color: var(--text-1); }
- .legend { position: relative; }
- .legend > summary { padding: 4px 6px; color: var(--text-3); font-size: 10px; cursor: pointer; list-style: none; }
- .legend > summary::-webkit-details-marker { display: none; }
- .legend-card { position: absolute; z-index: 45; top: calc(100% + 5px); left: 0; width: 210px; display: grid; gap: 7px; padding: 10px; border: 1px solid var(--border-strong); border-radius: var(--r-md); background: var(--bg-1); box-shadow: var(--shadow-2); }
+ .legend { border-block: 1px solid var(--border); }
+ .legend > summary { padding: 7px; color: var(--text-2); font-size: var(--fs-xs); cursor: pointer; }
+ .legend-card { display: grid; gap: 7px; padding: 4px 7px 10px; }
.legend-card > strong { margin-top: 2px; color: var(--text-3); font-size: 9px; letter-spacing: .06em; text-transform: uppercase; }
.legend-card > span { display: flex; align-items: center; gap: 8px; color: var(--text-2); font-size: var(--fs-xs); }
.legend-card p { margin: 2px 0 0; color: var(--text-2); font-size: var(--fs-xs); line-height: 1.35; }
@@ -2131,26 +2905,26 @@
.sample.suggested::after { content: ''; position: absolute; top: 2px; right: 2px; width: 4px; height: 4px; border-radius: 50%; background: var(--track-statement); box-shadow: 0 0 0 1px var(--bg-1); }
.sample.refuted { position: relative; opacity: .8; }
.sample.refuted::after { content: ''; position: absolute; left: 2px; right: 2px; top: 4px; border-top: 1px solid var(--text-2); transform: rotate(-8deg); }
- .utc-readout { margin-left: auto; color: var(--text-3); font: 10px var(--mono); letter-spacing: .03em; }
- /* Wraps rather than scrolls: the Add-a-track menu hangs out of this row, and an
- overflow container would clip it. */
- .track-toolbar { min-height: 38px; display: flex; flex-wrap: wrap; align-items: center; gap: 6px 12px; padding: 6px 24px; border-bottom: 1px solid var(--border); background: color-mix(in srgb, var(--bg-1) 82%, transparent); }
- .track-toolbar > label { display: inline-flex; align-items: center; gap: 6px; color: var(--text-3); font-size: 10px; }
- .track-toolbar > label select { width: 118px; }
- .track-toolbar > span { color: var(--text-3); font-size: 10px; }
- .track-toolbar > em { color: var(--accent); font-size: 10px; font-style: normal; }
- .track-add { position: relative; }
- .track-menu { position: absolute; z-index: 70; top: calc(100% + 5px); left: 0; width: 250px; display: grid; padding: 7px; border: 1px solid var(--border-strong); border-radius: var(--r-md); background: var(--bg-1); box-shadow: var(--shadow-2); }
- .track-menu > strong { padding: 5px 7px 7px; color: var(--text-3); font-size: 9px; letter-spacing: .07em; text-transform: uppercase; }
- .track-menu > button { display: flex; justify-content: space-between; gap: 8px; padding: 7px; border: 0; border-radius: var(--r-sm); background: none; color: var(--text-2); text-align: left; cursor: pointer; }
- .track-menu > button:hover { background: var(--bg-2); color: var(--text-1); }
- .track-menu > button small { color: var(--text-3); font-size: 9px; }
- .track-menu .custom { margin-top: 5px; border-top: 1px solid var(--border); border-radius: 0 0 var(--r-sm) var(--r-sm); }
- .timeline-grid { min-height: 0; flex: 1; display: grid; grid-template-columns: minmax(0, 1fr) 330px; }
- .chronology { position: relative; min-width: 0; overflow: auto; padding: 18px 24px 28px; }
+ .sample.shape-point { width: 8px; height: 8px; margin-inline: 10px; border: 0; border-radius: 50%; background: var(--track-statement); }
+ .sample.shape-bracket { height: 8px; border: 0; border-inline: 2px solid var(--track-statement); border-radius: 0; background: linear-gradient(to bottom, transparent 3px, var(--track-statement) 3px, var(--track-statement) 5px, transparent 5px); }
+ .sample.shape-bar { height: 8px; border-radius: 2px; background: color-mix(in srgb, var(--track-statement) 32%, var(--bg-1)); }
+ .timeline-grid { min-height: 0; flex: 1; display: grid; grid-template-columns: minmax(0, 1fr); grid-template-rows: minmax(0, 1fr); }
+ .timeline-grid.inspecting { grid-template-columns: minmax(0, 1fr) 330px; }
+ /* The overview, the axis, the bar between and the list: one reading in one column,
+ where the axis and the list scroll each on their own, so picking an entry in one
+ never scrolls the other out of view. */
+ .chronology { position: relative; min-width: 0; min-height: 0; display: flex; flex-direction: column; overflow: auto hidden; padding: 14px 24px 16px; }
+ /* A column rather than a grid of fixed rows: the strip under the axis comes and goes,
+ and a snapshot has no entry line, and neither may move the list into the wrong row. */
+ .chronology > * { flex: none; }
+ .chronology > .reading-pane { flex: 1 1 0; }
+ .chronology.blank { display: block; overflow: auto; padding-bottom: 28px; }
/* A panel is a border and a fill. The 35px drop shadow under each one read as a
floating card, which is a look rather than a reading of the case. */
.axis-card, .overview-card, .holding-card, .timeline-list { border: 1px solid var(--border); border-radius: var(--r); background: var(--bg-1); overflow: hidden; }
+ .axis-card { position: relative; min-height: 0; overflow: hidden auto; }
+ /* The ruler stays over the tracks it measures however far they scroll. */
+ .axis-row { position: sticky; top: 0; z-index: 6; background: var(--bg-1); }
/* One width for the gutter, and wide enough for a name the analyst chose: at 132px
"Events" arrived as "E." and a track nobody can read is a colour with a count. */
.axis-card, .overview-card { --gutter: 178px; }
@@ -2195,6 +2969,12 @@
.track-label strong { font-size: var(--fs-xs); }
.track-label small { padding: 1px 5px; border-radius: 999px; background: var(--bg-3); color: var(--text-3); font-size: 9px; }
.track-actions { grid-column: 3 / -1; display: flex; gap: 2px; }
+ /* A lane's own tools come with the pointer. Always shown, they were a grip and three
+ icons under every name, read by nobody who was reading the lane. */
+ .drag-track, .track-actions { opacity: 0; transition: opacity .12s ease; }
+ .track-row:hover .drag-track, .track-row:hover .track-actions,
+ .track-label:focus-within .drag-track, .track-label:focus-within .track-actions { opacity: 1; }
+ @media (hover: none) { .drag-track, .track-actions { opacity: 1; } }
.track-label.movable .track-actions { grid-column: 4 / -1; }
.track-actions button { display: grid; place-items: center; padding: 3px; border: 0; background: none; color: var(--text-3); cursor: pointer; }
.track-actions button:hover { color: var(--text-1); }
@@ -2208,64 +2988,126 @@
.gridline { position: absolute; inset-block: 0; border-left: 1px solid color-mix(in srgb, var(--border) 65%, transparent); pointer-events: none; }
.gridline.minor { border-left-color: color-mix(in srgb, var(--border) 35%, transparent); }
.track-now { inset-block: 0; opacity: .7; }
- .track-hint, .track-empty { position: absolute; right: 12px; top: 6px; color: color-mix(in srgb, var(--text-3) 65%, transparent); font-size: 9px; pointer-events: none; }
+ .track-hint, .track-empty { position: absolute; right: 12px; top: 2px; color: color-mix(in srgb, var(--text-3) 65%, transparent); font-size: 9px; pointer-events: none; }
.track-empty { left: 14px; right: auto; top: 26px; font-size: var(--fs-xs); }
.folded-note { position: absolute; top: 13px; left: 14px; color: var(--text-3); font-size: 9px; }
.draw-range { position: absolute; inset-block: 12px; z-index: 6; border: 1px solid color-mix(in srgb, var(--accent) 70%, transparent); border-radius: 4px; background: color-mix(in srgb, var(--accent) 14%, transparent); pointer-events: none; }
- .timeline-event { --event-color: var(--track-tint, var(--track-statement)); position: absolute; z-index: 2; height: 36px; display: flex; align-items: stretch; border: 1px solid color-mix(in srgb, var(--event-color) 65%, var(--border)); border-radius: 7px; background: color-mix(in srgb, var(--event-color) 11%, var(--bg-1)); color: var(--text-1); transform: translateX(-8px); box-shadow: 0 3px 10px color-mix(in srgb, var(--bg-0) 55%, transparent); }
- .timeline-event.media { --event-color: var(--track-tint, var(--track-media)); }
+ /* One row of marks is 18px: a point is an 8px dot centred on its instant, a bracket a
+ 2px line with a stop at each end of the period a reduced date covers, a bar an 8px
+ band as long as its period. Nothing is nudged sideways, so a mark sits exactly on
+ its date whichever way the axis is scrolled. */
+ .timeline-event { --event-color: var(--track-tint, var(--track-statement)); position: absolute; z-index: 2; height: 18px; color: var(--text-1); }
+ .timeline-event.media, .timeline-event.as-file { --event-color: var(--track-tint, var(--track-media)); }
.timeline-event.case_activity { --event-color: var(--track-tint, var(--track-activity)); }
- .timeline-event.period { min-width: 28px; transform: none; }
- .timeline-event.end-aligned { transform: translateX(calc(-100% + 8px)); }
- .timeline-event.chosen { z-index: 8; border-color: var(--accent); box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent) 18%, transparent), 0 5px 16px color-mix(in srgb, var(--bg-0) 70%, transparent); }
+ .timeline-event.chosen, .timeline-event.against, .timeline-event.guided { z-index: 8; }
+ .event-select { position: absolute; inset: 0; display: block; padding: 0; border: 0; background: none; color: inherit; font: inherit; cursor: pointer; }
+ /* 8px to the eye, 20px to the pointer. */
+ .point .event-select::before { content: ''; position: absolute; inset: 0 -5px; }
+ .event-shape { position: absolute; box-sizing: border-box; pointer-events: none; }
+ .point .event-shape { top: 5px; left: calc(50% - 4px); width: 8px; height: 8px; border-radius: 50%; background: var(--event-color); box-shadow: 0 0 0 1.5px var(--bg-1); }
+ .bracket .event-shape { inset: 5px 0; border-inline: 2px solid var(--event-color); background: linear-gradient(to bottom, transparent 3px, var(--event-color) 3px, var(--event-color) 5px, transparent 5px); }
+ .bar .event-shape { inset: 5px 0; border: 1px solid var(--event-color); border-radius: 2px; background: color-mix(in srgb, var(--event-color) 32%, var(--bg-1)); }
+ /* A span running past the window has no stop on that side: it goes on. */
+ .bracket.open-start .event-shape { border-left-width: 0; }
+ .bracket.open-end .event-shape { border-right-width: 0; }
+ .bar.open-start .event-shape { border-left-style: dotted; border-top-left-radius: 0; border-bottom-left-radius: 0; }
+ .bar.open-end .event-shape { border-right-style: dotted; border-top-right-radius: 0; border-bottom-right-radius: 0; }
+ .timeline-event.approximate.point .event-shape { box-shadow: none; outline: 1.5px dashed var(--event-color); outline-offset: 1px; }
+ .timeline-event.approximate.bracket .event-shape { border-inline-style: dashed; }
+ .timeline-event.approximate.bar .event-shape { border-style: dashed; }
+ .timeline-event.uncertain.point .event-shape { background: repeating-linear-gradient(135deg, var(--event-color) 0 2px, var(--bg-1) 2px 3px); }
+ .timeline-event.uncertain.bracket .event-shape { background: repeating-linear-gradient(90deg, var(--event-color) 0 3px, transparent 3px 5px) center / 100% 2px no-repeat; }
+ .timeline-event.uncertain.bar .event-shape { background-image: repeating-linear-gradient(135deg, transparent, transparent 3px, color-mix(in srgb, var(--text-2) 22%, transparent) 3px, color-mix(in srgb, var(--text-2) 22%, transparent) 5px); }
+ /* A proposal is hollow, the way every surface draws one. */
+ .timeline-event.suggested.point .event-shape { border: 2px solid var(--event-color); background: var(--bg-1); }
+ .timeline-event.suggested.bracket .event-shape { border-inline-style: dotted; opacity: .75; }
+ .timeline-event.suggested.bar .event-shape { border-style: dotted; background: color-mix(in srgb, var(--event-color) 10%, var(--bg-1)); }
+ .timeline-event.refuted { opacity: .55; }
+ .timeline-event.refuted .event-caption, .timeline-event.refuted .card-copy strong { text-decoration: line-through; text-decoration-thickness: 1px; }
+ .timeline-event.pinned::before { content: ''; position: absolute; z-index: 3; top: 0; left: calc(50% - 4px); width: 8px; height: 2px; border-radius: 1px; background: var(--accent); pointer-events: none; }
+ .timeline-event.chosen.point .event-shape { box-shadow: 0 0 0 2px var(--bg-1), 0 0 0 4px var(--accent); }
+ .timeline-event.chosen:not(.point) .event-shape { box-shadow: 0 0 0 1px var(--bg-1), 0 0 0 3px var(--accent); }
/* The entry held against the selected one. Marked apart rather than as a second
selection: only one of the two is the one being read. */
- .timeline-event.against { z-index: 8; border-color: var(--text-2); border-style: dashed; }
- .timeline-event.pinned { box-shadow: inset 0 2px 0 var(--accent), 0 3px 10px color-mix(in srgb, var(--bg-0) 55%, transparent); }
- .timeline-event.approximate { border-style: dashed; }
- .timeline-event.uncertain { background-image: repeating-linear-gradient(135deg, transparent, transparent 4px, color-mix(in srgb, var(--text-2) 12%, transparent) 4px, color-mix(in srgb, var(--text-2) 12%, transparent) 7px); }
- .timeline-event.suggested::after { content: ''; position: absolute; z-index: 5; top: 3px; right: 3px; width: 5px; height: 5px; border-radius: 50%; background: var(--event-color); box-shadow: 0 0 0 2px var(--bg-1); pointer-events: none; }
- .timeline-event.refuted { opacity: .8; }
- .timeline-event.refuted .event-label { text-decoration: line-through; text-decoration-thickness: 1px; }
- .event-select { min-width: 0; flex: 1; display: flex; align-items: center; gap: 6px; padding: 3px 7px; overflow: hidden; border: 0; background: none; color: inherit; text-align: left; cursor: pointer; }
- .event-point { width: 8px; height: 8px; flex: 0 0 auto; border: 2px solid var(--bg-1); border-radius: 50%; background: var(--event-color); box-shadow: 0 0 0 1px var(--event-color); }
- .event-text { min-width: 0; display: grid; line-height: 1.12; }
- .event-label, .event-date { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
- .event-label { font-size: 10px; font-weight: 650; }
- .event-date { margin-top: 2px; color: var(--text-3); font: 8px var(--mono); }
- .precision-span { --event-color: var(--track-tint, var(--track-statement)); position: absolute; z-index: 1; height: 10px; min-width: 1px; border-inline: 1px solid color-mix(in srgb, var(--event-color) 55%, transparent); background: linear-gradient(to bottom, transparent 4px, color-mix(in srgb, var(--event-color) 42%, transparent) 4px, color-mix(in srgb, var(--event-color) 42%, transparent) 6px, transparent 6px); pointer-events: none; }
- .precision-span.media { --event-color: var(--track-tint, var(--track-media)); }
- .precision-span.case_activity { --event-color: var(--track-tint, var(--track-activity)); }
- .precision-span.chosen { border-inline-color: var(--event-color); background: linear-gradient(to bottom, transparent 4px, color-mix(in srgb, var(--event-color) 72%, transparent) 4px, color-mix(in srgb, var(--event-color) 72%, transparent) 6px, transparent 6px); }
- .move-grip { display: none; width: 18px; place-items: center; padding: 0; border: 0; border-left: 1px solid var(--border); background: color-mix(in srgb, var(--bg-1) 90%, transparent); color: var(--text-3); cursor: ew-resize; }
+ .timeline-event.against .event-shape { outline: 1px dashed var(--text-2); outline-offset: 3px; }
+ .event-caption { position: absolute; top: 3px; height: 12px; box-sizing: content-box; overflow: hidden; color: var(--text-1); font-size: 10px; font-weight: 600; line-height: 12px; text-align: left; text-overflow: ellipsis; white-space: nowrap; }
+ .event-caption.left { text-align: right; }
+ .bracket .event-caption.inside { padding: 0 3px; background: var(--bg-1); }
+ /* A name inside a span interrupts its line rather than sitting on it, so it reads on
+ any tint. */
+ .bar .event-caption.inside { padding: 0 4px; border-radius: 3px; background: var(--bg-1); }
+ .timeline-event.chosen .event-caption { color: var(--accent); }
+ .card-stem { position: absolute; top: 13px; width: 0; border-left: 1px solid color-mix(in srgb, var(--event-color) 65%, transparent); pointer-events: none; }
+ .event-card { position: absolute; height: 40px; box-sizing: border-box; display: flex; align-items: center; gap: 7px; padding: 4px 8px; border: 1px solid color-mix(in srgb, var(--event-color) 55%, var(--border)); border-radius: 6px; background: color-mix(in srgb, var(--event-color) 8%, var(--bg-1)); box-shadow: 0 3px 10px color-mix(in srgb, var(--bg-0) 45%, transparent); text-align: left; }
+ .timeline-event.chosen .event-card { border-color: var(--accent); }
+ .event-card img { width: 32px; height: 30px; flex: 0 0 auto; border-radius: 3px; object-fit: cover; }
+ .card-copy { min-width: 0; display: grid; line-height: 1.15; }
+ .card-copy strong, .card-copy small { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+ .card-copy strong { font-size: 10px; font-weight: 650; }
+ .card-copy small { margin-top: 2px; color: var(--text-3); font: 9px var(--font-mono); }
+ .move-grip { display: none; position: absolute; z-index: 3; top: 100%; left: calc(50% - 9px); width: 18px; height: 14px; place-items: center; padding: 0; border: 1px solid var(--border); border-radius: 4px; background: var(--bg-2); color: var(--text-3); cursor: ew-resize; }
.timeline-event.chosen .move-grip { display: grid; }
- .resize { display: none; position: absolute; z-index: 3; top: 4px; bottom: 4px; width: 7px; padding: 0; border: 0; border-radius: 3px; background: var(--accent); cursor: ew-resize; }
+ .resize { display: none; position: absolute; z-index: 3; top: 2px; bottom: 2px; width: 7px; padding: 0; border: 0; border-radius: 3px; background: var(--accent); cursor: ew-resize; }
.timeline-event.chosen .resize { display: block; }
.resize.start { left: -4px; } .resize.end { right: -4px; }
- .timeline-cluster { position: absolute; z-index: 7; min-width: 32px; height: 24px; padding: 0 7px; border: 1px solid var(--border-strong); border-radius: 999px; background: var(--bg-3); color: var(--text-2); font: 700 10px var(--mono); transform: translateX(-50%); cursor: pointer; }
- .timeline-list { display: grid; padding-bottom: 5px; }
- .timeline-list h2 { display: flex; justify-content: space-between; margin: 0; padding: 9px 12px; border-top: 1px solid var(--border); background: var(--bg-2); color: var(--text-2); font-size: var(--fs-xs); }
- .timeline-list h2:first-child { border-top: 0; }
- .timeline-list h2 span { color: var(--text-3); font-weight: 400; }
- .timeline-list > button { display: grid; grid-template-columns: auto minmax(180px, 1fr) minmax(190px, auto) auto; align-items: center; gap: 10px; margin: 5px 7px 0; padding: 8px; border: 1px solid transparent; border-radius: var(--r-sm); background: none; color: var(--text-2); text-align: left; cursor: pointer; }
- .timeline-list > button:hover { background: var(--bg-2); }
- .timeline-list > button.chosen { border-color: var(--accent); background: var(--accent-soft); }
- .timeline-list > button.against { border-color: var(--text-3); border-style: dashed; }
- .list-copy, .list-date { min-width: 0; display: grid; }
- .list-copy strong, .list-copy small, .list-date strong, .list-date code { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
- .list-copy strong { color: var(--text-1); font-size: var(--fs-sm); }
- .list-copy small { color: var(--text-3); font-size: 10px; text-transform: capitalize; }
- .list-date { justify-items: end; }
- .list-date strong { font-size: var(--fs-xs); font-weight: 500; }
- .list-date code { color: var(--text-3); font-size: 9px; }
- .overview-card { display: grid; grid-template-columns: var(--gutter) minmax(500px, 1fr); min-height: 92px; margin-bottom: 12px; }
+ .timeline-cluster { position: absolute; z-index: 7; min-width: 26px; height: 16px; margin-top: 1px; padding: 0 6px; border: 1px solid var(--border-strong); border-radius: 999px; background: var(--bg-3); color: var(--text-2); font: 700 9px var(--font-mono); line-height: 14px; transform: translateX(-50%); cursor: pointer; }
+ .time-guide { position: absolute; inset: 0; z-index: 30; pointer-events: none; }
+ .guide-line { position: absolute; width: 0; border-left: 1px solid color-mix(in srgb, var(--accent) 75%, transparent); }
+ .guide-reading { position: absolute; transform: translateX(-50%); padding: 2px 7px; border: 1px solid color-mix(in srgb, var(--accent) 55%, var(--border)); border-radius: 999px; background: var(--bg-1); color: var(--text-1); font: 600 10px var(--font-mono); white-space: nowrap; box-shadow: var(--shadow-1); }
+ /* The list under the axis: one row per dated entry of the window, grouped by month
+ on the axis's clock, with what each is about, where, on what, and what it still
+ waits for. */
+ .reading-pane { min-height: 0; overflow: auto; }
+ .timeline-list { display: grid; }
+ .list-head { position: sticky; top: 0; z-index: 3; display: flex; align-items: center; gap: 10px; padding: 8px 12px; border-bottom: 1px solid var(--border); background: var(--bg-1); }
+ .list-head strong { font-size: var(--fs-xs); }
+ .list-head small { color: var(--text-3); font-size: 10px; }
+ .copy-menu { position: relative; margin-left: auto; }
+ .copy-options { position: absolute; z-index: 40; top: calc(100% + 4px); right: 0; display: grid; min-width: 170px; padding: 4px; border: 1px solid var(--border-strong); border-radius: var(--r-md); background: var(--bg-1); box-shadow: var(--shadow-2); }
+ .copy-options button { padding: 6px 8px; border: 0; border-radius: var(--r-sm); background: none; color: var(--text-2); font-size: var(--fs-xs); text-align: left; cursor: pointer; }
+ .copy-options button:hover { background: var(--bg-3); color: var(--text-1); }
+ .list-grid { display: grid; padding-bottom: 5px; }
+ /* The columns are the ones the window fills (`listTemplate`), set on the grid. */
+ .list-row { display: grid; grid-template-columns: var(--list-columns, 150px minmax(200px, 3fr) minmax(70px, 1.1fr) minmax(60px, .9fr) minmax(70px, 1.1fr) minmax(90px, auto)); align-items: center; gap: 10px; padding: 6px 12px; }
+ .list-row.headings { padding-block: 5px; color: var(--text-3); font-size: 9px; letter-spacing: .06em; text-transform: uppercase; }
+ .list-row.month { display: block; padding: 7px 12px; border-top: 1px solid var(--border); background: var(--bg-2); color: var(--text-2); font-size: var(--fs-xs); font-weight: 650; }
+ .list-row.month small { margin-left: 8px; color: var(--text-3); font-weight: 400; }
+ .list-row.entry { margin: 2px 6px 0; border: 1px solid transparent; border-radius: var(--r-sm); color: var(--text-2); cursor: pointer; }
+ .list-row.entry:hover, .list-row.entry.lit { background: var(--bg-2); }
+ .list-row.entry:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; }
+ .list-row.entry.chosen { border-color: var(--accent); background: var(--accent-soft); }
+ .list-row.entry.against { border-color: var(--text-3); border-style: dashed; }
+ .list-date, .list-links { min-width: 0; overflow: hidden; font-size: var(--fs-xs); text-overflow: ellipsis; white-space: nowrap; }
+ .list-date { color: var(--text-1); font-variant-numeric: tabular-nums; }
+ .list-links { color: var(--text-3); }
+ .list-copy { min-width: 0; display: flex; align-items: center; gap: 7px; }
+ .list-copy strong { min-width: 0; overflow: hidden; color: var(--text-1); font-size: var(--fs-sm); font-weight: 600; text-overflow: ellipsis; white-space: nowrap; }
+ .list-flags { display: flex; gap: 4px; justify-content: flex-end; }
+ .list-flags em { padding: 1px 6px; border: 1px solid var(--border); border-radius: 999px; color: var(--text-3); font-size: 9px; font-style: normal; white-space: nowrap; }
+ .list-flags em.suggested { border-style: dashed; color: var(--text-2); }
+ .list-flags em.assessed { border-color: transparent; background: var(--bg-3); color: var(--text-2); }
+ .list-flags em.refuted { text-decoration: line-through; }
+ .list-empty { margin: 0; padding: 14px 12px; color: var(--text-3); font-size: var(--fs-xs); }
+ .sr-only { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; }
+ /* The mark and the row of the entry under the pointer light each other. */
+ .timeline-event.lit .event-shape { box-shadow: 0 0 0 2px var(--bg-1), 0 0 0 4px color-mix(in srgb, var(--accent) 45%, transparent); }
+ .timeline-event.lit .event-caption { color: var(--accent); }
+ .entry-host { margin: 4px 0 10px; padding: 9px 10px 7px; border: 1px solid var(--border); border-radius: var(--r-md); background: var(--bg-1); }
+ .blank-line { width: min(860px, 62vw); margin-top: 14px; text-align: left; }
+ .blank-line .entry-host { margin: 0; }
+ .split { position: relative; height: 12px; cursor: row-resize; touch-action: none; }
+ .split::before { content: ''; position: absolute; top: 4px; left: calc(50% - 22px); width: 44px; height: 4px; border-radius: 2px; background: var(--border-strong); }
+ .split:hover::before, .split:focus-visible::before { background: var(--accent); }
+ .split:focus-visible { outline: none; }
+ /* Under the axis, so the axis stays where it was when the strip arrives. */
+ .overview-card { display: grid; grid-template-columns: var(--gutter) minmax(500px, 1fr); min-height: 84px; margin-top: 10px; }
.overview-title { display: grid; align-content: center; gap: 2px; padding: 10px 12px; border-right: 1px solid var(--border); }
.overview-title > span { font-size: var(--fs-xs); font-weight: 700; }
.overview-title small { color: var(--text-3); font-size: 9px; }
.overview-title .capped { color: var(--warn); }
.overview-counts { display: flex; flex-wrap: wrap; gap: 3px; margin-top: 3px; }
.overview-counts span { padding: 1px 4px; border-radius: 2px; background: var(--bg-3); color: var(--text-3); font-size: 8px; }
- .density-bars { position: relative; min-width: 500px; height: 68px; margin: 12px 10px; overflow: hidden; border-radius: 3px; background: color-mix(in srgb, var(--bg-2) 40%, transparent); cursor: crosshair; }
+ .density-bars { position: relative; min-width: 500px; height: 68px; margin: 8px 10px; overflow: hidden; border-radius: 3px; background: color-mix(in srgb, var(--bg-2) 40%, transparent); cursor: crosshair; }
/* One column per bin, as wide as the bin, stacked by category — a histogram, which
is only readable because the bins are cut as fine as they can be drawn. The floor
keeps a lone day visible and clickable at a scale where a day is under a pixel.
@@ -2312,11 +3154,16 @@
.blank-state { height: 100%; min-height: 340px; display: grid; place-content: center; justify-items: center; gap: 8px; color: var(--text-3); text-align: center; }
.blank-state h2 { margin: 0; color: var(--text-1); font-size: var(--fs-md); font-weight: 600; }
.blank-state p { max-width: 360px; margin: 0 0 6px; }
+ .text-button { padding: 0; border: 0; background: none; color: var(--accent); font: inherit; text-decoration: underline; text-underline-offset: 2px; cursor: pointer; }
.inspector { min-height: 0; display: flex; flex-direction: column; border-left: 1px solid var(--border); background: color-mix(in srgb, var(--bg-1) 97%, transparent); }
.inspector > header { display: flex; align-items: center; gap: 7px; min-height: 45px; padding: 0 13px; border-bottom: 1px solid var(--border); color: var(--text-3); font-size: 10px; font-weight: 700; text-transform: uppercase; letter-spacing: .08em; }
.inspector > header button { display: grid; margin-left: auto; padding: 4px; border: 0; background: none; color: var(--text-3); cursor: pointer; }
.inspector-body { min-height: 0; overflow: auto; padding: 16px; }
.inspector-loading { margin: -7px 0 9px; color: var(--text-3); font-size: 9px; }
+ .from-file { margin: -6px 0 12px; }
+ .date-change { margin-top: 8px; }
+ .date-edit { display: grid; gap: 8px; margin-top: 8px; padding: 10px; border: 1px solid var(--accent); border-radius: var(--r-sm); background: var(--bg-2); }
+ .date-edit-acts { display: flex; justify-content: flex-end; gap: 6px; }
.item-kind { color: var(--accent); font-size: 9px; font-weight: 800; letter-spacing: .08em; text-transform: uppercase; }
.inspector h2 { margin: 4px 0 16px; font-size: 17px; line-height: 1.3; }
.date-reading { display: flex; gap: 9px; padding: 10px; border: 1px solid var(--border); border-radius: var(--r-sm); background: var(--bg-2); }
@@ -2326,7 +3173,12 @@
.date-reading strong { font-size: var(--fs-xs); }
.date-reading code { margin-top: 3px; color: var(--text-3); font-size: 9px; }
.date-reading small { margin-top: 3px; color: var(--text-3); font-size: 9px; }
- .date-reading .in-zone { color: var(--text-2); }
+ .date-reading .as-stated { color: var(--text-2); }
+ .date-reading.plain { padding: 0; border: 0; background: none; }
+ .date-more { margin-top: 14px; border-top: 1px solid var(--border); }
+ .date-more > summary { padding: 9px 0 3px; color: var(--text-3); font-size: 10px; cursor: pointer; }
+ .date-more[open] > summary { color: var(--text-2); }
+ .date-more .temporal-facts { margin-top: 10px; }
/* The measurement between two entries. The figure reads first, what it rests on
under it, and every caveat the reading carries below that — a gap printed bare is
true and misleading in the same breath. */
@@ -2361,11 +3213,11 @@
.track-item-actions h3 { grid-column: 1 / -1; margin: 0 0 2px; color: var(--text-3); font-size: 9px; text-transform: uppercase; letter-spacing: .07em; }
.track-item-actions button { display: inline-flex; align-items: center; gap: 5px; padding: 6px 7px; border: 1px solid var(--border); border-radius: var(--r-sm); background: var(--bg-2); color: var(--text-2); font-size: 10px; cursor: pointer; }
.inspector footer { display: flex; justify-content: flex-end; gap: 5px; padding: 12px; border-top: 1px solid var(--border); }
- .inspector-empty { flex: 1; display: grid; place-content: center; justify-items: center; gap: 7px; color: var(--text-3); font-size: var(--fs-xs); }
.timeline-tooltip { position: fixed; z-index: 100; width: 270px; display: grid; gap: 3px; padding: 9px 10px; border: 1px solid var(--border-strong); border-radius: var(--r-md); background: var(--bg-1); box-shadow: var(--shadow-2); color: var(--text-2); pointer-events: none; }
.timeline-tooltip strong { color: var(--text-1); font-size: var(--fs-xs); }
.timeline-tooltip span { font: 10px var(--mono); }
.timeline-tooltip small { color: var(--text-3); font-size: 9px; text-transform: capitalize; }
+ .timeline-tooltip small.sentence { text-transform: none; }
/* Over the pointer, above the tooltip it replaces: a hover reading and a menu about
the same entry cannot both be answered, so the menu is the one on top. */
.item-menu { position: fixed; z-index: 110; width: 196px; padding: 6px; border: 1px solid var(--border-strong); border-radius: var(--r-md); background: var(--bg-1); box-shadow: var(--shadow-2); }
@@ -2376,22 +3228,16 @@
.item-menu button:disabled { color: var(--text-3); cursor: default; }
:global(.timeline-tool button:focus-visible), .axis-ruler:focus-visible, .track-canvas:focus-visible, .density-bars:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
@media (max-width: 1160px) {
- .timeline-head { grid-template-columns: 1fr auto; }
- .range { grid-column: 1 / -1; grid-row: 2; }
- .head-actions { grid-column: 2; grid-row: 1; }
- .timeline-grid { grid-template-columns: minmax(0, 1fr) 250px; }
- .utc-readout { display: none; }
+ .timeline-grid.inspecting { grid-template-columns: minmax(0, 1fr) 250px; }
}
@media (max-width: 760px) {
- .timeline-head { padding-inline: 14px; }
- .range { width: 100%; justify-self: stretch; }
- .filter-row { padding-inline: 14px; overflow-x: auto; }
- .track-toolbar { padding-inline: 14px; }
+ .timeline-bar { padding-inline: 14px; }
+ .range { flex: 1 1 100%; }
+ .range-face { flex: 1; }
.chronology { padding: 12px 14px 22px; }
- .timeline-grid { position: relative; grid-template-columns: minmax(0, 1fr); }
+ .timeline-grid, .timeline-grid.inspecting { position: relative; grid-template-columns: minmax(0, 1fr); }
.inspector { position: absolute; z-index: 30; right: 0; bottom: 0; top: 0; width: min(310px, 88vw); box-shadow: -12px 0 32px color-mix(in srgb, var(--bg-0) 70%, transparent); }
- .inspector.empty { display: none; }
- .timeline-list > button { grid-template-columns: auto minmax(0, 1fr) auto; }
- .list-date { grid-column: 2; justify-items: start; }
+ .list-row { grid-template-columns: 110px minmax(0, 1fr) auto; }
+ .list-row .list-links, .list-row.headings > :nth-child(n + 3):not(:last-child) { display: none; }
}
</style>
diff --git a/frontend/src/tools/Timeline.test.js b/frontend/src/tools/Timeline.test.js
index 47cfabc..9838dd0 100644
--- a/frontend/src/tools/Timeline.test.js
+++ b/frontend/src/tools/Timeline.test.js
@@ -30,7 +30,8 @@ describe('Timeline workspace', () => {
expect(source).toContain('{#each track.layout.clusters as cluster');
expect(source).toContain('onclick={() => expandTrack(baseId)}');
expect(source).toContain('>Collapse</button>');
- expect(source.indexOf('aria-label="Timeline overview"')).toBeLessThan(
+ // the whole-case strip sits under the axis, so the axis stays put when it arrives
+ expect(source.indexOf('aria-label="Timeline overview"')).toBeGreaterThan(
source.indexOf('aria-label="Timeline axis"')
);
});
@@ -38,15 +39,26 @@ describe('Timeline workspace', () => {
it('keeps the current workspace in native full screen', () => {
expect(source).toContain('await toolElement.requestFullscreen()');
expect(source).toContain('await document.exitFullscreen()');
- expect(source).toContain("fullscreen ? 'Exit full screen' : 'Full screen'");
+ // entered from `⋯`, left from the bar, where it can be seen while it is on
+ expect(source).toContain('{#if !fullscreen}<button class="more-act"');
+ expect(source).toContain('{#if fullscreen}<button class="btn btn-sm" onclick={toggleFullscreen}>Exit full screen</button>{/if}');
});
it('only creates assessments from the statement track', () => {
expect(source).toContain("!track?.categories.includes('statement')");
expect(source).toContain("event.target.closest('button')");
expect(source).toContain('class:createable={canCreate}');
- expect(source).toContain('Click or drag to add a claim');
- expect(source).toContain('Add claim');
+ expect(source).toContain('Click or drag to date a new entry');
+ expect(source).toContain('offerDate(draftWhen(from, to, draft.start, draft.end));');
+ });
+
+ it('writes a new entry on the line under the axis, and none over a snapshot', () => {
+ expect(source).toContain("{#if caseState.current && !snapshotReading}");
+ expect(source).toContain('<EntryLine');
+ expect(source).toContain('announce={false}');
+ expect(source).toContain('onsaved={lineAdded}');
+ expect(source).toContain("'Added · not in the tracks shown'");
+ expect(source).toContain("'Added · outside this window'");
});
it('shows uncertainty through patterns and a visible legend', () => {
@@ -57,8 +69,8 @@ describe('Timeline workspace', () => {
expect(source).toContain('<summary>Legend</summary>');
expect(source).toContain('Confidence and date quality are independent.');
expect(source).toContain('Date: approximate');
- expect(source).toContain('closeOnOutsidePointer(legendElement, () => (legendOpen = false))');
- expect(source).toContain('bind:open={legendOpen}');
+ // under `⋯`, where it closes with the menu that holds it
+ expect(source).toContain('<details class="legend">');
});
it('supports adaptive ticks, exact range controls and direct navigation', () => {
@@ -68,7 +80,9 @@ describe('Timeline workspace', () => {
expect(source).toContain('nowPosition');
expect(source).toContain('onpointerdown={panStart}');
expect(source).toContain('onwheel={navigateWheel}');
- expect(source).toContain('Wheel zoom · Shift-wheel pan');
+ // said where the window is read, not as a line of mouse hints across the header
+ expect(source).toContain(' · Scroll to zoom, Shift-scroll to pan`}');
+ expect(source).not.toContain('Wheel zoom · Shift-wheel pan');
expect(source).toContain('if (!event.shiftKey && !horizontal)');
});
@@ -88,7 +102,7 @@ describe('Timeline workspace', () => {
it('makes a track readable in its gutter: the name, its hover, its colour', () => {
expect(source).toContain('--gutter: 178px');
- expect(source).toContain('<strong>{track.label}</strong>');
+ expect(source).toContain('<strong dir="auto">{track.label}</strong>');
expect(source).toContain('title={trackTitle(track)}');
expect(source).toContain('-webkit-line-clamp: 2');
expect(source).not.toContain('track.short');
@@ -104,8 +118,14 @@ describe('Timeline workspace', () => {
expect(source).toContain('class="overview-handle start"');
expect(source).toContain('overviewRecenter');
expect(source).toContain('unplacedTotal} local');
- expect(source).toContain('exact counts on hover');
+ expect(source).not.toContain('exact counts on hover');
expect(source).toContain('class="overview-tick {slot.anchor}"');
+ // only once the window leaves part of the case out, and named where names fit
+ expect(source).toContain('const overviewShown = $derived(overviewNeeded(extent, axisWindow));');
+ expect(source).toContain('{#if overviewShown}');
+ expect(source).toContain('{#each overviewNames as slot (slot.key)}');
+ // its height comes out of the list, not out of the lanes being read
+ expect(source).toContain('const axisMax = $derived(Math.max(150, Math.round((chronologyHeight - 130) * axisShare)));');
// The ink answers the pointer and the box around it does not, so a bar the brush
// covers can still be clicked instead of the press landing on the brush.
expect(source).toContain('.density-bucket { position: absolute; z-index: 6;');
@@ -116,17 +136,24 @@ describe('Timeline workspace', () => {
expect(source).toContain('class="overview-shade"');
});
- it('offers readable events, a list view and a stable inspector column', () => {
+ it('offers readable events, a list view and an inspector while an entry is picked', () => {
expect(source).toContain("viewMode === 'list'");
- expect(source).toContain('formatTemporalValue(item.raw).label');
+ expect(source).toContain('formatTemporalValue(item.raw, item.tz).label');
expect(source).toContain('class="timeline-tooltip"');
- expect(source).toContain("item.zone === 'date-only'");
- expect(source).toContain('class={`precision-span ${item.category}`}');
- expect(source).toContain('grid-template-columns: minmax(0, 1fr) 330px');
- // the tool's own clock, not a target: nothing is being aimed at in an empty panel
- expect(source).toContain('<Icon name="clock" size={16} /><span>Select an entry</span>');
+ // one shape per kind of date, decided by the layout rather than by the zone
+ expect(source).toContain('class={`timeline-event ${item.category} ${item.mark}`}');
+ expect(source).not.toContain('precision-span');
+ expect(source).not.toContain('translateX(-8px)');
+ expect(source).not.toContain('end-aligned');
+ // the column is there only while an entry is picked: empty, it held a third of
+ // the width for "Select an entry"
+ expect(source).toContain('.timeline-grid.inspecting { grid-template-columns: minmax(0, 1fr) 330px; }');
+ expect(source).toContain('class:inspecting={Boolean(selected)}');
+ expect(source).toContain('{#if selected}\n <aside class="inspector">');
+ expect(source).not.toContain('Select an entry');
expect(source).toContain('inspectorConnections.cites');
- expect(source).toContain('Add correction');
+ // a file's date is corrected once, under the date, not a second time in the footer
+ expect(source).not.toContain('>Add correction</button>');
expect(source).toContain("openEditor(null, selected?.raw ?? '', {");
});
@@ -136,7 +163,7 @@ describe('Timeline workspace', () => {
expect(source).toContain('nudgeTemporalRaw(item, mode');
expect(source).toContain('aria-label="Resize start"');
expect(source).toContain("['ArrowLeft', 'ArrowRight'");
- expect(source).toContain("title={pendingEdit.item.shape === 'interval' ? 'Change this period?' : 'Move this date?'}");
+ expect(source).toContain("title={!pendingEdit.item.raw ? 'Date this entry?' : pendingEdit.item.shape === 'interval' ? 'Change this period?' : 'Move this date?'}");
});
it('separates local times from missing dates', () => {
@@ -160,10 +187,16 @@ describe('Timeline workspace', () => {
});
describe('which clock the axis is read on', () => {
- it('keeps UTC as the default and stores nothing else', () => {
+ it('opens on the zone of the case-s places and stores nothing else', () => {
// presentation only: the case is stored in UTC, the queries ask in UTC, and the
// switch moves where the ticks fall and what they are called
- expect(source).toContain("let zoneChoice = $state('utc')");
+ expect(source).toContain("let zoneChoice = $state('case')");
+ expect(source).toContain("if (zoneChoice === 'case') return caseClock && knownZone(caseClock.zone) ? caseClock.zone : UTC;");
+ expect(source).toContain('caseZone(points)');
+ // the clock picked is kept per case
+ expect(source).toContain('zoneChoice = rememberedClock(caseId);');
+ expect(source).toContain('onpick={(value) => rememberClock(caseState.current?.id, value)}');
+ expect(source).toContain('home={caseClock}');
expect(source).toContain('axisTicks(from, to, plotWidth, zone)');
expect(source).toContain('axisBands(from, to, plotWidth, zone)');
expect(source).toContain('windowInputValue(from, zone)');
@@ -191,7 +224,7 @@ describe('which clock the axis is read on', () => {
// the zone arrives with the daylight, so until it lands the axis stays on UTC
expect(source).toContain('const named = daylight?.zone?.name;');
expect(source).toContain('return named && knownZone(named) ? named : UTC;');
- expect(source).toContain("if (zoneChoice.startsWith('place:') && places.length && !sunPlace) zoneChoice = 'utc'");
+ expect(source).toContain("if (zoneChoice.startsWith('place:') && places.length && !sunPlace) zoneChoice = 'case'");
});
it('keeps a snapshot on the clock captured with it', () => {
@@ -260,7 +293,7 @@ describe('what an entry can be asked on a right-click', () => {
it('reads the entry before closing, and closes on the axis moving under it', () => {
expect(source).toContain('const held = itemMenu;\n itemMenu = null;');
expect(source).toContain('closeOnOutsidePointer(itemMenuElement, () => (itemMenu = null))');
- expect(source).toContain("if (event.key === 'Escape' && itemMenu) itemMenu = null;");
+ expect(source).toContain("if (itemMenu) itemMenu = null;\n else if (moreMenu) moreMenu = false;");
// panning, zooming and the wheel all move the spot the menu was opened on
expect(source).toContain('itemMenu = null;\n ({ from, to } = shiftWindow(from, to, fraction));');
expect(source).toContain('itemMenu = null;\n ({ from, to } = zoomWindow(from, to, factor, anchor));');
@@ -305,10 +338,120 @@ describe('measuring between two entries', () => {
});
});
+describe('one reading, the axis over the list', () => {
+ it('draws both whatever the mode, which only says which one gets the room', () => {
+ expect(source).not.toContain("{#if viewMode === 'plot'}");
+ expect(source).toContain('const SHARES = { plot: 0.62, list: 0.28 };');
+ expect(source).toContain('style:max-height={`${axisMax}px`}');
+ expect(source).toContain('role="separator"');
+ expect(source).toContain("onclick={() => setViewMode('list')}");
+ });
+
+ it('lists the window with what each entry is about, where, on what, and still waits for', () => {
+ expect(source).toContain('<div class="list-grid" role="grid" aria-label="Chronology"');
+ expect(source).toContain('<span role="columnheader">Statement</span>');
+ // a link column only when some entry of the window fills it
+ for (const [key, heading] of [['subjects', 'Subjects'], ['places', 'Places'], ['sources', 'Sources']]) {
+ expect(source).toContain(`{#if listColumns.${key}}<span role="columnheader">${heading}</span>{/if}`);
+ }
+ expect(source).toContain('style:--list-columns={listTemplate}');
+ expect(source).toContain('grid-template-columns: var(--list-columns');
+ // an instant on the axis's clock, named in the heading, and a day as stated
+ expect(source).toContain("{zone === UTC ? 'Date' : `Date · ${zoneWords(zone).place} time`}");
+ expect(source).toContain('instantOnClock(item) ? clockReading(item.earliest, zone, { named: false }) : formatTemporalValue(item.raw, item.tz).label');
+ expect(source).toContain("flags.push({ id: 'unsourced', label: 'no source' })");
+ expect(source).toContain("flags.push({ id: 'unassessed', label: 'not assessed' })");
+ // only a Claim is asked for a source and an assessment
+ expect(source).toContain("if (item.kind === 'claim') {");
+ });
+
+ it('lights the mark and the row of the entry under the pointer, both ways', () => {
+ expect(source).toContain('class:lit={hovered === item.id}');
+ expect(source).toContain('onpointerenter={() => hoverRow(item)}');
+ expect(source).toContain('selectItem(item, baseId, event); revealRow(item.id);');
+ });
+
+ it('copies the whole window, not the page, as Markdown or a spreadsheet block', () => {
+ expect(source).toContain("copyChronology('markdown')");
+ expect(source).toContain("copyChronology('block')");
+ expect(source).toContain('await readChronology((url) => api.get(url)');
+ // a frozen reading copies what it froze and asks nothing of the case
+ expect(source).toContain('? { items: windowItems, truncated: false }');
+ });
+
+ it('draws the Media lane as the files its events date, and opens the event when one is picked', () => {
+ expect(source).toContain('.map((item) => ({ ...(drawsFiles(track) ? asFile(item) : item), pinned:');
+ expect(source).toContain('statement: item.label, asFile: true');
+ // one item on two lanes is picked as its event, never as its file
+ expect(source).toContain("const item = picked?.asFile ? pageItems.find((row) => row.id === picked.id) ?? picked : picked;");
+ expect(source).toContain("detail: item.asFile ? item.statement :");
+ // a file is dated from its proof or an event, not by clicking its lane
+ expect(source).toContain("canCreate = track.categories.includes('statement') && !drawsFiles(track) && !snapshotReading");
+ expect(source).toContain("!track?.categories.includes('statement') || drawsFiles(track) ||");
+ expect(source).toContain("(item.category === 'media' || item.asFile) && item.thumb");
+ });
+
+ it('opens on the dated files over the events and says how many file dates an empty axis leaves out', () => {
+ expect(source).toContain('let trackSpecs = $state(defaultTimelineTracks());');
+ expect(source).toContain('/timeline?category=media&include_undated=false&limit=1');
+ expect(source).toContain('>Show them</button>');
+ // what was counted is what "Show them" puts on the axis
+ expect(source).toContain("read from {workingFilesHeld ? 'working files' : 'files'}");
+ expect(source).toContain('trackSpecs = workingFilesHeld');
+ expect(source).toContain("mediaTrack(trackSpecs, { collectedOnly: false })");
+ });
+
+ it('adds the track a handed-over file date or filing lives on before looking for it', () => {
+ expect(source).toContain("startsWith('temporal:media:') ? 'media'");
+ expect(source).toContain(' ensureTrackFor(itemId, producedHere);');
+ // a working file is let back onto the Media track that held it back
+ expect(source).toContain("producedHere && holding.length && holding.every(holdsBackWorkingFiles)");
+ expect(source).toContain("handOverSelection(focus.itemId, focus.producedHere === true);");
+ });
+
+ it('lands on the Undated queue when the Overview sent it there', () => {
+ expect(source).toContain("if (queue === 'undated') {");
+ expect(source).toContain('bind:open={undatedOpen} bind:this={undatedElement}');
+ });
+});
+
+describe('reading a mark', () => {
+ it('draws a line up to the ruler with the date as written, for one end or both', () => {
+ expect(source).toContain("const lines = item.mark === 'point' ? [middle] : [mark.left, mark.right];");
+ expect(source).toContain('class="time-guide" aria-hidden="true"');
+ expect(source).toContain("label: formatTemporalValue(item.raw ?? '', item.tz).label");
+ expect(source).toContain('showGuide(event.currentTarget, item)');
+ });
+
+ it('captions and cards belong to the mark, so reading one is clicking it', () => {
+ const button = source.slice(source.indexOf('class="event-select"'), source.indexOf('class="move-grip"'));
+ expect(button).toContain('class={`event-caption ${item.caption.side}`}');
+ expect(button).toContain('class="event-card"');
+ expect(button).toContain('loading="lazy"');
+ });
+
+ it('walks entries with Alt and an arrow, and keeps every other key for the canvas', () => {
+ expect(source).toContain("if (!event.altKey || !['ArrowLeft', 'ArrowRight'].includes(event.key)) return;");
+ expect(source).toContain("if (event.key === 'Enter' || event.key === ' ') {");
+ expect(source).toContain('onkeydown={(event) => markKey(event, track, item)}');
+ });
+
+ it('explains the three shapes in the legend', () => {
+ for (const shape of ['Instant', 'Reduced date, across what it covers', 'Period']) {
+ expect(source).toContain(`></i>${shape}</span>`);
+ }
+ });
+
+ it('asks the export for no selection, so a plate does not depend on a click', () => {
+ expect(source).toContain('tracks: buildTracks(PLATE_PLOT)');
+ expect(source).not.toContain('buildTracks(PLATE_PLOT, selected');
+ });
+});
+
describe('exporting the axis', () => {
it('serialises the tracks the tool laid out, never a canvas', () => {
expect(source).toContain('timelinePlate({');
- expect(source).toContain('const tracks = $derived(buildTracks(plotWidth));');
+ expect(source).toContain('const tracks = $derived(buildTracks(plotWidth, selected?.id ?? null));');
});
it('lays the page out at the plate’s width, not the browser’s', () => {
@@ -336,3 +479,94 @@ describe('exporting the axis', () => {
expect(source).toContain('<PlateExport surface="timeline" plate={capturePlate}');
});
});
+
+describe('the file an entry is about', () => {
+ it('opens the inspector on it, the file an event is about, or the first it cites', () => {
+ expect(source).toContain("const PREVIEWS = new Set(['media', 'capture']);");
+ // a proof's date is stated about the footage and cites the proof: the video is shown
+ expect(source).toContain(
+ "const file = out.find((row) => row.link?.type === 'about') ?? out.find((row) => row.link?.type === 'cites');"
+ );
+ const body = source.indexOf('<div class="inspector-body">');
+ expect(source.indexOf('<MediaPreview', body)).toBeLessThan(source.indexOf('<div class="item-kind">', body));
+ });
+
+ it('goes to its own line when the topbar asks for Add event, about the picked file', () => {
+ expect(source).toContain('if (!snapshotReading) untrack(() => focusLine());');
+ expect(source).toContain('lineFile = file ? { id: file.id, label: file.label, type: file.type, attrs: file.attrs ?? {} } : null;');
+ expect(source).toContain('Add event from this file');
+ // another entry picked lets go of the file
+ expect(source).toContain('if (lineFile && lineFile.id !== picked) lineFile = null;');
+ });
+});
+
+describe('changing a picked entry’s date', () => {
+ it('is offered where the date is read, and confirmed like a drag', () => {
+ expect(source).toContain("{selected.raw ? 'Change the date' : 'Give it a date'}");
+ expect(source).toContain('pendingEdit = { item: selected, raw: dateSettled.raw, zone: dateSettled.zone };');
+ // the clock is changed there too, and a drag keeps the one it has
+ expect(source).toContain('onpick={(zone) => (dateEditing = { ...dateEditing, picked: zone })}');
+ expect(source).toContain('...(pendingEdit.zone !== undefined ? { when_zone: pendingEdit.zone } : {}),');
+ // and a date typed anywhere in the case opens on the axis's clock
+ expect(source).toContain('if (!snapshotReading) noteAxisZone(caseState.current?.id, zone);');
+ // a file keeps its own date and is corrected beside it
+ expect(source).toContain('<Icon name="edit" size={12} /> Correct this date');
+ });
+
+ it('says both dates in words, each on its clock, when it asks', () => {
+ expect(source).toContain("detail={`${pendingEdit.item.raw ? formatTemporalValue(pendingEdit.item.raw, pendingEdit.item.tz).label : 'Undated'} → ${formatTemporalValue(pendingEdit.raw, pendingEdit.zone === undefined ? pendingEdit.item.tz : pendingEdit.zone).label}`}");
+ });
+});
+
+describe('one bar over the axis', () => {
+ it('keeps the period, its clock and the split in the open, and the rest under ⋯', () => {
+ expect(source).toContain('<header class="timeline-bar">');
+ // no title repeating the tab, no Add beside the line that adds
+ expect(source).not.toContain('class="title-block"');
+ expect(source).not.toContain('class="btn btn-primary add-event"');
+ expect(source).not.toContain('across tracks');
+ // tracks, grouping and the period handed on wait under one button
+ const menu = source.slice(source.indexOf('<div class="more-menu">'), source.indexOf('</header>'));
+ expect(menu).toContain('trackPresets(entityTypes())');
+ expect(menu).toContain('<select class="input input-sm" bind:value={groupBy}');
+ expect(menu).toContain('Open this period in');
+ expect(menu).toContain("openRangeIn('satellite')");
+ expect(source).toContain('closeOnOutsidePointer(moreElement, () => (moreMenu = false))');
+ });
+
+ it('puts a lane-s own tools under the pointer, and a count only where there is one', () => {
+ expect(source).toContain('.drag-track, .track-actions { opacity: 0;');
+ expect(source).toContain('.track-row:hover .drag-track, .track-row:hover .track-actions');
+ expect(source).toContain('@media (hover: none) { .drag-track, .track-actions { opacity: 1; } }');
+ expect(source).toContain('{#if shown || track.total}');
+ });
+
+ it('prints only the ruler names that fit, and says its clock in words', () => {
+ expect(source).toContain('const tickNames = $derived(fitTicks(ticks, plotWidth));');
+ expect(source).toContain('const bandNames = $derived(fitBands(bands, plotWidth));');
+ expect(source).toContain('{#each tickNames as tick (tick.at)}');
+ expect(source).toContain("{#if zone !== UTC}<small>{zoneWords(zone).place} time</small>{/if}");
+ // the window's boundaries in ISO no longer sit in the corner, only on hover
+ expect(source).not.toContain("<small>{windowInputValue(from, zone).replace('T', ' ')}");
+ });
+});
+
+describe('the picked entry', () => {
+ it('is named the way its track is, once', () => {
+ expect(source).toContain("const HEADINGS = { statement: 'Event', media: 'File date', case_activity: 'Case activity' };");
+ expect(source).toContain("{#if selected.kind !== 'claim' || selected.time_role}");
+ });
+
+ it('reads an instant on the axis clock first, the stated value under it', () => {
+ expect(source).toContain('<strong>{clockReading(selected.earliest, zone)}</strong>');
+ expect(source).toContain('<small class="as-stated">{selectedReading.label}</small>');
+ });
+
+ it('folds how the date is held, keeping every word of it', () => {
+ const fold = source.slice(source.indexOf('<details class="date-more">'), source.indexOf('</details>', source.indexOf('<details class="date-more">')));
+ expect(fold).toContain('<summary>About this date</summary>');
+ expect(fold).toContain('{#if selected.tz || selected.zone} · {selected.tz || selected.zone}{/if}');
+ expect(fold).toContain('<dd>{temporalZoneWords(selected)}</dd>');
+ expect(fold).toContain('Ctrl-click a second entry to measure between them.');
+ });
+});
diff --git a/frontend/src/tools/board/BoardGroup.svelte b/frontend/src/tools/board/BoardGroup.svelte
new file mode 100644
index 0000000..ae7d84d
--- /dev/null
+++ b/frontend/src/tools/board/BoardGroup.svelte
@@ -0,0 +1,546 @@
+<script>
+ /**
+ * One group of the Board: its heading, its rows, and its own "Show more".
+ *
+ * A subject row reads by what the case says about it: how many events name it, when
+ * they fall, and the span they cover. A material row (a file, a Claim, a piece of
+ * work) keeps the columns the flat table has always had, since what matters about a
+ * capture is where it was filed and when. Each group pages on its own, so a case of
+ * three hundred people still shows its places without scrolling past all of them.
+ *
+ * The Board owns every state here (the question, the ticks, the open row); this only
+ * draws one group of the answer and says what was pressed.
+ */
+ import Icon from '../../components/Icon.svelte';
+ import Sparkline from '../../components/Sparkline.svelte';
+ import { entityIcon } from '../../lib/entityIcon.js';
+ import { entityHint, entityLabel } from '../../lib/entityTypes.svelte.js';
+ import { eventWords, spanWords } from '../../lib/boardGroups.js';
+ import { formatTemporalValue } from '../../lib/timeline.js';
+
+ let {
+ group,
+ count = 0,
+ open = false,
+ rows = [],
+ types = [],
+ loading = false,
+ hasMore = false,
+ events = {},
+ currentId = null,
+ ticked = new Set(),
+ busyId = null,
+ readOnly = false,
+ query = '',
+ creatable = [],
+ matchReasons,
+ thumbUrl,
+ folderName,
+ created,
+ ontoggle,
+ onopen,
+ ontick,
+ onconfirm,
+ ondismiss,
+ ongraph,
+ oncreate,
+ onreads,
+ onmore,
+ } = $props();
+
+ const subject = $derived(group.kind === 'subject');
+ /** A group of one type says the type once, in its heading; a column repeating
+ * "Place" nine times is a column that says nothing. */
+ const mixed = $derived(types.length > 1);
+ const typeWords = $derived(types.map((type) => entityLabel(type)).join(', '));
+ const isSuggested = (entity) => entity.provenance?.status === 'suggested';
+ const headId = $derived(`board-group-${group.id}`);
+ /** The family's colour, the one its nodes wear in the Graph. */
+ const tone = $derived(`var(--graph-${group.families[0] ?? 'document'}, var(--text-3))`);
+ /** Events are Claims and nothing else: their heading lists no types, and their row
+ * says when the event happened rather than where it was filed. */
+ const eventsGroup = $derived(group.id === 'claim');
+ const listsTypes = $derived(!eventsGroup);
+ const typeColumn = $derived(!eventsGroup && (mixed || !subject));
+ /** Why a row answered the search, when it is not its own name: a vehicle found by
+ * its plate says so, and a name that matched needs no saying twice. */
+ const reasonOf = (entity) =>
+ (matchReasons(entity) ?? []).find((match) => match.key !== 'label') ?? null;
+</script>
+
+<section
+ class="group"
+ class:subject
+ class:folded={!open}
+ style="--tone: {tone}"
+ aria-labelledby={headId}
+>
+ <div class="head">
+ <button
+ id={headId}
+ class="fold"
+ aria-expanded={open}
+ title={open ? `Fold ${group.label}` : `Show ${group.label}`}
+ onclick={() => ontoggle?.()}
+ >
+ <span class="chevron" class:open><Icon name="chevronRight" size={12} /></span>
+ <span class="dot"></span>
+ <span class="title">{group.label}</span>
+ <span class="count">{count}</span>
+ {#if !open && listsTypes}
+ <!-- Folded, the heading says what is inside it. -->
+ <span class="types" title={typeWords}>{typeWords}</span>
+ {/if}
+ </button>
+ {#if group.reads}
+ <button class="as-link reads" onclick={() => onreads?.(group.reads.tool)}>
+ {group.reads.label} <Icon name="chevronRight" size={11} />
+ </button>
+ {/if}
+ {#if subject && creatable.length && !readOnly}
+ <button
+ class="btn btn-ghost btn-sm new"
+ title="New {creatable.map((entry) => entry.label.toLowerCase()).join(' or ')}"
+ onclick={() => oncreate?.(creatable[0].type)}
+ >
+ <Icon name="plus" size={12} /> New
+ </button>
+ {/if}
+ </div>
+
+ {#if open}
+ {#if !rows.length}
+ <p class="waiting">{loading ? 'Loading…' : 'Nothing here yet.'}</p>
+ {:else}
+ <table class="rows">
+ <colgroup>
+ {#if !readOnly}<col class="c-pick" />{/if}
+ <col />
+ {#if typeColumn}<col class="c-type" />{/if}
+ {#if subject}
+ <col class="c-n" /><col class="c-spark" /><col class="c-span" />
+ {:else}
+ <col class={eventsGroup ? 'c-when' : 'c-folder'} /><col class="c-created" />
+ {/if}
+ <col class="c-go" />
+ </colgroup>
+ <tbody>
+ {#each rows as entity (entity.id)}
+ {@const said = events[entity.id]}
+ <tr
+ data-row-id={entity.id}
+ class:current={currentId === entity.id}
+ class:suggested={isSuggested(entity)}
+ class:busy={busyId === entity.id}
+ tabindex="0"
+ aria-selected={currentId === entity.id}
+ onclick={() => onopen?.(entity)}
+ onkeydown={(e) => {
+ if (e.target !== e.currentTarget) return;
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault();
+ onopen?.(entity);
+ }
+ }}
+ >
+ {#if !readOnly}
+ <td class="pick">
+ <input
+ type="checkbox"
+ aria-label="Select {entity.label}"
+ checked={ticked.has(entity.id)}
+ onclick={(e) => {
+ e.stopPropagation();
+ ontick?.(entity, e.shiftKey);
+ }}
+ />
+ </td>
+ {/if}
+ <td class="who">
+ <span class="lead">
+ {#if entity.thumb}
+ <img class="thumb" src={thumbUrl(entity.thumb)} alt="" loading="lazy" />
+ {:else}
+ <span class="icon"><Icon name={entityIcon(entity)} size={13} /></span>
+ {/if}
+ <span class="name" dir="auto">{entity.label}</span>
+ {#if isSuggested(entity)}
+ <span class="tag" title="a tool proposed this, and nobody has confirmed it">suggested</span>
+ {#if !readOnly}
+ <span class="review">
+ <button
+ class="btn btn-ghost btn-sm act ok"
+ title="Confirm this item"
+ disabled={busyId === entity.id}
+ onclick={(e) => { e.stopPropagation(); onconfirm?.(entity); }}
+ ><Icon name="check" size={12} /></button>
+ <button
+ class="btn btn-ghost btn-sm act no"
+ title="Dismiss this item, recoverable from the trash"
+ disabled={busyId === entity.id}
+ onclick={(e) => { e.stopPropagation(); ondismiss?.(entity); }}
+ ><Icon name="x" size={12} /></button>
+ </span>
+ {/if}
+ {/if}
+ </span>
+ {#if query.trim() && reasonOf(entity)}
+ {@const match = reasonOf(entity)}
+ <span class="match-reason" title={match.value} dir="auto">
+ {match.label}: {match.value}
+ </span>
+ {/if}
+ </td>
+ {#if typeColumn}
+ <td class="type" title={entityHint(entity.type)}>{entityLabel(entity.type)}</td>
+ {/if}
+ {#if subject}
+ <td class="n" title={said ? eventWords(said.events) : ''}>
+ {#if said?.events}{said.events}{:else}<span class="none">—</span>{/if}
+ </td>
+ <td class="spark">
+ {#if said?.events && said.first}
+ <Sparkline buckets={said.buckets} label="When its events fall across the case" />
+ {/if}
+ </td>
+ <td class="span">{said ? spanWords(said.first, said.last) : ''}</td>
+ {:else if eventsGroup}
+ {@const when = formatTemporalValue(entity.attrs?.when ?? '', entity.attrs?.when_zone)}
+ <td class="when" class:none={!entity.attrs?.when} title="When it happened, as written">
+ {when.label}
+ </td>
+ <td class="created" title="When it was noted">{created(entity)}</td>
+ {:else}
+ <td class="folder">{folderName(entity)}</td>
+ <td class="created">{created(entity)}</td>
+ {/if}
+ <td class="go">
+ {#if !readOnly}
+ <button
+ class="btn btn-ghost btn-sm act"
+ aria-label="Show {entity.label} in the graph"
+ title="Show it in the graph, with what it is connected to"
+ onclick={(e) => { e.stopPropagation(); ongraph?.(entity); }}
+ ><Icon name="graph" size={13} /></button>
+ {/if}
+ </td>
+ </tr>
+ {/each}
+ </tbody>
+ </table>
+ {#if hasMore}
+ <div class="more">
+ <span>Showing {rows.length} of {count}</span>
+ <button class="btn btn-ghost btn-sm" disabled={loading} onclick={() => onmore?.()}>
+ {loading ? 'Loading…' : 'Show more'}
+ </button>
+ </div>
+ {/if}
+ {/if}
+ {/if}
+</section>
+
+<style>
+ .group {
+ margin-bottom: 6px;
+ }
+ /* The heading stays put while its rows scroll under it, so a long group still says
+ which group it is. */
+ .head {
+ position: sticky;
+ top: 0;
+ z-index: 1;
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ min-height: 34px;
+ padding: 0 2px;
+ background: var(--bg-1);
+ border-bottom: 1px solid var(--border);
+ }
+ .fold {
+ display: flex;
+ flex: 1;
+ align-items: center;
+ gap: 8px;
+ min-width: 0;
+ padding: 6px 0;
+ border: 0;
+ background: none;
+ color: var(--text-1);
+ font: inherit;
+ text-align: left;
+ cursor: pointer;
+ }
+ .chevron {
+ display: inline-flex;
+ color: var(--text-3);
+ transition: transform 120ms var(--ease);
+ }
+ .chevron.open {
+ transform: rotate(90deg);
+ }
+ .dot {
+ width: 8px;
+ height: 8px;
+ flex-shrink: 0;
+ border-radius: 50%;
+ background: var(--tone);
+ }
+ .title {
+ color: var(--text-2);
+ font-size: var(--fs-xs);
+ font-weight: 600;
+ letter-spacing: 0.05em;
+ text-transform: uppercase;
+ white-space: nowrap;
+ }
+ .subject .title {
+ color: var(--text-1);
+ }
+ .count {
+ color: var(--text-3);
+ font-size: var(--fs-xs);
+ font-variant-numeric: tabular-nums;
+ }
+ .types {
+ overflow: hidden;
+ min-width: 0;
+ color: var(--text-3);
+ font-size: var(--fs-xs);
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ .types::before {
+ content: '·';
+ margin-right: 8px;
+ }
+ /* The material reads quieter than the subjects, folded or not: it is what the case
+ is built from, not what it is about. */
+ .fold:hover .title,
+ .fold:focus-visible .title {
+ color: var(--text-1);
+ }
+ .as-link {
+ display: inline-flex;
+ align-items: center;
+ gap: 2px;
+ padding: 0;
+ border: 0;
+ background: none;
+ color: var(--text-3);
+ font: inherit;
+ font-size: var(--fs-xs);
+ white-space: nowrap;
+ cursor: pointer;
+ }
+ .as-link:hover {
+ color: var(--accent);
+ }
+ .new {
+ color: var(--text-3);
+ }
+ .new:hover {
+ color: var(--text-1);
+ }
+ .waiting {
+ margin: 0;
+ padding: 10px 28px;
+ color: var(--text-3);
+ font-size: var(--fs-xs);
+ }
+ .rows {
+ width: 100%;
+ border-collapse: collapse;
+ table-layout: fixed;
+ font-size: var(--fs-sm);
+ }
+ .c-pick { width: 28px; }
+ .c-type { width: 130px; }
+ .c-n { width: 40px; }
+ .c-spark { width: 72px; }
+ .c-span { width: 150px; }
+ .c-folder { width: 150px; }
+ .c-when { width: 190px; }
+ .c-created { width: 96px; }
+ .c-go { width: 36px; }
+ td {
+ height: 38px;
+ padding: 4px 8px 4px 0;
+ border-bottom: 1px solid var(--border);
+ color: var(--text-2);
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ vertical-align: middle;
+ }
+ tr {
+ cursor: pointer;
+ box-shadow: inset 2px 0 0 transparent;
+ }
+ tr.suggested {
+ box-shadow: inset 2px 0 0 color-mix(in srgb, var(--accent) 55%, transparent);
+ }
+ tr:hover td,
+ tr:focus-visible td {
+ background: var(--bg-2);
+ color: var(--text-1);
+ }
+ tr:focus-visible {
+ outline: 2px solid var(--accent);
+ outline-offset: -2px;
+ }
+ /* The row whose Details are open beside the list. */
+ tr.current td {
+ background: var(--accent-soft);
+ color: var(--text-1);
+ }
+ tr.current {
+ box-shadow: inset 2px 0 0 var(--accent);
+ }
+ tr.busy {
+ opacity: 0.5;
+ }
+ .pick {
+ padding-left: 4px;
+ }
+ .pick input {
+ display: block;
+ margin: 0;
+ cursor: pointer;
+ accent-color: var(--accent);
+ }
+ .lead {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ min-width: 0;
+ }
+ .thumb {
+ width: 26px;
+ height: 26px;
+ flex-shrink: 0;
+ border: 1px solid var(--border);
+ border-radius: var(--r-sm);
+ object-fit: cover;
+ background: var(--bg-2);
+ }
+ .icon {
+ display: grid;
+ place-items: center;
+ width: 26px;
+ height: 26px;
+ flex-shrink: 0;
+ border-radius: var(--r-sm);
+ background: var(--bg-2);
+ color: var(--text-3);
+ }
+ /* A subject wears its family's colour, as its node does in the Graph. */
+ .subject .icon {
+ border-radius: 50%;
+ background: color-mix(in srgb, var(--tone) 16%, transparent);
+ color: var(--tone);
+ }
+ .name {
+ overflow: hidden;
+ color: var(--text-1);
+ text-overflow: ellipsis;
+ }
+ .group:not(.subject) .name {
+ color: var(--text-2);
+ }
+ tr:hover .name,
+ tr.current .name {
+ color: var(--text-1);
+ }
+ .match-reason {
+ display: block;
+ margin: 1px 0 0 34px;
+ overflow: hidden;
+ color: var(--accent);
+ font-size: var(--fs-xs);
+ text-overflow: ellipsis;
+ }
+ .tag {
+ flex-shrink: 0;
+ padding: 1px 6px;
+ border-radius: 999px;
+ background: var(--bg-3);
+ color: var(--text-3);
+ font-size: 10px;
+ }
+ .review {
+ display: inline-flex;
+ flex-shrink: 0;
+ gap: 1px;
+ opacity: 0.55;
+ }
+ tr:hover .review,
+ tr:focus-within .review {
+ opacity: 1;
+ }
+ .act {
+ padding-inline: 5px;
+ }
+ .act.ok:hover {
+ color: var(--ok);
+ }
+ .act.no:hover {
+ color: var(--danger);
+ }
+ .type,
+ .folder,
+ .created,
+ .span,
+ .when {
+ color: var(--text-3);
+ font-size: var(--fs-xs);
+ }
+ .created {
+ font-family: var(--font-mono);
+ }
+ td.when {
+ color: var(--text-2);
+ font-variant-numeric: tabular-nums;
+ }
+ td.when.none {
+ color: var(--text-3);
+ }
+ .n {
+ color: var(--text-1);
+ font-variant-numeric: tabular-nums;
+ text-align: right;
+ padding-right: 12px;
+ }
+ .none {
+ color: var(--text-3);
+ }
+ .span {
+ font-variant-numeric: tabular-nums;
+ }
+ .go {
+ padding-right: 0;
+ text-align: right;
+ }
+ .go .act {
+ opacity: 0;
+ color: var(--text-3);
+ }
+ tr:hover .go .act,
+ tr:focus-within .go .act,
+ tr:focus-visible .go .act,
+ tr.current .go .act {
+ opacity: 1;
+ }
+ .go .act:hover {
+ color: var(--accent);
+ }
+ .more {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 8px 2px 4px 28px;
+ color: var(--text-3);
+ font-size: var(--fs-xs);
+ }
+</style>
diff --git a/frontend/src/tools/compare/DifferenceBar.svelte b/frontend/src/tools/compare/DifferenceBar.svelte
index 0f090cc..fc78c1c 100644
--- a/frontend/src/tools/compare/DifferenceBar.svelte
+++ b/frontend/src/tools/compare/DifferenceBar.svelte
@@ -2,11 +2,11 @@
/**
* Difference's controls, in the stage footer beside the view's own. The
* highlights lie over whichever view is on, so nothing here moves the maps;
- * the full settings open above the strip only when asked for.
+ * the gear opens the full settings, docked on the stage's right edge.
*
- * The strip keeps one width whatever the reading is doing, since the panel
- * hangs from its edge: a label that grew on every read moved the panel under
- * the pointer. What a read is doing is said in the panel and the map legend.
+ * Read keeps one width whatever the reading is doing, so the gear beside it
+ * never moves under the pointer. What a read is doing is said in the panel
+ * and the map legend.
*
* The reading follows the camera by itself. A method that reads Sentinel-2
* bands runs on the frames it holds, and past the ground they cover fetches
@@ -14,32 +14,21 @@
* Read says which of those it is: lit when the next move is the analyst's,
* and naming what the reading does otherwise, never a press that does nothing.
*/
- import { CHANGE_BASES, CHANGE_METHODS, CHANGE_INDICES, CHANGE_DISPLAYS, CHANGE_CLASSES,
- changeNeedsFrames, changeSettings, indexThreshold } from '../../lib/map/changeAssist.js';
- import CloudFilter from './CloudFilter.svelte';
+ import { CHANGE_BASES, changeNeedsFrames } from '../../lib/map/changeAssist.js';
import Icon from '../../components/Icon.svelte';
let {
settings = $bindable(),
+ /** Whether the settings panel is open; Compare draws it on the stage. */
+ open = $bindable(false),
status,
- result = null,
/** due: Read has something to do · reading · tiles: waiting on the maps · current: nothing moved. */
reading = 'due',
- error = '',
onrun = () => {},
- onzone = () => {},
- /** Keep this index reading as a Detect analyzer, to sweep areas with it. */
- onanalyzer = () => {},
} = $props();
- let open = $state(false);
- let tab = $state('detection');
const runnable = $derived(status.ok && status.methods.includes(settings.method));
- // What this reading has to fetch, and therefore whether it can follow the map.
const frames = $derived(changeNeedsFrames(settings, status));
- const index = $derived(CHANGE_INDICES.find((entry) => entry.id === settings.index));
- const busy = $derived(reading === 'reading' || reading === 'tiles');
- const stale = $derived(!!result && reading === 'due');
const due = $derived(runnable && reading === 'due');
const READ = {
due: ['Read', 'Read the pixels in this view'],
@@ -48,37 +37,14 @@
current: ['Up to date', 'Nothing moved since the last read'],
};
const read = $derived(READ[reading] ?? READ.due);
- // Choosing what to read is asking for it, as the cloud switch is: the reading
- // runs then, bands included, rather than waiting on a second press of Read.
- const chosen = () => queueMicrotask(() => onrun());
+ const busy = $derived(reading === 'reading' || reading === 'tiles');
const readTitle = $derived(!status.ok ? status.reason
: !runnable ? 'This method needs another imagery source'
: reading === 'due' && frames ? 'Read this view, one Sentinel-2 request a side'
: read[1]);
-
- // A press anywhere off the strip and its panel closes the panel. The strip
- // counts as inside: Read or a base pressed with the settings open is tuning
- // them, and the gear would otherwise close it on the way down and reopen it.
- let barEl = $state();
- $effect(() => {
- if (!open) return;
- const key = (event) => {
- if (event.key === 'Escape') open = false;
- };
- const outside = (event) => {
- if (barEl?.contains(event.target)) return;
- open = false;
- };
- window.addEventListener('keydown', key);
- document.addEventListener('pointerdown', outside, true);
- return () => {
- window.removeEventListener('keydown', key);
- document.removeEventListener('pointerdown', outside, true);
- };
- });
</script>
-<div class="difference-bar cmp-glass" aria-label="Difference" bind:this={barEl}>
+<div class="difference-bar cmp-glass" aria-label="Difference">
<span class="name">Difference</span>
<div class="cmp-seg" aria-label="Image under the highlights">
{#each CHANGE_BASES as entry}
@@ -110,152 +76,10 @@
>
<Icon name="settings" size={15} />
</button>
-
- {#if open}
- <aside class="cmp-dock settings" aria-label="Difference settings">
- <header>
- <strong>Difference settings</strong>
- <button class="cmp-icon" onclick={() => (open = false)} aria-label="Close the settings" title="Close">
- <Icon name="x" size={14} />
- </button>
- </header>
- <div class="cmp-dock-body">
- {#each status.notes ?? [] as note}<p class="hint">{note}</p>{/each}
-
- <!-- One box whatever the reading is doing, so a read never reflows the panel. -->
- <div class="readout" class:stale={stale || busy} aria-live="polite">
- {#if error}
- <strong class="warn">No reading</strong>
- <span role="alert">{error}</span>
- {:else if result}
- <strong>{Math.round(result.share * 100)}%</strong>
- <span>of the overlap highlighted</span>
- {:else}
- <strong class="dim">–</strong>
- <span>{busy ? 'Reading this view' : 'Not read yet'}</span>
- {/if}
- <small>
- {#if busy}Reading…{:else if stale && result}From an earlier read{:else if result}{Math.round(result.coverage * 100)}% coverage · {Math.round(result.area)} m²{:else}&nbsp;{/if}
- </small>
- </div>
-
- {#if status.clouds}
- <CloudFilter
- clouds={settings.ignore_clouds}
- shadows={settings.ignore_shadows}
- ontoggle={(on) => {
- settings = { ...settings, ignore_clouds: on, ignore_shadows: on };
- // The click is the act that asks for the sky, so the reading follows
- // it rather than leaving an unfiltered mask up behind an "on" switch.
- queueMicrotask(() => onrun());
- }}
- />
- {/if}
-
- {#if frames}
- <p class="hint">
- Reads Sentinel-2 bands, one request a side, kept with a margin around this view.
- Panning inside it costs nothing; past it, the bands are fetched again once the map rests.
- </p>
- {/if}
-
- <div class="settings-tabs" role="tablist" aria-label="Difference parameters">
- {#each [['detection', 'Detection'], ['display', 'Display'], ['filters', 'Filters']] as [id, label]}
- <button role="tab" aria-selected={tab === id} class:on={tab === id} onclick={() => (tab = id)}>{label}</button>
- {/each}
- </div>
-
- {#if tab === 'detection'}
- <label title="What to compare: colour, edges or a spectral index.">Method
- <select aria-label="Method" bind:value={settings.method} onchange={chosen}>
- {#each CHANGE_METHODS as method}<option value={method.id} disabled={!status.methods.includes(method.id)}>{method.label}</option>{/each}
- </select>
- </label>
- {#if settings.method === 'index'}
- <label title="The spectral index compared between the two passes.">Index
- <select bind:value={settings.index} onchange={chosen}>{#each CHANGE_INDICES as entry}<option value={entry.id}>{entry.label} · {entry.hint}</option>{/each}</select>
- </label>
- {:else}
- <label title="Adapt the threshold to this view, or follow the sensitivity.">Threshold
- <select bind:value={settings.threshold}><option value="auto">Automatic</option><option value="manual">Manual</option></select>
- </label>
- {/if}
- <label title="Higher values show weaker differences and more noise.">Sensitivity · {settings.sensitivity}
- <input aria-label="Change sensitivity" type="range" min="0" max="100" bind:value={settings.sensitivity} />
- </label>
- {#if settings.method === 'index'}
- <p class="hint">Highlights {index?.label} moved by {indexThreshold(settings.sensitivity).toFixed(2)} or more.</p>
- <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
- </button>
- {/if}
-
- {#if tab === 'display'}
- <label title="Draw the change as classes, a signal heatmap or outlines.">Display
- <select bind:value={settings.display}>{#each CHANGE_DISPLAYS as display}<option value={display.id}>{display.label}</option>{/each}</select>
- </label>
- <label title="Overlay colours only, none of them a sensor reading.">Palette
- <select bind:value={settings.palette}><option value="directional">Directional</option><option value="colourblind">Colour-blind</option><option value="thermal">Thermal</option></select>
- </label>
- <div class="classes">{#each CHANGE_CLASSES as entry}<label class="check"><input type="checkbox" bind:group={settings.classes} value={entry} /> {entry}</label>{/each}</div>
- <label title="Fade the highlights to inspect the imagery beneath them.">Overlay · {settings.opacity}%
- <input aria-label="Change overlay opacity" type="range" min="0" max="100" bind:value={settings.opacity} />
- </label>
- {/if}
-
- {#if tab === 'filters'}
- <label title="Even out exposure, at the risk of hiding a broad change.">Tone matching
- <select bind:value={settings.normalize}>
- <option value="auto">Automatic</option><option value="none">None</option>
- <option value="mean">Mean brightness</option><option value="histogram">Histogram</option>
- </select>
- </label>
- {#if settings.normalize === 'auto'}
- <p class="hint">
- {status.family === 'sentinel2'
- ? 'Nothing to match: both passes are corrected to surface reflectance.'
- : status.family === 'sentinel1'
- ? 'Nothing to match: both passes are calibrated backscatter.'
- : 'Histogram, because two releases carry two renderings.'}
- </p>
- {/if}
- <label title="Search for a small image offset before comparing pixels.">Alignment · ±{settings.alignment}px<input type="range" min="0" max="8" bind:value={settings.alignment} /></label>
- <label title="Reduce pixel noise before thresholding.">Smoothing · {settings.smoothing}px<input type="range" min="0" max="4" bind:value={settings.smoothing} /></label>
- <label title="Remove isolated speckles.">Cleanup · {settings.cleanup}<input type="range" min="0" max="3" bind:value={settings.cleanup} /></label>
- <label title="Discard connected regions below this ground area.">Minimum area (m²)<input type="number" min="0" max="1000000" bind:value={settings.min_area} /></label>
- {#if status.clouds}
- <label class="check" title="Exclude cloud, read from Sentinel-2's scene classification."><input type="checkbox" bind:checked={settings.ignore_clouds} /> Mask clouds</label>
- <label class="check" title="Exclude the shadow cloud casts, which moves with the sun."><input type="checkbox" bind:checked={settings.ignore_shadows} /> Mask shadows</label>
- <label title="Grow the mask over the soft edge a cloud leaves.">Mask margin · {settings.cloud_margin} m<input aria-label="Cloud mask margin" type="range" min="0" max="200" step="10" bind:value={settings.cloud_margin} /></label>
- {/if}
- <label class="check"><input type="checkbox" bind:checked={settings.zones} /> List change zones</label>
- <button class="link" onclick={() => (settings = changeSettings())}>Reset settings</button>
- {/if}
-
- {#if result && settings.zones}
- <section>
- <strong>{result.zoneCount} change zones{result.zoneCount > result.zones.length ? ` · largest ${result.zones.length}` : ''}</strong>
- <div class="zone-list">
- {#each result.zones as zone (zone.id)}
- <button onclick={() => onzone(zone)}>
- <span class="zone-strength {zone.strength}">{zone.strength}</span>
- Zone {zone.id} · {zone.kind} · {Math.round(zone.area)} m²
- </button>
- {/each}
- </div>
- </section>
- {/if}
- </div>
- </aside>
- {/if}
</div>
<style>
.difference-bar {
- position: relative;
flex: 0 0 auto;
display: flex;
align-items: center;
@@ -290,44 +114,4 @@
text-transform: uppercase;
color: var(--glass-dim);
}
- /* Opened on request, over the stage: the maps keep their width. One height
- for every tab, so switching tabs or a zone list arriving never moves the
- header under the pointer. */
- .settings.cmp-dock {
- position: absolute;
- right: 0;
- bottom: calc(100% + 8px);
- z-index: 30;
- width: clamp(290px, 24vw, 360px);
- height: min(540px, 62vh);
- border: 1px solid var(--border);
- border-radius: var(--r-md, 8px);
- box-shadow: 0 12px 32px rgba(0, 0, 0, 0.35);
- overflow: hidden;
- }
- .readout {
- display: grid;
- gap: 2px;
- padding: 9px 10px;
- border: 1px solid var(--border);
- border-radius: var(--r-sm);
- background: var(--bg-2);
- }
- .readout strong { font-size: var(--fs-lg); color: var(--accent); font-variant-numeric: tabular-nums; }
- .readout strong.warn { color: var(--warn); }
- .readout strong.dim { color: var(--text-3); }
- .readout span { overflow: hidden; font-size: var(--fs-xs); color: var(--text-2); text-overflow: ellipsis; white-space: nowrap; }
- .readout small { font-size: 10.5px; color: var(--text-3); }
- .readout.stale strong { opacity: 0.6; }
- .settings-tabs { display: flex; gap: 3px; border-bottom: 1px solid var(--border); }
- .settings-tabs button { flex: 1; padding: 7px 4px; color: var(--text-2); font-size: var(--fs-xs); }
- .settings-tabs button.on { color: var(--accent); border-bottom: 2px solid var(--accent); }
- .classes { display: flex; flex-wrap: wrap; gap: 10px; }
- section { display: grid; gap: 6px; border-top: 1px solid var(--border); padding-top: 10px; font-size: var(--fs-xs); }
- .zone-list { display: grid; gap: 4px; max-height: 170px; overflow: auto; }
- .zone-list button { padding: 5px; text-align: left; background: var(--bg-2); border-radius: var(--r-sm); font-size: 11px; }
- .zone-list button:hover { background: var(--bg-3); }
- .zone-strength { font-weight: 600; text-transform: capitalize; color: var(--text-2); }
- .zone-strength.strong { color: var(--accent); }
- .link { color: var(--accent); font-size: var(--fs-xs); text-align: left; }
</style>
diff --git a/frontend/src/tools/compare/DifferenceBar.test.js b/frontend/src/tools/compare/DifferenceBar.test.js
index 73282d0..e435500 100644
--- a/frontend/src/tools/compare/DifferenceBar.test.js
+++ b/frontend/src/tools/compare/DifferenceBar.test.js
@@ -10,7 +10,7 @@ import { changeSettings } from '../../lib/map/changeAssist.js';
const ready = { ok: true, label: 'Two dated passes', methods: ['colour', 'brightness'], notes: [],
family: 'sentinel2', clouds: true };
-function render(props = {}, { open = false } = {}) {
+function render(props = {}) {
const target = document.createElement('div');
document.body.append(target);
const live = mount(DifferenceBar, {
@@ -18,10 +18,6 @@ function render(props = {}, { open = false } = {}) {
props: { settings: changeSettings(), status: ready, ...props },
});
flushSync();
- if (open) {
- target.querySelector('button[aria-label="Difference settings"]').click();
- flushSync();
- }
return { target, done: () => { unmount(live); target.remove(); } };
}
@@ -34,33 +30,6 @@ const base = (target, label) =>
.find((entry) => entry.textContent.trim() === label);
describe('Difference strip', () => {
- it('keeps every tooltip to one short clause', () => {
- // The settings sit on three tabs, so the written titles are read off the
- // component rather than opened one tab at a time.
- const here = dirname(fileURLToPath(import.meta.url));
- const source = readFileSync(join(here, 'DifferenceBar.svelte'), 'utf8');
- const tips = [...source.matchAll(/title=(?:"([^"]*)"|\{([^}]*)\})/g)].flatMap(([, text, code]) =>
- text !== undefined ? [text] : [...code.matchAll(/'([^']+)'|`([^`]+)`/g)].map((m) => m[1] ?? m[2]));
-
- expect(tips.length).toBeGreaterThan(15);
- for (const tip of tips) {
- expect(tip.length, tip).toBeLessThanOrEqual(60);
- expect(tip, tip).not.toContain(';');
- }
- });
-
- 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');
@@ -71,21 +40,6 @@ describe('Difference strip', () => {
done();
});
- it('keeps its settings closed until asked, then opens them over the stage', () => {
- const { target, done } = render();
- expect(target.querySelector('.settings')).toBeNull();
- const gear = target.querySelector('button[aria-label="Difference settings"]');
- expect(gear.getAttribute('aria-expanded')).toBe('false');
- gear.click();
- flushSync();
- expect(target.querySelector('aside.settings')).not.toBeNull();
- expect(target.textContent).toContain('Sensitivity');
- window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' }));
- flushSync();
- expect(target.querySelector('.settings')).toBeNull();
- done();
- });
-
it('refuses to read a pair it cannot read, and says why', () => {
const { target, done } = render({
status: { ok: false, reason: 'Date both passes first', methods: [] },
@@ -145,102 +99,18 @@ describe('Difference strip', () => {
done();
});
- it('says so in the panel when the highlights are from an earlier read', () => {
- const result = { share: 0.1, coverage: 1, area: 20, zones: [], zoneCount: 0 };
- const { target, done } = render({ reading: 'due', result }, { open: true });
- expect(target.querySelector('.readout').textContent).toContain('From an earlier read');
- done();
- });
-
- it('keeps the strip the same through a read, so the panel hanging from it stays put', () => {
- // The strip once grew a status label on every read and error, which moved
- // the open panel under the pointer.
- const shape = (target) => [...target.querySelector('.difference-bar').children]
- .filter((node) => !node.matches('aside')).map((node) => node.tagName);
- const idle = render({}, { open: true });
- const before = shape(idle.target);
- idle.done();
- const reading = render({ reading: 'reading', error: 'Could not compare these pixels' }, { open: true });
- expect(shape(reading.target)).toEqual(before);
- expect(reading.target.querySelector('.readout [role="alert"]').textContent).toBe('Could not compare these pixels');
- reading.done();
- });
-
- it('closes the panel on a press off the strip, but not on one inside it or on the gear', () => {
- const { target, done } = render({}, { open: true });
- const press = (node) => node.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true }));
- press(target.querySelector('aside.settings select'));
- flushSync();
- expect(target.querySelector('aside.settings')).not.toBeNull();
- // Reading with the settings open is tuning them, not leaving them.
- press(button(target, 'Read'));
- flushSync();
- expect(target.querySelector('aside.settings')).not.toBeNull();
- // The gear's own press must not close it, or its click would reopen it.
+ it('opens and closes its settings from the gear, and draws none of them itself', () => {
+ // The panel is Compare's, docked on the stage, so the strip only says whether it is open.
+ const { target, done } = render();
const gear = target.querySelector('button[aria-label="Difference settings"]');
- press(gear);
+ expect(gear.getAttribute('aria-expanded')).toBe('false');
gear.click();
flushSync();
- expect(target.querySelector('aside.settings')).toBeNull();
+ expect(gear.getAttribute('aria-expanded')).toBe('true');
+ expect(target.querySelector('aside')).toBeNull();
gear.click();
flushSync();
- expect(target.querySelector('aside.settings')).not.toBeNull();
- press(document.body);
- flushSync();
- expect(target.querySelector('aside.settings')).toBeNull();
- done();
- });
-
- it('offers the cloud filter only where a scene classification exists', () => {
- const { target, done } = render({}, { open: true });
- expect(target.textContent).toContain('Clouds & shadows');
- done();
- const esri = render({ status: { ...ready, family: 'esri', clouds: false } }, { open: true });
- expect(esri.target.textContent).not.toContain('Clouds & shadows');
- esri.done();
- });
-
- it('says when a reading reads bands, and never asks to be turned on', () => {
- // The reading always follows the camera. Reading bands is a different
- // question: it is what costs a request, and only off the held ground.
- const { target, done } = render({ settings: changeSettings({ ignore_clouds: true }) }, { open: true });
- expect(target.textContent).toContain('one request a side');
- done();
- const free = render({}, { open: true });
- expect(free.target.textContent).not.toContain('one request a side');
- expect(free.target.textContent).not.toContain('Follow the map');
- free.done();
- });
-
- it('reads the view as soon as a method or an index is chosen', async () => {
- const onrun = vi.fn();
- const { target, done } = render({ settings: changeSettings({ method: 'index', index: 'nbr' }),
- status: { ...ready, methods: ['colour', 'index'] }, onrun }, { open: true });
- const [method, index] = target.querySelectorAll('aside.settings select');
- index.dispatchEvent(new Event('change', { bubbles: true }));
- await Promise.resolve();
- expect(onrun).toHaveBeenCalledTimes(1);
- method.dispatchEvent(new Event('change', { bubbles: true }));
- await Promise.resolve();
- expect(onrun).toHaveBeenCalledTimes(2);
- done();
- });
-
- it('reads the view as soon as the cloud filter is switched on', async () => {
- // The switch says the sky is being read, so it cannot leave an unfiltered
- // reading up behind it.
- const onrun = vi.fn();
- const { target, done } = render({ onrun }, { open: true });
- target.querySelector('.cloud-filter button').click();
- flushSync();
- await Promise.resolve();
- expect(onrun).toHaveBeenCalledTimes(1);
- done();
- });
-
- it('states the index change it draws the line at', () => {
- const { target, done } = render({ settings: changeSettings({ method: 'index', index: 'nbr' }) }, { open: true });
- expect(target.textContent).toContain('NBR moved by 0.19');
+ expect(gear.getAttribute('aria-expanded')).toBe('false');
done();
});
});
diff --git a/frontend/src/tools/compare/DifferencePanel.svelte b/frontend/src/tools/compare/DifferencePanel.svelte
new file mode 100644
index 0000000..68fb346
--- /dev/null
+++ b/frontend/src/tools/compare/DifferencePanel.svelte
@@ -0,0 +1,232 @@
+<script>
+ /**
+ * Difference's settings, docked on the stage's right edge over map B. It lies
+ * over the maps rather than narrowing them: a narrower view is a new view,
+ * and a Sentinel-2 reading would fetch its bands again for a panel opening.
+ *
+ * It stays open while the map moves, since tuning is watching the highlights
+ * answer; the gear, its close button or Escape put it away.
+ */
+ import { CHANGE_METHODS, CHANGE_INDICES, CHANGE_DISPLAYS, CHANGE_CLASSES,
+ changeNeedsFrames, changeSettings, indexThreshold } from '../../lib/map/changeAssist.js';
+ import CloudFilter from './CloudFilter.svelte';
+ import Icon from '../../components/Icon.svelte';
+
+ let {
+ settings = $bindable(),
+ status,
+ result = null,
+ /** due: Read has something to do · reading · tiles: waiting on the maps · current: nothing moved. */
+ reading = 'due',
+ error = '',
+ onrun = () => {},
+ onzone = () => {},
+ /** Keep this index reading as a Detect analyzer, to sweep areas with it. */
+ onanalyzer = () => {},
+ onclose = () => {},
+ } = $props();
+
+ let tab = $state('detection');
+ // What this reading has to fetch, and therefore whether it can follow the map.
+ const frames = $derived(changeNeedsFrames(settings, status));
+ const index = $derived(CHANGE_INDICES.find((entry) => entry.id === settings.index));
+ const busy = $derived(reading === 'reading' || reading === 'tiles');
+ const stale = $derived(!!result && reading === 'due');
+ // Choosing what to read is asking for it, as the cloud switch is: the reading
+ // runs then, bands included, rather than waiting on a second press of Read.
+ const chosen = () => queueMicrotask(() => onrun());
+
+ $effect(() => {
+ const key = (event) => {
+ if (event.key === 'Escape') onclose();
+ };
+ window.addEventListener('keydown', key);
+ return () => window.removeEventListener('keydown', key);
+ });
+</script>
+
+ <aside class="cmp-dock settings" aria-label="Difference settings">
+ <header>
+ <strong>Difference settings</strong>
+ <button class="cmp-icon" onclick={() => onclose()} aria-label="Close the settings" title="Close">
+ <Icon name="x" size={14} />
+ </button>
+ </header>
+ <div class="cmp-dock-body">
+ <!-- One box whatever the reading is doing, so a read never reflows the panel. -->
+ <div class="readout" class:stale={stale || busy} aria-live="polite">
+ {#if error}
+ <strong class="warn">No reading</strong>
+ <span role="alert">{error}</span>
+ {:else if result}
+ <strong>{Math.round(result.share * 100)}%</strong>
+ <span>of the overlap highlighted</span>
+ {:else}
+ <strong class="dim">–</strong>
+ <span>{busy ? 'Reading this view' : 'Not read yet'}</span>
+ {/if}
+ <small>
+ {#if busy}Reading…{:else if stale && result}From an earlier read{:else if result}{Math.round(result.coverage * 100)}% coverage · {Math.round(result.area)} m²{:else}&nbsp;{/if}
+ </small>
+ </div>
+ {#if status.notes?.length}
+ <ul class="notes">{#each status.notes as note}<li>{note}</li>{/each}</ul>
+ {/if}
+
+ {#if status.clouds}
+ <CloudFilter
+ clouds={settings.ignore_clouds}
+ shadows={settings.ignore_shadows}
+ ontoggle={(on) => {
+ settings = { ...settings, ignore_clouds: on, ignore_shadows: on };
+ // The click is the act that asks for the sky, so the reading follows
+ // it rather than leaving an unfiltered mask up behind an "on" switch.
+ queueMicrotask(() => onrun());
+ }}
+ />
+ {/if}
+
+ {#if frames}
+ <p class="hint">Reads Sentinel-2 bands, one request a side, fetched again only past this view’s margin.</p>
+ {/if}
+
+ <div class="settings-tabs" role="tablist" aria-label="Difference parameters">
+ {#each [['detection', 'Detection'], ['display', 'Display'], ['filters', 'Filters']] as [id, label]}
+ <button role="tab" aria-selected={tab === id} class:on={tab === id} onclick={() => (tab = id)}>{label}</button>
+ {/each}
+ </div>
+
+ {#if tab === 'detection'}
+ <label title="What to compare: colour, edges or a spectral index.">Method
+ <select aria-label="Method" bind:value={settings.method} onchange={chosen}>
+ {#each CHANGE_METHODS as method}<option value={method.id} disabled={!status.methods.includes(method.id)}>{method.label}</option>{/each}
+ </select>
+ </label>
+ {#if settings.method === 'index'}
+ <label title="The spectral index compared between the two passes.">Index
+ <select bind:value={settings.index} onchange={chosen}>{#each CHANGE_INDICES as entry}<option value={entry.id}>{entry.label} · {entry.hint}</option>{/each}</select>
+ </label>
+ {:else}
+ <label title="Adapt the threshold to this view, or follow the sensitivity.">Threshold
+ <select bind:value={settings.threshold}><option value="auto">Automatic</option><option value="manual">Manual</option></select>
+ </label>
+ {/if}
+ <label title="Higher values show weaker differences and more noise.">Sensitivity · {settings.sensitivity}
+ <input aria-label="Change sensitivity" type="range" min="0" max="100" bind:value={settings.sensitivity} />
+ </label>
+ {#if settings.method === 'index'}
+ <p class="hint">Highlights {index?.label} moved by {indexThreshold(settings.sensitivity).toFixed(2)} or more.</p>
+ <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
+ </button>
+ {/if}
+
+ {#if tab === 'display'}
+ <label title="Draw the change as classes, a signal heatmap or outlines.">Display
+ <select bind:value={settings.display}>{#each CHANGE_DISPLAYS as display}<option value={display.id}>{display.label}</option>{/each}</select>
+ </label>
+ <label title="Overlay colours only, none of them a sensor reading.">Palette
+ <select bind:value={settings.palette}><option value="directional">Directional</option><option value="colourblind">Colour-blind</option><option value="thermal">Thermal</option></select>
+ </label>
+ <div class="classes">{#each CHANGE_CLASSES as entry}<label class="check"><input type="checkbox" bind:group={settings.classes} value={entry} /> {entry}</label>{/each}</div>
+ <label title="Fade the highlights to inspect the imagery beneath them.">Overlay · {settings.opacity}%
+ <input aria-label="Change overlay opacity" type="range" min="0" max="100" bind:value={settings.opacity} />
+ </label>
+ {/if}
+
+ {#if tab === 'filters'}
+ <label title="Even out exposure, at the risk of hiding a broad change.">Tone matching
+ <select bind:value={settings.normalize}>
+ <option value="auto">Automatic</option><option value="none">None</option>
+ <option value="mean">Mean brightness</option><option value="histogram">Histogram</option>
+ </select>
+ </label>
+ {#if settings.normalize === 'auto'}
+ <p class="hint">
+ {status.family === 'sentinel2'
+ ? 'None needed, both are surface reflectance.'
+ : status.family === 'sentinel1'
+ ? 'None needed, both are calibrated backscatter.'
+ : 'Histogram, as two releases render differently.'}
+ </p>
+ {/if}
+ <label title="Search for a small image offset before comparing pixels.">Alignment · ±{settings.alignment}px<input type="range" min="0" max="8" bind:value={settings.alignment} /></label>
+ <label title="Reduce pixel noise before thresholding.">Smoothing · {settings.smoothing}px<input type="range" min="0" max="4" bind:value={settings.smoothing} /></label>
+ <label title="Remove isolated speckles.">Cleanup · {settings.cleanup}<input type="range" min="0" max="3" bind:value={settings.cleanup} /></label>
+ <label title="Discard connected regions below this ground area.">Minimum area (m²)<input type="number" min="0" max="1000000" bind:value={settings.min_area} /></label>
+ {#if status.clouds}
+ <label class="check" title="Exclude cloud, read from Sentinel-2's scene classification."><input type="checkbox" bind:checked={settings.ignore_clouds} /> Mask clouds</label>
+ <label class="check" title="Exclude the shadow cloud casts, which moves with the sun."><input type="checkbox" bind:checked={settings.ignore_shadows} /> Mask shadows</label>
+ <label title="Grow the mask over the soft edge a cloud leaves.">Mask margin · {settings.cloud_margin} m<input aria-label="Cloud mask margin" type="range" min="0" max="200" step="10" bind:value={settings.cloud_margin} /></label>
+ {/if}
+ <label class="check"><input type="checkbox" bind:checked={settings.zones} /> List change zones</label>
+ <button class="link" onclick={() => (settings = changeSettings())}>Reset settings</button>
+ {/if}
+
+ {#if result && settings.zones}
+ <section>
+ <strong>{result.zoneCount} change zones{result.zoneCount > result.zones.length ? ` · largest ${result.zones.length}` : ''}</strong>
+ <div class="zone-list">
+ {#each result.zones as zone (zone.id)}
+ <button onclick={() => onzone(zone)}>
+ <span class="zone-strength {zone.strength}">{zone.strength}</span>
+ Zone {zone.id} · {zone.kind} · {Math.round(zone.area)} m²
+ </button>
+ {/each}
+ </div>
+ </section>
+ {/if}
+ </div>
+ </aside>
+
+<style>
+ /* Inset like the chips around it, in the glass the map's floating panels
+ share: near opaque so the form reads over busy imagery. It starts under
+ the cards' row (8px, a 38px card, 8px), so B's card stays whole. One
+ height for every tab, so switching tabs or a zone list arriving never
+ moves the header under the pointer. */
+ .settings.cmp-dock {
+ position: absolute;
+ top: 54px;
+ right: 8px;
+ bottom: 8px;
+ z-index: 660;
+ width: var(--difference-dock);
+ border: 1px solid var(--border);
+ border-radius: var(--r-md, 8px);
+ background: color-mix(in srgb, var(--bg-1) 88%, transparent);
+ backdrop-filter: blur(6px);
+ box-shadow: 0 12px 32px rgba(0, 0, 0, 0.35);
+ overflow: hidden;
+ }
+ .readout {
+ display: grid;
+ gap: 2px;
+ padding: 9px 10px;
+ border: 1px solid var(--border);
+ border-radius: var(--r-sm);
+ background: var(--bg-2);
+ }
+ .readout strong { font-size: var(--fs-lg); color: var(--accent); font-variant-numeric: tabular-nums; }
+ .readout strong.warn { color: var(--warn); }
+ .readout strong.dim { color: var(--text-3); }
+ .readout span { overflow: hidden; font-size: var(--fs-xs); color: var(--text-2); text-overflow: ellipsis; white-space: nowrap; }
+ .readout small { font-size: 10.5px; color: var(--text-3); }
+ .readout.stale strong { opacity: 0.6; }
+ /* What this pair can't prove, set under the reading as one quiet block. */
+ .notes { display: grid; gap: 2px; margin: -8px 0 0; padding: 0; list-style: none; color: var(--text-3); font-size: var(--fs-xs); line-height: 1.4; }
+ .settings-tabs { display: flex; gap: 3px; border-bottom: 1px solid var(--border); }
+ .settings-tabs button { flex: 1; padding: 7px 4px; color: var(--text-2); font-size: var(--fs-xs); }
+ .settings-tabs button.on { color: var(--accent); border-bottom: 2px solid var(--accent); }
+ .classes { display: flex; flex-wrap: wrap; gap: 10px; }
+ section { display: grid; gap: 6px; border-top: 1px solid var(--border); padding-top: 10px; font-size: var(--fs-xs); }
+ .zone-list { display: grid; gap: 4px; max-height: 170px; overflow: auto; }
+ .zone-list button { padding: 5px; text-align: left; background: var(--bg-2); border-radius: var(--r-sm); font-size: 11px; }
+ .zone-list button:hover { background: var(--bg-3); }
+ .zone-strength { font-weight: 600; text-transform: capitalize; color: var(--text-2); }
+ .zone-strength.strong { color: var(--accent); }
+ .link { color: var(--accent); font-size: var(--fs-xs); text-align: left; }
+</style>
diff --git a/frontend/src/tools/compare/DifferencePanel.test.js b/frontend/src/tools/compare/DifferencePanel.test.js
new file mode 100644
index 0000000..4b0982e
--- /dev/null
+++ b/frontend/src/tools/compare/DifferencePanel.test.js
@@ -0,0 +1,159 @@
+// @vitest-environment happy-dom
+import { describe, expect, it, vi } from 'vitest';
+import { flushSync, mount, unmount } from 'svelte';
+import { readFileSync } from 'node:fs';
+import { dirname, join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import DifferencePanel from './DifferencePanel.svelte';
+import { changeSettings } from '../../lib/map/changeAssist.js';
+
+const ready = { ok: true, label: 'Two dated passes', methods: ['colour', 'brightness'], notes: [],
+ family: 'sentinel2', clouds: true };
+
+const here = dirname(fileURLToPath(import.meta.url));
+
+function render(props = {}) {
+ const target = document.createElement('div');
+ document.body.append(target);
+ const live = mount(DifferencePanel, {
+ target,
+ props: { settings: changeSettings(), status: ready, ...props },
+ });
+ flushSync();
+ return { target, done: () => { unmount(live); target.remove(); } };
+}
+
+const button = (target, name) =>
+ [...target.querySelectorAll('button')].find((node) =>
+ node.getAttribute('aria-label') === name || node.textContent.trim() === name);
+
+describe('Difference settings panel', () => {
+ it('keeps every tooltip to one short clause', () => {
+ // The settings sit on three tabs, so the written titles are read off the
+ // components rather than opened one tab at a time.
+ const tips = ['DifferencePanel.svelte', 'DifferenceBar.svelte'].flatMap((file) => {
+ const source = readFileSync(join(here, file), 'utf8');
+ return [...source.matchAll(/title=(?:"([^"]*)"|\{([^}]*)\})/g)].flatMap(([, text, code]) =>
+ text !== undefined ? [text] : [...code.matchAll(/'([^']+)'|`([^`]+)`/g)].map((m) => m[1] ?? m[2]));
+ });
+
+ expect(tips.length).toBeGreaterThan(15);
+ for (const tip of tips) {
+ expect(tip.length, tip).toBeLessThanOrEqual(60);
+ expect(tip, tip).not.toContain(';');
+ }
+ });
+
+ it('lies over the maps in the glass their floating panels share, rather than narrowing them', () => {
+ // A narrower map is a new view, and a band reading would fetch again for a panel opening.
+ const source = readFileSync(join(here, 'DifferencePanel.svelte'), 'utf8');
+ const rule = source.match(/\.settings\.cmp-dock \{([^}]*)\}/)[1];
+ expect(rule).toMatch(/position: absolute;/);
+ expect(rule).toMatch(/right: 8px;/);
+ expect(rule).toMatch(/top: 54px;/);
+ expect(rule).toMatch(/bottom: 8px;/);
+ expect(rule).toMatch(/color-mix\(in srgb, var\(--bg-1\) 88%, transparent\)/);
+ expect(rule).toMatch(/backdrop-filter: blur\(6px\);/);
+ });
+
+ it('closes on its button and on Escape, and stays open through presses anywhere else', () => {
+ const onclose = vi.fn();
+ const { target, done } = render({ onclose });
+ // Tuning is watching the map answer, so a press on the map leaves it up.
+ document.body.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true }));
+ target.querySelector('select').dispatchEvent(new PointerEvent('pointerdown', { bubbles: true }));
+ flushSync();
+ expect(onclose).not.toHaveBeenCalled();
+ button(target, 'Close the settings').click();
+ expect(onclose).toHaveBeenCalledTimes(1);
+ window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' }));
+ expect(onclose).toHaveBeenCalledTimes(2);
+ done();
+ });
+
+ it('stops listening for Escape once closed', () => {
+ const onclose = vi.fn();
+ const { done } = render({ onclose });
+ done();
+ window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' }));
+ expect(onclose).not.toHaveBeenCalled();
+ });
+
+ 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 });
+ button(index.target, 'Save as a Detect analyzer').click();
+ expect(onanalyzer).toHaveBeenCalledOnce();
+ index.done();
+ const colour = render();
+ expect(button(colour.target, 'Save as a Detect analyzer')).toBeUndefined();
+ colour.done();
+ });
+
+ it('says so when the highlights are from an earlier read', () => {
+ const result = { share: 0.1, coverage: 1, area: 20, zones: [], zoneCount: 0 };
+ const { target, done } = render({ reading: 'due', result });
+ expect(target.querySelector('.readout').textContent).toContain('From an earlier read');
+ done();
+ });
+
+ it('says a failed reading in its readout', () => {
+ const { target, done } = render({ reading: 'reading', error: 'Could not compare these pixels' });
+ expect(target.querySelector('.readout [role="alert"]').textContent).toBe('Could not compare these pixels');
+ done();
+ });
+
+ it('offers the cloud filter only where a scene classification exists', () => {
+ const { target, done } = render();
+ expect(target.textContent).toContain('Clouds & shadows');
+ done();
+ const esri = render({ status: { ...ready, family: 'esri', clouds: false } });
+ expect(esri.target.textContent).not.toContain('Clouds & shadows');
+ esri.done();
+ });
+
+ it('says when a reading reads bands, and never asks to be turned on', () => {
+ // The reading always follows the camera. Reading bands is a different
+ // question: it is what costs a request, and only off the held ground.
+ const { target, done } = render({ settings: changeSettings({ ignore_clouds: true }) });
+ expect(target.textContent).toContain('one request a side');
+ done();
+ const free = render();
+ expect(free.target.textContent).not.toContain('one request a side');
+ expect(free.target.textContent).not.toContain('Follow the map');
+ free.done();
+ });
+
+ it('reads the view as soon as a method or an index is chosen', async () => {
+ const onrun = vi.fn();
+ const { target, done } = render({ settings: changeSettings({ method: 'index', index: 'nbr' }),
+ status: { ...ready, methods: ['colour', 'index'] }, onrun });
+ const [method, index] = target.querySelectorAll('aside.settings select');
+ index.dispatchEvent(new Event('change', { bubbles: true }));
+ await Promise.resolve();
+ expect(onrun).toHaveBeenCalledTimes(1);
+ method.dispatchEvent(new Event('change', { bubbles: true }));
+ await Promise.resolve();
+ expect(onrun).toHaveBeenCalledTimes(2);
+ done();
+ });
+
+ it('reads the view as soon as the cloud filter is switched on', async () => {
+ // The switch says the sky is being read, so it cannot leave an unfiltered
+ // reading up behind it.
+ const onrun = vi.fn();
+ const { target, done } = render({ onrun });
+ target.querySelector('.cloud-filter button').click();
+ flushSync();
+ await Promise.resolve();
+ expect(onrun).toHaveBeenCalledTimes(1);
+ done();
+ });
+
+ it('states the index change it draws the line at', () => {
+ const { target, done } = render({ settings: changeSettings({ method: 'index', index: 'nbr' }) });
+ expect(target.textContent).toContain('NBR moved by 0.19');
+ done();
+ });
+});
diff --git a/frontend/src/tools/detect/AcquisitionPicker.svelte b/frontend/src/tools/detect/AcquisitionPicker.svelte
index a5112fd..16e7a2d 100644
--- a/frontend/src/tools/detect/AcquisitionPicker.svelte
+++ b/frontend/src/tools/detect/AcquisitionPicker.svelte
@@ -2,30 +2,31 @@
/**
* The Sentinel-2 passes the drawn areas actually have, to pick a run's dates from.
*
- * It replaces two bare date fields, which offered every day since 2015 and
- * knew nothing: a sweep pinned to a day without a pass reads nodata, and the
- * user finds that out after paying for the tiles. A calendar is the wrong
- * shape for the answer, too — Sentinel-2 revisits every five days, so four
- * cells in five are dead. So this lists what exists, newest first, with the
+ * It complements the A and B calendars with coverage and cloud details.
+ * A sweep pinned to a day without a pass reads nodata, and the user finds
+ * that out after paying for the tiles. This lists what exists, newest first, with the
* two facts that decide between them: how much of the areas the pass reaches,
* and how much of it was cloud.
*
- * The calendar has its place one step up, for where to look: past the year the
- * presets reach, two days picked in it bound the lookup. The catalogue answers
- * newest first, five pages at most, so a list it cut short offers the older ones.
+ * Date A and date B each have their own pass calendar above this list. The
+ * catalogue answers newest first, five pages at most, so a list it cut short
+ * offers the older ones.
+ *
+ * A caller that has a way to pick a day from a calendar hands it in as `dates`,
+ * and the window gains a Dates choice beside the last year that shows it in
+ * place of the list.
*/
import Icon from '../../components/Icon.svelte';
- import MonthGrid from '../../components/MonthGrid.svelte';
import {
- LOOKBACK_WINDOWS, MISSION_START, coverClass, coverLabel, lookupSpan, olderSpan, passKey, spanProblem,
+ LOOKBACK_WINDOWS, coverClass, coverLabel, olderSpan, passKey,
} from '../../lib/map/acquisitions.js';
- import { isoDay } from '../../lib/sentinel.js';
import { cloudClass, cloudLabel } from '../../lib/sentinel.js';
+ import { passBefore } from '../../lib/map/detectWhen.js';
import { orbitMark, sameTrack } from '../../lib/radar.js';
let {
list = [],
- /** Days back from today, or two days picked in the calendar, `{ start, end }`. */
+ /** Days back from today. */
lookback,
busy = false,
error = '',
@@ -40,25 +41,20 @@
/** The chosen sources, `{ date, time }` each, or null. */
a = null,
b = null,
+ /** What the two buttons of a row say. */
+ nameA = 'A',
+ nameB = 'B',
onlookback,
onlook,
/** Look again before the oldest pass listed, when the catalogue cut the list. */
onolder,
onpick,
+ /** What shows under a Dates window: the calendars to pick a day from. Left out, there is no such window. */
+ dates = null,
} = $props();
- const picked = $derived(typeof lookback === 'object' && lookback !== null);
- const problem = $derived(spanProblem(lookback));
- const older = $derived(truncated && onolder ? olderSpan(lookback, list) : null);
- const first = $derived(MISSION_START[radar ? 'sentinel1' : 'sentinel2']);
- const today = isoDay(new Date());
- /** Which picked day has its month open: 'start', 'end' or ''. */
- let calendar = $state('');
-
- function pickDay(day) {
- onlookback({ ...lookback, [calendar]: day });
- calendar = '';
- }
+ const older = $derived(truncated && onolder && typeof lookback === 'number' ? olderSpan(lookback, list) : null);
+ const byDate = $derived(!!dates && lookback === 'dates');
/** Whether a row is the pass a side names: a typed radar day matches its day. */
function names(source, entry) {
@@ -75,42 +71,23 @@
type="button"
class:on={lookback === option.id}
disabled={busy}
- onclick={() => { calendar = ''; onlookback(option.id); }}
+ onclick={() => onlookback(option.id)}
>{option.label}</button>
{/each}
- <button
- type="button"
- class:on={picked}
- disabled={busy}
- title="Pick the first and the last day in the calendar"
- onclick={() => { if (!picked) onlookback(lookupSpan(lookback)); }}
- >Dates…</button>
- </div>
- <button class="btn btn-sm" disabled={busy || !areas || !!problem} onclick={onlook}>
- {busy ? 'Looking…' : searched ? 'Look again' : 'Find passes'}
- </button>
- </div>
-
- {#if picked}
- <div class="span">
- <button type="button" class="day cmp-mono" class:open={calendar === 'start'} disabled={busy}
- aria-label="First day" aria-expanded={calendar === 'start'}
- onclick={() => (calendar = calendar === 'start' ? '' : 'start')}>{lookback.start || 'First day'}</button>
- <span aria-hidden="true">→</span>
- <button type="button" class="day cmp-mono" class:open={calendar === 'end'} disabled={busy}
- aria-label="Last day" aria-expanded={calendar === 'end'}
- onclick={() => (calendar = calendar === 'end' ? '' : 'end')}>{lookback.end || 'Last day'}</button>
+ {#if dates}
+ <button type="button" class:on={byDate} aria-pressed={byDate} disabled={busy} onclick={() => onlookback('dates')}>Dates</button>
+ {/if}
</div>
- {#if calendar}
- <MonthGrid value={lookback[calendar]} label={calendar === 'start' ? 'First day' : 'Last day'}
- min={calendar === 'start' ? first : lookback.start || first}
- max={calendar === 'start' ? lookback.end || today : today}
- onpick={pickDay} />
+ {#if !byDate}
+ <button class="btn btn-sm" disabled={busy || !areas} onclick={onlook}>
+ {busy ? 'Looking…' : searched ? 'Look again' : 'Find passes'}
+ </button>
{/if}
- {#if problem}<p class="warn">{problem}</p>{/if}
- {/if}
+ </div>
- {#if !areas}
+ {#if byDate}
+ {@render dates()}
+ {:else if !areas}
<p class="hint">Draw an area in step 1, then look up the passes it has.</p>
{:else if error}
<p class="warn" role="alert">{error}</p>
@@ -129,6 +106,8 @@
{#each list as entry (passKey(entry))}
{@const pairedA = !single && radar && a?.time && !sameTrack(entry.time, a.time)}
{@const pairedB = !single && radar && b?.time && !sameTrack(entry.time, b.time)}
+ {@const afterB = !single && !passBefore(entry, b, radar)}
+ {@const beforeA = !single && !passBefore(a, entry, radar)}
<li class:chosen={names(a, entry) || names(b, entry)}>
<div class="facts">
<strong class="cmp-mono">{entry.date}</strong>
@@ -147,21 +126,23 @@
type="button"
class:on={names(a, entry)}
aria-pressed={names(a, entry)}
- disabled={pairedB}
- title={pairedB ? 'Another track than B: it sees the ground from another angle' : 'Use as A, the picture before'}
+ disabled={pairedB || afterB}
+ title={pairedB ? 'Another track than B: it sees the ground from another angle'
+ : afterB ? 'Date A must be before date B' : 'Use as A, the picture before'}
onclick={() => onpick('a', entry)}
- >A</button>
+ >{nameA}</button>
{/if}
{#if wantsCompare}
<button
type="button"
class:on={names(b, entry)}
aria-pressed={names(b, entry)}
- disabled={pairedA}
+ disabled={pairedA || beforeA}
title={pairedA ? 'Another track than A: it sees the ground from another angle'
+ : beforeA ? 'Date A must be before date B'
: single ? 'Use this pass' : 'Use as B, the picture to look in'}
onclick={() => onpick('b', entry)}
- >{single ? 'Use' : 'B'}</button>
+ >{single ? 'Use' : nameB}</button>
{/if}
</div>
</li>
@@ -194,25 +175,6 @@
/* Underlined: it sits in the warning's own orange. */
.link { color: var(--accent); font-size: inherit; text-decoration: underline; }
.link:disabled { color: var(--text-3); }
- .span {
- display: flex;
- align-items: center;
- gap: 6px;
- color: var(--text-3);
- font-size: var(--fs-xs);
- }
- .day {
- padding: 3px 7px;
- border: 1px solid var(--border);
- border-radius: var(--r-sm);
- color: var(--text-1);
- font-size: var(--fs-xs);
- }
- .day:hover:not(:disabled),
- .day.open {
- border-color: var(--accent);
- background: var(--accent-soft);
- }
.hint {
display: flex;
align-items: center;
diff --git a/frontend/src/tools/detect/AcquisitionPicker.test.js b/frontend/src/tools/detect/AcquisitionPicker.test.js
index c6c4197..46405a4 100644
--- a/frontend/src/tools/detect/AcquisitionPicker.test.js
+++ b/frontend/src/tools/detect/AcquisitionPicker.test.js
@@ -2,6 +2,7 @@
import { describe, expect, it, vi } from 'vitest';
import { flushSync, mount, unmount } from 'svelte';
import AcquisitionPicker from './AcquisitionPicker.svelte';
+import { daysBefore } from '../../lib/sentinel.js';
const passes = [
{ date: '2026-05-11', cloud: 3, granules: 2, coverage: 1 },
@@ -27,6 +28,30 @@ const button = (target, name) =>
[...target.querySelectorAll('button')].find((node) => node.textContent.trim() === name);
describe('the acquisition picker', () => {
+ it('has no Dates window unless it is handed a way to pick a day', () => {
+ const { target, done } = render();
+ expect(button(target, 'Dates')).toBeUndefined();
+ done();
+ });
+
+ it('shows what it is handed under a Dates window, in place of the list and the lookup', async () => {
+ const { createRawSnippet } = await import('svelte');
+ const dates = createRawSnippet(() => ({ render: () => '<div class="calendars">pick a day</div>' }));
+ const onlookback = vi.fn();
+ const { target, done } = render({ dates, onlookback });
+ expect(button(target, 'Dates')).toBeDefined();
+ expect(target.querySelector('.calendars')).toBe(null);
+ button(target, 'Dates').click();
+ expect(onlookback).toHaveBeenCalledWith('dates');
+ done();
+ const shown = render({ dates, lookback: 'dates' });
+ expect(shown.target.querySelector('.calendars').textContent).toBe('pick a day');
+ expect(button(shown.target, 'Dates').getAttribute('aria-pressed')).toBe('true');
+ expect(rows(shown.target)).toHaveLength(0);
+ expect(button(shown.target, 'Look again')).toBeUndefined();
+ shown.done();
+ });
+
it('lists what exists rather than every day on the calendar', () => {
const { target, done } = render();
expect(rows(target)).toHaveLength(2);
@@ -84,74 +109,41 @@ describe('the acquisition picker', () => {
done();
});
+ it('disables a listed pass that would put A after B', () => {
+ const { target, done } = render({ a: { date: '2026-05-11' }, b: { date: '2026-05-08' } });
+ const latest = target.querySelector('[aria-label="Use 2026-05-11"]');
+ const older = target.querySelector('[aria-label="Use 2026-05-08"]');
+ expect(latest.querySelector('button[title="Date A must be before date B"]').disabled).toBe(true);
+ expect(older.querySelector('button[title="Date A must be before date B"]').disabled).toBe(true);
+ done();
+ });
+
it('says when the catalogue stopped short instead of implying a full list', () => {
const { target, done } = render({ truncated: true });
expect(target.textContent).toContain('stopped short');
done();
});
- it('opens the calendar on the window the presets were showing', () => {
+ it('uses a short search window while dates A and B keep their own calendars', () => {
const onlookback = vi.fn();
const { target, done } = render({ onlookback });
- button(target, 'Dates…').click();
- const [span] = onlookback.mock.calls[0];
- expect(span.end).toBe(new Date().toISOString().slice(0, 10));
- expect(span.start < span.end).toBe(true);
- done();
- });
-
- it('bounds a lookup by two days picked in the calendar, however old', () => {
- const onlookback = vi.fn();
- const { target, done } = render({ lookback: { start: '2019-03-01', end: '2019-06-30' }, onlookback });
- expect(button(target, 'Dates…').classList.contains('on')).toBe(true);
- target.querySelector('[aria-label="First day"]').click(); flushSync();
- target.querySelector('.cal button[title="2019-03-12"]').click(); flushSync();
- expect(onlookback).toHaveBeenLastCalledWith({ start: '2019-03-12', end: '2019-06-30' });
- // the calendar closes on the day it was opened for
- expect(target.querySelector('.cal')).toBe(null);
- done();
- });
-
- it('keeps each picked day on its side of the other', () => {
- const { target, done } = render({ lookback: { start: '2019-06-10', end: '2019-06-20' } });
- const day = (iso) => target.querySelector(`.cal button[title="${iso}"]`);
- target.querySelector('[aria-label="First day"]').click(); flushSync();
- expect([day('2019-06-15').disabled, day('2019-06-25').disabled]).toEqual([false, true]);
- target.querySelector('[aria-label="Last day"]').click(); flushSync();
- expect([day('2019-06-05').disabled, day('2019-06-15').disabled]).toEqual([true, false]);
- done();
- });
-
- it('starts the calendar at the launch of the satellite the passes come from', () => {
- const lookback = { start: '2014-04-01', end: '2014-04-30' };
- const optical = render({ lookback });
- optical.target.querySelector('[aria-label="First day"]').click(); flushSync();
- expect(optical.target.querySelector('.cal button[title="2014-04-10"]').disabled).toBe(true);
- optical.done();
- const radar = render({ lookback, radar: true, list: [] });
- radar.target.querySelector('[aria-label="First day"]').click(); flushSync();
- const day = (iso) => radar.target.querySelector(`.cal button[title="${iso}"]`);
- expect([day('2014-04-02').disabled, day('2014-04-10').disabled]).toEqual([true, false]);
- radar.done();
- });
-
- it('will not look up two days in the wrong order', () => {
- const { target, done } = render({ lookback: { start: '2020-06-01', end: '2020-01-01' } });
- expect(target.textContent).toContain('The first day comes after the last.');
- expect(button(target, 'Look again').disabled).toBe(true);
+ expect(button(target, 'Dates…')).toBeUndefined();
+ button(target, '1 year').click();
+ expect(onlookback).toHaveBeenCalledWith(365);
done();
});
it('offers the older passes a cut list is missing', () => {
const onolder = vi.fn();
- const { target, done } = render({ truncated: true, lookback: { start: '2026-01-01', end: '2026-05-31' }, onolder });
+ const { target, done } = render({ truncated: true, lookback: 365, onolder });
button(target, 'Older passes').click();
expect(onolder).toHaveBeenCalledOnce();
done();
});
it('offers nothing older once the list reaches the first day asked', () => {
- const { target, done } = render({ truncated: true, lookback: { start: '2026-05-08', end: '2026-05-31' }, onolder: vi.fn() });
+ const { target, done } = render({ truncated: true, lookback: 30,
+ list: [{ date: daysBefore(30), cloud: 2, coverage: 1 }], onolder: vi.fn() });
expect(button(target, 'Older passes')).toBeUndefined();
done();
});
diff --git a/frontend/src/tools/detect/AnalysisOverlay.svelte b/frontend/src/tools/detect/AnalysisOverlay.svelte
index be11c5f..f9afa91 100644
--- a/frontend/src/tools/detect/AnalysisOverlay.svelte
+++ b/frontend/src/tools/detect/AnalysisOverlay.svelte
@@ -41,8 +41,8 @@
{#each shown as layer (layer.id)}
{#if layer.input.recipe.style !== 'pins'}
{#each layer.boxes as shape (shape.id)}
- <path d={shape.path} fill={layer.input.recipe.colour} fill-opacity="0.08" fill-rule="evenodd"
- stroke={layer.input.recipe.colour} stroke-width="1.5" stroke-dasharray={shape.manual ? '5 3' : undefined} />
+ <path d={shape.path} fill={layer.displayColour || layer.display_colour || layer.input.recipe.colour} fill-opacity="0.08" fill-rule="evenodd"
+ stroke={layer.displayColour || layer.display_colour || layer.input.recipe.colour} stroke-width="1.5" stroke-dasharray={shape.manual ? '5 3' : undefined} />
{/each}
{/if}
{#each layer.groups as group, i (i)}
@@ -57,7 +57,7 @@
fill="none" stroke="#fff" stroke-width="2" />
{/if}
<circle cx={group.x} cy={group.y} r={group.rows.length > 1 ? 13 : 6}
- fill={layer.input.recipe.colour} stroke="#fff" stroke-width="1.5"
+ fill={layer.displayColour || layer.display_colour || layer.input.recipe.colour} stroke="#fff" stroke-width="1.5"
stroke-dasharray={group.rows.some((row) => row.origin === 'manual') ? '3 2' : undefined} />
{#if group.rows.length > 1}<text x={group.x} y={group.y + 4}>{group.rows.length}</text>
{:else if kept}<circle cx={group.x} cy={group.y} r="2" fill="#fff" />{/if}
diff --git a/frontend/src/tools/detect/AnalyzerBuilder.svelte b/frontend/src/tools/detect/AnalyzerBuilder.svelte
index f45f7c4..af190e1 100644
--- a/frontend/src/tools/detect/AnalyzerBuilder.svelte
+++ b/frontend/src/tools/detect/AnalyzerBuilder.svelte
@@ -1,62 +1,46 @@
<script>
/**
- * An analyzer of your own, built rule by rule over the map.
+ * An analyzer of your own, built rule by rule and proved on 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.
+ * A rule is a line a pixel has to cross: a quantity, the date it is read on
+ * and the value. What it reads was chosen when the analyzer was made: a
+ * satellite, and one date or the change between two. The map is where the
+ * rules are tried. A check is a pair of passes and the pins laid on them;
+ * picking one puts its passes on the map, and Test paints what each rule
+ * keeps on the ground under its pins and says whether every pin came out as
+ * it should. The column holds the rules, the list of checks and the
+ * settings, and waits while a check is being made on the map.
*
- * 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.
+ * Checks are how an analyzer is proved, so one is needed to save it. 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, olderSpan, withOlder } from '../../lib/map/acquisitions.js';
- import { clone, viewZone } from '../../lib/map/analyzers.js';
+ import { toast } from '../../lib/state.svelte.js';
+ import { Bench } from '../../lib/map/bench.svelte.js';
+ import { clone } from '../../lib/map/analyzers.js';
import {
- RULE_COLOURS, checksSummary, describeRecipe, formatShare, markOutcomes, newCheck, newRule, readsOneDate,
- readsRadar, recipeCapability, recipeProblem, signalOf, signature, suggestedLayer, withMark, withoutMark,
+ RULE_COLOURS, checksSummary, describeOutcome, describeReads, describeRecipe, describeWithout, newRule, pinTicks,
+ readsOneDate, readsRadar, recipeCapability, savingProblem, signalOf,
} 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. */
+ /** Where to open: `{ tab, check }`, a tab and a check to put on the map. */
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. */
+ /** What the map draws while the builder is open: the bench (`lib/map/bench.svelte.js`). */
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 () => {},
@@ -64,423 +48,51 @@
} = $props();
const limits = $derived(catalogue?.rules ?? {});
+ const bench = untrack(() => new Bench({
+ api, recipe, limits: catalogue?.rules ?? {}, layers: () => layers, viewBounds: () => viewBounds(),
+ fly: (target) => onfly(target), say: toast,
+ }));
+ builder = bench;
+
const capability = $derived(recipeCapability(recipe, catalogue?.methods ?? []));
- const single = $derived(readsOneDate(recipe));
const radar = $derived(readsRadar(recipe));
- const problem = $derived(recipeProblem(recipe, limits));
+ const single = $derived(readsOneDate(recipe));
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();
+ const summary = $derived(checksSummary(recipe));
+ const saveProblem = $derived(recipe.name.trim() ? savingProblem(recipe, limits) : 'Name it to save it.');
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([]);
- /** What the map paints: each rule's pixels, or only what a run would return. */
- let view = $state('rules');
- let hover = $state(null);
- let probe = $state(null);
- let showing = $state('basemap');
- let layer = $state('TRUE_COLOR');
- let passes = $state({ list: [], lookback: 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 open check's own count, while its last read matches the rules and passes on the map:
- * the map then shows its frame only, so the view's count would not be what is seen. */
- const framed = $derived(bench?.result && bench.result.signature === current && bench.b.date === b.date
- && (single || (bench.a?.date ?? '') === a.date) ? bench.result : 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) {
- // With the detections alone on the map every eye reads closed, so one
- // pressed there opens its rule and brings the others back as they were.
- const opening = view === 'detections';
- view = 'rules';
- shown = recipe.rules.map((_, k) => (k === i ? opening || !isShown(k) : isShown(k)));
- }
- const painted = (i) => view === 'rules' && isShown(i);
-
- /** 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 -----------------------------------------------------------------
+ let error = $state('');
- $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 && painted(hover) ? hover : null,
- shown: recipe.rules.map((_, i) => painted(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();
+ if (start?.check) bench.select(start.check);
});
+ // The map is let go of by whoever opened the builder (AnalyzerLibrary), not here: a builder
+ // made in this one's place may already have taken it, and clearing it now would take it back.
+ onDestroy(() => bench.destroy());
+
+ const badge = $derived(!summary.total ? '!' : summary.pass + summary.fail ? `${summary.pass}/${summary.total}` : `${summary.total}`);
function add() {
if (recipe.rules.length >= most) return;
- recipe.rules = [...recipe.rules, newRule(radar ? 'radar' : 'index', 'b')];
+ recipe.rules = [...recipe.rules, newRule(radar ? 'radar' : 'index', single ? 'b' : 'a')];
}
function remove(i) {
- shown = recipe.rules.map((_, k) => isShown(k)).filter((_, k) => k !== i);
recipe.rules = recipe.rules.filter((_, k) => k !== i);
- hover = null;
+ bench.ruleRemoved(i);
}
/** 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);
- }
-
- const lookUp = () => search(passes.lookback, false);
- const lookOlder = () => search(olderSpan(passes.lookback, passes.list), true);
-
- async function search(span, more) {
- if (!region || !span) return;
- passes = { ...passes, busy: true, error: '', open: true };
- try {
- const found = await api.post('/api/satellite/sentinel/acquisitions',
- acquisitionQuery([viewZone(region, 'Preview')], span, new Date(), radar ? 'sentinel1' : 'sentinel2'));
- const list = more ? withOlder(passes.list, found.dates) : found.dates ?? [];
- passes = { ...passes, list, searched: true, truncated: !!found.truncated };
- } catch (e) {
- passes = { ...passes, error: e.message };
- } finally {
- passes = { ...passes, busy: false };
- }
+ bench.rulesReordered(order);
}
async function save() {
- if (saving || saveProblem || !recipe.name.trim()) return;
+ if (saving || saveProblem) return;
saving = true;
error = '';
try {
@@ -492,168 +104,126 @@
}
}
- const checksBadge = $derived(!summary.total ? '' : summary.pass + summary.fail ? `${summary.pass}/${summary.total}` : `${summary.total}`);
+ /** What the check on the map last said, for the strip above the rules. */
+ const verdict = $derived.by(() => {
+ const check = bench.check;
+ if (!check) return 'Pick a check on the map to try the rules on it.';
+ if (bench.last?.error) return bench.last.error;
+ if (bench.stale) return 'The rules changed since the last test.';
+ return describeOutcome(check, bench.current);
+ });
</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>
+ {#if bench.locked}
+ <div class="waiting" role="status">
+ <span><strong>Making a check on the map</strong><br />Pick its passes, drop its pins, then finish it there.</span>
+ <button class="btn btn-sm" onclick={() => bench.cancelDraft()}>Cancel the check</button>
+ </div>
+ {/if}
+ <div class="panel" class:locked={bench.locked} inert={bench.locked}>
+ {#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="reads" title="Chosen when the analyzer was made">
+ <Icon name="lock" size={11} /> <span>{describeReads(recipe)}</span>
+ </p>
+ <p class="phrase">{phrase || 'Add a rule.'}</p>
+
+ <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 <span class="count" class:need={!summary.total} class:fail={summary.fail}
+ class:pass={summary.total > 0 && !summary.fail && summary.pass === summary.total}>{badge}</span>
+ </button>
+ <button role="tab" aria-selected={tab === 'settings'} class:on={tab === 'settings'} onclick={() => (tab = 'settings')}>Settings</button>
+ </div>
- <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}
+ {#if tab === 'rules'}
+ <div class="strip" class:stale={bench.stale} class:hidden={bench.locked} aria-label="The check on the map">
+ <div class="said">
+ <strong>{bench.check?.name ?? 'No check on the map'}</strong>
+ <span aria-live="polite">{verdict}</span>
</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}
+ <button class="btn btn-sm" class:btn-primary={!bench.tested} class:done={bench.tested} disabled={!bench.canTest}
+ title={bench.blocked || undefined} onclick={() => bench.test()}>{bench.testLabel}</button>
</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} lookback={passes.lookback} busy={passes.busy} error={passes.error}
- searched={passes.searched} truncated={passes.truncated} areas={region ? 1 : 0} {single} {radar}
- wantsReference={!single} wantsCompare={true} {a} {b}
- onlookback={(lookback) => (passes = { ...passes, lookback })} onlook={lookUp} onolder={lookOlder}
- 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>
+ <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 the rules</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 rule</button>
+ </div>
+ </div>
+ {#each recipe.rules as _, i (i)}
+ <RuleRow bind:rule={recipe.rules[i]} {recipe} index={i} colour={RULE_COLOURS[i % RULE_COLOURS.length]}
+ signal={i === signal} reading={bench.detail?.rules?.[i] ?? null} stale={bench.stale}
+ ticks={pinTicks(recipe.rules[i], bench.marks, bench.detail?.readings, i)}
+ effect={bench.stale ? '' : describeWithout(bench.marks, bench.detail?.covered, bench.detail?.without?.[i]?.covered)}
+ match={recipe.match} shown={bench.painted(i)} ontoggle={() => bench.toggleRule(i)}
+ bands={limits.bands} classes={limits.classes} maxAround={limits.max_around}
+ canRemove={recipe.rules.length > 1} onremove={() => remove(i)} onsignal={() => rank(i)}
+ onhover={(index) => bench.hoverRule(index)} />
{/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>
+ <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 {bench} />
+ {: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 cannot tell you.">Description
+ <textarea bind:value={recipe.description} maxlength="500" placeholder={phrase}></textarea>
+ </label>
+ </section>
+ <AnalyzerLabel bind:recipe />
{/if}
-
- <div class="status" aria-live="polite">
- {#if needs}
- <p class="hint">{needs}</p>
- {:else}
- {#if preview}
- <div class="row">
- {#if framed}
- <p class="result grow"><strong>{framed.count} candidate{framed.count === 1 ? '' : 's'}</strong>
- in “{bench.name}”{#if working} · updating…{/if}</p>
- {:else}
- <p class="result grow"><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}
- <div class="cmp-seg" role="group" aria-label="What the map shows">
- <button type="button" class:on={view === 'rules'} aria-pressed={view === 'rules'}
- title="Each rule's pixels in its colour" onclick={() => (view = 'rules')}>Rules</button>
- <button type="button" class:on={view === 'detections'} aria-pressed={view === 'detections'}
- title="Only what a detection would return" onclick={() => (view = 'detections')}>Detections</button>
- </div>
- </div>
- {#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, and the frames already read stay live as you move.</p>
- {/if}
- {#if preview}
- {#if preview.clipped}<p class="hint">The preview covers only the middle {limits.preview_span ?? 3} tiles a side of this view.</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={painted(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 cannot tell you.">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="cmp-dock-foot" inert={bench.locked}>
<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}>
+ <button class="btn btn-primary grow" disabled={saving || !!saveProblem} 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>
+ <span class="reason" class:warn={!!saveProblem}>{saveProblem || 'Shared by every case, and carried by Settings backup.'}</span>
</div>
<style>
- .builder { grid-template-columns: minmax(0, 1fr); }
+ .builder { grid-template-columns: minmax(0, 1fr); align-content: start; gap: 10px; }
+ .panel { display: grid; grid-template-columns: minmax(0, 1fr); gap: 10px; transition: opacity 0.15s var(--ease); }
+ .panel.locked { opacity: 0.4; pointer-events: none; user-select: none; }
+ /* Kept in sight however far the column is scrolled. */
+ .waiting {
+ position: sticky;
+ top: -12px;
+ z-index: 6;
+ display: grid;
+ gap: 8px;
+ padding: 9px 10px;
+ border: 1px solid var(--accent);
+ border-radius: var(--r-sm);
+ background: color-mix(in srgb, var(--accent) 14%, var(--bg-1));
+ color: var(--text-1);
+ font-size: var(--fs-xs);
+ line-height: 1.45;
+ }
+ .waiting .btn { justify-self: start; }
h3 { margin: 0; font-size: var(--fs-sm); font-weight: 700; }
- section { display: grid; grid-template-columns: minmax(0, 1fr); gap: 7px; }
+ section { display: grid; grid-template-columns: minmax(0, 1fr); gap: 8px; }
section > strong {
color: var(--text-2);
font-size: var(--fs-xs);
@@ -662,23 +232,49 @@
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); }
+ .reads {
+ display: inline-flex;
+ align-items: center;
+ gap: 5px;
+ justify-self: start;
+ margin: 0;
+ padding: 2px 8px;
+ border: 1px solid var(--border);
+ border-radius: 999px;
+ color: var(--text-2);
+ font-size: 10.5px;
+ font-weight: 600;
+ }
.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); }
+ .count.pass { background: var(--ok-soft); color: var(--ok); }
+ .count.fail { background: var(--danger-soft); color: var(--danger); }
+ .count.need { background: color-mix(in srgb, var(--warn) 20%, transparent); color: var(--warn); }
+ /* The check on the map and what it last said, with the Test button, kept in
+ sight while the rules scroll under it. */
+ .strip {
+ position: sticky;
+ top: -12px;
+ z-index: 5;
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ margin: 0 -12px;
+ padding: 8px 12px;
+ border-bottom: 1px solid var(--border);
+ background: var(--bg-1);
+ }
+ .said { display: grid; flex: 1; gap: 1px; min-width: 0; }
+ .said strong { overflow: hidden; color: var(--text-1); font-size: var(--fs-xs); text-overflow: ellipsis; white-space: nowrap; }
+ .said span { color: var(--text-2); font-size: 10.5px; line-height: 1.4; }
+ .strip.stale .said span { color: var(--warn); }
+ .strip.hidden { visibility: hidden; }
+ .strip .btn { flex: 0 0 auto; }
+ .strip .btn.done { border-color: var(--border); background: transparent; color: var(--ok); opacity: 1; }
+ .strip .btn.done::before { margin-right: 5px; content: '✓'; }
.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
index 03c6509..b97ea4a 100644
--- a/frontend/src/tools/detect/AnalyzerChecks.svelte
+++ b/frontend/src/tools/detect/AnalyzerChecks.svelte
@@ -1,131 +1,106 @@
<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.
+ * The checks of the analyzer being built, as a list. A check is made and
+ * tried on the map, where its passes are the imagery and its pins are
+ * dropped by a click; this is where they are kept in view: how each one came
+ * out the last time, what trying them all would cost, and the pins of the
+ * one on the bench, to turn or take away.
+ *
+ * Checks are how an analyzer is proved, so one is needed to save it: a place
+ * with a pin where something should be found. The others may be traps, where
+ * nothing may be.
*/
- import { checkState, describeOutcome, markOutcomes } from '../../lib/map/analyzerRules.js';
+ import { checkState, describeOutcome } 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();
+ let { bench } = $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']];
+ const ICONS = { pass: '✓', fail: '✗', stale: '–', unrun: '–', unpinned: '!' };
+ const single = $derived(bench.single);
+ const passes = (check) => (!check.b?.date ? 'no passes yet'
+ : single ? check.b.date : `Before ${check.a?.date || '…'} → After ${check.b.date}`);
+ const requests = (count) => `${count} request${count === 1 ? '' : 's'}`;
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`;
+ const test = bench.tests[check.id];
+ if (test?.busy) return 'Testing…';
+ if (test?.error) return test.error;
+ const state = checkState(check, bench.current);
+ const plan = bench.plans[check.id];
+ if ((state === 'unrun' || state === 'stale') && plan?.missing) {
+ return `${describeOutcome(check, bench.current)} · ${requests(plan.missing)} to read`;
}
- return describeOutcome(check, current);
+ return describeOutcome(check, bench.current);
}
</script>
<section class="checks" aria-label="Checks">
+ <p class="hint">A check is two passes and the pins that say where something should be found and where nothing may be.</p>
<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 class="btn btn-sm" disabled={bench.atMostChecks} onclick={() => bench.startDraft()}>
+ <Icon name="plus" size={12} /> New 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')}
+ {#if bench.checks.length}
+ <button class="btn btn-sm" disabled={!!bench.running || !!bench.problem} onclick={() => bench.testAll()}>
+ {bench.running || (bench.allMissing ? `Test all · up to ${requests(bench.allMissing)}` : 'Test all')}
</button>
{/if}
</div>
- {#if !checks.length}
- <p class="hint">Checks are optional places you trust, pinned on two passes where a candidate should come out or
- none should, and rerun to show which rule broke what.</p>
+ {#if !bench.checks.length}
+ <p class="hint need">Saving needs a check with a pin where something should be found.</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)}>
+ {#each bench.checks as check (check.id)}
+ {@const state = checkState(check, bench.current)}
+ {@const open = bench.selected === check.id}
+ <div class="check" class:on={open}>
+ <div class="head">
+ <span class="state {state}" class:busy={bench.tests[check.id]?.busy} aria-hidden="true">{ICONS[state]}</span>
+ <button class="open" aria-label={`Put the check ${check.name} on the map`} aria-pressed={open}
+ onclick={() => bench.select(open ? null : check.id)}>
<strong>{check.name}</strong>
- <small>{passes(check)} · {status(check)}</small>
+ <small>{passes(check)}</small>
+ <small class="outcome {state}">{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>
+ onclick={() => bench.remove(check.id)}><Icon name="trash" size={12} /></button>
</div>
- {#if active === check.id}
+ {#if open}
<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())} />
+ onchange={(event) => bench.rename(check.id, event.currentTarget.value)} />
</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>
+ <span class="grow">{passes(check)}</span>
+ <button class="link" onclick={() => bench.changePasses()}>Change</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>
+ {#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 bench.outcomes.length}
+ <span class="verdict" class:ok={bench.outcomes[i]} title={bench.outcomes[i] ? 'Came out as it should' : 'Did not'}>
+ {bench.outcomes[i] ? '✓' : '✗'}</span>
+ {/if}
+ <button class="link" aria-label={`Turn pin ${i + 1} into ${mark.expect === 'found' ? 'a pin that should stay empty' : 'a pin that should be found'}`}
+ onclick={() => bench.flipPin(i)}>Turn</button>
+ <button class="cmp-icon" aria-label={`Remove pin ${i + 1}`} title="Remove this pin"
+ onclick={() => bench.removePin(i)}><Icon name="x" size={11} /></button>
+ </li>
+ {/each}
+ </ul>
+ {:else}
+ <span class="hint need">No pin yet: pick one on the map and click the ground.</span>
+ {/if}
</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>
@@ -133,44 +108,35 @@
</section>
<style>
- .checks { display: grid; grid-template-columns: minmax(0, 1fr); gap: 7px; }
+ .checks { display: grid; grid-template-columns: minmax(0, 1fr); gap: 8px; }
.actions { flex-wrap: wrap; gap: 6px; }
+ .need { color: var(--warn); }
.check {
display: grid;
- gap: 6px;
- padding: 6px 8px;
+ gap: 7px;
+ padding: 7px 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; }
+ .head { display: flex; align-items: flex-start; gap: 7px; }
+ .open { display: grid; flex: 1; 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); }
+ .outcome.pass { color: var(--ok); }
+ .outcome.fail { color: var(--danger); }
+ .state { flex: 0 0 auto; width: 16px; margin-top: 1px; color: var(--text-3); font-weight: 700; text-align: center; }
+ .state.pass { color: var(--ok); }
+ .state.fail { color: var(--danger); }
+ .state.unpinned { color: var(--warn); }
.state.busy { color: var(--accent); }
- .editor { display: grid; gap: 8px; }
+ .editor { display: grid; gap: 9px; padding-top: 2px; }
.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); }
+ .marks .cmp-icon { width: 22px; height: 22px; }
/* 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%; }
@@ -186,8 +152,7 @@
transform: translateY(-50%) rotate(-45deg);
content: '';
}
- .verdict { color: var(--danger, #ef4444); font-weight: 700; }
- .verdict.ok { color: var(--ok, #46a758); }
+ .verdict { color: var(--danger); font-weight: 700; }
+ .verdict.ok { color: var(--ok); }
.link { color: var(--accent); font-size: var(--fs-xs); }
- .done { justify-self: start; }
</style>
diff --git a/frontend/src/tools/detect/AnalyzerChecks.svelte.test.js b/frontend/src/tools/detect/AnalyzerChecks.svelte.test.js
new file mode 100644
index 0000000..3fa0ce6
--- /dev/null
+++ b/frontend/src/tools/detect/AnalyzerChecks.svelte.test.js
@@ -0,0 +1,109 @@
+// @vitest-environment happy-dom
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { flushSync, mount, unmount } from 'svelte';
+import { Bench } from '../../lib/map/bench.svelte.js';
+import { newCheck, newRecipe, signature } from '../../lib/map/analyzerRules.js';
+import AnalyzerChecks from './AnalyzerChecks.svelte';
+
+const METHODS = [{ id: 'rules', sizes: { all: {} } }];
+const pass = (date) => ({ provider: 'sentinel2', date, layer: 'TRUE_COLOR', maxcc: 100 });
+const made = (name, marks = [{ point: [2.01, 48.01], expect: 'found' }, { point: [2.05, 48.05], expect: 'empty' }], extra = {}) =>
+ ({ ...newCheck({ name, a: pass('2026-05-04'), b: pass('2026-05-11'), marks }), ...extra });
+
+let live, bench, target;
+beforeEach(() => vi.useFakeTimers());
+afterEach(() => {
+ if (live) unmount(live);
+ bench?.destroy();
+ live = bench = null;
+ target?.remove();
+ vi.useRealTimers();
+});
+
+function open({ dates = 'two', checks = [] } = {}) {
+ const recipe = $state({ ...newRecipe(METHODS, { dates }), name: 'Mine', checks });
+ const api = { post: vi.fn(async (url, body) => (url.endsWith('/plan') ? { tiles: 1, missing: 2 }
+ : { ready: true, missing: 0, count: 1, covered: body.check.marks.map((mark) => mark.expect === 'found'), size: 512, tiles: [],
+ rules: [], candidates: [], readings: [] })) };
+ bench = new Bench({ api, recipe, limits: { max_checks: 2, max_marks: 20 }, viewBounds: () => null });
+ target = document.createElement('div');
+ document.body.append(target);
+ live = mount(AnalyzerChecks, { target, props: { bench } });
+ flushSync();
+ return recipe;
+}
+const settle = async () => { await vi.advanceTimersByTimeAsync(300); flushSync(); };
+const query = (selector) => target.querySelector(selector);
+const named = (text) => [...target.querySelectorAll('button')].find((button) => button.textContent.trim().startsWith(text));
+const click = (node) => { node.click(); flushSync(); };
+
+it('says what a check is, and that one is needed, while there are none', () => {
+ open();
+ expect(query('.hint').textContent).toBe('A check is two passes and the pins that say where something should be found and where nothing may be.');
+ expect(query('.need').textContent).toBe('Saving needs a check with a pin where something should be found.');
+ expect(named('Test all')).toBeUndefined();
+});
+
+it('lists each check with its passes and how it last came out, and puts the one pressed on the map', async () => {
+ const recipe = open({ checks: [made('The plot'), made('The reef', [], {})] });
+ await settle();
+ const rows = [...target.querySelectorAll('.check')].map((row) => row.querySelector('.open').textContent.replace(/\s+/g, ' ').trim());
+ expect(rows[0]).toBe('The plot Before 2026-05-04 → After 2026-05-11 Not tested yet · 2 requests to read');
+ expect(rows[1]).toContain('Needs a pin');
+ expect(query('.check:last-child .state').textContent).toBe('!');
+ click(query('button[aria-label="Put the check The plot on the map"]'));
+ expect(bench.selected).toBe(recipe.checks[0].id);
+ expect(query('.check.on')).not.toBe(null);
+ click(query('button[aria-label="Put the check The plot on the map"]'));
+ expect(bench.selected).toBe(null);
+});
+
+it('reads one date as a date, and a check with no pass as none', () => {
+ open({ dates: 'one', checks: [made('Ships', [{ point: [2, 48], expect: 'found' }], { a: {} }), made('Nothing', [{ point: [2, 48], expect: 'found' }], { a: {}, b: { date: '' } })] });
+ const lines = [...target.querySelectorAll('.check')].map((row) => row.querySelectorAll('small')[0].textContent);
+ expect(lines).toEqual(['2026-05-11', 'no passes yet']);
+});
+
+it('opens the check on the map for renaming, changing its passes, and turning or removing its pins', async () => {
+ const recipe = open({ checks: [made('The plot')] });
+ bench.select(recipe.checks[0].id); flushSync();
+ const name = query('input[aria-label="Check name"]');
+ name.value = 'The burned plot'; name.dispatchEvent(new Event('change', { bubbles: true })); flushSync();
+ expect(recipe.checks[0].name).toBe('The burned plot');
+ click(named('Change'));
+ expect(bench.editingPasses).toBe(true);
+ const pins = [...target.querySelectorAll('.marks li')].map((li) => li.textContent.replace(/\s+/g, ' ').trim());
+ expect(pins).toEqual(['Should be found Turn', 'Should stay empty Turn']);
+ click(query('button[aria-label="Turn pin 2 into a pin that should be found"]'));
+ expect(recipe.checks[0].marks.map((mark) => mark.expect)).toEqual(['found', 'found']);
+ click(query('button[aria-label="Remove pin 1"]'));
+ expect(recipe.checks[0].marks).toHaveLength(1);
+});
+
+it('shows a verdict on each pin once the check has been tested with the rules as they stand', async () => {
+ const recipe = open({ checks: [made('The plot')] });
+ bench.select(recipe.checks[0].id); flushSync();
+ await settle();
+ expect(query('.verdict')).toBe(null);
+ await bench.test(); flushSync();
+ expect([...target.querySelectorAll('.verdict')].map((node) => node.textContent)).toEqual(['✓', '✓']);
+ expect(query('.check .state').textContent).toBe('✓');
+ expect(query('.outcome').textContent).toBe('1 of 1 found · stayed empty');
+ expect(recipe.checks[0].result.signature).toBe(signature(recipe));
+});
+
+it('tests them all, says what that would cost, and stops at the limit of checks', async () => {
+ const recipe = open({ checks: [made('One'), made('Two')] });
+ await settle();
+ expect(named('Test all').textContent.trim()).toBe('Test all · up to 4 requests');
+ expect(named('New check').disabled).toBe(true); // two checks is the limit here
+ click(named('Test all')); await settle();
+ expect(recipe.checks.map((check) => check.result?.count)).toEqual([1, 1]);
+ expect(named('Test all').textContent.trim()).toBe('Test all');
+});
+
+it('removes a check', () => {
+ const recipe = open({ checks: [made('The plot')] });
+ click(query('button[aria-label="Remove the check The plot"]'));
+ expect(recipe.checks).toHaveLength(0);
+});
diff --git a/frontend/src/tools/detect/AnalyzerLibrary.svelte b/frontend/src/tools/detect/AnalyzerLibrary.svelte
index 2d02a23..0ec6970 100644
--- a/frontend/src/tools/detect/AnalyzerLibrary.svelte
+++ b/frontend/src/tools/detect/AnalyzerLibrary.svelte
@@ -8,11 +8,16 @@
* 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.
+ *
+ * A new one of your own starts by saying what it reads: Sentinel-2 or radar,
+ * and one date or the change between two. That is fixed from then on, so the
+ * rules it is given and the checks that prove it always fit it.
*/
+ import { onDestroy, untrack } from 'svelte';
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 { describeChecks, describeReads, newRecipe } from '../../lib/map/analyzerRules.js';
import AnalyzerBuilder from './AnalyzerBuilder.svelte';
import AnalyzerLabel from './AnalyzerLabel.svelte';
import AnalyzerSettings from './AnalyzerSettings.svelte';
@@ -22,33 +27,42 @@
catalogue,
onchanged = async () => {},
onsaved = () => {},
- /** What the map draws while an analyzer of your own is being built. */
+ /** What the map draws while an analyzer of your own is being built (the bench). */
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,
+ /** The Copernicus layers on offer and a way to frame a place: what the
+ * builder needs of the map. */
layers = [],
onfly = () => {},
- onshow = () => {},
- onleavepass = () => {},
- onblink = () => {},
} = $props();
- /** 'list', 'base' (what a new one starts from), 'edit' (a copy of a
+ /** 'list', 'base' (what a new one reads, and 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);
+ /** Counts the analyzers opened in the builder, so each one gets a bench of its own. */
+ let session = $state(0);
+ /** What a new analyzer of your own will read, asked before anything else. */
+ let reads = $state({ sensor: 'sentinel2', dates: 'two' });
/** Where the builder opens: `{ tab, check }`. */
let start = $state(null);
let readonly = $state(false);
let busy = $state(false);
let error = $state('');
+ // The map holds the builder's bench only while a builder is open, and this is what lets it go: on
+ // leaving the builder, and on leaving the library. An analyzer opened while another is, takes it over.
+ $effect(() => {
+ if (mode !== 'build') untrack(() => { builder = null; });
+ });
+ onDestroy(() => { builder = null; });
+
const builtins = $derived(catalogue?.builtins ?? []);
const custom = $derived(catalogue?.custom ?? []);
const examples = $derived(catalogue?.examples ?? []);
+ /** The examples that read what was asked for. */
+ const matching = $derived(examples.filter((example) => example.recipe.sensor === reads.sensor && example.recipe.dates === reads.dates));
+ const radarLock = $derived(catalogue?.radar_layer ? '' : analyzerLock({ method: 'rules', sensor: 'sentinel1' }, catalogue));
const methodOf = (method) => catalogue?.methods?.find((m) => m.id === method) ?? {};
const capability = $derived(methodOf(recipe?.method));
const isNew = $derived(recipe?.id === 'custom');
@@ -64,13 +78,15 @@
recipe = entry.method === 'rules' ? { checks: [], ...clone(entry) } : clone(entry);
readonly = builtins.some((r) => r.id === entry.id);
start = opening;
+ session++;
mode = entry.method === 'rules' ? 'build' : 'edit';
}
- function build(from = newRecipe(catalogue?.methods ?? [])) {
+ function build(from = newRecipe(catalogue?.methods ?? [], reads)) {
recipe = { checks: [], ...clone(from), id: 'custom' };
readonly = false;
start = null;
+ session++;
mode = 'build';
}
@@ -100,15 +116,6 @@
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` };
@@ -139,7 +146,7 @@
{#if mode === 'list'}
<div class="cmp-dock-body">
{#if error}<p class="warn" role="alert">{error}</p>{/if}
- <p class="hint">Start from an example, build your own from rules you try on the map, or copy a calibrated built-in to tune it.</p>
+ <p class="hint">Start from an example, build your own from rules you prove 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">
@@ -183,45 +190,59 @@
{:else if mode === 'base'}
<div class="cmp-dock-body">
{#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 whose checks turn red when a rule you change breaks one.</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}
+ <h3>New analyzer</h3>
+ <p class="hint">What it reads is fixed from here on, so its rules and checks always fit it.</p>
+
+ <section aria-label="What it reads">
+ <span class="ask">Satellite</span>
+ <div class="cmp-seg fill" role="group" aria-label="Satellite">
+ <button type="button" class:on={reads.sensor === 'sentinel2'} aria-pressed={reads.sensor === 'sentinel2'}
+ onclick={() => (reads = { ...reads, sensor: 'sentinel2' })}>Sentinel-2 · optical</button>
+ <button type="button" class:on={reads.sensor === 'sentinel1'} aria-pressed={reads.sensor === 'sentinel1'}
+ onclick={() => (reads = { ...reads, sensor: 'sentinel1' })}>Sentinel-1 · radar</button>
</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">A built-in brings its calibrated method for you to tune, and one marked rules opens as the rules it applies.</p>
- <div class="bases">
- {#each [...builtins, ...custom] as entry (entry.id)}
- {@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>
+ {#if reads.sensor === 'sentinel1'}
+ <p class="hint">Radar sees through cloud and at night.{#if radarLock} <span class="lock"><Icon name="key" size={10} /> {radarLock}</span>{/if}</p>
+ {:else}
+ <p class="hint">Colour and infrared, where the sky is clear.</p>
+ {/if}
+ <span class="ask">Dates</span>
+ <div class="cmp-seg fill" role="group" aria-label="Dates">
+ <button type="button" class:on={reads.dates === 'one'} aria-pressed={reads.dates === 'one'}
+ onclick={() => (reads = { ...reads, dates: 'one' })}>One date</button>
+ <button type="button" class:on={reads.dates === 'two'} aria-pressed={reads.dates === 'two'}
+ onclick={() => (reads = { ...reads, dates: 'two' })}>Two dates</button>
+ </div>
+ <p class="hint">{reads.dates === 'one' ? 'Spots what is there on a day, like a ship or a fire.'
+ : 'Finds what changed between a day before and a day after.'}</p>
+ </section>
+
+ <section aria-label="Start from">
+ <span class="ask">Start from</span>
+ <button class="pick base own" onclick={() => build()}>
+ <span class="swatch" aria-hidden="true"></span>
+ <span class="name">Blank<small>One rule to begin with.</small></span>
+ </button>
+ {#each matching 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 !matching.length}
+ <p class="hint">No ready example for {describeReads(reads)} yet.</p>
+ {:else}
+ <p class="hint">An example comes with checks that turn red when a rule you change breaks one.</p>
+ {/if}
+ </section>
</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} />
+ {#key session}
+ <AnalyzerBuilder {catalogue} bind:recipe isNew={isNew} {start} bind:builder {viewBounds} {layers} {onfly}
+ onsave={(next) => save(next)} oncancel={back} />
+ {/key}
{:else if recipe}
<div class="cmp-dock-body">
{#if error}<p class="warn" role="alert">{error}</p>{/if}
@@ -281,8 +302,7 @@
.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, .examples { display: grid; gap: 6px; }
- .examples { margin-bottom: 4px; }
+ .ask { color: var(--text-2); font-size: var(--fs-xs); font-weight: 700; }
.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; }
diff --git a/frontend/src/tools/detect/AnalyzerSettings.svelte b/frontend/src/tools/detect/AnalyzerSettings.svelte
index b366b28..43308d0 100644
--- a/frontend/src/tools/detect/AnalyzerSettings.svelte
+++ b/frontend/src/tools/detect/AnalyzerSettings.svelte
@@ -22,6 +22,7 @@
readonly = false,
/** The wizard asks for the size first, above the analyzers, and not here. */
showSize = true,
+ showCloud = true,
} = $props();
let showThresholds = $state(false);
@@ -40,7 +41,7 @@
<fieldset class="settings" disabled={readonly}>
{#if showSize}<AnalyzerSize bind:recipe {capability} {readonly} />{/if}
- {#if capability.clouds}
+ {#if showCloud && capability.clouds}
<CloudFilter clouds={recipe.parameters.ignore_clouds} shadows={recipe.parameters.ignore_shadows}
ontoggle={setWeather} />
{/if}
diff --git a/frontend/src/tools/detect/AreaDates.svelte b/frontend/src/tools/detect/AreaDates.svelte
index f0b3a72..4261952 100644
--- a/frontend/src/tools/detect/AreaDates.svelte
+++ b/frontend/src/tools/detect/AreaDates.svelte
@@ -3,12 +3,16 @@
import {
acquisitionQuery, cloudWarning, coverageWarning, olderSpan, passKey, withOlder,
} from '../../lib/map/acquisitions.js';
- import { newestLabel, newestLine, newestPick } from '../../lib/map/detectWhen.js';
+ import { canPickPass, newestLabel, newestLine, newestPick, passBefore } from '../../lib/map/detectWhen.js';
+ import { isoDay } from '../../lib/sentinel.js';
+ import Icon from '../../components/Icon.svelte';
import AcquisitionPicker from './AcquisitionPicker.svelte';
+ import PassCalendar from './PassCalendar.svelte';
import DateField from '../../components/DateField.svelte';
let {
zones, pairs = $bindable([]), single = false, baselineOnly = false,
+ routine = false, previous = false, lastPasses = {},
/** Which collection the passes come from: radar passes carry a time. */
sensor = 'sentinel2',
onshow = () => {},
@@ -22,13 +26,29 @@
let searched = $state(false);
let truncated = $state(false);
let generation = 0;
+ let calendarArea = $state('');
+ let calendarSide = $state('');
+ let calendarPasses = $state([]);
+ let calendarBusy = $state(false);
+ let calendarError = $state('');
+ let calendarGeneration = 0;
+ const calendarCache = new Map();
const pairFor = (id) => pairs.find((p) => p.area_id === id);
+ const zoneFor = (id) => zones.find((zone) => zone.id === id);
+ const currentA = (id) => previous && lastPasses[id] ? lastPasses[id] : pairFor(id)?.a;
+ const eligibleFor = (id, letter) => (pass) =>
+ canPickPass(letter, pass, currentA(id), pairFor(id)?.b, radar);
+ function show(id, letter, source, known = passes) {
+ if (!source?.date) return;
+ const cloud = radar ? null : known.find((pass) => pass.date === source.date)?.cloud ?? null;
+ onshow({ ...source, cloud, area: zoneFor(id), side: letter });
+ }
/** The passes over one area, or with `more` those before the oldest listed. */
async function lookup(zone, more = false) {
const span = more ? olderSpan(lookback, passes) : lookback;
if (!span) return;
- looking = zone.id; busy = true; error = '';
+ looking = zone.id; busy = true; error = ''; calendarSide = '';
if (!more) { searched = false; passes = []; }
const mine = ++generation;
try {
@@ -37,18 +57,48 @@
if (mine !== generation) return;
passes = more ? withOlder(passes, found.dates) : found.dates ?? [];
searched = true; truncated = !!found.truncated;
+ const pair = pairFor(zone.id);
+ if (pair && (routine || !pair.b.date)) {
+ const picked = newestPick(passes, { maxcc: radar ? 100 : pair.b.maxcc,
+ radar, track: radar && !single ? currentA(zone.id)?.time ?? '' : '' });
+ if (picked.pass) show(zone.id, 'B', { ...pair.b, date: picked.pass.date, time: picked.pass.time ?? '' }, passes);
+ }
} catch (e) { if (mine === generation) error = e.message; }
finally { if (mine === generation) busy = false; }
}
+ async function lookupMonth(zone, month) {
+ const key = `${zone.id}:${month}`;
+ const cached = calendarCache.get(key);
+ const mine = ++calendarGeneration;
+ if (cached) { calendarPasses = cached; calendarBusy = false; calendarError = ''; return; }
+ calendarPasses = []; calendarBusy = true; calendarError = '';
+ const last = new Date(Date.UTC(Number(month.slice(0, 4)), Number(month.slice(5, 7)), 0))
+ .toISOString().slice(0, 10);
+ const today = isoDay(new Date());
+ const end = last < today ? last : today;
+ try {
+ const found = await api.post('/api/satellite/sentinel/acquisitions',
+ acquisitionQuery([zone], { start: `${month}-01`, end }, new Date(), sensor));
+ calendarCache.set(key, found.dates ?? []);
+ if (mine === calendarGeneration) calendarPasses = found.dates ?? [];
+ } catch (e) { if (mine === calendarGeneration) calendarError = e.message; }
+ finally { if (mine === calendarGeneration) calendarBusy = false; }
+ }
+ function openCalendar(id, side) {
+ if (calendarArea !== id) calendarPasses = [];
+ calendarArea = id;
+ calendarSide = side;
+ }
/** A typed day has no time yet: the engine settles which pass of it at launch. */
- function pick(id, letter, date, time = '') {
+ function pick(id, letter, date, time = '', closeCalendar = true) {
pairs = pairs.map((pair) => pair.area_id !== id ? pair : {
...pair, [letter]: { ...pair[letter], date, time: radar ? time : '' },
date_rule: letter === 'b' && pair.date_rule !== 'latest_previous' ? (date ? 'manual' : 'latest_reference') : pair.date_rule,
});
+ if (closeCalendar) calendarSide = '';
if (!date) return;
- const cloud = radar || looking !== id ? null : passes.find((pass) => pass.date === date)?.cloud ?? null;
- onshow({ ...pairFor(id)[letter], date, cloud, ...(radar ? { provider: 'sentinel1', time } : {}) });
+ show(id, letter, { ...pairFor(id)[letter], date, ...(radar ? { provider: 'sentinel1', time } : {}) },
+ looking === id ? [...calendarPasses, ...passes] : calendarPasses);
}
const at = (source) => (radar && source?.time ? `${source.time.slice(0, 5)} UTC` : '');
/** "Newest" as this area's ceiling makes it, capitalised for a cell. */
@@ -56,63 +106,128 @@
const label = newestLabel({ maxcc: pair?.b?.maxcc, radar });
return label.charAt(0).toUpperCase() + label.slice(1);
};
- const track = (pair) => (radar && !single ? pair?.a?.time ?? '' : '');
+ const track = (pair) => (radar && !single ? currentA(pair.area_id)?.time ?? '' : '');
+ const pickedB = (pair) => looking === pair.area_id && searched && !pair.b.date
+ ? newestPick(passes, { maxcc: radar ? 100 : pair.b.maxcc, radar, track: track(pair) }) : null;
+ const cloudSkip = (picked, maxcc) => {
+ const pass = picked?.skipped?.find((entry) => entry.why === 'cloud');
+ return pass ? `${pass.date} was skipped (${Math.round(pass.cloud)}% cloud; limit ${maxcc}%).` : '';
+ };
</script>
<div class="dates-table">
- <table aria-label="Dates per area">
- <thead><tr><th>Area</th>{#if !single}<th>A · before</th>{/if}{#if !baselineOnly}<th>{single ? 'Image' : 'B · after'}</th>{/if}<th></th></tr></thead>
- <tbody>
- {#each zones as zone (zone.id)}
- {@const pair = pairFor(zone.id)}
- {#if pair}
- <tr>
- <th>{zone.name}</th>
- {#if !single}
- <td><DateField day reading={false} label={`Reference for ${zone.name}`} value={pair.a.date}
- onchange={(value) => pick(zone.id, 'a', value ?? '')} />
- {#if at(pair.a)}<small class="mono">{at(pair.a)}</small>{/if}
- {#if pair.date_rule === 'latest_previous'}<small>Then the pass before</small>{/if}</td>
+ {#each zones as zone (zone.id)}
+ {@const pair = pairFor(zone.id)}
+ {#if pair}
+ <section class="area-date" aria-label={`Dates for ${zone.name}`}>
+ <div class="area-head"><strong>{zone.name}</strong>
+ {#if looking !== zone.id}
+ <button class="btn btn-sm" disabled={busy} onclick={() => lookup(zone)}
+ aria-label={`Find passes for ${zone.name}`}>Find passes</button>
+ {/if}
+ </div>
+ {#if !single}
+ <div class="side">
+ <strong>Date A · {previous && lastPasses[zone.id] ? 'Last completed pass' : routine && previous ? 'First run only' : 'Before'}</strong>
+ {#if previous && lastPasses[zone.id]}
+ <button class="link" onclick={() => show(zone.id, 'A', currentA(zone.id))}>
+ {currentA(zone.id).date}{#if at(currentA(zone.id))} · {at(currentA(zone.id))}{/if} · View A</button>
+ {:else}
+ <button class="date-pick" aria-label={`Date A for ${zone.name}`}
+ aria-expanded={calendarArea === zone.id && calendarSide === 'a'}
+ onclick={() => openCalendar(zone.id, 'a')}>
+ <Icon name="calendar" size={13} /><span>{pair.a.date || 'Choose a pass'}</span>
+ <Icon name="chevronDown" size={12} />
+ </button>
+ {#if pair.a.date}<button class="link" onclick={() => show(zone.id, 'A', pair.a)}>View A</button>{/if}
+ {#if calendarArea === zone.id && calendarSide === 'a'}
+ <PassCalendar list={calendarPasses} value={pair.a.date} label={`Reference for ${zone.name}`}
+ {radar} busy={calendarBusy} error={calendarError} eligible={eligibleFor(zone.id, 'a')}
+ onmonth={(month) => lookupMonth(zone, month)}
+ onclose={() => (calendarSide = '')}
+ onpick={(pass) => pick(zone.id, 'a', pass.date, pass.time ?? '')} />
+ <details class="manual-date"><summary>Enter a date</summary>
+ <DateField day reading={false} label={`Reference for ${zone.name}`} value={pair.a.date}
+ onchange={(value) => pick(zone.id, 'a', value ?? '', '', false)} />
+ </details>
+ {/if}
{/if}
- {#if !baselineOnly}
- <td><DateField day reading={false} label={`Pass for ${zone.name}`} value={pair.b.date}
- onchange={(value) => pick(zone.id, 'b', value ?? '')} />
- {#if at(pair.b)}<small class="mono">{at(pair.b)}</small>{/if}
- {#if !pair.b.date}<small>{newestFor(pair)}</small>{:else}<button class="link" onclick={() => pick(zone.id, 'b', '')}>{newestFor(pair)}</button>{/if}</td>
+ </div>
+ {/if}
+ <div class="side">
+ <strong>{single ? 'Image date' : 'Date B · after'}</strong>
+ {#if routine && baselineOnly}<small>{newestFor(pair)} at each run</small>
+ {:else}
+ <button class="date-pick" aria-label={`${single ? 'Image date' : 'Date B'} for ${zone.name}`}
+ aria-expanded={calendarArea === zone.id && calendarSide === 'b'}
+ onclick={() => openCalendar(zone.id, 'b')}>
+ <Icon name="calendar" size={13} /><span>{pair.b.date || newestFor(pair)}</span>
+ <Icon name="chevronDown" size={12} />
+ </button>
+ {#if pair.b.date}<button class="link" onclick={() => show(zone.id, 'B', pair.b)}>View B</button>
+ <button class="link" onclick={() => pick(zone.id, 'b', '')}>Use newest</button>{/if}
+ {#if calendarArea === zone.id && calendarSide === 'b'}
+ <PassCalendar list={calendarPasses} value={pair.b.date} label={`Pass for ${zone.name}`}
+ {radar} busy={calendarBusy} error={calendarError} eligible={eligibleFor(zone.id, 'b')}
+ onmonth={(month) => lookupMonth(zone, month)}
+ onclose={() => (calendarSide = '')}
+ onpick={(pass) => pick(zone.id, 'b', pass.date, pass.time ?? '')} />
+ <details class="manual-date"><summary>Enter a date</summary>
+ <DateField day reading={false} label={`Pass for ${zone.name}`} value={pair.b.date}
+ onchange={(value) => pick(zone.id, 'b', value ?? '', '', false)} />
+ </details>
{/if}
- <td><button class="btn btn-sm" disabled={busy} onclick={() => lookup(zone)} aria-label={`Find passes for ${zone.name}`}>Find passes</button></td>
- </tr>
+ {/if}
+ {#if pickedB(pair)?.pass}
+ <button class="link" onclick={() => show(zone.id, 'B', { ...pair.b, date: pickedB(pair).pass.date,
+ time: pickedB(pair).pass.time ?? '' })}>View B · {pickedB(pair).pass.date}</button>
+ {/if}
+ </div>
+ {#if !single && pair.b.date && !passBefore(currentA(zone.id), pair.b, radar)}
+ <p class="warn" role="alert">Date A must be before date B.</p>
{/if}
- {/each}
- </tbody>
- </table>
-</div>
-{#if looking}
- {@const pair = pairFor(looking)}
- <p class="hint">{zones.find((zone) => zone.id === looking)?.name}</p>
- <AcquisitionPicker list={passes} {lookback} {busy} {error} {searched} {truncated} areas={1} {radar}
- {single} wantsReference={!single} wantsCompare={!baselineOnly} a={pair?.a ?? null} b={pair?.b ?? null}
- onlookback={(value) => (lookback = value)} onlook={() => lookup(zones.find((zone) => zone.id === looking))}
- onolder={() => lookup(zones.find((zone) => zone.id === looking), true)}
- onpick={(letter, entry) => pick(looking, letter, entry.date, entry.time ?? '')} />
- {#if searched && !baselineOnly && !pair?.b?.date}
- {@const maxcc = radar ? 100 : pair?.b?.maxcc}
- <p class="hint">{newestLine(newestPick(passes, { maxcc, radar, track: track(pair) }), { maxcc, radar })}</p>
- {/if}
- {#each [single ? null : pair?.a, pair?.b].filter((source) => source?.date) as source}
- {@const entry = passes.find((pass) => passKey(pass) === passKey(source) || (!source.time && pass.date === source.date))}
- {#each [coverageWarning(entry), radar ? '' : cloudWarning(entry, source.maxcc)].filter(Boolean) as warning (warning)}
- <p class="warn">{warning}</p>
- {/each}
+ {#if looking === zone.id}
+ <p class="hint">Passes over {zone.name}</p>
+ <AcquisitionPicker list={passes} {lookback} {busy} {error} {searched} {truncated} areas={1} {radar}
+ {single} wantsReference={!single && !(previous && lastPasses[zone.id])} wantsCompare={!baselineOnly}
+ a={currentA(zone.id) ?? null} b={pair.b ?? null}
+ onlookback={(value) => (lookback = value)} onlook={() => lookup(zone)}
+ onolder={() => lookup(zone, true)}
+ onpick={(letter, entry) => pick(zone.id, letter, entry.date, entry.time ?? '')} />
+ {#if searched && !pair.b?.date}
+ {@const maxcc = radar ? 100 : pair.b?.maxcc}
+ {@const picked = newestPick(passes, { maxcc, radar, track: track(pair) })}
+ {#if cloudSkip(picked, maxcc)}<p class="warn">{cloudSkip(picked, maxcc)}</p>{/if}
+ <p class="hint">{newestLine(picked, { maxcc, radar })}</p>
+ {/if}
+ {#each [single ? null : pair.a, pair.b].filter((source) => source?.date) as source}
+ {@const entry = passes.find((pass) => passKey(pass) === passKey(source) || (!source.time && pass.date === source.date))}
+ {#each [coverageWarning(entry), radar ? '' : cloudWarning(entry, source.maxcc)].filter(Boolean) as warning (warning)}
+ <p class="warn">{warning}</p>
+ {/each}
+ {/each}
+ {/if}
+ </section>
+ {/if}
{/each}
-{/if}
+</div>
<style>
- .dates-table { overflow: auto; }
- table { width: 100%; border-collapse: collapse; font-size: var(--fs-xs); }
- th, td { padding: 7px 5px; border-bottom: 1px solid var(--border); text-align: left; vertical-align: top; }
- td :global(.date-field) { width: 145px; }
+ .dates-table { display: grid; gap: 7px; }
+ .area-date { display: grid; gap: 7px; padding: 8px; border: 1px solid var(--border); border-radius: var(--r-sm); }
+ .area-head { display: flex; align-items: center; gap: 8px; }
+ .area-head strong { flex: 1; font-size: var(--fs-xs); }
+ .side { display: grid; justify-items: start; gap: 3px; font-size: var(--fs-xs); }
+ .side strong { color: var(--text-2); }
+ .date-pick { display: flex; align-items: center; gap: 7px; width: min(100%, 246px);
+ padding: 6px 8px; border: 1px solid var(--border); border-radius: var(--r-sm);
+ background: var(--bg-2); color: var(--text-1); font-size: var(--fs-xs); text-align: left; }
+ .date-pick:hover, .date-pick[aria-expanded="true"] { border-color: var(--accent); }
+ .date-pick span { flex: 1; }
+ .manual-date { color: var(--text-3); font-size: 10px; }
+ .manual-date summary { cursor: pointer; }
+ .side :global(.date-field) { width: 145px; }
+ .warn { margin: 0; color: var(--warn); font-size: 10.5px; }
small { display: block; color: var(--text-3); max-width: 150px; }
- .mono { font-family: var(--font-mono); }
.link { color: var(--accent); font-size: var(--fs-xs); }
</style>
diff --git a/frontend/src/tools/detect/AreasPanel.svelte b/frontend/src/tools/detect/AreasPanel.svelte
index 7136aaa..4f8bfbc 100644
--- a/frontend/src/tools/detect/AreasPanel.svelte
+++ b/frontend/src/tools/detect/AreasPanel.svelte
@@ -18,10 +18,11 @@
import { zoneRing } from '../../lib/map/analyzers.js';
import { formatArea, polygonArea } from '../../lib/measure.js';
import { plural } from '../../lib/map/detections.js';
+ import { closeOnOutsidePointer } from '../../lib/dismiss.js';
import Icon from '../../components/Icon.svelte';
import Modal from '../../components/Modal.svelte';
- let { caseId, areas = [], routines = [], selectedArea = null, hidden = $bindable([]),
+ let { caseId, areas = [], groups = [], routines = [], selectedArea = null, hidden = $bindable([]),
zones = $bindable([]), drawing = $bindable('select'),
/** The shape the map shows its corners for. */
selectedZone = $bindable(null),
@@ -31,6 +32,18 @@
let busy = $state(false);
let removing = $state(null);
let editing = $state(null);
+ let search = $state('');
+ /** Groups opened by hand; every group starts folded, the first one too. */
+ let unfolded = $state({});
+ const open = (group) => !!search || !!unfolded[group.id];
+ /** The one ⋯ menu open: a press anywhere else, or a choice in it, shuts it. */
+ let openMenu = $state.raw(null);
+ let creatingGroup = $state(false);
+ let newGroupName = $state('');
+ let removingGroup = $state(null);
+ let editingGroup = $state(null);
+ let dragging = $state(null);
+ let landing = $state(null);
/** The area whose corners are on the map, and whether it was drawn before. */
let reshaping = $state(null);
@@ -41,8 +54,19 @@
prefs.units
);
const ringOf = (area) => [{ kind: 'polygon', points: area.geometry.coordinates[0] }];
+ const groupedIds = $derived(new Set(groups.flatMap((group) => group.area_ids ?? [])));
+ const ungrouped = $derived(areas.filter((area) => !groupedIds.has(area.id)));
+ const members = (group) => (group.area_ids ?? []).map((id) => areas.find((area) => area.id === id)).filter(Boolean);
+ const matches = (name) => name.toLowerCase().includes(search.trim().toLowerCase());
+ const visibleUngrouped = $derived(ungrouped.filter((area) => !search || matches(area.name)));
+ function groupBody(group, patch = {}) {
+ const body = { title: group.title, area_ids: group.area_ids ?? [], position: group.position,
+ pending_review: group.pending_review ?? [], ...patch };
+ return { ...body, pending_review: body.pending_review.filter((review) => body.area_ids.includes(review.saved_area_id)) };
+ }
async function act(fn) {
+ if (busy) return;
busy = true; error = '';
try { await fn(); await onrefresh(); await reloadCase(); }
catch (e) { error = e.message; }
@@ -57,9 +81,182 @@
}
async function update(area, patch) {
await api.put(`/api/cases/${caseId}/analysis/areas/${area.id}`, {
- name: area.name, colour: area.colour, geometry: area.geometry, ...patch,
+ name: area.name, colour: area.colour, geometry: area.geometry, position: area.position, ...patch,
+ });
+ }
+
+ async function updateGroup(group, patch) {
+ await api.put(`/api/cases/${caseId}/analysis/zones/${group.id}`, groupBody(group, patch));
+ }
+
+ function resolveReview(group, review, current) {
+ const area_ids = current
+ ? [...new Set(group.area_ids.map((id) => id === review.saved_area_id ? review.current_area_id : id))]
+ : group.area_ids;
+ const pending_review = (group.pending_review ?? []).filter((item) => item.saved_area_id !== review.saved_area_id);
+ void act(() => updateGroup(group, { area_ids, pending_review }));
+ }
+
+ async function createGroup() {
+ if (!newGroupName.trim()) return;
+ const owner = await ensureCase();
+ await api.post(`/api/cases/${owner.id}/analysis/zones`, {
+ title: newGroupName.trim(), area_ids: [],
+ });
+ newGroupName = '';
+ search = '';
+ creatingGroup = false;
+ await onrefresh(owner.id);
+ }
+
+ async function reorderGroups(fromId, toId) {
+ if (fromId === toId) return;
+ const ordered = [...groups];
+ const from = ordered.findIndex((group) => group.id === fromId);
+ const to = ordered.findIndex((group) => group.id === toId);
+ if (from < 0 || to < 0) return;
+ ordered.splice(to, 0, ordered.splice(from, 1)[0]);
+ await act(async () => {
+ for (const [position, group] of ordered.entries()) {
+ if (group.position !== position) await updateGroup(group, { position });
+ }
+ });
+ }
+
+ async function changeMembership(areaId, fromId, toId, beforeId = null, add = false) {
+ const next = new Map(groups.map((group) => [group.id, [...(group.area_ids ?? [])]]));
+ if (toId === null) {
+ for (const ids of next.values()) {
+ const at = ids.indexOf(areaId);
+ if (at >= 0) ids.splice(at, 1);
+ }
+ } else {
+ if (!add && fromId && fromId !== toId) {
+ const source = next.get(fromId);
+ const at = source?.indexOf(areaId) ?? -1;
+ if (at >= 0) source.splice(at, 1);
+ }
+ const target = next.get(toId);
+ if (!target) return;
+ const old = target.indexOf(areaId);
+ if (old >= 0) target.splice(old, 1);
+ const at = beforeId ? target.indexOf(beforeId) : -1;
+ target.splice(at < 0 ? target.length : at, 0, areaId);
+ }
+ await act(async () => {
+ for (const group of groups) {
+ const ids = next.get(group.id);
+ if (ids.join('\0') !== (group.area_ids ?? []).join('\0')) await updateGroup(group, { area_ids: ids });
+ }
+ if (toId === null) {
+ const ordered = [...ungrouped];
+ const area = areas.find((entry) => entry.id === areaId);
+ if (area && !ordered.some((entry) => entry.id === areaId)) {
+ const at = beforeId ? ordered.findIndex((entry) => entry.id === beforeId) : -1;
+ ordered.splice(at < 0 ? ordered.length : at, 0, area);
+ for (const [position, entry] of ordered.entries()) {
+ if (entry.position !== position) await update(entry, { position });
+ }
+ }
+ }
+ });
+ }
+
+ function removeFromGroup(areaId, group) {
+ const ids = (group.area_ids ?? []).filter((id) => id !== areaId);
+ void act(() => updateGroup(group, { area_ids: ids }));
+ }
+
+ async function reorderUngrouped(fromId, toId, after = false) {
+ if (fromId === toId) return;
+ const moved = ungrouped.find((area) => area.id === fromId);
+ const ordered = ungrouped.filter((area) => area.id !== fromId);
+ const to = ordered.findIndex((area) => area.id === toId);
+ if (!moved || to < 0) return;
+ ordered.splice(to + Number(after), 0, moved);
+ await act(async () => {
+ for (const [position, area] of ordered.entries()) {
+ if (area.position !== position) await update(area, { position });
+ }
});
}
+
+ function shiftArea(areaId, groupId, step) {
+ const siblings = groupId ? members(groups.find((group) => group.id === groupId)) : ungrouped;
+ const index = siblings.findIndex((area) => area.id === areaId);
+ if (index + step < 0 || index + step >= siblings.length) return;
+ if (groupId) {
+ const before = step < 0 ? siblings[index - 1].id : siblings[index + 2]?.id ?? null;
+ void changeMembership(areaId, groupId, groupId, before);
+ } else {
+ void reorderUngrouped(areaId, siblings[index + step].id, step > 0);
+ }
+ }
+
+ function startDrag(event, item) {
+ if (busy) { event.preventDefault(); return; }
+ dragging = item;
+ landing = null;
+ event.dataTransfer?.setData('text/plain', item.id);
+ if (event.dataTransfer) event.dataTransfer.effectAllowed = 'move';
+ }
+
+ function dragOverArea(event, areaId, groupId) {
+ if (dragging?.kind !== 'area') return;
+ event.preventDefault();
+ if (event.dataTransfer) event.dataTransfer.dropEffect = 'move';
+ const bounds = event.currentTarget.getBoundingClientRect();
+ landing = dragging.id === areaId ? null : {
+ kind: 'area', id: areaId, groupId, after: event.clientY > bounds.top + bounds.height / 2,
+ };
+ }
+
+ function dragOverGroup(event, groupId) {
+ if (!dragging || (groupId === null && dragging.kind !== 'area')) return;
+ event.preventDefault();
+ if (event.dataTransfer) event.dataTransfer.dropEffect = 'move';
+ if (dragging.kind === 'area') {
+ landing = dragging.from === groupId && groupId === null ? null : { kind: 'group', id: groupId, area: true };
+ } else {
+ const from = groups.findIndex((group) => group.id === dragging.id);
+ const to = groups.findIndex((group) => group.id === groupId);
+ landing = from < 0 || to < 0 || from === to ? null : {
+ kind: 'group', id: groupId, area: false, after: from < to,
+ };
+ }
+ }
+
+ function leaveDrop(event) {
+ if (!event.currentTarget.contains(event.relatedTarget)) landing = null;
+ }
+
+ function endDrag() {
+ dragging = null;
+ landing = null;
+ }
+
+ function dropOnGroup(event, groupId) {
+ event.preventDefault();
+ const item = dragging;
+ endDrag();
+ if (item?.kind === 'group') void reorderGroups(item.id, groupId);
+ if (item?.kind === 'area') void changeMembership(item.id, item.from, groupId);
+ }
+
+ function dropOnArea(event, areaId, groupId) {
+ event.preventDefault();
+ event.stopPropagation();
+ const item = dragging;
+ endDrag();
+ if (item?.kind !== 'area' || item.id === areaId) return;
+ const target = event.currentTarget.getBoundingClientRect();
+ const after = event.clientY > target.top + target.height / 2;
+ const siblings = groupId ? members(groups.find((group) => group.id === groupId)) : ungrouped;
+ const index = siblings.findIndex((area) => area.id === areaId);
+ const beforeId = after ? siblings[index + 1]?.id ?? null : areaId;
+ if (groupId === null && item.from === null) void reorderUngrouped(item.id, areaId, after);
+ else void changeMembership(item.id, item.from, groupId, beforeId);
+ }
/** The area put on the map as a shape to drag, in place of its own outline. */
function reshape(area) {
reshaping = { area, wasHidden: hidden.includes(area.id) };
@@ -97,9 +294,34 @@
$effect(() => () => untrack(endReshape));
const toggle = (id) => (hidden = hidden.includes(id) ? hidden.filter((value) => value !== id) : [...hidden, id]);
+ /** A group's eye: one of its areas on the map shows as on, and hides them all. */
+ function toggleGroup(group) {
+ const ids = members(group).map((area) => area.id);
+ const anyShown = ids.some((id) => !hidden.includes(id));
+ hidden = anyShown ? [...new Set([...hidden, ...ids])] : hidden.filter((id) => !ids.includes(id));
+ }
+
+ function closeMenu() {
+ if (openMenu) openMenu.open = false;
+ openMenu = null;
+ }
+ function menuToggled(event) {
+ const menu = event.currentTarget;
+ if (menu.open) {
+ if (openMenu && openMenu !== menu) openMenu.open = false;
+ openMenu = menu;
+ } else if (openMenu === menu) {
+ openMenu = null;
+ }
+ }
+ $effect(() => (openMenu ? closeOnOutsidePointer(openMenu, closeMenu) : undefined));
+ const chose = (event) => { if (event.target.closest('button')) closeMenu(); };
+ const menuKey = (event) => { if (event.key === 'Escape' && openMenu) closeMenu(); };
</script>
-<div class="area-actions">
+<svelte:window onkeydown={menuKey} />
+
+<div class="area-actions primary-tools">
<button class="btn btn-sm" class:active={drawing === 'polygon'}
onclick={() => (drawing = drawing === 'polygon' ? 'select' : 'polygon')}>Draw an area</button>
<button class="btn btn-sm" onclick={onusecurrentview}>Use current view</button>
@@ -107,6 +329,17 @@
<button class="btn btn-sm" onclick={() => onframe(areas.flatMap(ringOf))}>Show all</button>
{/if}
</div>
+<div class="area-actions list-tools">
+ <input aria-label="Search areas or groups" placeholder="Search areas or groups…" bind:value={search} />
+ <button class="btn btn-sm" onclick={() => (creatingGroup = !creatingGroup)}>New group</button>
+</div>
+{#if creatingGroup}
+ <div class="area-actions">
+ <input aria-label="New group name" bind:value={newGroupName} maxlength="120" />
+ <button class="btn btn-sm btn-primary" disabled={busy || !newGroupName.trim()}
+ onclick={() => act(createGroup)}>Create</button>
+ </div>
+{/if}
{#if error}<p class="warn" role="alert">{error}</p>{/if}
{#if drawing === 'polygon'}<p class="hint">Click corners; Enter finishes, Escape cancels.</p>{/if}
@@ -140,9 +373,18 @@
</div>
{/if}
-{#each areas as area (area.id)}
+{#snippet areaRow(area, groupId)}
{@const off = hidden.includes(area.id)}
- <div class="area-row" class:selected={selectedArea === area.id} class:off>
+ <div class="area-row" role="group" aria-label={area.name} class:selected={selectedArea === area.id} class:off
+ class:dragging={dragging?.kind === 'area' && dragging.id === area.id && dragging.from === groupId}
+ class:landing-before={landing?.kind === 'area' && landing.id === area.id && landing.groupId === groupId && !landing.after}
+ class:landing-after={landing?.kind === 'area' && landing.id === area.id && landing.groupId === groupId && landing.after}
+ ondragover={(event) => dragOverArea(event, area.id, groupId)}
+ ondragleave={leaveDrop}
+ ondrop={(event) => dropOnArea(event, area.id, groupId)}>
+ <button class="drag-handle" draggable="true" aria-label={`Drag ${area.name}`}
+ ondragstart={(event) => startDrag(event, { kind: 'area', id: area.id, from: groupId })}
+ ondragend={endDrag}>⠿</button>
<button class="cmp-icon" aria-label={off ? `Show ${area.name}` : `Hide ${area.name}`} aria-pressed={!off}
title={off ? 'Show on the map' : 'Hide on the map'} onclick={() => toggle(area.id)}>
<Icon name={off ? 'eyeOff' : 'eye'} size={14} />
@@ -154,8 +396,34 @@
</button>
<button class="cmp-icon" aria-label={`Edit ${area.name}`} title="Rename, recolour or reshape"
onclick={() => (editing = editing === area.id ? null : area.id)}><Icon name="edit" size={13} /></button>
- <button class="cmp-icon" title="Delete area" aria-label={`Delete ${area.name}`} disabled={busy}
- onclick={() => (removing = area)}><Icon name="trash" size={13} /></button>
+ <details class="item-menu" ontoggle={menuToggled}>
+ <summary aria-label={`More actions for ${area.name}`} title="More actions">⋯</summary>
+ <div class="menu-content" role="presentation" onclick={chose} onchange={closeMenu}>
+ <button disabled={busy} onclick={() => shiftArea(area.id, groupId, -1)}>Move up</button>
+ <button disabled={busy} onclick={() => shiftArea(area.id, groupId, 1)}>Move down</button>
+ {#if groups.some((group) => !group.area_ids?.includes(area.id))}
+ <select aria-label={`Add ${area.name} to group`} disabled={busy}
+ onchange={(event) => { if (event.currentTarget.value) void changeMembership(area.id, groupId, event.currentTarget.value, null, true); event.currentTarget.value = ''; }}>
+ <option value="">Add to group…</option>
+ {#each groups.filter((group) => !group.area_ids?.includes(area.id)) as group (group.id)}
+ <option value={group.id}>{group.title}</option>
+ {/each}
+ </select>
+ {/if}
+ <select aria-label={`Move ${area.name} to group`} disabled={busy}
+ onchange={(event) => { const value = event.currentTarget.value; if (value) void changeMembership(area.id, groupId, value === 'ungrouped' ? null : value); event.currentTarget.value = ''; }}>
+ <option value="">Move to…</option>
+ <option value="ungrouped">Ungrouped</option>
+ {#each groups.filter((group) => group.id !== groupId) as group (group.id)}
+ <option value={group.id}>{group.title}</option>
+ {/each}
+ </select>
+ {#if groupId}
+ <button disabled={busy} onclick={() => removeFromGroup(area.id, groups.find((group) => group.id === groupId))}>Remove from this group</button>
+ {/if}
+ <button disabled={busy} onclick={() => (removing = area)}>Delete area</button>
+ </div>
+ </details>
</div>
{#if editing === area.id}
<div class="edit">
@@ -166,8 +434,94 @@
<button class="btn btn-sm" disabled={busy || !!reshaping} onclick={() => reshape(area)}>Reshape on the map</button>
</div>
{/if}
+{/snippet}
+
+{#each groups as group, index (group.id)}
+ {@const matched = members(group).filter((area) => !search || matches(group.title) || matches(area.name))}
+ {#if !search || matches(group.title) || matched.length}
+ <section class="area-group" aria-label={group.title}>
+ <div class="group-head" role="group" aria-label={`Drop into ${group.title}`}
+ class:dragging={dragging?.kind === 'group' && dragging.id === group.id}
+ class:landing-area={landing?.kind === 'group' && landing.id === group.id && landing.area}
+ class:landing-before={landing?.kind === 'group' && landing.id === group.id && !landing.area && !landing.after}
+ class:landing-after={landing?.kind === 'group' && landing.id === group.id && !landing.area && landing.after}
+ ondragover={(event) => dragOverGroup(event, group.id)}
+ ondragleave={leaveDrop}
+ ondrop={(event) => dropOnGroup(event, group.id)}>
+ <button class="drag-handle" draggable="true" aria-label={`Drag group ${group.title}`}
+ ondragstart={(event) => startDrag(event, { kind: 'group', id: group.id })}
+ ondragend={endDrag}>⠿</button>
+ <button class="fold" aria-expanded={open(group)}
+ onclick={() => (unfolded = { ...unfolded, [group.id]: !unfolded[group.id] })}>
+ <Icon name={open(group) ? 'chevronDown' : 'chevronRight'} size={12} />
+ <span class="group-icon"><Icon name={open(group) ? 'folderOpen' : 'folder'} size={15} /></span>
+ <strong class="group-title">{group.title}</strong>
+ <!-- The colours its areas are drawn in, so a folded group still reads as its ground. -->
+ <span class="group-tints" aria-hidden="true">
+ {#each members(group).slice(0, 5) as area (area.id)}<span class="swatch" style={`--tint: ${area.colour}`}></span>{/each}
+ </span>
+ <small class="group-count">{members(group).length}</small>
+ </button>
+ {#if members(group).length}
+ {@const off = members(group).every((area) => hidden.includes(area.id))}
+ <button class="cmp-icon" aria-label={off ? `Show group ${group.title}` : `Hide group ${group.title}`}
+ aria-pressed={!off} title={off ? 'Show its areas on the map' : 'Hide its areas on the map'}
+ onclick={() => toggleGroup(group)}>
+ <Icon name={off ? 'eyeOff' : 'eye'} size={14} />
+ </button>
+ {/if}
+ <details class="item-menu" ontoggle={menuToggled}>
+ <summary aria-label={`More actions for group ${group.title}`} title="More actions">⋯</summary>
+ <div class="menu-content" role="presentation" onclick={chose}>
+ <button disabled={busy || index === 0} onclick={() => reorderGroups(group.id, groups[index - 1].id)}>Move up</button>
+ <button disabled={busy || index === groups.length - 1} onclick={() => reorderGroups(group.id, groups[index + 1].id)}>Move down</button>
+ <button onclick={() => (editingGroup = editingGroup === group.id ? null : group.id)}>Rename group</button>
+ <button disabled={busy} onclick={() => (removingGroup = group)}>Delete group</button>
+ </div>
+ </details>
+ </div>
+ {#if editingGroup === group.id}
+ <div class="edit"><input aria-label={`Rename group ${group.title}`} value={group.title} maxlength="120"
+ onchange={(event) => { const title = event.currentTarget.value.trim(); if (title) void act(() => updateGroup(group, { title })); }} /></div>
+ {/if}
+ {#if group.pending_review?.length}
+ <div class="group-review">
+ <p>Choose which shape this group should use.</p>
+ {#each group.pending_review as review (review.saved_area_id)}
+ {@const savedArea = areas.find((area) => area.id === review.saved_area_id)}
+ {@const currentArea = areas.find((area) => area.id === review.current_area_id)}
+ <div><strong>{review.name}</strong>
+ {#if savedArea}<button class="link" onclick={() => onframe(ringOf(savedArea))}>Show saved</button>{/if}
+ {#if currentArea}<button class="link" onclick={() => onframe(ringOf(currentArea))}>Show current</button>{/if}
+ <button class="btn btn-sm" disabled={busy} onclick={() => resolveReview(group, review, false)}>Keep saved</button>
+ <button class="btn btn-sm" disabled={busy || !currentArea}
+ onclick={() => resolveReview(group, review, true)}>Use current</button>
+ </div>
+ {/each}
+ </div>
+ {/if}
+ {#if open(group) && matched.length}
+ <div class="group-members">
+ {#each matched as area (area.id)}{@render areaRow(area, group.id)}{/each}
+ </div>
+ {:else if open(group) && !members(group).length}
+ <p class="hint group-empty">Empty. Drag an area here.</p>
+ {/if}
+ </section>
+ {/if}
{/each}
+{#if visibleUngrouped.length || (!search && (areas.length || groups.length))}
+ <section class="area-group ungrouped" aria-label="Ungrouped">
+ <div class="ungrouped-head" role="group" aria-label="Drop into Ungrouped"
+ class:landing-area={landing?.kind === 'group' && landing.id === null && landing.area}
+ ondragover={(event) => dragOverGroup(event, null)}
+ ondragleave={leaveDrop}
+ ondrop={(event) => dropOnGroup(event, null)}><strong>Ungrouped</strong><small>{plural(visibleUngrouped.length, 'area')}</small></div>
+ {#each visibleUngrouped as area (area.id)}{@render areaRow(area, null)}{/each}
+ </section>
+{/if}
+
{#if removing}
<Modal title={`Delete ${removing.name}?`} onclose={() => (removing = null)}>
{#if users.length}
@@ -183,9 +537,65 @@
</Modal>
{/if}
+{#if removingGroup}
+ <Modal title={`Delete ${removingGroup.title}?`} onclose={() => (removingGroup = null)}>
+ <p>The areas stay in this case.</p>
+ <button class="btn btn-danger" disabled={busy} onclick={() => act(async () => {
+ await api.del(`/api/cases/${caseId}/analysis/zones/${removingGroup.id}`); removingGroup = null;
+ })}>Move group to Trash</button>
+ </Modal>
+{/if}
+
<style>
.area-actions, .draft, .edit { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; }
+ .primary-tools { padding-bottom: 10px; border-bottom: 1px solid var(--border); }
+ .list-tools { flex-wrap: nowrap; padding: 4px 0 10px; }
+ .list-tools input { min-width: 0; }
.draft, .edit { padding: 7px 0; }
+ .area-group { display: grid; gap: 0; margin-top: 8px; }
+ /* A group is a band and its areas hang off a rail under it, so a folder
+ never reads as one more area in the list. */
+ .group-members { margin: 2px 0 4px 12px; padding-left: 6px; border-left: 2px solid var(--border-strong); }
+ .group-members > .area-row:last-child { border-bottom: 0; }
+ .group-empty { margin: 4px 0 2px 20px; }
+ .group-head, .ungrouped-head { position: relative; display: flex; align-items: center; gap: 5px;
+ min-height: 36px; padding: 3px 5px; border-radius: var(--r-sm);
+ transition: background 120ms ease, box-shadow 120ms ease, opacity 120ms ease; }
+ .group-head { background: var(--bg-2); }
+ .group-head:hover { background: var(--bg-3); }
+ .group-head.dragging, .area-row.dragging { opacity: 0.42; }
+ .group-head.landing-area, .ungrouped-head.landing-area {
+ background: var(--accent-soft); box-shadow: inset 0 0 0 2px var(--accent); }
+ .group-head.landing-before, .area-row.landing-before { box-shadow: inset 0 3px 0 var(--accent); }
+ .group-head.landing-after, .area-row.landing-after { box-shadow: inset 0 -3px 0 var(--accent); }
+ .ungrouped-head { margin-top: 6px; border-bottom: 1px solid var(--border); color: var(--text-2); }
+ .ungrouped-head > strong { flex: 1; font-size: var(--fs-xs); font-weight: 600; letter-spacing: 0.04em; text-transform: uppercase; }
+ .ungrouped-head small { color: var(--text-3); font-size: 10px; }
+ .fold { display: flex; flex: 1; align-items: center; gap: 6px; min-width: 0; text-align: left; font-size: var(--fs-xs); }
+ .group-icon { display: grid; place-items: center; flex: 0 0 auto; color: var(--accent); }
+ .group-title { flex: 0 1 auto; min-width: 0; overflow: hidden; font-size: var(--fs-sm); font-weight: 650;
+ text-overflow: ellipsis; white-space: nowrap; }
+ .group-tints { display: flex; flex: 1; gap: 2px; min-width: 0; }
+ .group-tints .swatch { width: 7px; height: 7px; }
+ .group-count { flex: 0 0 auto; min-width: 18px; padding: 0 5px; border-radius: 9px; background: var(--bg-1);
+ color: var(--text-2); font-size: 10.5px; line-height: 16px; text-align: center; font-variant-numeric: tabular-nums; }
+ .drag-handle { flex: 0 0 auto; width: 16px; padding: 0; cursor: grab; color: var(--text-3); font-size: 14px; }
+ .drag-handle:active { cursor: grabbing; }
+ .item-menu { position: relative; flex: 0 0 auto; }
+ .item-menu summary { display: grid; place-items: center; width: 20px; height: 22px; cursor: pointer;
+ color: var(--text-2); list-style: none; }
+ .item-menu summary::-webkit-details-marker { display: none; }
+ .menu-content { position: absolute; right: 0; top: 22px; z-index: 20; display: grid; gap: 3px;
+ min-width: 174px; padding: 6px; border: 1px solid var(--border); border-radius: var(--r-sm);
+ background: var(--bg-1); box-shadow: 0 4px 18px #0003; }
+ .menu-content button, .menu-content select { width: 100%; padding: 5px 6px; text-align: left;
+ font-size: var(--fs-xs); }
+ .menu-content button:hover { background: var(--bg-2); }
+ .group-review { display: grid; gap: 5px; padding: 7px; border: 1px solid var(--accent);
+ border-radius: var(--r-sm); background: var(--accent-soft); }
+ .group-review p { margin: 0; font-size: var(--fs-xs); }
+ .group-review > div { display: flex; align-items: center; flex-wrap: wrap; gap: 5px; }
+ .group-review strong { flex: 1; min-width: 80px; font-size: var(--fs-xs); }
.reshape {
display: grid;
gap: 6px;
@@ -196,29 +606,34 @@
}
.reshape p { margin: 0; font-size: var(--fs-xs); }
.area-row {
+ position: relative;
display: flex;
align-items: center;
gap: 6px;
- padding: 5px 4px;
+ padding: 8px 4px;
+ border-bottom: 1px solid var(--border);
border-radius: var(--r-sm);
+ transition: background 120ms ease, box-shadow 120ms ease, opacity 120ms ease;
+ }
+ @media (prefers-reduced-motion: reduce) {
+ .area-row, .group-head, .ungrouped-head { transition: none; }
}
.area-row:hover { background: var(--bg-2); }
.area-row.selected { background: var(--accent-soft); }
.area-row.off .name { opacity: 0.55; }
- .swatch { flex: 0 0 auto; width: 10px; height: 10px; border-radius: 3px; background: var(--tint); }
+ .swatch { flex: 0 0 auto; width: 9px; height: 9px; border-radius: 2px; background: var(--tint); }
.name { display: grid; flex: 1; gap: 1px; min-width: 0; text-align: left; }
- .name strong { overflow: hidden; font-size: var(--fs-xs); font-weight: 600; text-overflow: ellipsis; white-space: nowrap; }
- .name small { color: var(--text-3); font-size: 10.5px; }
+ .name strong { overflow: hidden; font-size: var(--fs-sm); font-weight: 600; text-overflow: ellipsis; white-space: nowrap; }
+ .name small { color: var(--text-2); font-size: var(--fs-xs); }
.name:hover strong { color: var(--accent); }
.empty {
display: grid;
- gap: 4px;
- padding: 14px 12px;
- border: 1px dashed var(--border);
- border-radius: var(--r-sm);
- text-align: center;
+ gap: 7px;
+ padding: 18px 4px;
+ border-top: 1px solid var(--border);
+ text-align: left;
}
- .empty p { margin: 0; font-size: var(--fs-xs); color: var(--text-2); }
+ .empty p { margin: 0; font-size: var(--fs-sm); color: var(--text-2); }
input:not([type]) { flex: 1; width: 100px; }
input[type='color'] { width: 26px; height: 26px; padding: 0; }
.active { outline: 1px solid var(--accent); }
diff --git a/frontend/src/tools/detect/BenchPanel.fixture.svelte b/frontend/src/tools/detect/BenchPanel.fixture.svelte
new file mode 100644
index 0000000..e90efbb
--- /dev/null
+++ b/frontend/src/tools/detect/BenchPanel.fixture.svelte
@@ -0,0 +1,11 @@
+<script>
+ /** Detect's column with its bench handed to the test (`benchHolder.fixture.svelte.js`). */
+ import DetectPanel from './DetectPanel.svelte';
+ import { holder } from './benchHolder.fixture.svelte.js';
+
+ let props = $props();
+ let builder = $state(null);
+ $effect(() => { holder.bench = builder; });
+</script>
+
+<DetectPanel {...props} bind:builder />
diff --git a/frontend/src/tools/detect/CheckBench.svelte b/frontend/src/tools/detect/CheckBench.svelte
new file mode 100644
index 0000000..88296c2
--- /dev/null
+++ b/frontend/src/tools/detect/CheckBench.svelte
@@ -0,0 +1,438 @@
+<script>
+ /**
+ * The console over the map where an analyzer of your own is proved.
+ *
+ * One check is on the map at a time. The selector picks it, or none to see the
+ * basemap alone, or starts a new one: a drawer takes its passes, then the pins
+ * are dropped with a click, and Finish keeps it. The map is split between the
+ * two passes of a check that has two, and the same row switches between the
+ * sides. Test runs the rules on the ground under the pins, says its cost
+ * first, and the row under it says how every pin came out and keeps a chip for
+ * each rule, to show it or hide it and see which ones help.
+ *
+ * It only asks the bench (`lib/map/bench.svelte.js`); the map itself, the
+ * pins and the painted rules are drawn by Detect from the same bench.
+ */
+ import { checkState, describeOutcome, shortRule } from '../../lib/map/analyzerRules.js';
+ import AcquisitionPicker from './AcquisitionPicker.svelte';
+ import PassDates from './PassDates.svelte';
+ import Icon from '../../components/Icon.svelte';
+
+ let { bench } = $props();
+
+ let width = $state(0);
+ let deckHeight = $state(0);
+ // What the console covers of the map's bottom edge, which the reading card keeps clear of.
+ $effect(() => { bench.reach = deckHeight ? deckHeight + 42 : 0; });
+ /** The menu that is open: 'check' (which check), 'look' (how the passes are shown) or ''. */
+ let open = $state('');
+ let root = $state(null);
+ const narrow = $derived(width > 0 && width < 620);
+
+ const GLYPHS = { pass: '✓', fail: '✗', stale: '–', unrun: '–', unpinned: '!' };
+ const check = $derived(bench.check);
+ const state = $derived(check ? checkState(check, bench.current) : 'unrun');
+ const before = $derived(check?.a?.date ?? '');
+ const after = $derived(check?.b?.date ?? '');
+ const side = $derived(bench.divider >= 99 ? 'before' : bench.divider <= 1 ? 'after' : 'split');
+ const pinCount = $derived(bench.marks.length);
+ /** The layer's name without its explanation: "NDVI (vegetation index)" is NDVI on a button. */
+ const layerLabel = $derived((bench.offered.find((entry) => entry.id === bench.layer)?.label ?? bench.layer).replace(/\s*\(.*$/, ''));
+ const suggestion = $derived(bench.suggestion);
+
+ /** How every pin came out, from the last test, with the count of what it found. */
+ const outcome = $derived.by(() => {
+ if (!check) return '';
+ const text = describeOutcome(check, bench.current);
+ const count = check.result?.signature === bench.current ? check.result.count : null;
+ return count === null ? text : `${text} · ${count} candidate${count === 1 ? '' : 's'}`;
+ });
+
+ function choose(id) {
+ open = '';
+ bench.select(id);
+ }
+ function startNew() {
+ open = '';
+ bench.startDraft();
+ }
+ function closeDrawer() {
+ if (bench.draft && !bench.dated) bench.cancelDraft();
+ else bench.closePasses();
+ }
+ /** The row that switches sides: the whole map on the before pass, the split, or the whole map on the after one. */
+ function show(which) {
+ bench.setDivider(which === 'before' ? 100 : which === 'after' ? 0 : 50);
+ }
+ function onOutside(event) {
+ if (open && !event.target.closest?.('.pick')) open = '';
+ }
+ function onKey(event) {
+ if (event.key !== 'Escape') return;
+ if (open) {
+ open = '';
+ } else if (bench.choosingPasses) {
+ closeDrawer();
+ } else {
+ return;
+ }
+ event.stopPropagation();
+ }
+</script>
+
+<svelte:window onpointerdown={onOutside} />
+<!-- svelte-ignore a11y_no_static_element_interactions -->
+<div class="bench-root" bind:clientWidth={width} bind:this={root} onkeydown={onKey}>
+ <div class="console cmp-glass" class:narrow role="region" aria-label="Checks on the map" bind:clientHeight={deckHeight}>
+ {#if bench.choosingPasses}
+ <section class="drawer cmp-glass" aria-label={bench.draft ? 'Passes of the new check' : 'Change the passes of the check'}>
+ <header>
+ <strong>{bench.draft ? 'New check' : 'Change the passes'}</strong>
+ <button class="cmp-icon" aria-label="Close" title="Close" onclick={closeDrawer}><Icon name="x" size={13} /></button>
+ </header>
+ <div class="body">
+ <p class="hint">{bench.single ? 'Pick the pass this check is read on' : 'Pick the pass before and the pass after'},
+ looked up for the ground at the middle of the map.</p>
+ <div class="slots">
+ {#if !bench.single}
+ <span class="slot"><i class="cmp-letter a" aria-hidden="true">A</i> Before <strong class="cmp-mono">{before || 'not picked'}</strong></span>
+ {/if}
+ <span class="slot"><i class="cmp-letter b" aria-hidden="true">B</i> {bench.single ? 'Pass' : 'After'} <strong class="cmp-mono">{after || 'not picked'}</strong></span>
+ </div>
+ <AcquisitionPicker list={bench.passes.list} lookback={bench.passes.lookback} busy={bench.passes.busy}
+ error={bench.passes.error} searched={bench.passes.searched} truncated={bench.passes.truncated} areas={1}
+ single={bench.single} radar={bench.radar} wantsReference={!bench.single} wantsCompare={true}
+ a={check?.a?.date ? check.a : null} b={check?.b?.date ? check.b : null} nameA="Before" nameB="After"
+ onlookback={(lookback) => bench.setLookback(lookback)} onlook={() => bench.lookUpPasses()}
+ onolder={() => bench.lookOlder()} onpick={(letter, entry) => bench.setPass(letter, entry)}>
+ {#snippet dates()}<PassDates {bench} />{/snippet}
+ </AcquisitionPicker>
+ </div>
+ <footer>
+ {#if bench.draft}<button class="btn btn-sm" onclick={() => bench.cancelDraft()}>Cancel</button>{/if}
+ <button class="btn btn-sm btn-primary" disabled={!bench.dated} onclick={() => bench.closePasses()}>
+ {bench.draft ? 'Place the pins' : 'Done'}</button>
+ </footer>
+ </section>
+ {/if}
+
+ <div class="head">
+ {#if bench.draft}
+ <input class="name" aria-label="Name of the new check" title="Name of the new check" value={bench.draft.check.name}
+ oninput={(event) => bench.nameDraft(event.currentTarget.value)} maxlength="120" />
+ {:else}
+ <div class="pick">
+ <button class="select" aria-haspopup="menu" aria-expanded={open === 'check'} aria-label="Check on the map"
+ onclick={() => (open = open === 'check' ? '' : 'check')}>
+ {#if check}<span class="state {state}" aria-hidden="true">{GLYPHS[state]}</span>{/if}
+ <strong>{check?.name ?? 'Basemap only'}</strong>
+ <Icon name="chevronDown" size={13} />
+ </button>
+ {#if open === 'check'}
+ <div class="menu cmp-glass" role="menu" aria-label="Checks">
+ <button role="menuitemradio" aria-checked={!check} onclick={() => choose(null)}>
+ <span class="state" aria-hidden="true"></span><span class="grow">Basemap only</span>
+ </button>
+ {#if bench.checks.length}<hr />{/if}
+ {#each bench.checks as entry (entry.id)}
+ {@const entryState = checkState(entry, bench.current)}
+ <button role="menuitemradio" aria-checked={bench.selected === entry.id} onclick={() => choose(entry.id)}>
+ <span class="state {entryState}" aria-hidden="true">{GLYPHS[entryState]}</span>
+ <span class="grow">{entry.name}</span>
+ <small>{describeOutcome(entry, bench.current)}</small>
+ </button>
+ {/each}
+ <hr />
+ <button role="menuitem" disabled={bench.atMostChecks} onclick={startNew}><Icon name="plus" size={12} /><span class="grow">New check</span></button>
+ </div>
+ {/if}
+ </div>
+ {/if}
+
+ {#if check && bench.dated && !bench.choosingPasses}
+ {#if !bench.single}
+ <div class="cmp-seg" role="group" aria-label="Which pass to look at">
+ <button type="button" class:on={side === 'before'} aria-pressed={side === 'before'} disabled={bench.basemap}
+ title="Show the before pass alone" onclick={() => show('before')}>Before <span class="cmp-mono">{before}</span></button>
+ <button type="button" class:on={side === 'split'} aria-pressed={side === 'split'} disabled={bench.basemap}
+ title="Split the map between the two passes" onclick={() => show('split')}>Split</button>
+ <button type="button" class:on={side === 'after'} aria-pressed={side === 'after'} disabled={bench.basemap}
+ title="Show the after pass alone" onclick={() => show('after')}>After <span class="cmp-mono">{after}</span></button>
+ </div>
+ {:else}
+ <span class="date cmp-mono">{after}</span>
+ {/if}
+ <button class="cmp-icon" aria-label="Change the passes" title="Change the passes" onclick={() => bench.changePasses()}>
+ <Icon name="calendar" size={14} /></button>
+ <button class="cmp-icon eye" class:on={!bench.basemap} aria-pressed={!bench.basemap} aria-label="Passes on the map"
+ title={bench.basemap ? 'Show the passes' : 'Show the basemap'} onclick={() => bench.setBasemap(!bench.basemap)}>
+ <Icon name={bench.basemap ? 'eyeOff' : 'eye'} size={15} /></button>
+ {#if !bench.radar}
+ <div class="pick">
+ <button class="select look" class:off={bench.basemap} aria-haspopup="menu" aria-expanded={open === 'look'}
+ aria-label="Copernicus layer" title="How the passes are shown" onclick={() => (open = open === 'look' ? '' : 'look')}>
+ <Icon name="layers" size={14} /><span>{layerLabel}</span><Icon name="chevronDown" size={13} />
+ </button>
+ {#if open === 'look'}
+ <div class="menu look-menu cmp-glass" role="menu" aria-label="Copernicus layer">
+ {#each bench.offered as entry (entry.id)}
+ <button role="menuitemradio" aria-checked={bench.layer === entry.id} title={entry.hint ?? ''}
+ onclick={() => { bench.setLayer(entry.id); open = ''; }}>
+ <span class="grow">{entry.label}</span>
+ {#if entry.id === suggestion}<small>best for rule ★</small>{/if}
+ </button>
+ {/each}
+ </div>
+ {/if}
+ </div>
+ {/if}
+ {:else if !check}
+ <span class="hint grow">Pick a check to try the rules on it.</span>
+ <button class="btn btn-sm" disabled={bench.atMostChecks} onclick={startNew}><Icon name="plus" size={12} /> New check</button>
+ {/if}
+
+ {#if bench.draft && !bench.choosingPasses}
+ <span class="grow"></span>
+ <button class="btn btn-sm" onclick={() => bench.cancelDraft()}>Cancel</button>
+ <button class="btn btn-sm btn-primary" disabled={!bench.canFinish} onclick={() => bench.finishDraft()}>Finish</button>
+ {/if}
+ </div>
+
+ {#if check && !bench.choosingPasses}
+ <div class="tools">
+ <div class="pins" role="group" aria-label="Pin to drop on the map">
+ <button type="button" class="pin" class:on={bench.pinning === 'found'} aria-pressed={bench.pinning === 'found'}
+ onclick={() => bench.arm('found')}><i class="shape shape-found" aria-hidden="true"></i>Should be found</button>
+ <button type="button" class="pin" class:on={bench.pinning === 'empty'} aria-pressed={bench.pinning === 'empty'}
+ onclick={() => bench.arm('empty')}><i class="shape shape-empty" aria-hidden="true"></i>Should stay empty</button>
+ <span class="count cmp-mono">{pinCount} pin{pinCount === 1 ? '' : 's'}</span>
+ </div>
+ <button class="btn test" class:btn-primary={!bench.tested} class:done={bench.tested} disabled={!bench.canTest}
+ title={bench.blocked || undefined} onclick={() => bench.test()}>{bench.testLabel}</button>
+ </div>
+ {#if bench.pinning}
+ <p class="note" role="status">Click the ground where {bench.pinning === 'found' ? 'a candidate should be found' : 'none should be'} (Esc stops).</p>
+ {:else if bench.blocked && bench.dated}
+ <p class="note" class:warn={!!bench.plan?.error} role="status">{bench.blocked}</p>
+ {/if}
+ {/if}
+
+ {#if check && !bench.choosingPasses && (bench.detail || bench.last?.error)}
+ <div class="result" class:stale={bench.stale} aria-live="polite">
+ {#if bench.last?.error}
+ <span class="outcome fail">{bench.last.error}</span>
+ {:else}
+ <span class="outcome {bench.stale ? 'stale' : state}">{bench.stale ? 'The rules or pins changed since this test.' : outcome}</span>
+ <div class="legend" role="group" aria-label="Rules on the map">
+ {#each bench.recipe.rules as rule, i (i)}
+ <button type="button" class="chip" class:off={!bench.painted(i)} style={`--tint: ${bench.colours[i % bench.colours.length]}`}
+ aria-pressed={bench.painted(i)} title={`${bench.painted(i) ? 'Hide' : 'Show'} rule ${i + 1} on the map`}
+ onpointerenter={() => bench.hoverRule(i)} onpointerleave={() => bench.hoverRule(null)}
+ onfocus={() => bench.hoverRule(i)} onblur={() => bench.hoverRule(null)} onclick={() => bench.toggleRule(i)}>
+ <i class="dot">{i + 1}</i>{shortRule(rule, { single: bench.single })}</button>
+ {/each}
+ </div>
+ <div class="cmp-seg" role="group" aria-label="What the map shows">
+ <button type="button" class:on={bench.view === 'rules'} aria-pressed={bench.view === 'rules'}
+ title="Each rule's pixels in its colour" onclick={() => (bench.view = 'rules')}>Rules</button>
+ <button type="button" class:on={bench.view === 'detections'} aria-pressed={bench.view === 'detections'}
+ title="Only what a run would return" onclick={() => (bench.view = 'detections')}>Detections</button>
+ </div>
+ {/if}
+ </div>
+ {/if}
+ </div>
+</div>
+
+<style>
+ .bench-root { position: absolute; inset: 0; z-index: 650; pointer-events: none; }
+ .console {
+ position: absolute;
+ bottom: 34px;
+ left: 50%;
+ display: grid;
+ width: min(760px, calc(100% - 24px));
+ transform: translateX(-50%);
+ box-shadow: var(--shadow-2);
+ pointer-events: auto;
+ }
+ .console > .head, .console > .tools, .console > .result, .console > .note { padding: 7px 10px; }
+ .console > * + * { border-top: 1px solid var(--glass-line); }
+ .head, .tools, .result { display: flex; align-items: center; flex-wrap: wrap; gap: 8px; min-width: 0; }
+ .grow { flex: 1; }
+
+ /* Which check is on the map, which pass of it, and how the passes are shown. */
+ .pick { position: relative; min-width: 0; }
+ .select {
+ display: inline-flex;
+ align-items: center;
+ gap: 7px;
+ max-width: 230px;
+ min-height: 28px;
+ padding: 0 8px;
+ border-radius: var(--r-sm);
+ color: var(--glass-ink);
+ }
+ .select:hover, .select[aria-expanded='true'] { background: var(--glass-hover); }
+ .select strong { overflow: hidden; font-size: var(--fs-sm); text-overflow: ellipsis; white-space: nowrap; }
+ .select.look { max-width: 170px; border: 1px solid var(--glass-line); color: var(--glass-muted); font-size: var(--fs-xs); }
+ .select.look span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+ .select.look.off { opacity: 0.55; }
+ .state { flex: 0 0 auto; width: 14px; color: var(--glass-dim); font-weight: 700; text-align: center; }
+ .state.pass { color: var(--ok); }
+ .state.fail { color: var(--danger); }
+ .state.unpinned { color: var(--warn); }
+ .name {
+ flex: 0 1 150px;
+ min-width: 100px;
+ border-color: transparent;
+ background: transparent;
+ font-weight: 650;
+ }
+ .name:hover { border-color: var(--glass-line); }
+ .name:focus { border-color: var(--accent); background: var(--bg-0); }
+ .date { color: var(--glass-muted); font-size: var(--fs-xs); }
+ .head .cmp-seg > button { min-height: 24px; padding: 0 8px; }
+ .head .cmp-seg .cmp-mono { color: var(--glass-dim); font-size: 10px; }
+ .head .cmp-seg .on .cmp-mono { color: inherit; }
+ .head .cmp-icon { width: 28px; height: 28px; }
+ .menu {
+ position: absolute;
+ bottom: calc(100% + 10px);
+ left: 0;
+ z-index: 3;
+ display: grid;
+ width: 320px;
+ max-width: calc(100vw - 48px);
+ max-height: 300px;
+ overflow: auto;
+ padding: 4px;
+ box-shadow: var(--shadow-2);
+ }
+ .look-menu { width: 280px; gap: 0; }
+ .menu button {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ min-height: 30px;
+ padding: 0 8px;
+ border-radius: var(--r-sm);
+ color: var(--glass-ink);
+ font-size: var(--fs-xs);
+ text-align: left;
+ }
+ .menu button:hover:not(:disabled) { background: var(--glass-hover); }
+ .menu button[aria-checked='true'] { color: var(--accent); background: var(--accent-soft); }
+ .menu button:disabled { opacity: 0.4; cursor: not-allowed; }
+ .menu small { overflow: hidden; max-width: 130px; color: var(--glass-dim); font-size: 10px; text-overflow: ellipsis; white-space: nowrap; }
+ .menu hr { width: 100%; margin: 4px 0; border: 0; border-top: 1px solid var(--glass-line); }
+
+ /* The passes of a check, in a drawer that opens above the console. */
+ /* The title and the buttons stay where they are; only the passes scroll, so
+ Place the pins is always in reach however short the window is. */
+ .drawer {
+ position: absolute;
+ right: -1px;
+ bottom: calc(100% + 8px);
+ left: -1px;
+ display: flex;
+ flex-direction: column;
+ max-height: min(480px, calc(100vh - 230px));
+ overflow: hidden;
+ box-shadow: var(--shadow-2);
+ }
+ .drawer header { display: flex; flex: 0 0 auto; align-items: center; gap: 8px; padding: 10px 12px 6px; }
+ .drawer header strong { flex: 1; font-size: var(--fs-sm); }
+ .drawer .body { display: grid; flex: 1 1 auto; gap: 8px; min-height: 0; overflow: auto; padding: 2px 12px 10px; }
+ .drawer .hint { margin: 0; color: var(--glass-dim); font-size: var(--fs-xs); line-height: 1.45; }
+ .slots { display: flex; flex-wrap: wrap; gap: 6px 16px; }
+ .slot { display: inline-flex; align-items: center; gap: 6px; color: var(--glass-muted); font-size: var(--fs-xs); }
+ .slot strong { color: var(--glass-ink); font-weight: 600; }
+ .drawer footer {
+ display: flex;
+ flex: 0 0 auto;
+ justify-content: flex-end;
+ gap: 6px;
+ padding: 8px 12px;
+ border-top: 1px solid var(--glass-line);
+ }
+
+ /* The pins to drop, and the test. */
+ .pins { display: flex; align-items: center; flex-wrap: wrap; gap: 6px; }
+ .pin {
+ display: inline-flex;
+ align-items: center;
+ gap: 7px;
+ min-height: 28px;
+ padding: 0 10px;
+ border: 1px solid var(--glass-line);
+ border-radius: 999px;
+ color: var(--glass-muted);
+ font-size: var(--fs-xs);
+ transition: background 0.12s var(--ease), border-color 0.12s var(--ease), color 0.12s var(--ease);
+ }
+ .pin:hover { border-color: var(--glass-line-strong); color: var(--glass-ink); }
+ .pin.on { border-color: var(--accent); color: var(--glass-ink); background: var(--accent-soft); }
+ /* The shapes the map draws: filled where a candidate should come out, struck where none should. The
+ names keep clear of the app's own empty-state class. */
+ .shape { position: relative; flex: 0 0 auto; width: 11px; height: 11px; border: 2px solid currentColor; border-radius: 50%; box-sizing: border-box; }
+ .shape-found::after { position: absolute; inset: 1px; border-radius: 50%; background: currentColor; content: ''; }
+ .shape-empty { border-style: dashed; }
+ .shape-empty::after {
+ position: absolute;
+ top: 50%;
+ left: -2px;
+ width: 11px;
+ height: 2px;
+ background: currentColor;
+ transform: translateY(-50%) rotate(-45deg);
+ content: '';
+ }
+ .count { color: var(--glass-dim); font-size: 10.5px; }
+ .test { min-width: 116px; min-height: 30px; margin-left: auto; }
+ /* Nothing left to do: a quiet check mark, not a button asking to be pressed. */
+ .test.done { border-color: var(--glass-line); background: transparent; color: var(--ok); opacity: 1; }
+ .test.done::before { margin-right: 5px; content: '✓'; }
+ .note { margin: 0; color: var(--glass-muted); font-size: var(--fs-xs); line-height: 1.45; }
+ .note.warn { color: var(--warn); }
+
+ /* How it came out, and a chip for each rule. */
+ .result { gap: 8px 12px; }
+ .result.stale { background: color-mix(in srgb, var(--warn) 8%, transparent); }
+ .outcome { flex: 1 1 200px; color: var(--glass-muted); font-size: var(--fs-xs); font-weight: 600; line-height: 1.4; }
+ .outcome.pass { color: var(--ok); }
+ .outcome.fail { color: var(--danger); }
+ .outcome.stale { color: var(--warn); }
+ .legend { display: flex; flex-wrap: wrap; gap: 5px; }
+ .chip {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ min-height: 24px;
+ padding: 0 9px 0 4px;
+ border: 1px solid color-mix(in srgb, var(--tint) 55%, transparent);
+ border-radius: 999px;
+ color: var(--glass-ink);
+ font-size: 10.5px;
+ font-weight: 600;
+ transition: background 0.12s var(--ease), opacity 0.12s var(--ease);
+ }
+ .chip:hover { background: color-mix(in srgb, var(--tint) 16%, transparent); }
+ .chip.off { border-style: dashed; color: var(--glass-dim); opacity: 0.75; }
+ .chip .dot {
+ display: grid;
+ place-items: center;
+ width: 16px;
+ height: 16px;
+ border-radius: 50%;
+ background: var(--tint);
+ color: #111;
+ font-size: 9.5px;
+ font-style: normal;
+ font-weight: 800;
+ line-height: 1;
+ }
+ .chip.off .dot { background: transparent; color: var(--glass-dim); box-shadow: inset 0 0 0 1.5px var(--tint); }
+ .narrow .pin { padding: 0 8px; }
+ .narrow .test { flex: 1; margin-left: 0; }
+</style>
diff --git a/frontend/src/tools/detect/CheckBench.svelte.test.js b/frontend/src/tools/detect/CheckBench.svelte.test.js
new file mode 100644
index 0000000..f2fdf19
--- /dev/null
+++ b/frontend/src/tools/detect/CheckBench.svelte.test.js
@@ -0,0 +1,237 @@
+// @vitest-environment happy-dom
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { flushSync, mount, unmount } from 'svelte';
+import { Bench } from '../../lib/map/bench.svelte.js';
+import { newCheck, newRecipe, newRule, signature } from '../../lib/map/analyzerRules.js';
+import CheckBench from './CheckBench.svelte';
+
+const METHODS = [{ id: 'rules', sizes: { all: {} } }];
+const VIEW = { west: 2, south: 48, east: 2.2, north: 48.2 };
+const pass = (date) => ({ provider: 'sentinel2', date, layer: 'TRUE_COLOR', maxcc: 100 });
+const made = (name, extra = {}) => ({ ...newCheck({ name, a: pass('2026-05-04'), b: pass('2026-05-11'),
+ marks: [{ point: [2.01, 48.01], expect: 'found' }, { point: [2.05, 48.05], expect: 'empty' }] }), ...extra });
+
+let live, bench, target, calls;
+beforeEach(() => { vi.useFakeTimers(); calls = []; });
+afterEach(() => {
+ if (live) unmount(live);
+ bench?.destroy();
+ live = bench = null;
+ target?.remove();
+ vi.useRealTimers();
+});
+
+function open({ dates = 'two', sensor = 'sentinel2', checks = [], layers } = {}) {
+ const recipe = $state({ ...newRecipe(METHODS, { sensor, dates }), name: 'Mine', checks });
+ const api = { post: vi.fn(async (url, body) => {
+ calls.push([url, body]);
+ if (url.endsWith('/check/plan')) return { tiles: 1, missing: 4 };
+ if (url.endsWith('/check')) {
+ const covered = body.check.marks.map((mark) => mark.expect === 'found');
+ return { ready: true, missing: 0, count: 1, covered, size: 512, tiles: [], rules: body.recipe.rules.map(() => ({ share: 0.1, kept: 0.1 })),
+ candidates: [], readings: [] };
+ }
+ return { dates: [{ date: '2026-05-11', cloud: 4, coverage: 1 }, { date: '2026-05-04', cloud: 2, coverage: 1 }], truncated: false };
+ }) };
+ bench = new Bench({ api, recipe, limits: { max_checks: 12, max_marks: 20 }, layers: () => layers ?? [], viewBounds: () => VIEW });
+ target = document.createElement('div');
+ document.body.append(target);
+ live = mount(CheckBench, { target, props: { bench } });
+ flushSync();
+ return { bench, recipe };
+}
+const settle = async () => { await vi.advanceTimersByTimeAsync(300); flushSync(); };
+const query = (selector) => target.querySelector(selector);
+const buttons = (selector = '.console') => [...query(selector).querySelectorAll('button')];
+const named = (text, selector) => buttons(selector).find((button) => button.textContent.trim().startsWith(text));
+const click = (node) => { node.click(); flushSync(); };
+
+it('asks for a check when none is on the map, and offers a new one', () => {
+ open();
+ expect(query('.head').textContent).toContain('Basemap only');
+ expect(query('.head').textContent).toContain('Pick a check to try the rules on it.');
+ expect(query('.tools')).toBe(null);
+ click(named('New check'));
+ expect(bench.draft).not.toBe(null);
+ expect(query('[aria-label="Passes of the new check"]')).not.toBe(null);
+});
+
+it('lists the checks with how each came out, picks one, and closes on Escape or a press elsewhere', async () => {
+ const good = made('The plot', { result: null });
+ open({ checks: [good, made('The reef', { marks: [] })] });
+ click(query('[aria-label="Check on the map"]'));
+ const menu = query('[role="menu"][aria-label="Checks"]');
+ expect([...menu.querySelectorAll('[role="menuitemradio"]')].map((row) => row.textContent.replace(/\s+/g, ' ').trim()))
+ .toEqual(['Basemap only', '– The plot Not tested yet', '! The reef Needs a pin']);
+ click(menu.querySelectorAll('[role="menuitemradio"]')[1]);
+ expect(bench.check.name).toBe('The plot');
+ expect(query('[role="menu"]')).toBe(null);
+ expect(query('[aria-label="Check on the map"]').textContent).toContain('The plot');
+ // a press elsewhere, and Escape, each close it
+ click(query('[aria-label="Check on the map"]'));
+ expect(query('[role="menu"]')).not.toBe(null);
+ document.body.dispatchEvent(new Event('pointerdown', { bubbles: true })); flushSync();
+ expect(query('[role="menu"]')).toBe(null);
+ click(query('[aria-label="Check on the map"]'));
+ query('.bench-root').dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true })); flushSync();
+ expect(query('[role="menu"]')).toBe(null);
+ await settle();
+});
+
+it('switches between the before pass, the split and the after pass of a check of two dates, not of one', () => {
+ open({ checks: [made('The plot')] });
+ bench.select(bench.checks[0].id); flushSync();
+ const seg = query('[role="group"][aria-label="Which pass to look at"]');
+ expect([...seg.querySelectorAll('button')].map((b) => b.textContent.replace(/\s+/g, ' ').trim()))
+ .toEqual(['Before 2026-05-04', 'Split', 'After 2026-05-11']);
+ click(seg.querySelectorAll('button')[0]);
+ expect(bench.divider).toBe(100);
+ click(seg.querySelectorAll('button')[2]);
+ expect(bench.divider).toBe(0);
+ click(seg.querySelectorAll('button')[1]);
+ expect(bench.divider).toBe(50);
+ // with the basemap up there is no pass to switch between
+ bench.setBasemap(true); flushSync();
+ expect([...seg.querySelectorAll('button')].every((b) => b.disabled)).toBe(true);
+ unmount(live); bench.destroy(); target.remove();
+ open({ dates: 'one', checks: [made('The plot', { a: {} })] });
+ bench.select(bench.checks[0].id); flushSync();
+ expect(query('[aria-label="Which pass to look at"]')).toBe(null);
+ expect(query('.date').textContent).toBe('2026-05-11');
+});
+
+it('arms a pin, says what a click will do, and says how many are down', () => {
+ open({ checks: [made('The plot')] });
+ bench.select(bench.checks[0].id); flushSync();
+ const pins = query('[role="group"][aria-label="Pin to drop on the map"]');
+ expect(pins.textContent).toContain('2 pins');
+ click([...pins.querySelectorAll('button')][1]);
+ expect(bench.pinning).toBe('empty');
+ expect(query('.note').textContent).toBe('Click the ground where none should be (Esc stops).');
+ click([...pins.querySelectorAll('button')][1]);
+ expect(bench.pinning).toBe(null);
+});
+
+it('says what a test costs before it reads, then that it is done, and draws a chip for each rule', async () => {
+ const { recipe } = open({ checks: [made('The plot')] });
+ recipe.rules = [newRule('index', 'change'), newRule('index', 'a')];
+ bench.select(bench.checks[0].id); flushSync();
+ await settle();
+ expect(query('.test').textContent.trim()).toBe('Test · 4 requests');
+ expect(query('.result')).toBe(null);
+ click(query('.test')); await settle();
+ expect(query('.test').textContent.trim()).toBe('Tested');
+ expect(query('.test').disabled).toBe(true);
+ expect(query('.outcome').textContent).toBe('1 of 1 found · stayed empty · 1 candidate');
+ const chips = [...query('[role="group"][aria-label="Rules on the map"]').querySelectorAll('button')];
+ expect(chips.map((chip) => chip.textContent.trim())).toEqual(['1NDVI change', '2NDVI before']);
+ // a chip hides its rule, shows it again, and a pointer on it lights that rule alone
+ click(chips[1]);
+ expect(bench.painted(1)).toBe(false);
+ chips[0].dispatchEvent(new Event('pointerenter')); flushSync();
+ expect(bench.hover).toBe(0);
+ chips[0].dispatchEvent(new Event('pointerleave')); flushSync();
+ expect(bench.hover).toBe(null);
+ const view = query('[role="group"][aria-label="What the map shows"]');
+ click(view.querySelectorAll('button')[1]);
+ expect(bench.view).toBe('detections');
+});
+
+it('says the rules changed, in place of the outcome, and what went wrong in the engine’s words', async () => {
+ const { recipe } = open({ checks: [made('The plot')] });
+ bench.select(bench.checks[0].id); flushSync();
+ await settle();
+ click(query('.test')); await settle();
+ recipe.rules[0].value = -0.5; flushSync();
+ expect(query('.result').classList.contains('stale')).toBe(true);
+ expect(query('.outcome').textContent).toBe('The rules or pins changed since this test.');
+ expect(query('.test').textContent.trim()).toBe('Test again'); // its frames are held now, so it costs nothing
+ expect(signature(recipe)).toBeTruthy();
+});
+
+it('shows the passes in the layer the rules read best, or the basemap in their place, from an eye', () => {
+ open({ checks: [made('The plot')], layers: [{ id: 'TRUE_COLOR', label: 'True colour' }, { id: 'NDVI', label: 'NDVI (vegetation index)', hint: 'Greens' }] });
+ bench.select(bench.checks[0].id); flushSync();
+ const look = query('[aria-label="Copernicus layer"][aria-haspopup]');
+ expect(look.textContent.trim()).toBe('True colour'); // the layer the check was saved in
+ click(look);
+ const menu = query('[role="menu"][aria-label="Copernicus layer"]');
+ const rows = [...menu.querySelectorAll('[role="menuitemradio"]')];
+ expect(rows.map((row) => row.textContent.replace(/\s+/g, ' ').trim())).toEqual(['True colour', 'NDVI (vegetation index) best for rule ★']);
+ click(rows[1]);
+ expect(bench.layer).toBe('NDVI');
+ expect(look.textContent.trim()).toBe('NDVI');
+ expect(query('[role="menu"]')).toBe(null);
+
+ // the eye puts the basemap where the passes were, and back
+ const eye = query('button[aria-label="Passes on the map"]');
+ expect(eye.getAttribute('aria-pressed')).toBe('true');
+ expect(eye.getAttribute('title')).toBe('Show the basemap');
+ click(eye);
+ expect(bench.basemap).toBe(true);
+ expect(eye.getAttribute('aria-pressed')).toBe('false');
+ expect(eye.getAttribute('title')).toBe('Show the passes');
+ expect(look.classList.contains('off')).toBe(true);
+ click(eye);
+ expect(bench.basemap).toBe(false);
+ // a layer picked with the basemap up brings the passes back in it
+ click(eye);
+ click(look);
+ click(query('[role="menu"]').querySelectorAll('[role="menuitemradio"]')[0]);
+ expect(bench.basemap).toBe(false);
+ expect(bench.layer).toBe('TRUE_COLOR');
+});
+
+it('has no layer to choose for radar, which has one picture, and still has the eye', () => {
+ open({ sensor: 'sentinel1', checks: [made('The plot', { a: { provider: 'sentinel1', date: '2026-05-04', time: '05:30:12' },
+ b: { provider: 'sentinel1', date: '2026-05-11', time: '05:30:12' } })] });
+ bench.select(bench.checks[0].id); flushSync();
+ expect(query('[aria-label="Copernicus layer"]')).toBe(null);
+ expect(query('button[aria-label="Passes on the map"]')).not.toBe(null);
+});
+
+it('makes a new check in three steps: its passes, its pins, and Finish', async () => {
+ const { recipe } = open();
+ click(named('New check'));
+ expect(query('.drawer header strong').textContent).toBe('New check');
+ expect(query('.drawer .hint').textContent.replace(/\s+/g, ' ')).toBe('Pick the pass before and the pass after, looked up for the ground at the middle of the map.');
+ expect(named('Place the pins', '.drawer').disabled).toBe(true);
+ click(named('Find passes', '.drawer')); await settle();
+ expect(calls.at(-1)[0]).toBe('/api/satellite/sentinel/acquisitions');
+ const rows = [...target.querySelectorAll('.drawer li')];
+ expect(rows[1].textContent).toContain('2026-05-04');
+ click(rows[1].querySelectorAll('button')[0]); // Before
+ click(rows[0].querySelectorAll('button')[1]); // After
+ expect(query('.slots').textContent.replace(/\s+/g, ' ')).toContain('Before 2026-05-04');
+ expect(query('.slots').textContent.replace(/\s+/g, ' ')).toContain('After 2026-05-11');
+ click(named('Place the pins', '.drawer'));
+ expect(query('.drawer')).toBe(null);
+ expect(bench.pinning).toBe('found');
+ // the name can be changed while the pins go down, and Finish waits for one
+ const name = query('input.name');
+ name.value = 'The plot'; name.dispatchEvent(new Event('input', { bubbles: true })); flushSync();
+ expect(named('Finish').disabled).toBe(true);
+ bench.dropPin({ lon: 2.01, lat: 48.01 }); flushSync();
+ click(named('Finish'));
+ expect(recipe.checks.map((check) => check.name)).toEqual(['The plot']);
+ expect(query('[aria-label="Check on the map"]').textContent).toContain('The plot');
+});
+
+it('lets the passes be picked from a calendar too, with the month asked for only when it is opened', async () => {
+ open();
+ click(named('New check'));
+ click(named('Dates', '.drawer'));
+ expect(query('.dates')).not.toBe(null);
+ expect(calls.filter(([url]) => url.endsWith('/acquisitions'))).toHaveLength(0);
+ click(query('button[aria-label="After pass"]')); await settle();
+ expect(calls.filter(([url]) => url.endsWith('/acquisitions'))).toHaveLength(1);
+ expect(query('.pass-calendar')).not.toBe(null);
+});
+
+it('closes the drawer of a check being made by giving the check up, and Escape does the same', () => {
+ open();
+ click(named('New check'));
+ query('.bench-root').dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true })); flushSync();
+ expect(bench.draft).toBe(null);
+ expect(query('.drawer')).toBe(null);
+});
diff --git a/frontend/src/tools/detect/CheckMarks.render.test.js b/frontend/src/tools/detect/CheckMarks.render.test.js
index a05414e..de2a707 100644
--- a/frontend/src/tools/detect/CheckMarks.render.test.js
+++ b/frontend/src/tools/detect/CheckMarks.render.test.js
@@ -1,52 +1,54 @@
// @vitest-environment happy-dom
-import { expect, it } from 'vitest';
+import { expect, it, vi } 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 engine = { on: () => () => {}, latLngToContainerPoint: ({ lon }) => ({ x: lon * 100, y: 50 }) };
+
+function render(props) {
const target = document.createElement('div');
document.body.append(target);
- const live = mount(CheckMarks, { target, props: { engine, marks: [
+ const live = mount(CheckMarks, { target, props: { engine, ...props } });
+ flushSync();
+ return { target, done: () => { unmount(live); target.remove(); } };
+}
+
+it('pins each pin to its ground point, saying what it expects and how it came out', () => {
+ const { target, done } = render({ pins: [
{ 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']);
+ 'Pin 1: Should be found, and it is', 'Pin 2: Should stay empty, and it is not', 'Pin 3: Should be found']);
expect(marks[0].classList.contains('pass')).toBe(true);
expect(marks[1].classList.contains('fail')).toBe(true);
- unmount(live);
- target.remove();
+ expect(marks[2].classList.contains('pass') || marks[2].classList.contains('fail')).toBe(false);
+ done();
});
-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');
- // The ground outside the frame is veiled: the frame is cut out of a ring past the screen.
- const veil = target.querySelector('path.veil');
- expect(veil.getAttribute('fill-rule')).toBe('evenodd');
- expect(veil.getAttribute('d')).toBe('M-1e5,-1e5H1e5V1e5H-1e5Z M100,100 L200,100 L200,200 L100,200Z');
- unmount(live);
- target.remove();
+it('hands a pressed pin back by its place in the list, and marks the one the card is about', () => {
+ const onpick = vi.fn();
+ const { target, done } = render({ onpick, selected: 1, pins: [
+ { point: [1, 48], expect: 'found', ok: null }, { point: [2, 48], expect: 'empty', ok: null }] });
+ const marks = [...target.querySelectorAll('.mark')];
+ marks[1].click();
+ expect(onpick).toHaveBeenCalledWith(1);
+ expect(marks.map((mark) => mark.classList.contains('selected'))).toEqual([false, true]);
+ done();
});
-it('veils nothing while no check is open', () => {
- const engine = { on: () => () => {}, latLngToContainerPoint: () => ({ x: 0, y: 0 }) };
- const target = document.createElement('div');
- document.body.append(target);
- const live = mount(CheckMarks, { target, props: { engine, marks: [{ point: [1, 48], expect: 'found', ok: null }] } });
- flushSync();
- expect(target.querySelector('path.veil')).toBeNull();
- unmount(live);
- target.remove();
+it('leaves the click to the map while a pin is armed', () => {
+ const { target, done } = render({ armed: true, pins: [{ point: [1, 48], expect: 'found', ok: null }] });
+ expect(target.querySelector('.mark').classList.contains('armed')).toBe(true);
+ done();
+});
+
+it('draws no frame and no veil: a check is its pins and nothing around them', () => {
+ const { target, done } = render({ pins: [{ point: [1, 48], expect: 'found', ok: null }] });
+ expect(target.querySelector('svg')).toBeNull();
+ expect(target.querySelector('.ground-name')).toBeNull();
+ done();
});
diff --git a/frontend/src/tools/detect/CheckMarks.svelte b/frontend/src/tools/detect/CheckMarks.svelte
index fd2fb89..ed03d49 100644
--- a/frontend/src/tools/detect/CheckMarks.svelte
+++ b/frontend/src/tools/detect/CheckMarks.svelte
@@ -1,15 +1,12 @@
<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.
- *
- * The ground outside the frame is veiled. The rules' preview covers the whole
- * view, which opens with a margin around the check, so without the veil the
- * painted ground ran past the frame and read as the frame being off.
+ * The pins of the check on the map: a filled ring where a candidate should
+ * come out and a struck ring where none should, green or red once the check
+ * has been tested with the rules as they stand. A press on one reads the
+ * rules under it, to turn it or take it away. While a pin is armed the map
+ * takes the click instead, so a pin can be dropped beside another.
*/
- let { engine, marks = [], ground = null } = $props();
+ let { engine, pins = [], armed = false, selected = null, onpick = () => {} } = $props();
let revision = $state(0);
$effect(() => {
@@ -18,76 +15,43 @@
});
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 },
+ return pins.map((pin, index) => ({
+ ...pin,
+ index,
+ at: engine?.latLngToContainerPoint({ lon: pin.point[0], lat: pin.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]);
- const points = corners.map((point) => `${point.x},${point.y}`).join(' ');
- // Everything but the frame: a ring far past any screen, the frame cut out of it.
- const veil = `M-1e5,-1e5H1e5V1e5H-1e5Z M${corners.map((point) => `${point.x},${point.y}`).join(' L')}Z`;
- return { points, veil, 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' : ''}`;
+ const words = (pin) => `${pin.expect === 'found' ? 'Should be found' : 'Should stay empty'}${
+ pin.ok === true ? ', and it is' : pin.ok === false ? ', and it is not' : ''}`;
</script>
-{#if frame}
- <svg class="ground" aria-hidden="true">
- <path class="veil" d={frame.veil} fill-rule="evenodd" />
- <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 placed as pin (pin.index)}
+ <button type="button" class="mark pin-{pin.expect}" class:pass={pin.ok === true} class:fail={pin.ok === false}
+ class:selected={selected === pin.index} class:armed
+ style:left={`${pin.at.x}px`} style:top={`${pin.at.y}px`} title={words(pin)} aria-label={`Pin ${pin.index + 1}: ${words(pin)}`}
+ onclick={() => onpick(pin.index)}></button>
{/each}
<style>
- .ground {
- position: absolute;
- inset: 0;
- z-index: 550;
- width: 100%;
- height: 100%;
- overflow: visible;
- pointer-events: none;
- }
- .ground polygon { fill: none; stroke: #f8fafc; stroke-width: 1.5; stroke-dasharray: 6 4; }
- .ground .veil { fill: rgb(0 0 0 / 0.5); }
- .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;
+ width: 18px;
+ height: 18px;
+ padding: 0;
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;
+ background: transparent;
+ box-shadow: 0 0 0 1px rgb(0 0 0 / 0.65), 0 1px 5px rgb(0 0 0 / 0.45);
+ cursor: pointer;
+ transition: transform 0.12s var(--ease), box-shadow 0.12s var(--ease);
}
+ .mark.armed { pointer-events: none; }
+ .mark:hover { transform: translate(-50%, -50%) scale(1.15); }
+ .mark.selected { box-shadow: 0 0 0 1px rgb(0 0 0 / 0.65), 0 0 0 4px rgb(255 255 255 / 0.35); }
+ .mark:focus-visible { outline: 2px solid var(--accent); outline-offset: 3px; }
.mark.pass { --ring: #4ade80; }
.mark.fail { --ring: #f87171; }
.mark.pin-found::after {
@@ -102,7 +66,7 @@
position: absolute;
top: 50%;
left: -2px;
- width: 16px;
+ width: 18px;
height: 2px;
background: var(--ring);
transform: rotate(-45deg);
diff --git a/frontend/src/tools/detect/DetectHome.svelte b/frontend/src/tools/detect/DetectHome.svelte
index ce7d145..908f929 100644
--- a/frontend/src/tools/detect/DetectHome.svelte
+++ b/frontend/src/tools/detect/DetectHome.svelte
@@ -6,7 +6,10 @@
* reviewed and done with, a routine is a place you keep coming back to.
*/
import Icon from '../../components/Icon.svelte';
- import { isActive, plural, ruleLabel, runDays, runState, savedGroups } from '../../lib/map/detections.js';
+ import SearchInput from '../../components/SearchInput.svelte';
+ import {
+ ROUTINE_SEARCH_FROM, isActive, plural, routineMatches, ruleLabel, runDays, runState, savedGroups,
+ } from '../../lib/map/detections.js';
let {
tab = 'routines',
@@ -22,6 +25,8 @@
oncancel = () => {},
onopen = () => {},
onopenrun = () => {},
+ oncolour = () => {},
+ onruncolour = () => {},
ondelete = () => {},
onhover = () => {},
/** Put the map on some ground, so a layer turned on is a layer seen. */
@@ -32,6 +37,10 @@
const single = (method) => !!methods.find((entry) => entry.id === method)?.single;
const idle = $derived(routines.filter((item) => !item.active));
+ let routineSearch = $state('');
+ const searchable = $derived(routines.length >= ROUTINE_SEARCH_FROM);
+ const listed = $derived(searchable && routineSearch.trim()
+ ? routines.filter((item) => routineMatches(item, routineSearch)) : routines);
const groups = $derived(savedGroups(routines, passes));
/** Groups folded shut; every group opens unfolded. */
let folded = $state({});
@@ -58,7 +67,12 @@
<section aria-label="Routines">
{#if routines.length > 1}
<div class="row head">
- <span class="grow"></span>
+ {#if searchable}
+ <SearchInput bind:value={routineSearch} placeholder="Search routines…" width="100%"
+ count={routineSearch.trim() ? `${listed.length}/${routines.length}` : null} />
+ {:else}
+ <span class="grow"></span>
+ {/if}
<button class="btn btn-sm" disabled={busy || !idle.length} onclick={onrunall}
title="Queue every routine that is not already working">
<Icon name="play" size={11} /> Run all
@@ -68,11 +82,13 @@
{#if !routines.length}
<div class="empty">
<p>No routine in this case yet.</p>
- <p class="hint">A routine is an area, what to look for there and what each pass compares against.</p>
<button class="btn btn-sm" onclick={() => onnew('routine')}>Create a routine</button>
</div>
{/if}
- {#each routines as item (item.id)}
+ {#if searchable && !listed.length}
+ <p class="none">No routine matches “{routineSearch.trim()}”.</p>
+ {/if}
+ {#each listed as item (item.id)}
{@const state = runState(item.active ?? item.latest)}
<article class="card" style={`--tint: ${item.colour || 'var(--accent)'}`}>
<div class="row">
@@ -106,7 +122,6 @@
{#if !passes.length}
<div class="empty">
<p>Nothing has been swept in this case yet.</p>
- <p class="hint">A run lands here when it finishes, whichever tool you are in.</p>
<button class="btn btn-sm" onclick={() => onnew('once')}>Sweep an area once</button>
</div>
{/if}
@@ -115,10 +130,22 @@
{@const allOn = shown.length > 0 && shown.every((layer) => layer.visible)}
<div class="group" style={`--tint: ${group.colour || 'var(--text-3)'}`}>
<div class="row group-head">
- <button class="fold grow" aria-expanded={!folded[group.id]}
+ <button class="fold-toggle" aria-label={`${folded[group.id] ? 'Expand' : 'Collapse'} ${group.title}`}
+ title={folded[group.id] ? 'Expand group' : 'Collapse group'}
+ aria-expanded={!folded[group.id]}
onclick={() => (folded = { ...folded, [group.id]: !folded[group.id] })}>
<Icon name={folded[group.id] ? 'chevronRight' : 'chevronDown'} size={12} />
- {#if group.kind === 'routine'}<span class="swatch" aria-hidden="true"></span>{/if}
+ </button>
+ {#if group.kind === 'routine'}
+ <label class="colour-control" title={`Colour of ${group.title}`}>
+ <span class="swatch" style:background={group.colour || '#38bdf8'} aria-hidden="true"></span>
+ <input type="color" aria-label={`Colour of ${group.title}`}
+ value={group.colour || '#38bdf8'} disabled={busy}
+ onchange={(event) => oncolour(group, event.currentTarget.value)} />
+ </label>
+ {/if}
+ <button class="fold grow" aria-expanded={!folded[group.id]}
+ onclick={() => (folded = { ...folded, [group.id]: !folded[group.id] })}>
<span class="name">{group.title}</span>
<small>{plural(group.runs.length, 'run')}</small>
</button>
@@ -142,6 +169,14 @@
{@const layer = layerOf(run)}
{@const name = rowName(group, run)}
<div class="row single">
+ {#if group.kind === 'once'}
+ <label class="colour-control" title={`Colour of ${run.title}`}>
+ <span class="swatch" style:background={run.colour || 'var(--text-3)'} aria-hidden="true"></span>
+ <input type="color" aria-label={`Colour of ${run.title}`}
+ value={run.colour || '#38bdf8'} disabled={busy || isActive(run)}
+ onchange={(event) => onruncolour(run, event.currentTarget.value)} />
+ </label>
+ {/if}
<button class="past grow" disabled={busy} onclick={() => onopenrun(run)}>
{#if group.kind === 'routine'}
<span class={state.tone}>{state.text}</span>
@@ -182,87 +217,99 @@
</div>
<style>
- .home { display: grid; gap: 16px; }
- section { display: grid; gap: 8px; }
+ .home { display: grid; gap: 18px; }
+ section { display: grid; gap: 0; }
+ .head { gap: 8px; min-height: 36px; padding-bottom: 8px; }
+ .head :global(.search-box) { flex: 1 1 auto; min-width: 0; }
+ .none { margin: 0; padding: 14px 4px; border-top: 1px solid var(--border); color: var(--text-2); font-size: var(--fs-sm); }
.empty {
display: grid;
- gap: 4px;
- padding: 14px 12px;
- border: 1px dashed var(--border);
- border-radius: var(--r-sm);
- text-align: center;
+ gap: 7px;
+ padding: 18px 4px;
+ border-top: 1px solid var(--border);
+ text-align: left;
}
- .empty p { margin: 0; font-size: var(--fs-xs); color: var(--text-2); }
- .empty button { justify-self: center; margin-top: 4px; }
+ .empty p { margin: 0; font-size: var(--fs-sm); color: var(--text-2); }
+ .empty button { justify-self: start; margin-top: 4px; }
.card {
+ position: relative;
display: grid;
- gap: 3px;
- padding: 8px 6px 8px 10px;
- border: 1px solid var(--border);
- border-left: 3px solid var(--tint);
- border-radius: var(--r-sm);
- background: var(--bg-2);
+ gap: 5px;
+ padding: 12px 4px 13px 15px;
+ border-top: 1px solid var(--border);
+ background: transparent;
}
- .card .row { gap: 2px; }
+ .card::before {
+ position: absolute;
+ top: 15px;
+ bottom: 15px;
+ left: 3px;
+ width: 3px;
+ background: var(--tint);
+ content: '';
+ }
+ .card:hover { background: var(--bg-2); }
+ .card .row { gap: 4px; }
.title {
min-width: 0;
overflow: hidden;
color: var(--text-1);
- font-size: var(--fs-sm);
- font-weight: 600;
+ font-size: var(--fs-md);
+ font-weight: 650;
text-align: left;
text-overflow: ellipsis;
white-space: nowrap;
}
.title:hover:not(:disabled) { color: var(--accent); }
.go { color: var(--accent); }
- .note, .meta, .state { margin: 0; font-size: var(--fs-xs); line-height: 1.4; }
+ .note, .meta, .state { margin: 0; font-size: var(--fs-xs); line-height: 1.5; }
.note { color: var(--text-2); }
- .meta { color: var(--text-3); }
+ .meta { color: var(--text-2); }
.state { color: var(--text-2); }
- .state.new { color: var(--accent); font-weight: 600; }
+ .state.new { color: var(--info); font-weight: 600; }
.state.busy { color: var(--info); }
.state.warn { color: var(--warn); }
progress { width: 100%; height: 6px; accent-color: var(--accent); }
.past {
display: grid;
- gap: 1px;
+ gap: 3px;
min-width: 0;
- padding: 4px 6px;
- border-radius: var(--r-sm);
+ padding: 8px 6px;
color: var(--text-2);
font-size: var(--fs-xs);
text-align: left;
}
.past:hover:not(:disabled) { background: var(--bg-3); }
- .past span { color: var(--text-1); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
- .past small { color: var(--text-2); font-size: 10.5px; }
- .past small.new { color: var(--accent); font-weight: 600; }
+ .past span { color: var(--text-1); font-size: var(--fs-sm); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+ .past small { color: var(--text-2); font-size: var(--fs-xs); }
+ .past small.new { color: var(--info); font-weight: 600; }
.past small.busy { color: var(--info); }
.past small.warn { color: var(--warn); }
- .past small.what { color: var(--text-3); }
- .past span.new { color: var(--accent); font-weight: 600; }
+ .past small.what { color: var(--text-2); }
+ .past span.new { color: var(--info); font-weight: 600; }
.past span.busy { color: var(--info); }
.past span.warn { color: var(--warn); }
- .single { gap: 2px; padding-left: 14px; }
- .group { display: grid; gap: 2px; }
- .group-head { gap: 2px; }
- .fold {
+ .single { gap: 4px; padding: 0 2px 0 16px; border-top: 1px solid var(--border); }
+ .group { display: grid; gap: 0; border-top: 1px solid var(--border); }
+ .group-head { gap: 4px; min-height: 42px; }
+ .fold, .fold-toggle {
display: flex;
align-items: center;
- gap: 6px;
min-width: 0;
- padding: 3px 4px;
+ padding: 6px 4px;
border-radius: var(--r-sm);
color: var(--text-2);
- font-size: 10.5px;
- font-weight: 700;
- letter-spacing: 0.04em;
+ font-size: var(--fs-sm);
+ font-weight: 600;
text-align: left;
- text-transform: uppercase;
}
- .fold:hover { background: var(--bg-2); color: var(--text-1); }
+ .fold { gap: 6px; }
+ .fold:hover, .fold-toggle:hover { background: var(--bg-2); color: var(--text-1); }
.fold .name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.fold small { flex: 0 0 auto; color: var(--text-3); font-weight: 400; letter-spacing: 0; text-transform: none; white-space: nowrap; }
- .swatch { flex: 0 0 auto; width: 8px; height: 8px; border-radius: 2px; background: var(--tint); }
+ .colour-control { position: relative; flex: 0 0 18px; display: grid; place-items: center; height: 22px; cursor: pointer; }
+ .colour-control .swatch { width: 8px; height: 8px; border-radius: 2px; }
+ .colour-control:hover .swatch, .colour-control:focus-within .swatch { outline: 1px solid var(--text-1); outline-offset: 2px; }
+ .colour-control input { position: absolute; inset: 0; width: 100%; height: 100%; padding: 0; opacity: 0; cursor: pointer; }
+ .colour-control input:disabled { cursor: default; }
</style>
diff --git a/frontend/src/tools/detect/DetectPanel.svelte b/frontend/src/tools/detect/DetectPanel.svelte
index cc0acce..3315c43 100644
--- a/frontend/src/tools/detect/DetectPanel.svelte
+++ b/frontend/src/tools/detect/DetectPanel.svelte
@@ -15,6 +15,7 @@
import { ensureCase, reloadCase, toast } from '../../lib/state.svelte.js';
import { detectRuns, refreshRuns } from '../../lib/detectRuns.svelte.js';
import { clone, zoneRing } from '../../lib/map/analyzers.js';
+ import { passBefore } from '../../lib/map/detectWhen.js';
import { recipeCapability } from '../../lib/map/analyzerRules.js';
import { containsPoint } from '../../lib/measure.js';
import { detectionsWithRuns, isActive, plural } from '../../lib/map/detections.js';
@@ -31,6 +32,10 @@
let {
caseId,
collapsed = $bindable(false),
+ dockWidth = 380,
+ maxDockWidth = () => 720,
+ onwidth = () => {},
+ onwidthend = () => {},
/** Whether Detect holds the whole screen, and the way in and out of it. */
fullscreen = false,
onfullscreen = () => {},
@@ -47,6 +52,8 @@
blinking = $bindable(false),
/** Whether a run's results are open, which holds the map on them. */
reviewing = $bindable(false),
+ /** The run being reviewed; the map isolates its overlay without changing saved visibility. */
+ focusedRunId = $bindable(null),
/** Every watched area of the case, for the map to draw while the list is up. */
areaGroups = $bindable([]),
/** The areas the pointer is on, drawn heavier on the map. */
@@ -64,20 +71,47 @@
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). */
+ /** The bench 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. */
+ /** The map's view, for the builder to look up passes 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,
+ /** The Copernicus layers on offer and a way to frame a place, which the builder uses. */
passLayers = [],
onfly = () => {},
} = $props();
const TITLES = { new: 'New detection', review: 'Results', library: 'Analyzers' };
+ let resizing = $state(false);
+ let stopResize = () => {};
+ function startResize(event) {
+ if (event.button !== 0) return;
+ event.preventDefault();
+ stopResize();
+ resizing = true;
+ const startX = event.clientX;
+ const startWidth = dockWidth;
+ const move = (next) => onwidth(startWidth + startX - next.clientX);
+ const end = () => { stopResize(); onwidthend(); };
+ stopResize = () => {
+ window.removeEventListener('pointermove', move);
+ window.removeEventListener('pointerup', end);
+ window.removeEventListener('pointercancel', end);
+ resizing = false;
+ };
+ window.addEventListener('pointermove', move);
+ window.addEventListener('pointerup', end);
+ window.addEventListener('pointercancel', end);
+ }
+ function resizeKey(event) {
+ const next = event.key === 'ArrowLeft' ? dockWidth + 20
+ : event.key === 'ArrowRight' ? dockWidth - 20
+ : event.key === 'Home' ? 300 : event.key === 'End' ? maxDockWidth() : null;
+ if (next === null) return;
+ event.preventDefault();
+ onwidth(next);
+ onwidthend();
+ }
+ $effect(() => () => stopResize());
let catalogue = $state(null);
let lists = $state({ zones: [], followups: [], areas: [] });
@@ -125,12 +159,16 @@
const detection = $derived(routines.find((row) => row.id === detectionId) ?? null);
/** What a recipe's method can do; an analyzer of your own answers from its rules. */
const capabilityOf = (recipe) => recipeCapability(recipe, catalogue?.methods ?? []);
+ const launchOrderInvalid = (item) => !capabilityOf(item.recipe).single && item.area_dates.some((pair) =>
+ !passBefore(item.date_rule === 'latest_previous' && item.lastPasses[pair.area_id] || pair.a,
+ pair.b, capabilityOf(item.recipe).sensor === 'sentinel1'));
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(() => { focusedRunId = view === 'review' ? current?.id ?? null : null; });
$effect(() => {
if (view === 'review') return;
bare = false;
@@ -172,11 +210,13 @@
async function refresh(id = caseId) {
if (!id) return;
const epoch = generation;
- const [zoneSets, followups, areas] = await Promise.all([
- api.get(`${base(id)}/zones`), api.get(`${base(id)}/followups`), api.get(`${base(id)}/areas`),
+ // Reading groups can promote drawings from older area sets into shared areas.
+ const groups = await api.get(`${base(id)}/zones`);
+ const [followups, areas] = await Promise.all([
+ api.get(`${base(id)}/followups`), api.get(`${base(id)}/areas`),
]);
if (epoch !== generation) return;
- lists = { zones: zoneSets, followups, areas };
+ lists = { zones: groups, followups, areas };
// Opening Detect on a case that already watches ground should show that
// ground, not the home view it has nothing to do with. Once per case: after
// that the camera is the analyst's.
@@ -234,6 +274,17 @@
});
});
+ // A routine's chosen colour paints all of its saved overlays, including
+ // earlier runs. Their recorded imagery and results remain as they were.
+ $effect(() => {
+ const colours = new Map(lists.followups.map((item) => [item.id, item.colour]));
+ const updated = layers.map((layer) => {
+ const colour = colours.get(layer.input?.followup_id) || layer.display_colour || null;
+ return layer.displayColour === colour ? layer : { ...layer, displayColour: colour };
+ });
+ if (updated.some((layer, index) => layer !== layers[index])) layers = updated;
+ });
+
// A run under review that is still working is read again until it settles.
$effect(() => {
if (!pending || !caseId) return;
@@ -282,6 +333,7 @@
onleavepass();
view = 'home';
draft = null;
+ launch = null;
detectionId = null; detail = null; findings = [];
zones = []; selectedZone = null; drawing = 'select';
}
@@ -290,6 +342,7 @@
manual = null;
onleavepass();
offer = null;
+ launch = null;
draft = seed;
selectedZone = null; drawing = 'select';
view = 'new';
@@ -331,10 +384,12 @@
async function editDetection(id) {
const epoch = generation;
- const body = await api.get(`${base()}/followups/${id}`);
+ const [body, lastPasses] = await Promise.all([
+ api.get(`${base()}/followups/${id}`), api.get(`${base()}/followups/${id}/last-passes`),
+ ]);
if (epoch !== generation) return;
zones = clone(body.zones);
- startWizard({ body, followupId: id, kind: 'routine' });
+ startWizard({ body, followupId: id, kind: 'routine', lastPasses });
}
async function openItem(kind, id) {
@@ -342,9 +397,17 @@
if (kind === 'areas') { openTab('areas'); return; }
if (kind === 'runs') return openRun(id);
if (kind === 'followups') return openDetection(id);
- const set = await api.get(`${base()}/zones/${id}`);
- zones = clone(set.zones);
- startWizard({ kind: 'once', zonesId: id, zonesTitle: set.title });
+ const group = await api.get(`${base()}/zones/${id}`);
+ if (group.pending_review?.length) { openTab('areas'); return; }
+ if (group.area_ids) {
+ if (group.area_ids.length > 32) { openTab('areas'); return; }
+ const shared = await api.get(`${base()}/areas`);
+ zones = group.area_ids.map((areaId) => shared.find((area) => area.id === areaId))
+ .filter(Boolean).map(areaZone);
+ } else {
+ zones = clone(group.zones ?? []);
+ }
+ startWizard({ kind: 'once' });
}
function newDetection(kind) {
@@ -376,6 +439,7 @@
}
function back() {
+ if (launch) { launch = null; onleavepass(); return; }
if (view === 'library') {
view = libraryFrom === 'new' && draft ? 'new' : libraryFrom === 'detection' && detection ? 'detection' : 'home';
return;
@@ -398,13 +462,21 @@
*/
async function submit({ input, followupId, kind, run }) {
const owner = await ensureCase();
+ let runStatus = run ? 'queued' : '';
if (kind === 'routine') {
const saved = followupId
? await api.put(`${base(owner.id)}/followups/${followupId}`, input)
: await api.post(`${base(owner.id)}/followups`, input);
if (run) {
const started = await api.post(`${base(owner.id)}/followups/${saved.id}/run`, {});
+ runStatus = started.status ?? 'queued';
+ if (runStatus === 'failed' || runStatus === 'no_new_imagery')
+ toast(started.message || 'No new eligible pass for these areas', runStatus === 'failed' ? 'danger' : 'info');
if (started.duplicates) repeatRequest = started;
+ if (runStatus === 'queued') {
+ const skipped = started.area_runs?.map((row) => row.message).filter((message) => message?.includes('Skipped '));
+ if (skipped?.length) toast(skipped.join(' '), 'info', 7000);
+ }
}
draft = null;
await Promise.all([refresh(owner.id), refreshRuns(owner.id)]);
@@ -412,25 +484,38 @@
await openDetection(saved.id);
} else {
const started = await api.post(`${base(owner.id)}/runs`, input);
+ if (!started.id) { error = started.message || 'No area could be checked'; return; }
if (started.duplicates) { repeatRequest = started; return; }
draft = null;
await Promise.all([refresh(owner.id), refreshRuns(owner.id)]);
await reloadCase();
await openRun(started.id);
}
- toast(run ? 'Detection started. Carry on elsewhere; the top bar follows it.' : 'Routine saved', 'ok', 5000);
+ if (!run || runStatus === 'queued') toast(run ? 'Detection started. Carry on elsewhere; the top bar follows it.' : 'Routine saved', 'ok', 5000);
}
async function runDetection(item, pass = {}) {
const started = await api.post(`${base()}/followups/${item.id}/run`, pass);
- if (started.duplicates) repeatRequest = started;
- else { launch = null; onleavepass(); }
+ if (started.status === 'failed') { error = started.message || 'No area could be checked'; return; }
+ if (started.status === 'no_new_imagery') {
+ toast(started.message || 'No new eligible pass for these areas', 'info');
+ launch = null; onleavepass();
+ } else if (started.duplicates) repeatRequest = started;
+ else {
+ const count = started.area_runs?.filter((row) => row.status === 'pending').length ?? item.zones.length;
+ toast(`${plural(count, 'area')} queued`, 'ok');
+ launch = null; onleavepass();
+ }
+ const skippedCloud = started.area_runs?.map((row) => row.message).filter((message) => message?.includes('Skipped '));
+ if (started.status !== 'no_new_imagery' && skippedCloud?.length) toast(skippedCloud.join(' '), 'info', 7000);
await refreshRuns(caseId);
}
async function prepareLaunch(item) {
- const body = await api.get(`${base()}/followups/${item.id}`);
- launch = { ...body, area_dates: (body.area_dates ?? body.zones.map((zone) => ({
+ const [body, lastPasses] = await Promise.all([
+ api.get(`${base()}/followups/${item.id}`), api.get(`${base()}/followups/${item.id}/last-passes`),
+ ]);
+ launch = { ...body, lastPasses: lastPasses ?? {}, area_dates: (body.area_dates ?? body.zones.map((zone) => ({
area_id: zone.id, a: body.a, b: body.b, date_rule: body.date_rule,
}))).map((pair) => ({ ...pair, b: { ...pair.b, date: '' } })) };
}
@@ -448,6 +533,20 @@
toast('Snapshot saved in SAT layers', 'ok');
}
+ async function changeRoutineColour(group, colour) {
+ await api.patch(`${base()}/followups/${group.id}/colour`, { colour });
+ await refresh();
+ await reloadCase();
+ }
+
+ async function changeRunColour(run, colour) {
+ await api.patch(`${base()}/runs/${run.id}/colour`, { colour });
+ layers = layers.map((layer) => layer.id === run.id
+ ? { ...layer, display_colour: colour, displayColour: colour } : layer);
+ if (current?.id === run.id) current = { ...current, display_colour: colour };
+ await refreshRuns(caseId);
+ }
+
function nextRepeat() {
repeatRequest = repeatQueue[0] ?? null;
repeatQueue = repeatQueue.slice(1);
@@ -457,10 +556,13 @@
async function runAll() {
const problems = [];
let started = 0;
+ let current = 0;
for (const item of routines.filter((entry) => !entry.active)) {
try {
const response = await api.post(`${base()}/followups/${item.id}/run`, {});
- if (response.duplicates) repeatQueue = [...repeatQueue, response];
+ if (response.status === 'no_new_imagery') current++;
+ else if (response.status === 'failed') problems.push(`${item.title}: ${response.message}`);
+ else if (response.duplicates) repeatQueue = [...repeatQueue, response];
else started++;
} catch (e) {
problems.push(`${item.title}: ${e.message}`);
@@ -468,6 +570,7 @@
}
await refreshRuns(caseId);
if (started) toast(`${plural(started, 'routine')} queued`, 'ok');
+ if (current) toast(`${plural(current, 'routine')} already up to date`, 'info');
if (!repeatRequest && repeatQueue.length) nextRepeat();
if (problems.length) error = problems.join(' · ');
}
@@ -526,16 +629,6 @@
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;
@@ -553,50 +646,89 @@
}
</script>
-<aside class="cmp-dock" class:collapsed aria-label="Detect">
- <nav class="dock-tabs" class:rail={collapsed} aria-label="Detect sections">
- <button class="cmp-icon" aria-label={collapsed ? 'Expand Detect panel' : 'Collapse Detect panel'}
- title="Toggle Detect panel (])" onclick={() => (collapsed = !collapsed)}>
- <Icon name={collapsed ? 'chevronLeft' : 'chevronRight'} size={16} />
- </button>
- {#each [['routines', 'Routines', 'clock'], ['saved', 'Saved', 'bookmark'], ['areas', 'Areas', 'polygon']] as [id, label, icon]}
- <button class="section-tab" class:on={tab === id && view === 'home'} aria-label={label} aria-pressed={tab === id && view === 'home'}
- title={label} onclick={() => openTab(id)}><Icon name={icon} size={15} />{#if !collapsed}{label}{/if}</button>
- {/each}
- <button class="cmp-icon" aria-label="Analyzers" title="Make and tune what detections look for"
- onclick={openLibrary}><Icon name="sliders" size={15} /></button>
- <button class="cmp-icon" class:on={fullscreen} aria-pressed={fullscreen}
- aria-label={fullscreen ? 'Exit full screen' : 'Full screen'}
- title={fullscreen ? 'Back to the window (Esc)' : 'Detect on the whole screen'}
- onclick={onfullscreen}><Icon name={fullscreen ? 'minimize' : 'maximize'} size={15} /></button>
- </nav>
+<aside class="cmp-dock" class:collapsed class:resizing class:compact={dockWidth <= 340} aria-label="Detect"
+ style:flex-basis={collapsed ? undefined : `${dockWidth}px`}>
+ {#if !collapsed}
+ <button type="button" class="dock-resizer" aria-label="Resize Detect panel"
+ title="Drag to resize; double-click to reset"
+ onpointerdown={startResize} onkeydown={resizeKey}
+ ondblclick={() => { onwidth(380); onwidthend(); }}></button>
+ {/if}
+ <div class="dock-chrome" class:rail={collapsed}>
+ <header class="dock-heading">
+ {#if !collapsed}<strong>Detect</strong>{/if}
+ <button class="cmp-icon" aria-label={collapsed ? 'Expand Detect panel' : 'Collapse Detect panel'}
+ title="Toggle Detect panel (])" onclick={() => (collapsed = !collapsed)}>
+ <Icon name={collapsed ? 'chevronLeft' : 'chevronRight'} size={16} />
+ </button>
+ {#if !collapsed}
+ <button class="cmp-icon" aria-label="Analyzers" title="Edit analyzers"
+ onclick={openLibrary}><Icon name="sliders" size={15} /></button>
+ <button class="cmp-icon" class:on={fullscreen} aria-pressed={fullscreen}
+ aria-label={fullscreen ? 'Exit full screen' : 'Full screen'}
+ title={fullscreen ? 'Exit full screen' : 'Full screen'}
+ onclick={onfullscreen}><Icon name={fullscreen ? 'minimize' : 'maximize'} size={15} /></button>
+ {/if}
+ </header>
+ <nav class="dock-tabs" class:rail={collapsed} aria-label="Detect sections">
+ {#each [['routines', 'Routines', 'clock'], ['saved', 'Saved', 'bookmark'], ['areas', 'Areas', 'polygon']] as [id, label, icon]}
+ <button class="section-tab" class:on={tab === id && view === 'home'} aria-label={label} aria-pressed={tab === id && view === 'home'}
+ title={label} onclick={() => openTab(id)}><Icon name={icon} size={15} />{#if !collapsed}{label}{/if}</button>
+ {/each}
+ </nav>
+ {#if collapsed}
+ <div class="rail-tools">
+ <button class="cmp-icon" aria-label="Analyzers" title="Edit analyzers"
+ onclick={openLibrary}><Icon name="sliders" size={15} /></button>
+ <button class="cmp-icon" class:on={fullscreen} aria-pressed={fullscreen}
+ aria-label={fullscreen ? 'Exit full screen' : 'Full screen'}
+ title={fullscreen ? 'Exit full screen' : 'Full screen'}
+ onclick={onfullscreen}><Icon name={fullscreen ? 'minimize' : 'maximize'} size={15} /></button>
+ </div>
+ {/if}
+ </div>
<div class="dock-content" hidden={collapsed}>
- <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>
+ <div class="new-action" class:quiet={view !== 'home' || !!launch} bind:this={newActionEl}>
+ <button class="btn btn-primary create-trigger" aria-expanded={picking}
+ onclick={() => (picking = !picking)}>
+ <Icon name="plus" size={15} /> <span>New detection</span>
+ <Icon name={picking ? 'chevronUp' : 'chevronDown'} size={14} />
+ </button>
{#if picking}
<!-- The kind is the first question because it changes every one after
it, so each says in a line what it commits you to. -->
<div class="new-menu cmp-glass" role="group" aria-label="New detection">
<button class="kind" aria-label="New one pass" onclick={() => newDetection('once')}>
- <strong>One pass</strong><small>Sweep two dates you name, review it, done.</small>
+ <span class="kind-copy"><strong>One pass</strong><small>Choose dates for one sweep.</small></span>
</button>
<button class="kind" aria-label="New routine" onclick={() => newDetection('routine')}>
- <strong>Routine</strong><small>Ground you come back to. Each run picks its own pass.</small>
+ <span class="kind-copy"><strong>Routine</strong><small>Watch the same areas over time.</small></span>
</button>
</div>
{/if}
</div>
- {#if view !== 'home'}
+ {#if launch || view !== 'home'}
<header>
<button class="cmp-icon" aria-label="Back" title="Back" onclick={back}>
<Icon name="chevronLeft" size={15} />
</button>
- <strong>{view === 'new' ? kindTitle : view === 'detection' ? 'Routine' : TITLES[view]}</strong>
+ <strong>{launch ? `Run ${launch.title}` : view === 'new' ? kindTitle : view === 'detection' ? 'Routine' : TITLES[view]}</strong>
</header>
{/if}
- {#if !catalogue}
+ {#if launch}
+ <div class="cmp-dock-body launch-body">
+ <AreaDates zones={launch.zones} bind:pairs={launch.area_dates} single={!!capabilityOf(launch.recipe).single}
+ routine previous={launch.date_rule === 'latest_previous'} lastPasses={launch.lastPasses}
+ sensor={capabilityOf(launch.recipe).sensor} {onshow} />
+ {#if error}<p class="warn" role="alert">{error}</p>{/if}
+ <button class="btn btn-primary" disabled={busy || launchOrderInvalid(launch)}
+ onclick={() => act(() => runDetection(launch, { area_dates: clone(launch.area_dates) }))}>
+ Check for new passes
+ </button>
+ </div>
+ {:else if !catalogue}
<div class="cmp-dock-body">
{#if error}<p class="warn" role="alert">{error}</p>{/if}
<p class="hint">Reading the local analyzer library…</p>
@@ -607,7 +739,8 @@
survives a detour to make the analyzer it needs. -->
<div class="pane" hidden={view !== 'new'}>
{#key draft}
- <DetectWizard {caseId} {catalogue} areaSets={lists.zones} areas={lists.areas} seed={draft} {offer} {busy} failure={error}
+ <DetectWizard {caseId} {catalogue} areaGroups={lists.zones} areas={lists.areas} seed={draft} {offer} {busy} failure={error}
+ onopenareas={() => openTab('areas')}
bind:zones bind:drawing bind:selectedZone bind:showZones
{onfocus} {onusecurrentview} {onshow} onlibrary={openLibrary}
onareas={(id) => refresh(id)} onsubmit={(request) => act(() => submit(request))} />
@@ -619,7 +752,7 @@
<div class="cmp-dock-body">
{#if error}<p class="warn" role="alert">{error}</p>{/if}
{#if tab === 'areas'}
- <AreasPanel {caseId} areas={lists.areas} {selectedArea} routines={lists.followups} bind:hidden={hiddenAreas} bind:zones bind:drawing bind:selectedZone
+ <AreasPanel {caseId} areas={lists.areas} groups={lists.zones} {selectedArea} routines={lists.followups} bind:hidden={hiddenAreas} bind:zones bind:drawing bind:selectedZone
onrefresh={() => refresh()} {onusecurrentview} {onframe} />
{:else}
<DetectHome {tab} {routines} passes={runs} methods={catalogue.methods} {busy} bind:layers
@@ -628,6 +761,8 @@
oncancel={(run) => act(() => cancelRun(run))}
onopen={(item) => act(() => openDetection(item.id))}
onopenrun={(run) => act(() => openRun(run.id))}
+ oncolour={(group, colour) => act(() => changeRoutineColour(group, colour))}
+ onruncolour={(run, colour) => act(() => changeRunColour(run, colour))}
ondelete={(kind, row) => act(() => removeItem(kind, row))}
{onframe} onexport={(kind, id) => act(() => exportLayer(kind, id))}
onhover={(id) => {
@@ -674,24 +809,14 @@
{/if}
</div>
{:else if view === 'library'}
- <AnalyzerLibrary bind:this={library} {catalogue} onchanged={loadCatalogue} bind:builder {viewBounds} {onshow} {onleavepass}
- {mapView} layers={passLayers} {onfly} {onblink}
+ <AnalyzerLibrary bind:this={library} {catalogue} onchanged={loadCatalogue} bind:builder {viewBounds}
+ layers={passLayers} {onfly}
onsaved={(recipe) => { if (draft) offer = recipe.id; }} />
{/if}
{/if}
</div>
</aside>
-{#if launch}
- <Modal title={`Run ${launch.title}`} width="760px" onclose={() => { launch = null; onleavepass(); }}>
- <AreaDates zones={launch.zones} bind:pairs={launch.area_dates} single={!!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'}
- </button>
- </Modal>
-{/if}
{#if repeatRequest}
<Modal title="Already run between these dates" width="560px" onclose={nextRepeat}>
{#each repeatRequest.duplicates as match (`${match.run_id}-${match.area_id}`)}
@@ -703,24 +828,49 @@
{/if}
<style>
+ .cmp-dock { position: relative; min-width: 300px; max-width: 720px; }
.cmp-dock.collapsed { flex: 0 0 42px; width: 42px; min-width: 42px; }
+ .dock-resizer { position: absolute; z-index: 10; top: 0; bottom: 0; left: -4px; width: 8px;
+ padding: 0; border: 0; background: transparent; cursor: col-resize; touch-action: none; }
+ .dock-resizer:hover, .dock-resizer:focus-visible, .resizing .dock-resizer {
+ background: var(--accent-soft); outline: 1px solid var(--accent); }
.dock-content { display: flex; flex: 1; flex-direction: column; min-height: 0; }
.dock-content[hidden] { display: none; }
- .dock-content > header { display: flex; align-items: center; gap: 7px; padding: 6px 10px; border-bottom: 1px solid var(--border); }
- .dock-content > header strong { flex: 1; font-size: var(--fs-xs); }
- .dock-tabs { display: flex; align-items: center; gap: 2px; padding: 5px; border-bottom: 1px solid var(--border); }
- .dock-tabs.rail { flex-direction: column; }
- .section-tab { display: flex; flex: 1; align-items: center; justify-content: center; gap: 5px; min-height: 30px; padding: 5px; border-radius: var(--r-sm); font-size: var(--fs-xs); color: var(--text-2); }
- .section-tab:hover { background: var(--bg-2); color: var(--text-1); }
- .section-tab.on { color: var(--accent); background: var(--accent-soft); }
- .rail .section-tab { flex: 0 0 32px; width: 32px; }
- .new-action { position: relative; padding: 8px 10px; }
+ .dock-content > header { display: flex; align-items: center; gap: 7px; padding: 10px 12px; border-bottom: 1px solid var(--border); }
+ .dock-content > header strong { flex: 1; font-size: var(--fs-sm); }
+ .dock-chrome { flex: 0 0 auto; border-bottom: 1px solid var(--border); }
+ .dock-heading { display: flex; align-items: center; gap: 3px; min-height: 42px; padding: 5px 8px 3px 13px; }
+ .dock-heading strong { flex: 1; min-width: 0; font-size: var(--fs-md); font-weight: 650; }
+ .dock-tabs { display: flex; align-items: center; gap: 0; padding: 0 8px; }
+ .section-tab { display: flex; flex: 1; align-items: center; justify-content: center; gap: 6px;
+ min-width: 0; min-height: 38px; padding: 6px 4px 8px; border-bottom: 2px solid transparent;
+ font-size: var(--fs-xs); font-weight: 600; color: var(--text-2); }
+ .compact .section-tab { gap: 0; font-size: 0; }
+ .section-tab:hover { color: var(--text-1); background: var(--bg-2); }
+ .section-tab.on { color: var(--text-1); border-bottom-color: var(--accent); }
+ .dock-chrome.rail { display: flex; flex: 1; flex-direction: column; width: 42px; }
+ .rail .dock-heading { justify-content: center; min-height: 40px; padding: 5px; }
+ .rail .dock-tabs { flex-direction: column; gap: 2px; padding: 0 5px; }
+ .rail .section-tab { flex: 0 0 32px; width: 32px; min-height: 32px; padding: 5px;
+ border-bottom: 0; border-left: 2px solid transparent; }
+ .rail .section-tab.on { border-left-color: var(--accent); }
+ .rail-tools { display: grid; gap: 2px; margin-top: auto; padding: 7px 5px; border-top: 1px solid var(--border); }
+ .new-action { position: relative; padding: 11px 12px; border-bottom: 1px solid var(--border); }
.new-action > button { width: 100%; }
- .new-menu { position: absolute; top: 100%; left: 10px; right: 10px; z-index: 700; display: grid; gap: 2px; padding: 6px; }
- .kind { display: grid; gap: 2px; padding: 7px 9px; border-radius: var(--r-sm); text-align: left; }
- .kind:hover { background: var(--bg-3); }
- .kind strong { font-size: var(--fs-xs); }
- .kind small { color: var(--text-3); font-size: 10.5px; line-height: 1.35; }
+ .create-trigger { display: flex; align-items: center; justify-content: flex-start; gap: 7px; min-height: 36px; padding: 7px 11px; font-weight: 650; }
+ .create-trigger span { flex: 1; text-align: left; }
+ .quiet .create-trigger { border: 1px solid var(--border); color: var(--text-1); background: var(--bg-2); }
+ .quiet .create-trigger:hover { background: var(--bg-3); }
+ .new-menu { position: absolute; top: calc(100% + 2px); left: 12px; right: 12px; z-index: 700;
+ display: grid; padding: 5px 9px; border: 1px solid var(--border-strong);
+ border-radius: var(--r-sm); background: var(--bg-1); box-shadow: var(--shadow-2); }
+ .kind { min-width: 0; padding: 10px 7px; text-align: left; }
+ .kind + .kind { border-top: 1px solid var(--border); }
+ .kind:hover, .kind:focus-visible { background: var(--bg-2); }
+ .kind:focus-visible { outline: 2px solid var(--accent); outline-offset: -2px; }
+ .kind-copy { display: grid; gap: 2px; min-width: 0; }
+ .kind strong { color: var(--text-1); font-size: var(--fs-sm); }
+ .kind small { color: var(--text-2); font-size: var(--fs-xs); line-height: 1.4; }
.pane { display: contents; }
.pane[hidden] { display: none; }
.cmp-dock-body-host { display: contents; }
diff --git a/frontend/src/tools/detect/DetectPanel.test.js b/frontend/src/tools/detect/DetectPanel.test.js
index 27113f8..04c2402 100644
--- a/frontend/src/tools/detect/DetectPanel.test.js
+++ b/frontend/src/tools/detect/DetectPanel.test.js
@@ -48,6 +48,15 @@ function slide(value) {
slider.dispatchEvent(new Event('input', { bubbles: true }));
flushSync();
}
+async function typeWhenDay(buttonLabel, fieldLabel, value) {
+ labelled(buttonLabel).click(); await settle();
+ const details = target.querySelector('.manual-date');
+ if (!details.open) { details.querySelector('summary').click(); await settle(); }
+ const field = target.querySelector(`[aria-label="${fieldLabel}"]`);
+ field.value = value;
+ field.dispatchEvent(new Event('input', { bubbles: true }));
+ await settle();
+}
const area = [{ id: 'area', name: 'Area', kind: 'rect', points: [[2, 48], [2.001, 48.001]] }];
const WATCH = 'abcdef123456';
@@ -133,8 +142,8 @@ it('shows a routine with what it is for and where its last run stands', async ()
expect(target.textContent).toContain('2026-09-06 · 3 to review');
labelled('Run Harbour weekly').click(); await settle();
expect(post).not.toHaveBeenCalled();
- expect(document.querySelector('[aria-label="Dates per area"]')).not.toBe(null);
- button('Run this area').click(); await settle();
+ expect(target.querySelector('[aria-label="Dates for Area"]')).not.toBe(null);
+ button('Check for new passes').click(); await settle();
expect(post).toHaveBeenCalledWith(`/api/cases/case-a/analysis/followups/${WATCH}/run`, {
area_dates: [expect.objectContaining({ area_id: 'area', b: expect.objectContaining({ date: '' }) })],
});
@@ -202,6 +211,54 @@ it('groups the saved runs by routine, and puts one on the map beside its trash',
expect(target.textContent).not.toContain('2026-09-06 · 3 to review');
});
+it('changes a saved routine colour from its square without folding the group', async () => {
+ let current = watchRow({ colour: '#38bdf8' });
+ const body = watchBody();
+ get.mockImplementation(async (path) => {
+ if (path === '/api/compare/analyzers') return catalogue();
+ if (path === `/api/cases/case-a/analysis/followups/${WATCH}`) return structuredClone(body);
+ if (path.endsWith('/followups')) return [structuredClone(current)];
+ if (path.endsWith('/runs')) return [runRow()];
+ return [];
+ });
+ patch.mockImplementation(async (_, payload) => {
+ current = { ...current, colour: payload.colour };
+ return payload;
+ });
+ await open();
+ button('Saved').click(); await settle();
+ const picker = target.querySelector('input[aria-label="Colour of Harbour weekly"]');
+ expect(picker.value).toBe('#38bdf8');
+ picker.value = '#22d3ee';
+ picker.dispatchEvent(new Event('change', { bubbles: true })); await settle();
+ expect(patch).toHaveBeenCalledWith(`/api/cases/case-a/analysis/followups/${WATCH}/colour`,
+ { colour: '#22d3ee' });
+ expect(target.querySelector('input[aria-label="Colour of Harbour weekly"]').value).toBe('#22d3ee');
+ expect(target.querySelector('.fold[aria-expanded="true"]')).not.toBe(null);
+});
+
+it('changes a one pass colour without changing its recorded analyzer', async () => {
+ let once = runRow({ title: 'Port sweep', followup_id: null, colour: '#f6a81a' });
+ get.mockImplementation(async (path) => {
+ if (path === '/api/compare/analyzers') return catalogue();
+ if (path.endsWith('/runs')) return [structuredClone(once)];
+ return [];
+ });
+ patch.mockImplementation(async (_, payload) => {
+ once = { ...once, colour: payload.colour };
+ return { display_colour: payload.colour };
+ });
+ await open();
+ button('Saved').click(); await settle();
+ const picker = target.querySelector('input[aria-label="Colour of Port sweep"]');
+ expect(picker.value).toBe('#f6a81a');
+ picker.value = '#eab308';
+ picker.dispatchEvent(new Event('change', { bubbles: true })); await settle();
+ expect(patch).toHaveBeenCalledWith(`/api/cases/case-a/analysis/runs/${RUN}/colour`,
+ { colour: '#eab308' });
+ expect(target.querySelector('input[aria-label="Colour of Port sweep"]').value).toBe('#eab308');
+});
+
it('reshapes a shared area on the map, saying what its routines will sweep', async () => {
const ring = [[2, 48], [2.01, 48], [2.01, 48.01], [2, 48.01], [2, 48]];
const shared = { id: 'aaaaaaaaaaaa', name: 'North site', colour: '#38bdf8', geometry: { type: 'Polygon', coordinates: [ring] } };
@@ -239,6 +296,227 @@ it('reshapes a shared area on the map, saying what its routines will sweep', asy
expect(put).toHaveBeenCalledTimes(1);
});
+it('shows shared groups and ungrouped areas in Where without selecting an area twice', async () => {
+ const ring = [[2, 48], [2.01, 48], [2.01, 48.01], [2, 48.01], [2, 48]];
+ const harbor = { id: 'aaaaaaaaaaaa', name: 'Harbor', colour: '#38bdf8',
+ geometry: { type: 'Polygon', coordinates: [ring] } };
+ const river = { ...harbor, id: 'bbbbbbbbbbbb', name: 'River' };
+ answer({
+ '/api/cases/case-a/analysis/areas': [harbor, river],
+ '/api/cases/case-a/analysis/zones': [
+ { id: '111111111111', title: 'Ports', area_ids: [harbor.id], position: 0 },
+ { id: '222222222222', title: 'Priority', area_ids: [harbor.id], position: 1 },
+ ],
+ });
+ post.mockResolvedValue({ id: '333333333333' });
+ await open();
+ button('New detection').click(); await settle();
+ labelled('New one pass').click(); await settle();
+ const where = target.querySelector('[aria-label="Where to look"]');
+ expect(where.textContent).toContain('Ungrouped');
+ expect(where.textContent).toContain('River');
+ labelled('Use Ports').click(); await settle();
+ labelled('Use Priority').click(); await settle();
+ expect(where.querySelectorAll('.area-row')).toHaveLength(1);
+ const search = where.querySelector('[aria-label="Search areas or groups"]');
+ search.value = 'River'; search.dispatchEvent(new Event('input', { bubbles: true })); await settle();
+ expect(where.textContent).not.toContain('Ports');
+ expect(where.textContent).toContain('River');
+ search.value = ''; search.dispatchEvent(new Event('input', { bubbles: true })); await settle();
+ button('River').click(); await settle();
+ expect(where.querySelectorAll('.area-row')).toHaveLength(2);
+ [...where.querySelectorAll('summary')].find((node) => node.textContent === 'Save selection as group').click();
+ const name = where.querySelector('[aria-label="Group name"]');
+ name.value = 'My sweep'; name.dispatchEvent(new Event('input', { bubbles: true })); await settle();
+ button('Save group').click(); await settle();
+ expect(post).toHaveBeenCalledWith('/api/cases/case-a/analysis/zones', {
+ title: 'My sweep', area_ids: [harbor.id, river.id],
+ });
+});
+
+it('asks which shape a migrated group should use before offering it in Where', async () => {
+ const ring = [[2, 48], [2.01, 48], [2.01, 48.01], [2, 48.01], [2, 48]];
+ const current = { id: 'aaaaaaaaaaaa', name: 'Harbor', colour: '#38bdf8',
+ geometry: { type: 'Polygon', coordinates: [ring] } };
+ const saved = { ...current, id: 'bbbbbbbbbbbb', name: 'Harbor saved shape' };
+ const review = { saved_area_id: saved.id, current_area_id: current.id, name: 'Harbor' };
+ answer({
+ '/api/cases/case-a/analysis/areas': [current, saved],
+ '/api/cases/case-a/analysis/zones': [
+ { id: '111111111111', title: 'Ports', area_ids: [saved.id], position: 0, pending_review: [review] },
+ ],
+ });
+ put.mockResolvedValue({});
+ const onframe = vi.fn();
+ await open({ onframe });
+ button('New detection').click(); await settle();
+ labelled('New one pass').click(); await settle();
+ expect(labelled('Use Ports').disabled).toBe(true);
+ button('Review saved shapes in Areas').click(); await settle();
+ expect(target.textContent).toContain('Choose which shape this group should use.');
+ button('Show saved').click(); await settle();
+ expect(onframe).toHaveBeenCalledWith([{ kind: 'polygon', points: ring }]);
+ button('Use current').click(); await settle();
+ expect(put).toHaveBeenCalledWith('/api/cases/case-a/analysis/zones/111111111111', {
+ title: 'Ports', area_ids: [current.id], position: 0, pending_review: [],
+ });
+ expect(del).not.toHaveBeenCalled();
+});
+
+it('reorders groups and adds an area to another group without copying it', async () => {
+ const ring = [[2, 48], [2.01, 48], [2.01, 48.01], [2, 48.01], [2, 48]];
+ const harbor = { id: 'aaaaaaaaaaaa', name: 'Harbor', colour: '#38bdf8',
+ geometry: { type: 'Polygon', coordinates: [ring] } };
+ answer({
+ '/api/cases/case-a/analysis/areas': [harbor],
+ '/api/cases/case-a/analysis/zones': [
+ { id: '111111111111', title: 'Ports', area_ids: [harbor.id], position: 0 },
+ { id: '222222222222', title: 'Priority', area_ids: [], position: 1 },
+ ],
+ });
+ put.mockResolvedValue({});
+ await open();
+ button('Areas').click(); await settle();
+ starts('Ports').click(); await settle();
+ const add = target.querySelector('[aria-label="Add Harbor to group"]');
+ add.value = '222222222222'; add.dispatchEvent(new Event('change', { bubbles: true })); await settle();
+ expect(put).toHaveBeenCalledWith('/api/cases/case-a/analysis/zones/222222222222',
+ { title: 'Priority', area_ids: [harbor.id], position: 1, pending_review: [] });
+ expect(put).not.toHaveBeenCalledWith('/api/cases/case-a/analysis/areas/aaaaaaaaaaaa', expect.anything());
+
+ const drag = labelled('Drag group Ports');
+ const event = new Event('dragstart', { bubbles: true });
+ Object.defineProperty(event, 'dataTransfer', { value: { setData: () => {}, effectAllowed: '' } });
+ drag.dispatchEvent(event);
+ const priorityHead = target.querySelector('[aria-label="Drop into Priority"]');
+ priorityHead.dispatchEvent(new Event('dragover', { bubbles: true, cancelable: true }));
+ await settle();
+ expect(priorityHead.classList.contains('landing-after')).toBe(true);
+ priorityHead.dispatchEvent(new Event('drop', { bubbles: true }));
+ await settle();
+ expect(priorityHead.classList.contains('landing-after')).toBe(false);
+ expect(put).toHaveBeenCalledWith('/api/cases/case-a/analysis/zones/111111111111',
+ { title: 'Ports', area_ids: [harbor.id], position: 1, pending_review: [] });
+
+ const areaDrag = new Event('dragstart', { bubbles: true });
+ Object.defineProperty(areaDrag, 'dataTransfer', { value: { setData: () => {}, effectAllowed: '' } });
+ labelled('Drag Harbor').dispatchEvent(areaDrag);
+ priorityHead.dispatchEvent(new Event('dragover', { bubbles: true, cancelable: true }));
+ await settle();
+ expect(priorityHead.classList.contains('landing-area')).toBe(true);
+ priorityHead.dispatchEvent(new Event('drop', { bubbles: true }));
+ await settle();
+ expect(priorityHead.classList.contains('landing-area')).toBe(false);
+ expect(put).toHaveBeenCalledWith('/api/cases/case-a/analysis/zones/111111111111',
+ { title: 'Ports', area_ids: [], position: 0, pending_review: [] });
+ expect(put).toHaveBeenCalledWith('/api/cases/case-a/analysis/zones/222222222222',
+ { title: 'Priority', area_ids: [harbor.id], position: 1, pending_review: [] });
+});
+
+it('orders ungrouped areas and creates an empty group in Areas', async () => {
+ const ring = [[2, 48], [2.01, 48], [2.01, 48.01], [2, 48.01], [2, 48]];
+ const harbor = { id: 'aaaaaaaaaaaa', name: 'Harbor', colour: '#38bdf8',
+ geometry: { type: 'Polygon', coordinates: [ring] } };
+ const river = { ...harbor, id: 'bbbbbbbbbbbb', name: 'River' };
+ answer({ '/api/cases/case-a/analysis/areas': [harbor, river] });
+ put.mockResolvedValue({});
+ post.mockResolvedValue({ id: '111111111111' });
+ await open();
+ button('Areas').click(); await settle();
+ const drag = new Event('dragstart', { bubbles: true });
+ Object.defineProperty(drag, 'dataTransfer', { value: { setData: () => {}, effectAllowed: '' } });
+ labelled('Drag River').dispatchEvent(drag);
+ const harborRow = target.querySelector('[role="group"][aria-label="Harbor"]');
+ harborRow.dispatchEvent(new Event('dragover', { bubbles: true, cancelable: true }));
+ await settle();
+ expect(harborRow.classList.contains('landing-before')).toBe(true);
+ harborRow.dispatchEvent(new Event('drop', { bubbles: true }));
+ await settle();
+ expect(harborRow.classList.contains('landing-before')).toBe(false);
+ expect(put).toHaveBeenCalledWith('/api/cases/case-a/analysis/areas/bbbbbbbbbbbb',
+ expect.objectContaining({ position: 0 }));
+ button('New group').click(); await settle();
+ const name = target.querySelector('[aria-label="New group name"]');
+ name.value = 'Ports'; name.dispatchEvent(new Event('input', { bubbles: true })); await settle();
+ button('Create').click(); await settle();
+ expect(post).toHaveBeenCalledWith('/api/cases/case-a/analysis/zones',
+ { title: 'Ports', area_ids: [] });
+});
+
+it('searches the routines once there are more than five', async () => {
+ const names = ['Harbour weekly', 'Airbase apron', 'Río crossing', 'Depot north', 'Quarry', 'Border road'];
+ const rows = names.map((title, i) => watchRow({ id: `abcdef12345${i}`, title, note: '' }));
+ answer({ '/api/cases/case-a/analysis/followups': rows.slice(0, 5) });
+ await open();
+ expect(target.querySelector('[aria-label="Search routines…"]')).toBe(null);
+ unmount(live);
+ answer({ '/api/cases/case-a/analysis/followups': rows });
+ await open();
+ const search = target.querySelector('[aria-label="Search routines…"]');
+ const shown = () => [...target.querySelectorAll('.card .title')].map((node) => node.textContent.trim());
+ expect(shown()).toHaveLength(6);
+ search.value = 'rio'; search.dispatchEvent(new Event('input', { bubbles: true })); await settle();
+ expect(shown()).toEqual(['Río crossing']);
+ expect(target.textContent).toContain('1/6');
+ search.value = 'nowhere'; search.dispatchEvent(new Event('input', { bubbles: true })); await settle();
+ expect(shown()).toEqual([]);
+ expect(target.textContent).toContain('No routine matches “nowhere”.');
+});
+
+it('starts every area group folded, hides a whole group at once, and shuts a menu on a press elsewhere', async () => {
+ const ring = [[2, 48], [2.01, 48], [2.01, 48.01], [2, 48.01], [2, 48]];
+ const harbor = { id: 'aaaaaaaaaaaa', name: 'Harbor', colour: '#38bdf8',
+ geometry: { type: 'Polygon', coordinates: [ring] } };
+ const quay = { ...harbor, id: 'bbbbbbbbbbbb', name: 'Quay' };
+ const river = { ...harbor, id: 'cccccccccccc', name: 'River' };
+ answer({
+ '/api/cases/case-a/analysis/areas': [harbor, quay, river],
+ '/api/cases/case-a/analysis/zones': [
+ { id: '111111111111', title: 'Ports', area_ids: [harbor.id, quay.id], position: 0 },
+ { id: '222222222222', title: 'Rivers', area_ids: [river.id], position: 1 },
+ ],
+ });
+ await open();
+ button('Areas').click(); await settle();
+ // the first group used to open by itself
+ expect([...target.querySelectorAll('.fold')].map((fold) => fold.getAttribute('aria-expanded')))
+ .toEqual(['false', 'false']);
+ expect(labelled('Hide Harbor')).toBe(null);
+
+ labelled('Hide group Ports').click(); await settle();
+ expect(labelled('Show group Ports')).not.toBe(null);
+ starts('Ports').click(); await settle();
+ expect(labelled('Show Harbor')).not.toBe(null);
+ expect(labelled('Show Quay')).not.toBe(null);
+ // one area back on the map makes the group read as shown, and its eye hides it again
+ labelled('Show Quay').click(); await settle();
+ expect(labelled('Hide group Ports')).not.toBe(null);
+ labelled('Hide group Ports').click(); await settle();
+ expect(labelled('Show Quay')).not.toBe(null);
+ labelled('Show group Ports').click(); await settle();
+ expect(labelled('Hide Harbor')).not.toBe(null);
+ expect(labelled('Hide Quay')).not.toBe(null);
+
+ const menu = (name) => target.querySelector(`summary[aria-label="More actions for ${name}"]`).parentElement;
+ const toggle = async (details) => { details.open = !details.open; details.dispatchEvent(new Event('toggle')); await settle(); };
+ await toggle(menu('Harbor'));
+ // a second menu shuts the first
+ await toggle(menu('Quay'));
+ expect(menu('Harbor').open).toBe(false);
+ expect(menu('Quay').open).toBe(true);
+ target.querySelector('[aria-label="Search areas or groups"]').dispatchEvent(new Event('pointerdown', { bubbles: true }));
+ await settle();
+ expect(menu('Quay').open).toBe(false);
+
+ // and the areas step of a new detection folds them the same way
+ button('New detection').click(); await settle();
+ labelled('New one pass').click(); await settle();
+ const where = target.querySelector('[aria-label="Where to look"]');
+ expect([...where.querySelectorAll('.group-fold')].map((fold) => fold.getAttribute('aria-expanded')))
+ .toEqual(['false', 'false']);
+ expect(where.textContent).not.toContain('Harbor');
+});
+
// -- a routine's own page ---------------------------------------------------------
it('opens a routine on what it has found, and runs it again on a chosen pass', async () => {
@@ -265,10 +543,66 @@ it('opens a routine on what it has found, and runs it again on a chosen pass', a
button('Find passes').click(); await settle();
expect(post).toHaveBeenCalledWith('/api/satellite/sentinel/acquisitions', expect.objectContaining({ zones: area }));
button('Use').click(); await settle();
- button('Run this area').click(); await settle();
+ button('Check for new passes').click(); await settle();
expect(post).toHaveBeenCalledWith(`/api/cases/case-a/analysis/followups/${WATCH}/run`, { area_dates: [expect.objectContaining({ b: expect.objectContaining({ date: '2026-09-16' }) })] });
});
+it('shows the last pass per area and leaves a current routine unqueued', async () => {
+ const second = { ...area[0], id: 'second', name: 'Second area' };
+ const body = watchBody({ recipe: structuredClone(recipe), zones: [...area, second], area_dates: [...area, second].map((zone) => ({
+ area_id: zone.id, a: { provider: 'sentinel2', date: '2026-09-01' },
+ b: { provider: 'sentinel2', date: '' }, date_rule: 'latest_previous',
+ })) });
+ answer({
+ '/api/cases/case-a/analysis/followups': [watchRow({ zones: body.zones, areas: 2, method: 'surface' })],
+ [`/api/cases/case-a/analysis/followups/${WATCH}`]: body,
+ [`/api/cases/case-a/analysis/followups/${WATCH}/last-passes`]: {
+ area: { provider: 'sentinel2', date: '2026-09-06' },
+ second: { provider: 'sentinel2', date: '2026-09-07' },
+ },
+ });
+ const onshow = vi.fn();
+ post.mockImplementation(async (path) => path.endsWith('/acquisitions')
+ ? { dates: [{ date: '2026-09-16', cloud: 4, coverage: 1 }], truncated: false }
+ : { status: 'no_new_imagery', message: 'No new pass since 2026-09-07' });
+ await open({ onshow });
+ labelled('Run Harbour weekly').click(); await settle();
+ expect(target.querySelectorAll('.area-date')).toHaveLength(2);
+ expect(target.textContent).toContain('Last completed pass');
+ target.querySelector('.area-date .side button.link').click(); await settle();
+ expect(onshow).toHaveBeenCalledWith(expect.objectContaining({ date: '2026-09-06', side: 'A',
+ area: expect.objectContaining({ id: 'area' }) }));
+ const cards = target.querySelectorAll('.area-date');
+ cards[1].querySelector('button[aria-label="Date B for Second area"]').click(); await settle();
+ expect(cards[1].querySelector('[aria-label="Pass for Second area pass calendar"]')).not.toBe(null);
+ expect(cards[0].querySelector('.pass-calendar')).toBe(null);
+ labelled('Find passes for Second area').click(); await settle();
+ expect(cards[1].querySelector('.passes')).not.toBe(null);
+ expect(cards[0].querySelector('.passes')).toBe(null);
+ await typeWhenDay('Date B for Second area', 'Pass for Second area', '01/09/2026');
+ expect(button('Check for new passes').disabled).toBe(true);
+ button('Use newest').click(); await settle();
+ expect(button('Check for new passes').disabled).toBe(false);
+ button('Check for new passes').click(); await settle();
+ expect(toast).toHaveBeenCalledWith('No new pass since 2026-09-07', 'info');
+ expect(target.querySelector('.launch-body')).toBe(null);
+});
+
+it('resizes the dock through the keyboard and pointer handle', async () => {
+ const onwidth = vi.fn();
+ const onwidthend = vi.fn();
+ await open({ dockWidth: 380, maxDockWidth: () => 720, onwidth, onwidthend });
+ const handle = labelled('Resize Detect panel');
+ handle.dispatchEvent(new KeyboardEvent('keydown', { key: 'Home', bubbles: true }));
+ handle.dispatchEvent(new KeyboardEvent('keydown', { key: 'End', bubbles: true }));
+ expect(onwidth.mock.calls.map(([width]) => width)).toEqual([300, 720]);
+ handle.dispatchEvent(new PointerEvent('pointerdown', { button: 0, clientX: 900, bubbles: true }));
+ window.dispatchEvent(new PointerEvent('pointermove', { clientX: 820 }));
+ window.dispatchEvent(new PointerEvent('pointerup'));
+ expect(onwidth).toHaveBeenLastCalledWith(460);
+ expect(onwidthend).toHaveBeenCalledTimes(3);
+});
+
it('lists a routine\'s runs, and opens one on its candidates', async () => {
const saved = { ...runRow(), engine_version: 2, frames: {}, results: [],
input: { title: 'Harbour weekly', zones: area, recipe: structuredClone(vessels), followup_id: WATCH,
@@ -289,6 +623,22 @@ it('lists a routine\'s runs, and opens one on its candidates', async () => {
// -- building one ------------------------------------------------------------------
+it('opens a saved group from Files after loading its current shared area', async () => {
+ const ring = [[2, 48], [2.01, 48], [2.01, 48.01], [2, 48.01], [2, 48]];
+ const shared = { id: 'bbbbbbbbbbbb', name: 'Harbor', colour: '#38bdf8',
+ geometry: { type: 'Polygon', coordinates: [ring] } };
+ answer({
+ '/api/cases/case-a/analysis/areas': [shared],
+ '/api/cases/case-a/analysis/zones/aaaaaaaaaaaa': {
+ id: 'aaaaaaaaaaaa', title: 'Ports', area_ids: [shared.id], position: 0,
+ },
+ });
+ await open({ opening: 'zones-aaaaaaaaaaaa' });
+ expect(heading()).toBe('Where to look');
+ expect(target.querySelectorAll('[aria-label="Where to look"] .area-row')).toHaveLength(1);
+ expect(target.textContent).toContain('Harbor');
+});
+
it('walks a single pass through its steps and runs it once', async () => {
answer({ '/api/cases/case-a/analysis/zones/aaaaaaaaaaaa': { id: 'aaaaaaaaaaaa', title: 'Port', zones: area } });
post.mockResolvedValue({ id: RUN, status: 'queued', input: {}, results: [], total: 1, progress: 0 });
@@ -304,13 +654,11 @@ it('walks a single pass through its steps and runs it once', async () => {
expect(target.textContent).toContain('Choose A, the picture before.');
// B is the newest pass under the ceiling until a day is asked for, and the
// button says which ceiling rather than promising the newest pass there is
- expect(button('Newest pass under 30% cloud').getAttribute('aria-checked')).toBe('true');
- button('A day I choose').click(); await settle();
- const pass = target.querySelector('[aria-label="Day of B"]');
- pass.value = '06/09/2026'; pass.dispatchEvent(new Event('input', { bubbles: true })); await settle();
+ expect(labelled('Date B').textContent).toContain('Newest pass under 30% cloud');
+ await typeWhenDay('Date B', 'Day of B', '06/09/2026');
expect(target.textContent).toContain('Choose A, the picture before.');
// the passes are listed in the step itself, and only when asked for
- expect(post).not.toHaveBeenCalled();
+ expect(post.mock.calls.every(([path]) => path.endsWith('/acquisitions'))).toBe(true);
post.mockImplementationOnce(async () => ({
dates: [{ date: '2026-08-01', cloud: 2, granules: 1, coverage: 1 }], truncated: false }));
button('Find passes').click(); await settle();
@@ -357,11 +705,8 @@ it('says why a pass did not start, beside the button that started it', async ()
await open({ opening: 'zones-aaaaaaaaaaaa' });
button('Next: What').click(); await settle();
button('Next: When').click(); await settle();
- button('A day I choose').click(); await settle();
- for (const [label, day] of [['Day of A', '01/08/2026'], ['Day of B', '06/09/2026']]) {
- const field = target.querySelector(`[aria-label="${label}"]`);
- field.value = day; field.dispatchEvent(new Event('input', { bubbles: true })); await settle();
- }
+ await typeWhenDay('Date A', 'Day of A', '01/08/2026');
+ await typeWhenDay('Date B', 'Day of B', '06/09/2026');
button('Next: Start').click(); await settle();
button('Run this pass').click(); await settle();
expect(heading()).toBe('Name and start');
@@ -394,13 +739,12 @@ it('asks a routine what each pass compares against, not which day to read', asyn
button('New detection').click(); await settle();
labelled('New routine').click(); await settle();
expect(target.textContent).toContain('New routine');
- button('Port1 area').click(); await settle();
+ labelled('Use Port').click(); await settle();
button('Next: What').click(); await settle();
- button('Next: When').click(); await settle();
- expect(heading()).toBe('Which images, each run');
- expect(target.textContent).toContain('Each run takes the newest pass under 30% cloud as B and compares it with');
expect(ceilingSlider().value).toBe('30');
slide(40);
+ button('Next: When').click(); await settle();
+ expect(heading()).toBe('Which images, each run');
expect(target.textContent).toContain('Each run takes the newest pass under 40% cloud as B');
expect(target.textContent).toContain('The pass before');
expect(target.textContent).toContain('Only the first run');
@@ -444,11 +788,14 @@ it('says which day the newest pass is and why newer ones were skipped, and reads
expect(target.textContent).toContain(
'Now 2026-09-19. Newer: 2026-09-26 (51% cloud), 2026-09-24 (82% cloud), 2026-09-22 (89% cloud).');
// the ceiling sits beside "newest": raised, it takes the 26th and says what that costs
+ button('Back').click(); await settle();
slide(60);
+ button('Next: When').click(); await settle();
expect(button('Newest pass under 60% cloud')).toBeDefined();
expect(target.textContent).toContain('Now 2026-09-26, looked up again when the run starts.');
- expect(target.textContent).toContain('Above 30%, the pass taken can be mostly cloud');
+ button('Back').click(); await settle();
slide(30);
+ button('Next: When').click(); await settle();
expect(target.textContent).not.toContain('Above 30%');
// the analyst has the last word: the cloudier pass is offered, and read
target.querySelector('[aria-label="Use 2026-09-26"] button').click(); await settle();
@@ -479,9 +826,9 @@ it('reads the newest pass for a one-image sweep unless a day is asked for', asyn
expect(target.textContent).toContain('The newest pass under 30% cloud, looked up when the run starts.');
expect(target.querySelector('[aria-label="Day of A"]')).toBe(null);
expect(button('Next: Start').disabled).toBe(false);
- button('A day I choose').click(); await settle();
- expect(button('Next: Start').disabled).toBe(true);
- expect(target.textContent).toContain('Choose the day, or take the newest pass.');
+ labelled('Image date').click(); await settle();
+ expect(target.querySelector('[aria-label="B pass calendar"]')).not.toBe(null);
+ expect(button('Next: Start').disabled).toBe(false);
button('Find passes').click(); await settle();
button('Use').click(); await settle();
button('Next: Start').click(); await settle();
@@ -492,7 +839,7 @@ it('reads the newest pass for a one-image sweep unless a day is asked for', asyn
}));
});
-it('gives every area the same days, and keeps a table for areas that differ', async () => {
+it('shows each area its own dates and pass lookup in When', async () => {
const two = [...area, { id: 'far', name: 'Far', kind: 'rect', points: [[9, 40], [9.001, 40.001]] }];
answer({ '/api/cases/case-a/analysis/zones/aaaaaaaaaaaa': { id: 'aaaaaaaaaaaa', title: 'Port', zones: two } });
post.mockImplementation(async (path) => (path.endsWith('/acquisitions')
@@ -501,18 +848,14 @@ it('gives every area the same days, and keeps a table for areas that differ', as
await open({ opening: 'zones-aaaaaaaaaaaa' });
button('Next: What').click(); await settle();
button('Next: When').click(); await settle();
- expect(target.textContent).toContain('Passes over these areas');
- // one lookup over both, so a pass that covers them all says so
- button('Find passes').click(); await settle();
- expect(post).toHaveBeenCalledWith('/api/satellite/sentinel/acquisitions', expect.objectContaining({ zones: two }));
+ expect(target.querySelectorAll('[aria-label^="Dates for "]')).toHaveLength(2);
+ labelled('Find passes for Area').click(); await settle();
+ expect(post).toHaveBeenCalledWith('/api/satellite/sentinel/acquisitions', expect.objectContaining({ zones: [two[0]] }));
button('A').click(); await settle();
- expect(target.textContent).toContain('The same days for all 2 areas.');
- button('Set them per area…').click(); await settle();
- const far = document.querySelector('[aria-label="Reference for Far"]');
- far.value = '20/07/2026'; far.dispatchEvent(new Event('input', { bubbles: true })); await settle();
- button('Done').click(); await settle();
- expect(target.textContent).toContain('The areas have days of their own.');
- expect(target.textContent).toContain('A 2026-07-20 → B newest pass');
+ labelled('Find passes for Far').click(); await settle();
+ expect(post).toHaveBeenCalledWith('/api/satellite/sentinel/acquisitions', expect.objectContaining({ zones: [two[1]] }));
+ await typeWhenDay('Date A for Far', 'Reference for Far', '20/07/2026');
+ expect(target.textContent).toContain('View A');
button('Next: Start').click(); await settle();
expect(target.textContent).toContain('Its own days for each area');
button('Run this pass').click(); await settle();
@@ -531,17 +874,16 @@ it('asks a routine of one image for nothing but its picture', async () => {
await open();
button('New detection').click(); await settle();
labelled('New routine').click(); await settle();
- button('Port1 area').click(); await settle();
+ labelled('Use Port').click(); await settle();
button('Next: What').click(); await settle();
+ slide(45);
+ expect(target.textContent).toContain('Above 30%, the pass taken can be mostly cloud, and ground under cloud is left out.');
button('Next: When').click(); await settle();
expect(heading()).toBe('Which image, each run');
- expect(target.textContent).toContain('Each run reads the newest pass under 30% cloud over the area.');
expect(button('Find passes')).toBeUndefined();
// its one question is the cloud ceiling, right there, with a word above 30%
expect(target.textContent).not.toContain('Above 30%');
- slide(45);
expect(target.textContent).toContain('Each run reads the newest pass under 45% cloud over the area.');
- expect(target.textContent).toContain('Above 30%, the pass taken can be mostly cloud, and ground under cloud is left out.');
expect(button('Next: Start').disabled).toBe(false);
button('Next: Start').click(); await settle();
expect(target.textContent).toContain('Each run: the newest pass under 45% cloud');
@@ -556,15 +898,14 @@ it('holds a routine to one fixed picture when asked', async () => {
await open();
button('New detection').click(); await settle();
labelled('New routine').click(); await settle();
- button('Port1 area').click(); await settle();
+ labelled('Use Port').click(); await settle();
button('Next: What').click(); await settle();
button('Next: When').click(); await settle();
[...target.querySelectorAll('[role="radio"]')].find((node) => node.textContent.includes('A fixed picture')).click();
await settle();
expect(target.textContent).toContain('Every run compares with');
expect(target.textContent).toContain('Choose A, the picture every run compares with.');
- const day = target.querySelector('[aria-label="Day of A"]');
- day.value = '01/08/2026'; day.dispatchEvent(new Event('input', { bubbles: true })); await settle();
+ await typeWhenDay('Date A', 'Day of A', '01/08/2026');
button('Next: Start').click(); await settle();
expect(target.textContent).toContain('Each run: the newest pass under 30% cloud against 2026-08-01');
button('Save without running').click(); await settle();
@@ -657,16 +998,14 @@ 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('build your own from rules you try on the map, or copy a calibrated built-in');
+ expect(target.textContent).toContain('build your own from rules you prove 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();
expect(button('Copy to tune')).toBeDefined();
button('Back').click(); await settle();
- button('New analyzer').click(); await settle();
- expect(heading()).toBe('Or start from a built-in');
- [...target.querySelectorAll('button.base')].find((b) => b.textContent.includes(recipe.name)).click(); await settle();
+ labelled(`Copy ${recipe.name}`).click(); await settle();
const name = target.querySelector('[aria-label="Analyzer name"]');
expect(name.value).toBe(`${recipe.name} copy`);
name.value = 'Weekly harbour'; name.dispatchEvent(new Event('input', { bubbles: true }));
@@ -695,124 +1034,220 @@ const rulesMethods = [...methods, { id: 'rules', label: 'Your own rules', single
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 });
+ max_rules: 6, max_bands: 6, max_around: 300, max_checks: 12, max_marks: 20, max_check_tiles: 12 }, ...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 });
+const group = (name) => target.querySelector(`[role="group"][aria-label="${name}"]`);
+const inGroup = (name, text) => [...group(name).querySelectorAll('button')].find((b) => b.textContent.trim().startsWith(text));
+const type = (input, value, event = 'input') => { input.value = value; input.dispatchEvent(new Event(event, { bubbles: true })); };
+
+/** What a test of a check sends back: every pin found or left empty as it should, unless told otherwise. */
+const tested = (body, covered = body.check.marks.map((mark) => mark.expect === 'found'), without) => ({
+ ready: true, missing: 0, count: covered.filter(Boolean).length, covered, size: 512, tiles: [], measured: 0.9, without,
+ rules: body.recipe.rules.map(() => ({ share: 0.012, kept: 0.012 })), kept: 0.01,
+ 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 }],
+ readings: body.check.marks.map(() => ({ imaged: true, measured: true, kept: true,
+ rules: body.recipe.rules.map(() => ({ passes: true, value: -0.6, before: 0.8, after: 0.2 })) })) });
-function copernicus(previewed = PREVIEWED, checked = () => ({ ready: true, missing: 0, count: 1, covered: [true] })) {
+function copernicus({ test = (body) => tested(body), plan = () => ({ tiles: 1, missing: 2 }) } = {}) {
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/check/plan') return plan(body);
+ if (path === '/api/compare/analyzers/check') return body.read ? test(body) : { ready: false, missing: 2 };
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' };
});
}
+/** The panel with the bench the map would read, open on a new analyzer of Sentinel-2 and two dates. */
async function openBuilder(props = {}) {
- await open({ viewBounds: () => VIEW, ...props });
+ const { default: Fixture } = await import('./BenchPanel.fixture.svelte');
+ live = mount(Fixture, { target, props: { caseId: 'case-a', viewBounds: () => VIEW, ...props } });
+ await settle();
labelled('Analyzers').click(); await settle();
button('New analyzer').click(); await settle();
- starts('Build your own rules').click(); await settle();
+ starts('Blank').click(); await settle();
+ return benchOf();
}
-
-/** 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();
+const benchOf = async () => (await import('./benchHolder.fixture.svelte.js')).holder.bench;
+
+/** What the console over the map does to make a check: its passes, then its pins. */
+async function makeCheck(bench, points = [{ lon: 2.01, lat: 48.01 }]) {
+ bench.startDraft(); await settle();
+ await bench.lookUpPasses(); await settle();
+ bench.setPass('a', { date: '2026-05-04' });
+ bench.setPass('b', { date: '2026-05-11' });
+ bench.continueDraft();
+ for (const point of points) bench.dropPin(point);
+ bench.finishDraft(); 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 () => {
+const SHIP = { id: 'ships', place: 'Fujairah', when: 'one pass, January 2024', recipe: {
+ id: 'custom', name: 'Ships at anchor', description: '', phenomenon: 'Vessel candidate', method: 'rules', sensor: 'sentinel2',
+ dates: 'one', colour: '#38bdf8', style: 'both', match: 'all', parameters: recipe.parameters,
+ rules: [rule({ measure: 'band', band: 'B08', on: 'b', op: 'ge', value: 0.04 })], checks: [] } };
+
+it('asks what a new analyzer reads before anything else, and offers the examples that fit it', async () => {
+ answer({ '/api/compare/analyzers': rulesCatalogue({ examples: [EXAMPLE, SHIP], radar_layer: '' }) });
+ post.mockImplementation(async (_, body) => ({ ...body, id: 'custom-aaaaaaaaaaaa' }));
+ await open({ viewBounds: () => VIEW });
+ labelled('Analyzers').click(); await settle();
+ button('New analyzer').click(); await settle();
+ expect(heading()).toBe('New analyzer');
+ expect(target.textContent).toContain('What it reads is fixed from here on');
+ // Sentinel-2 and two dates to begin with: the burn fits, the ships do not
+ expect(inGroup('Satellite', 'Sentinel-2').getAttribute('aria-pressed')).toBe('true');
+ expect(inGroup('Dates', 'Two dates').getAttribute('aria-pressed')).toBe('true');
+ expect(labelled('Start from the example Fresh burn')).not.toBe(null);
+ expect(labelled('Start from the example Ships at anchor')).toBe(null);
+ inGroup('Dates', 'One date').click(); await settle();
+ expect(labelled('Start from the example Ships at anchor')).not.toBe(null);
+ expect(labelled('Start from the example Fresh burn')).toBe(null);
+ // radar has no example yet, and says what it needs
+ inGroup('Satellite', 'Sentinel-1').click(); await settle();
+ expect(target.textContent).toContain('No ready example for Sentinel-1 radar · one date yet.');
+ expect(target.textContent).toContain('Needs the Sentinel-1 layer');
+
+ starts('Blank').click(); await settle();
+ expect(heading()).toBe('Build an analyzer');
+ expect(target.querySelector('.reads').textContent.trim()).toBe('Sentinel-1 radar · one date');
+ expect(target.querySelector('[aria-label="Rule 1 polarisation"]')).not.toBe(null);
+ // one date has no before or after to choose, and radar has one thing to measure
+ expect(target.querySelector('[aria-label="Rule 1 reads"]')).toBe(null);
+ expect(target.querySelector('[aria-label="Rule 1 measures"]')).toBe(null);
+ expect(phrase()).toBe('Keeps ground where VV is at least −4.0 dB.');
+});
+
+it('builds an analyzer from rules, proves it on a check made on the map, and keeps it for every case', async () => {
answer({ '/api/compare/analyzers': rulesCatalogue() });
copernicus();
- await openBuilder();
+ const bench = await openBuilder();
expect(heading()).toBe('Build an analyzer');
- expect(target.textContent).toContain('Pick pass A and pass B to try the rules on.');
+ expect(target.querySelector('.reads').textContent.trim()).toBe('Sentinel-2 · two dates');
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
+ // building reads nothing, and with no check on the map there is nothing to test
await debounce(); await settle();
expect(post).not.toHaveBeenCalled();
-
- button('Find passes').click(); await settle();
+ expect(target.querySelector('.strip').textContent).toContain('No check on the map');
+ expect(button('Test').disabled).toBe(true);
+ expect(button('Add to my analyzers').disabled).toBe(true);
+ expect(target.querySelector('.reason').textContent).toBe('Name it to save it.');
+ type(target.querySelector('[aria-label="Analyzer name"]'), 'Cleared ground'); await settle();
+ expect(target.querySelector('.reason').textContent).toBe('Add a check: a place where this analyzer should find something.');
+
+ // the map makes the check: the column waits while it does
+ bench.startDraft(); await settle();
+ expect(target.querySelector('.panel').classList.contains('locked')).toBe(true);
+ expect(target.textContent).toContain('Making a check on the map');
+ await bench.lookUpPasses(); 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();
+ bench.setPass('a', { date: '2026-05-04' });
+ bench.setPass('b', { date: '2026-05-11' });
+ bench.continueDraft();
+ bench.dropPin({ lon: 2.01, lat: 48.01 });
+ bench.finishDraft(); await settle();
+ expect(target.querySelector('.panel').classList.contains('locked')).toBe(false);
+ expect(tab('Checks').textContent.replace(/\s+/g, '')).toBe('Checks1');
+
+ // what testing it costs is asked once, and said on the button
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');
+ const planned = post.mock.calls.filter(([path]) => path === '/api/compare/analyzers/check/plan');
+ expect(planned).toHaveLength(1);
+ expect(planned[0][1]).toMatchObject({ recipe: { method: 'rules', sensor: 'sentinel2', dates: 'two' },
+ check: { name: 'Check 1', a: { date: '2026-05-04' }, b: { date: '2026-05-11' } } });
+ expect(target.querySelector('.strip').textContent).toContain('Check 1');
+ expect(button('Test · 2 requests')).toBeDefined();
+ button('Test · 2 requests').click(); await settle();
+ expect(post).toHaveBeenLastCalledWith('/api/compare/analyzers/check', expect.objectContaining({ read: true, detail: true }));
+ expect(target.querySelector('.strip').textContent).toContain('1 of 1 found');
+ expect(button('Tested').disabled).toBe(true);
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();
+ expect(button('Add to my analyzers').disabled).toBe(false);
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: [],
+ id: 'custom', method: 'rules', name: 'Cleared ground', match: 'all', sensor: 'sentinel2', dates: 'two',
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);
+ rules: [expect.objectContaining({ measure: 'index', index: 'ndvi', on: 'change', op: 'le', value: -0.25 })],
+ checks: [expect.objectContaining({ name: 'Check 1', marks: [{ point: [2.01, 48.01], expect: 'found' }],
+ result: expect.objectContaining({ count: 1, covered: [true] }) })] }));
+});
+
+it('needs a pin where something should be found before it is saved, and a trap alone does not do', async () => {
+ answer({ '/api/compare/analyzers': rulesCatalogue() });
+ copernicus();
+ const bench = await openBuilder();
+ type(target.querySelector('[aria-label="Analyzer name"]'), 'Cleared ground'); await settle();
+ bench.startDraft();
+ await bench.lookUpPasses();
+ bench.setPass('a', { date: '2026-05-04' });
+ bench.setPass('b', { date: '2026-05-11' });
+ bench.continueDraft();
+ bench.arm('empty');
+ bench.dropPin({ lon: 2.02, lat: 48.02 });
+ bench.finishDraft(); await settle();
+ expect(button('Add to my analyzers').disabled).toBe(true);
+ expect(target.querySelector('.reason').textContent).toBe('A check needs a pin where something should be found.');
+ bench.select(bench.checks[0].id);
+ bench.arm('found');
+ bench.dropPin({ lon: 2.03, lat: 48.02 }); await settle();
+ expect(button('Add to my analyzers').disabled).toBe(false);
+});
+
+it('waits for a check being made on the map, and lets it go', async () => {
+ answer({ '/api/compare/analyzers': rulesCatalogue() });
+ copernicus();
+ const bench = await openBuilder();
+ bench.startDraft(); await settle();
+ expect(target.querySelector('.panel').hasAttribute('inert')).toBe(true);
+ expect(target.querySelector('.cmp-dock-foot').hasAttribute('inert')).toBe(true);
+ button('Cancel the check').click(); await settle();
+ expect(bench.draft).toBe(null);
+ expect(target.querySelector('.panel').hasAttribute('inert')).toBe(false);
+ expect(target.textContent).not.toContain('Making a check on the map');
});
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 },
+ sensor: 'sentinel2', dates: 'two', 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 () => {
+it('starts from an example: copies it with its checks, opens on the first and tests them all 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++;
+ const tests = [];
+ copernicus({ test: (body) => {
+ tests.push(body);
// 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] };
- });
+ // and without the second rule the town would lose a pin
+ return tested(body, body.check.id === 'town' ? [true, true] : [true],
+ body.check.id === 'town' ? [{ covered: [true, true] }, { covered: [false, true] }] : undefined);
+ }, plan: () => ({ tiles: 1, missing: 2 }) });
const onfly = vi.fn();
- const onshow = vi.fn();
- await open({ viewBounds: () => VIEW, onfly, onshow });
+ const { default: Fixture } = await import('./BenchPanel.fixture.svelte');
+ live = mount(Fixture, { target, props: { caseId: 'case-a', viewBounds: () => VIEW, onfly } });
+ await settle();
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();
@@ -822,200 +1257,128 @@ it('starts from an example: copies it with its checks, opens on them and reads t
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);
+ // the first check is on the map: its pins are framed, its passes are the imagery
+ const bench = await benchOf();
+ expect(bench.check.name).toBe('The town that burned');
+ expect(onfly).toHaveBeenCalledWith({ bounds: expect.objectContaining({ west: expect.any(Number) }) });
+ expect(bench.imagery).toMatchObject({ mode: 'swipe', a: { date: '2023-08-08' }, b: { date: '2023-08-13', layer: 'SWIR' } });
+ expect(target.textContent).toContain('Before 2023-08-08 → After 2023-08-13');
+
+ // what testing costs is asked for each check, and Test all says the total before it reads anything
+ await debounce(); await settle();
+ expect(tests).toHaveLength(0);
+ expect(button('Test all · up to 4 requests')).toBeDefined();
+ expect(target.textContent).toContain('2 requests to read');
+ button('Test all · up to 4 requests').click(); await settle();
+ expect(tests.map((body) => [body.check.id, body.detail])).toEqual([['town', true], ['reef', false]]);
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');
+
+ // the rules say what the pins would come to without each of them
+ tab('Rules').click(); await settle();
+ expect(target.querySelector('[aria-label="Rule 1 effect"]').textContent).toBe('Without it, no pin changes.');
+ expect(target.querySelector('[aria-label="Rule 2 effect"]').textContent).toBe('Without it, 1 pin would come out wrong.');
+ // and stop saying it once a line has moved, since it was said for the old one
+ type(target.querySelector('[aria-label="Rule 1 value"]'), '0.5', 'change'); await settle();
+ expect(target.querySelector('[aria-label="Rule 1 effect"]')).toBe(null);
});
-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();
+it('gives each analyzer opened in the builder a bench of its own, even when another is already open', async () => {
+ const one = { ...structuredClone(recipe), id: 'custom-aaaaaaaaaaaa', name: 'First', method: 'rules', match: 'all', sensor: 'sentinel2',
+ dates: 'two', rules: [rule({ value: -0.3 })], checks: [] };
+ const two = { ...one, id: 'custom-bbbbbbbbbbbb', name: 'Second', rules: [rule({ value: -0.5 })] };
+ answer({ '/api/compare/analyzers': rulesCatalogue({ custom: [one, two] }) });
+ const props = liveProps({ caseId: null, opening: 'analyzer:custom-aaaaaaaaaaaa', viewBounds: () => VIEW });
+ const { default: Fixture } = await import('./BenchPanel.fixture.svelte');
+ live = mount(Fixture, { target, props });
+ await settle();
+ await settle();
+ const first = await benchOf();
+ expect(first.recipe.name).toBe('First');
+ expect(heading()).toBe('Edit First');
+
+ // asked for from elsewhere while the first is open: the second takes the map, and the first lets go of it
+ props.opening = 'analyzer:custom-bbbbbbbbbbbb'; await settle();
+ const second = await benchOf();
+ expect(second).not.toBe(first);
+ expect(second.recipe.name).toBe('Second');
+ expect(heading()).toBe('Edit Second');
+ expect(target.querySelector('[aria-label="Rule 1 value"]').value).toBe('0.5');
+ // what is made now is kept on the second, not on a bench left over from the first
+ second.startDraft(); await settle();
+ expect(target.querySelector('.panel').classList.contains('locked')).toBe(true);
+ second.cancelDraft(); await settle();
+ expect(first.recipe.checks).toEqual([]);
+ // leaving the builder puts the map back
+ button('Cancel').click(); await settle();
+ expect((await benchOf())).toBe(null);
+});
- // 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');
+it('reads a point on the map and drops a pin from it, and a stricter line turns the check red', async () => {
+ answer({ '/api/compare/analyzers': rulesCatalogue() });
+ let covered = true;
+ copernicus({ test: (body) => tested(body, [covered]) });
+ const bench = await openBuilder();
+ type(target.querySelector('[aria-label="Analyzer name"]'), 'Cleared ground'); await settle();
+ await makeCheck(bench);
+ bench.select(bench.checks[0].id);
+ await debounce(); await settle();
+ button('Test · 2 requests').click(); await settle();
+ expect(target.querySelector('.strip').textContent).toContain('1 of 1 found');
+
+ // a click on the ground reads every rule there, and can leave a pin
+ await bench.probeAt({ lon: 2.02, lat: 48.02 }); await settle();
+ expect(post).toHaveBeenLastCalledWith('/api/compare/analyzers/probe', expect.objectContaining({ point: [2.02, 48.02] }));
+ bench.markProbe('empty'); await settle();
+ expect(bench.marks.map((mark) => mark.expect)).toEqual(['found', 'empty']);
+ expect(target.querySelector('.strip').textContent).toContain('The rules changed since the last test.');
+
+ // a stricter line loses the plot: nothing is reread until the button is pressed
+ covered = false;
+ const tests = () => post.mock.calls.filter(([path, body]) => path === '/api/compare/analyzers/check' && body.read).length;
+ const before = tests();
+ type(target.querySelector('[aria-label="Rule 1 value"]'), '0.6', 'change'); await settle();
+ await debounce(); await settle();
+ expect(tests()).toBe(before);
+ expect(post.mock.calls.filter(([path]) => path === '/api/compare/analyzers/check/plan')).toHaveLength(2);
+ starts('Test again').click(); await settle();
+ expect(tests()).toBe(before + 1);
+ expect(target.querySelector('.strip').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]+$/);
+ expect(post.mock.calls.findLast(([path]) => path === '/api/compare/analyzers/check')[1].recipe.rules[0].value).toBe(-0.6);
});
-it('shows the detections alone on the map, keeps each eye for the way back, and counts an open check', async () => {
+it('shows the detections alone on the map, and keeps each eye for the way back', async () => {
answer({ '/api/compare/analyzers': rulesCatalogue() });
- copernicus(PREVIEWED, () => ({ ready: true, missing: 0, count: 2, covered: [true] }));
- await openBuilder();
+ copernicus();
+ const bench = await openBuilder();
button('Add a rule').click(); await settle();
- await readTheView();
- const eye = (n) => target.querySelector(`button.eye[aria-label$="rule ${n} on the map"]`).getAttribute('aria-pressed');
- const view = (name) => target.querySelector(`[aria-label="What the map shows"]`)
- .querySelector(`button:nth-child(${name === 'Rules' ? 1 : 2})`);
+ const eye = (n) => target.querySelector(`button.dot[aria-label$="rule ${n} on the map"]`).getAttribute('aria-pressed');
labelled('Hide rule 2 on the map').click(); await settle();
expect([eye(1), eye(2)]).toEqual(['true', 'false']);
-
// the detections alone: nothing of the rules is painted, so every eye reads closed
- view('Detections').click(); await settle();
- expect(view('Detections').getAttribute('aria-pressed')).toBe('true');
+ bench.view = 'detections'; await settle();
expect([eye(1), eye(2)]).toEqual(['false', 'false']);
// back to the rules, each eye as it was left
- view('Rules').click(); await settle();
+ bench.view = 'rules'; await settle();
expect([eye(1), eye(2)]).toEqual(['true', 'false']);
-
// an eye pressed from the detections opens its rule and brings the rules back
- view('Detections').click(); await settle();
+ bench.view = 'detections'; await settle();
labelled('Show rule 2 on the map').click(); await settle();
- expect(view('Rules').getAttribute('aria-pressed')).toBe('true');
+ expect(bench.view).toBe('rules');
expect([eye(1), eye(2)]).toEqual(['true', 'true']);
-
- // an open check counts its own frame, which is all the map shows, and the choice rides along
- view('Detections').click(); await settle();
- await live.probeAt({ lon: 2.01, lat: 48.01 }); await settle();
- live.markProbe('found'); await settle();
- await debounce(900); await settle();
- expect(tab('Checks').getAttribute('aria-selected')).toBe('true');
- expect(target.textContent).toContain('2 candidates in “Check 1”');
- expect(target.textContent).not.toContain('candidate on the map');
- expect(view('Detections').getAttribute('aria-pressed')).toBe('true');
-});
-
-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');
+ expect(phrase()).toBe('Keeps ground where NDVI dropped by 0.25 or more and NDVI before is at least 0.40, outside cloud.');
+ button('any rule').click(); await settle();
+ expect(phrase()).toContain('or NDVI before is 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/);
+ expect(phrase()).toMatch(/^Keeps ground where NDVI before is 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');
@@ -1030,13 +1393,13 @@ it('adds, ranks, rewrites and removes rules, and the sentence follows', async ()
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: [] };
+ method: 'rules', sensor: 'sentinel2', dates: 'two', 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();
+ starts('Any surface change').click(); await settle();
+ button('Open 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.');
@@ -1056,7 +1419,7 @@ it('says in the library how an analyzer’s checks last came out', async () => {
answer({ '/api/compare/analyzers': rulesCatalogue({ custom: [own] }) });
await open();
labelled('Analyzers').click(); await settle();
- expect(target.textContent).toContain('2 checks · not run');
+ expect(target.textContent).toContain('2 checks · not tested');
});
// -- review --------------------------------------------------------------------------
@@ -1077,7 +1440,7 @@ it('offers three verdicts, and only the pin reaches the case', async () => {
await open({ opening: `runs-${RUN}` });
expect(target.textContent).toContain('1 of 2');
expect(target.textContent).toContain('Strong · Reflectance moved by 12.3%');
- expect(target.textContent).toContain('Keep stays in this run. Pin creates a place and evidence in Files.');
+ expect(target.textContent).toContain('Keep in this run, or pin the place and evidence to Files.');
// kept here: no pin, no entity, and it stays among what the detection holds
button('Keep').click(); await settle();
diff --git a/frontend/src/tools/detect/DetectReview.show.svelte.test.js b/frontend/src/tools/detect/DetectReview.show.svelte.test.js
index f3676f4..06a6db0 100644
--- a/frontend/src/tools/detect/DetectReview.show.svelte.test.js
+++ b/frontend/src/tools/detect/DetectReview.show.svelte.test.js
@@ -21,12 +21,14 @@ const run = { id: RUN, title: 'Vessels by radar', status: 'ready', progress: 1,
results: [row('0-1', pass), row('0-2', pass), row('0-3', other)],
input: { title: 'Vessels by radar', zones: area, recipe, note: '', a: pass, b: pass, offline: false,
date_rule: 'manual', followup_id: null } };
+/** The run the mocked API serves, so a test can hand it verdicts already given. */
+let served = run;
const catalogue = { builtins: [recipe], custom: [], max_tiles: 4096, max_results: 2000, grid: [13, 512],
methods: [{ id: 'sar-vessels', single: true, sensor: 'sentinel1', frames: 3, sizes: {}, measure: '{value} dB' }] };
vi.mock('../../lib/api.js', () => ({ api: {
get: async (path) => (path === '/api/compare/analyzers' ? structuredClone(catalogue)
- : path.endsWith(`/runs/${RUN}`) ? structuredClone(run) : []),
+ : path.endsWith(`/runs/${RUN}`) ? structuredClone(served) : []),
post: vi.fn(), put: vi.fn(), patch: vi.fn(), del: vi.fn(),
} }));
vi.mock('../../lib/state.svelte.js', () => ({ ensureCase: async () => ({ id: 'case-a' }),
@@ -35,7 +37,7 @@ const { default: Panel } = await import('./DetectPanel.svelte');
let live, target;
const settle = async () => { for (let i = 0; i < 120; i++) await Promise.resolve(); flushSync(); };
-afterEach(() => { if (live) unmount(live); live = null; target?.remove(); });
+afterEach(() => { if (live) unmount(live); live = null; target?.remove(); served = run; });
it('shows a radar pass once, however the map writes it back', async () => {
// what Detect does: the shown pass is read and replaced by a fresh object
@@ -60,3 +62,27 @@ it('shows a radar pass once, however the map writes it back', async () => {
expect(shown.length).toBeLessThanOrEqual(3);
expect([...new Set(shown)]).toEqual(['2026-09-22 02:06:41', '2026-09-10 02:06:40']);
});
+
+it('keeps every verdict tab while another is open, and lands on its first candidate', async () => {
+ served = { ...run, results: [row('0-1', pass), { ...row('0-2', pass), review: 'noted' },
+ { ...row('0-3', other), review: 'kept' }] };
+ target = document.createElement('div'); document.body.append(target);
+ live = mount(Panel, { target, props: { caseId: 'case-a', opening: `runs-${RUN}` } });
+ await settle();
+ const tabs = () => [...target.querySelectorAll('[aria-label="Which candidates to walk"] .chip:not(.order)')]
+ .map((button) => button.textContent.replace(/\s+/g, ' ').trim());
+ const press = async (name) => {
+ [...target.querySelectorAll('.chip')].find((button) => button.textContent.trim().startsWith(name)).click();
+ await settle();
+ };
+ expect(tabs()).toEqual(['All 3', 'To review 1', 'Kept 1', 'Pinned 1']);
+ await press('To review');
+ // counted over the filter, "Kept" read zero here and was gone
+ expect(tabs()).toEqual(['All 3', 'To review 1', 'Kept 1', 'Pinned 1']);
+ await press('Kept');
+ expect(target.textContent).toContain('1 of 1');
+ expect(target.textContent).not.toContain('outside this filter');
+ expect(target.textContent).toContain('Kept in this detection');
+ await press('Pinned');
+ expect(target.textContent).toContain('Kept as a pin in this case');
+});
diff --git a/frontend/src/tools/detect/DetectReview.svelte b/frontend/src/tools/detect/DetectReview.svelte
index da683fa..1939617 100644
--- a/frontend/src/tools/detect/DetectReview.svelte
+++ b/frontend/src/tools/detect/DetectReview.svelte
@@ -67,18 +67,28 @@
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));
+ /** Counted over the whole run, not the filter: counted over "To review",
+ * "Kept" read zero and its tab went missing until "All" was pressed. */
const counts = $derived.by(() => {
const tally = { kept: 0, noted: 0, dismissed: 0, new: 0 };
- for (const row of candidates) tally[row.review] = (tally[row.review] ?? 0) + 1;
+ for (const row of all) tally[row.review] = (tally[row.review] ?? 0) + 1;
return tally;
});
+ /** A tab lands on its own first candidate, not on "outside this filter". */
+ function pickFilter(id) {
+ filter = id;
+ if (!candidates.some((row) => row.id === candidateId) && candidates[0]) {
+ candidateId = candidates[0].id;
+ focus(candidates[0].coordinates);
+ }
+ }
const verdicts = $derived([
counts.kept ? `${counts.kept} pinned` : '',
counts.noted ? `${counts.noted} kept here` : '',
counts.dismissed ? `${counts.dismissed} dismissed` : '',
].filter(Boolean).join(', ') || 'no verdict yet');
const tally = $derived(
- counts.new === 0 ? `All ${candidates.length} reviewed · ${verdicts}`
+ counts.new === 0 ? `All ${all.length} reviewed · ${verdicts}`
: `${counts.new} still to review · ${verdicts}`
);
const previewAlt = $derived(recipeCapability(run.input.recipe, methods).single
@@ -250,7 +260,7 @@
{#if run.message}<p class="hint" role="status">{run.message}</p>{/if}
<!-- "Nothing found" and "never looked" are not the same answer. -->
{#if sweptNote(run.swept)}<p class="warn">{sweptNote(run.swept)}</p>{/if}
- {#if run.status === 'ready' && !candidates.length}<p class="hint">Nothing passed these thresholds.</p>{/if}
+ {#if run.status === 'ready' && !all.length}<p class="hint">Nothing passed these thresholds.</p>{/if}
{#if run.status === 'ready'}
<div class="row"><button class="btn btn-sm" onclick={() => {
adding = !adding;
@@ -284,9 +294,9 @@
<section class="candidate">
<div class="row filters" role="group" aria-label="Which candidates to walk">
{#each [['all', 'All', all.length], ['new', 'To review', counts.new], ['kept', 'Kept', counts.noted], ['pinned', 'Pinned', counts.kept]] as [id, label, n]}
- {#if id === 'all' || n}
+ {#if id === 'all' || n || filter === id}
<button class="chip" class:on={filter === id} aria-pressed={filter === id}
- onclick={() => (filter = id)}>{label} <span class="n">{n}</span></button>
+ onclick={() => pickFilter(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. -->
@@ -342,7 +352,7 @@
{:else if candidate?.review === 'dismissed'}
<button class="link" disabled={busy} onclick={() => act(() => review('new'))}>Put it back among the candidates</button>
{:else}
- <p class="hint">Keep stays in this run. Pin creates a place and evidence in Files.</p>
+ <p class="hint">Keep in this run, or pin the place and evidence to Files.</p>
<p class="keys">K keep · D dismiss · P pin · ← → walk the queue</p>
{/if}
</div>
@@ -383,25 +393,26 @@
.pin-form .check { display: flex; align-items: center; gap: 8px; }
.pin-form fieldset { display: flex; gap: 20px; padding: 8px 10px; border: 1px solid var(--border); border-radius: var(--r-sm); }
.manual { border-bottom: 1px dashed var(--accent); }
- section { display: grid; gap: 7px; }
- section.candidate, section:not(.run) { border-top: 1px solid var(--border); padding-top: 10px; }
- section > strong, .run-head strong { font-size: var(--fs-xs); }
+ section { display: grid; gap: 9px; }
+ section.candidate, section:not(.run) { border-top: 1px solid var(--border); padding-top: 16px; }
+ section > strong, .run-head strong { font-size: var(--fs-md); font-weight: 650; }
.link { color: var(--accent); font-size: var(--fs-xs); text-align: left; }
.link:disabled { opacity: 0.5; }
.link.inline { display: inline; font-family: var(--font-mono); font-size: 11px; }
.centre { text-align: center; }
- .nav { justify-content: space-between; }
- .position { color: var(--text-2); font-size: var(--fs-xs); }
- .filters { flex-wrap: wrap; gap: 4px; }
- .chip { padding: 2px 8px; border: 1px solid var(--border); border-radius: 999px; color: var(--text-2); font-size: 10.5px; }
+ .nav { justify-content: space-between; min-height: 32px; }
+ .position { color: var(--text-1); font-size: var(--fs-sm); font-variant-numeric: tabular-nums; }
+ .filters { flex-wrap: wrap; gap: 2px 12px; border-bottom: 1px solid var(--border); }
+ .chip { min-height: 30px; padding: 4px 1px 6px; border-bottom: 2px solid transparent;
+ color: var(--text-2); font-size: var(--fs-xs); text-align: left; }
.chip:hover { color: var(--text-1); }
- .chip.on { color: var(--accent); border-color: var(--accent); background: var(--accent-soft); }
+ .chip.on { color: var(--text-1); border-bottom-color: var(--accent); }
.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; }
+ .facts { margin: 0; color: var(--text-2); font-size: var(--fs-xs); line-height: 1.55; }
.strength { margin: 0; font-size: var(--fs-xs); font-weight: 600; color: var(--text-1); }
.strength.strong { color: var(--ok); }
.strength.weak { color: var(--text-3); }
@@ -413,9 +424,9 @@
.review-status { display: grid; align-content: center; overflow: auto; }
.verdict-row { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 6px; }
.tally { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
- .preview-open { display: block; width: 100%; padding: 0; border-radius: var(--r-sm); cursor: zoom-in; }
- .preview-open:hover { outline: 1px solid var(--accent); }
- .preview { display: block; width: 100%; height: 210px; object-fit: contain; border-radius: var(--r-sm); background: var(--bg-0); }
+ .preview-open { display: block; width: 100%; padding: 0; border: 1px solid var(--border); cursor: zoom-in; }
+ .preview-open:hover { border-color: var(--accent); }
+ .preview { display: block; width: 100%; height: 210px; object-fit: contain; background: var(--bg-0); }
.big { width: 100%; max-height: 78vh; object-fit: contain; background: var(--bg-0); }
progress { width: 100%; accent-color: var(--accent); }
</style>
diff --git a/frontend/src/tools/detect/DetectWizard.svelte b/frontend/src/tools/detect/DetectWizard.svelte
index 1a24eae..cbe68b7 100644
--- a/frontend/src/tools/detect/DetectWizard.svelte
+++ b/frontend/src/tools/detect/DetectWizard.svelte
@@ -28,7 +28,8 @@
import { plural } from '../../lib/map/detections.js';
import { recipeCapability } from '../../lib/map/analyzerRules.js';
import { openCopernicusSettings } from '../../lib/navigate.js';
- import { ADVISED_MAXCC, uniform, whenNeed, whenSummary } from '../../lib/map/detectWhen.js';
+ import { ADVISED_MAXCC, ceilingWarning, uniform, whenNeed, whenSummary } from '../../lib/map/detectWhen.js';
+ import CloudFilter from '../compare/CloudFilter.svelte';
import AnalyzerSettings from './AnalyzerSettings.svelte';
import AnalyzerSize from './AnalyzerSize.svelte';
import WhenStep from './WhenStep.svelte';
@@ -37,10 +38,10 @@
let {
caseId,
catalogue,
- /** Saved area sets of this case. */
- areaSets = [],
+ /** Ordered area groups shared with the Areas tab. */
+ areaGroups = [],
areas = [],
- /** Where it starts: `{ kind, body, followupId, fromRun, zonesId, zonesTitle }`. */
+ /** Where it starts: `{ kind, body, followupId, fromRun }`. */
seed = {},
/** An analyzer just made in the library, to pick. */
offer = null,
@@ -58,6 +59,7 @@
onsubmit = () => {},
onlibrary = () => {},
onareas = async () => {},
+ onopenareas = () => {},
} = $props();
const EMPTY_SOURCE = { provider: 'sentinel2', date: '', layer: 'TRUE_COLOR', maxcc: ADVISED_MAXCC };
@@ -78,8 +80,11 @@
let against = $state('previous');
let offline = $state(false);
let followupId = $state(null);
- let zonesId = $state(null);
- let zonesTitle = $state('Analysis areas');
+ let lastPasses = $state({});
+ let groupTitle = $state('');
+ let areaSearch = $state('');
+ /** Groups opened by hand; every group starts folded, the first one too. */
+ let openGroups = $state({});
let pairs = $state([]);
/** A one pass reads B on a chosen day rather than the newest pass. */
let chooseB = $state(false);
@@ -117,7 +122,7 @@
// Said here rather than discovered when the run comes back failed. A routine
// that compares each pass with the one before it still needs a first one.
const imageryNeeds = $derived(
- whenNeed({ single: isSingle, routine, against, followupId, pairs, chooseB })
+ whenNeed({ single: isSingle, routine, against, pairs, chooseB, lastPasses, radar })
);
// A locked analyzer can still be picked and read about; a run of it cannot
// start, and saying why here beats a run that comes back failed.
@@ -162,8 +167,6 @@
kind = seed.kind ?? (seed.followupId ? 'routine' : 'once');
if (!seed.body) {
choose(builtins[0]?.id);
- zonesId = seed.zonesId ?? null;
- zonesTitle = seed.zonesTitle ?? zonesTitle;
return;
}
const body = seed.body;
@@ -178,6 +181,7 @@
against = body.date_rule === 'latest_reference' ? 'reference' : 'previous';
chooseB = kind !== 'routine' && (!!body.b?.date || pairs.some((pair) => pair.b?.date));
followupId = seed.followupId ?? null;
+ lastPasses = seed.lastPasses ?? {};
step = seed.followupId ? 4 : 1;
});
@@ -217,37 +221,57 @@
b = { ...b, ...patch };
pairs = pairs.map((pair) => ({ ...pair, a: { ...pair.a, ...patch }, b: { ...pair.b, ...patch } }));
}
+ function setWeather(on) {
+ recipe.parameters = { ...recipe.parameters, ignore_clouds: on, ignore_shadows: on };
+ }
function removeZone(id) {
zones = zones.filter((z) => z.id !== id);
if (selectedZone === id) selectedZone = null;
}
- async function saveAreas(asNew = false) {
- const owner = await ensureCase();
- const base = `/api/cases/${owner.id}/analysis/zones`;
- const data = { title: zonesTitle, zones: clone(zones) };
- const saved = zonesId && !asNew ? await api.put(`${base}/${zonesId}`, data) : await api.post(base, data);
- zonesId = saved.id;
- await onareas(owner.id);
- await reloadCase();
- toast('Areas saved in this case', 'ok');
- }
+ const areaZone = (area) => ({ id: area.id, name: area.name, kind: 'polygon',
+ points: clone(area.geometry.coordinates[0].slice(0, -1)) });
+ const groupZones = (group) => group.area_ids
+ ? group.area_ids.map((id) => areas.find((area) => area.id === id)).filter(Boolean).map(areaZone)
+ : clone(group.zones ?? []);
+ const groupedIds = $derived(new Set(areaGroups.flatMap((group) => group.area_ids ?? [])));
+ const ungrouped = $derived(areas.filter((area) => !groupedIds.has(area.id)));
+ const matching = (name) => name.toLowerCase().includes(areaSearch.trim().toLowerCase());
- async function openAreas(id) {
- const body = await api.get(`/api/cases/${caseId}/analysis/zones/${id}`);
- zones = clone(body.zones);
- zonesTitle = body.title;
- zonesId = id;
- showZones = true;
+ function useGroup(group) {
+ const additions = groupZones(group).filter((zone) => !zones.some((selected) => selected.id === zone.id));
+ if (zones.length + additions.length > 32) return;
+ zones = [...zones, ...additions];
}
- async function removeAreas(id) {
- await api.del(`/api/cases/${caseId}/analysis/zones/${id}`);
- if (zonesId === id) zonesId = null;
- await onareas(caseId);
- await reloadCase();
- toast('Moved to Trash', 'ok');
+ async function saveGroup() {
+ if (!groupTitle.trim()) return;
+ const owner = await ensureCase();
+ const replacements = new Map();
+ try {
+ for (const zone of zones) {
+ if (areas.some((area) => area.id === zone.id)) continue;
+ const ring = zoneRing(zone);
+ const saved = await api.post(`/api/cases/${owner.id}/analysis/areas`, {
+ name: zone.name, colour: recipe.colour,
+ geometry: { type: 'Polygon', coordinates: [[...ring, ring[0]]] },
+ });
+ replacements.set(zone.id, saved.id);
+ }
+ await api.post(`/api/cases/${owner.id}/analysis/zones`, {
+ title: groupTitle.trim(), area_ids: zones.map((zone) => replacements.get(zone.id) ?? zone.id),
+ });
+ groupTitle = '';
+ toast('Group saved', 'ok');
+ } finally {
+ if (replacements.size) {
+ zones = zones.map((zone) => ({ ...zone, id: replacements.get(zone.id) ?? zone.id }));
+ pairs = pairs.map((pair) => ({ ...pair, area_id: replacements.get(pair.area_id) ?? pair.area_id }));
+ }
+ await onareas(owner.id);
+ await reloadCase();
+ }
}
async function saveArea(zone) {
@@ -304,18 +328,58 @@
{#if step === 1}
<section class="step" aria-label="Where to look">
<h3>Where to look</h3>
- <!-- The case's own ground comes first: picking an area it already
- watches is one press, and drawing is for ground it does not. -->
- {#if areas.length}
- <div class="shared">
- {#each areas as area (area.id)}
- {@const on = zones.some((zone) => zone.id === area.id)}
- <button class="area-chip" class:on aria-pressed={on} disabled={!on && zones.length >= 32}
- onclick={() => (on ? removeZone(area.id) : useArea(area))}>
- <span class="swatch" style={`--tint: ${area.colour}`}></span>{area.name}
- </button>
- {/each}
- </div>
+ {#if areas.length || areaGroups.length}
+ <input class="area-search" aria-label="Search areas or groups" placeholder="Search areas or groups…"
+ bind:value={areaSearch} />
+ {#each areaGroups as group (group.id)}
+ {@const members = groupZones(group)}
+ {@const shown = members.filter((zone) => !areaSearch || matching(group.title) || matching(zone.name))}
+ {#if !areaSearch || matching(group.title) || shown.length}
+ <div class="area-group">
+ <div class="area-group-head">
+ <button class="group-fold grow" aria-expanded={!!areaSearch || !!openGroups[group.id]}
+ onclick={() => (openGroups = { ...openGroups, [group.id]: !openGroups[group.id] })}>
+ <Icon name={(areaSearch || openGroups[group.id]) ? 'chevronDown' : 'chevronRight'} size={12} />
+ {group.title} <small>{plural(members.length, 'area')}</small>
+ </button>
+ <button class="btn btn-sm" aria-label={`Use ${group.title}`}
+ disabled={!!group.pending_review?.length || !members.length || zones.length + members.filter((zone) => !zones.some((selected) => selected.id === zone.id)).length > 32}
+ onclick={() => useGroup(group)}>Use</button>
+ </div>
+ {#if group.pending_review?.length}
+ <button class="link" onclick={onopenareas}>Review saved shapes in Areas</button>
+ {/if}
+ {#if areaSearch || openGroups[group.id]}
+ <div class="shared">
+ {#each shown as zone (zone.id)}
+ {@const area = areas.find((item) => item.id === zone.id)}
+ {@const on = zones.some((selected) => selected.id === zone.id)}
+ <button class="area-chip" class:on aria-pressed={on}
+ disabled={!!group.pending_review?.length || (!on && zones.length >= 32)}
+ onclick={() => (on ? removeZone(zone.id) : area ? useArea(area) : (zones = [...zones, zone]))}>
+ <span class="swatch" style={`--tint: ${area?.colour ?? '#38bdf8'}`}></span>{zone.name}
+ </button>
+ {/each}
+ </div>
+ {/if}
+ </div>
+ {/if}
+ {/each}
+ {@const loose = ungrouped.filter((area) => !areaSearch || matching(area.name))}
+ {#if loose.length}
+ <div class="area-group">
+ <div class="area-group-head"><strong>Ungrouped</strong><small>{plural(loose.length, 'area')}</small></div>
+ <div class="shared">
+ {#each loose as area (area.id)}
+ {@const on = zones.some((zone) => zone.id === area.id)}
+ <button class="area-chip" class:on aria-pressed={on} disabled={!on && zones.length >= 32}
+ onclick={() => (on ? removeZone(area.id) : useArea(area))}>
+ <span class="swatch" style={`--tint: ${area.colour}`}></span>{area.name}
+ </button>
+ {/each}
+ </div>
+ </div>
+ {/if}
{/if}
<div class="row wrap">
{#each [['rect', 'Rectangle'], ['polygon', 'Polygon'], ['ellipse', 'Circle']] as [shape, label]}
@@ -352,27 +416,12 @@
tooMany ? '' : `${plural(frames, 'request')} a run, about ${duration}`,
].filter(Boolean).join(' · ')}</p>
{/if}
- {#if areaSets.length}
- <details>
- <summary>Saved area sets · {areaSets.length}</summary>
- {#each areaSets as set (set.id)}
- <div class="row">
- <button class="link grow" disabled={working} onclick={() => act(() => openAreas(set.id))}>
- {set.title}<small>{plural(set.areas ?? 0, 'area')}</small>
- </button>
- <button class="cmp-icon" disabled={working} aria-label={`Delete ${set.title}`} title={`Delete ${set.title}`}
- onclick={() => act(() => removeAreas(set.id))}><Icon name="trash" size={13} /></button>
- </div>
- {/each}
- </details>
- {/if}
{#if zones.length}
<details>
- <summary>Save these areas as a set</summary>
+ <summary>Save selection as group</summary>
<div class="row">
- <input class="grow" aria-label="Area set name" bind:value={zonesTitle} maxlength="120" />
- <button class="btn btn-sm" disabled={working} onclick={() => act(() => saveAreas())}>Save</button>
- {#if zonesId}<button class="btn btn-sm" disabled={working} onclick={() => act(() => saveAreas(true))}>As new</button>{/if}
+ <input class="grow" aria-label="Group name" bind:value={groupTitle} maxlength="120" />
+ <button class="btn btn-sm" disabled={working || !groupTitle.trim()} onclick={() => act(saveGroup)}>Save group</button>
</div>
</details>
{/if}
@@ -385,6 +434,17 @@
<p class="group">Target size</p>
<AnalyzerSize bind:recipe {capability} onpick={(name) => (pickedSize = name)} />
</div>
+ {#if capability.clouds}
+ <CloudFilter clouds={recipe.parameters.ignore_clouds} shadows={recipe.parameters.ignore_shadows}
+ ontoggle={setWeather} />
+ {/if}
+ {#if !radar}
+ <label class="cloud-ceiling">Maximum cloud cover · {b.maxcc}%
+ <input type="range" min="0" max="100" value={b.maxcc} aria-label="Maximum cloud cover"
+ oninput={(event) => setPicture({ maxcc: Number(event.currentTarget.value) })} />
+ </label>
+ {#if ceilingWarning(b.maxcc)}<p class="hint warn">{ceilingWarning(b.maxcc)}</p>{/if}
+ {/if}
{/if}
<div class="choices" role="radiogroup" aria-label="Analyzer">
{#each groups as group (group.label)}
@@ -409,12 +469,12 @@
{/if}
</div>
{#if recipe.description}<p class="hint">{recipe.description}</p>{/if}
- <AnalyzerSettings bind:recipe {capability} showSize={false} />
+ <AnalyzerSettings bind:recipe {capability} showSize={false} showCloud={false} />
<button class="link" onclick={onlibrary}>Make an analyzer of your own…</button>
</section>
{:else if step === 3}
- <WhenStep {zones} bind:pairs {routine} single={isSingle} sensor={capability.sensor} {followupId}
- maxcc={radar ? 100 : b.maxcc} onmaxcc={radar ? null : (value) => setPicture({ maxcc: value })}
+ <WhenStep {zones} bind:pairs {routine} single={isSingle} sensor={capability.sensor} {lastPasses}
+ maxcc={radar ? 100 : b.maxcc}
bind:against bind:chooseB bind:lookup {onshow} />
{#if radar}
{#if !routine}
@@ -495,6 +555,15 @@
</div>
<style>
+ .area-search { width: 100%; }
+ .area-group { display: grid; gap: 6px; }
+ .area-group-head { display: flex; align-items: center; gap: 7px; min-height: 30px;
+ padding: 3px 0; font-size: var(--fs-xs); }
+ .area-group-head strong { flex: 1; }
+ .area-group-head small { color: var(--text-3); }
+ .group-fold { display: flex; align-items: center; gap: 5px; min-width: 0; text-align: left;
+ font-size: var(--fs-xs); }
+ .group-fold small { margin-left: auto; }
.shared { display: flex; flex-wrap: wrap; gap: 5px; }
.area-chip {
display: flex;
@@ -512,38 +581,33 @@
.stepper {
display: grid;
grid-template-columns: repeat(4, 1fr);
- gap: 2px;
- padding: 8px 10px;
+ gap: 8px;
+ padding: 7px 12px 0;
border-bottom: 1px solid var(--border);
}
.stepper button {
display: flex;
align-items: center;
justify-content: center;
- gap: 5px;
- padding: 4px 2px;
- border-radius: var(--r-sm);
- color: var(--text-3);
+ gap: 6px;
+ min-height: 37px;
+ padding: 5px 2px 8px;
+ border-bottom: 2px solid transparent;
+ color: var(--text-2);
font-size: var(--fs-xs);
font-weight: 600;
}
- .stepper button:hover:not(:disabled) { background: var(--bg-2); color: var(--text-1); }
+ .stepper button:hover:not(:disabled) { color: var(--text-1); }
.stepper button:disabled { opacity: 0.45; cursor: not-allowed; }
.stepper .n {
- display: grid;
- place-items: center;
- width: 17px;
- height: 17px;
- border-radius: 50%;
- background: var(--bg-3);
- font: 700 10px/1 var(--font-sans);
+ color: var(--text-3);
+ font: 700 10px/1 var(--font-mono);
}
- .stepper .done { color: var(--text-2); }
- .stepper .done .n { color: var(--bg-0); background: var(--accent); }
- .stepper .current { color: var(--accent); background: var(--accent-soft); }
- .stepper .current .n { color: var(--bg-0); background: var(--accent); }
- .step { display: grid; gap: 9px; }
- h3 { margin: 0; font-size: var(--fs-sm); font-weight: 700; }
+ .stepper .done { color: var(--text-1); }
+ .stepper .current { color: var(--text-1); border-bottom-color: var(--accent); }
+ .stepper .current .n { color: var(--accent); }
+ .step { display: grid; gap: 12px; }
+ h3 { margin: 0 0 3px; font-size: var(--fs-lg); font-weight: 650; }
.row.wrap { flex-wrap: wrap; }
.active { outline: 1px solid var(--accent); }
.area-row input { font-size: var(--fs-xs); }
@@ -552,10 +616,9 @@
summary { color: var(--text-2); font-size: var(--fs-xs); cursor: pointer; }
.link { color: var(--accent); font-size: var(--fs-xs); text-align: left; justify-self: start; }
.link:disabled { opacity: 0.5; }
- .link small { display: block; color: var(--text-3); font-size: 10px; }
.centre { justify-self: center; text-align: center; }
.size { display: grid; gap: 5px; }
- .choices { display: grid; gap: 2px; }
+ .choices { display: grid; gap: 0; }
.group {
margin: 6px 0 2px;
color: var(--text-3);
@@ -569,15 +632,15 @@
display: flex;
align-items: center;
gap: 8px;
- padding: 5px 8px;
- border: 1px solid transparent;
- border-radius: var(--r-sm);
+ min-height: 35px;
+ padding: 7px 8px;
+ border-bottom: 1px solid var(--border);
color: var(--text-1);
- font-size: var(--fs-xs);
+ font-size: var(--fs-sm);
text-align: left;
}
.choice:hover { background: var(--bg-2); }
- .choice.on { border-color: var(--accent); background: var(--accent-soft); font-weight: 600; }
+ .choice.on { color: var(--text-1); background: var(--accent-soft); font-weight: 600; }
.choice small { margin-left: auto; color: var(--text-3); font-weight: 400; }
.choice.locked { color: var(--text-2); }
.choice .lock { display: inline-flex; align-items: center; gap: 3px; color: var(--accent); }
diff --git a/frontend/src/tools/detect/MapSurface.stub.svelte b/frontend/src/tools/detect/MapSurface.stub.svelte
new file mode 100644
index 0000000..e01a0eb
--- /dev/null
+++ b/frontend/src/tools/detect/MapSurface.stub.svelte
@@ -0,0 +1,12 @@
+<script>
+ /** Stands in for MapSurface in tests: no WebGL, just the bindings the tool reads. */
+ let { engine = $bindable(null), element = $bindable(null), ready = $bindable(false), providerId = $bindable(''),
+ chrome = true, armed = null, controlsTop = 0 } = $props();
+
+ $effect(() => {
+ engine = { fake: true, resize() {} };
+ ready = true;
+ });
+</script>
+
+<div class="stub" data-provider={providerId} data-chrome={String(chrome)} data-armed={String(armed)} data-top={controlsTop}></div>
diff --git a/frontend/src/tools/detect/PassCalendar.svelte b/frontend/src/tools/detect/PassCalendar.svelte
new file mode 100644
index 0000000..06d910e
--- /dev/null
+++ b/frontend/src/tools/detect/PassCalendar.svelte
@@ -0,0 +1,115 @@
+<script>
+ /** Calendar of passes over one Detect area, using Satellite's day colours. */
+ import { onMount } from 'svelte';
+ import Icon from '../../components/Icon.svelte';
+ import { monthDays, monthOf, monthOutOfRange, shiftMonth, today } from '../../lib/calendar.js';
+ import { MISSION_START } from '../../lib/map/acquisitions.js';
+ import { cloudClass, cloudLabel, monthLabel } from '../../lib/sentinel.js';
+ import { orbitMark } from '../../lib/radar.js';
+
+ let { list = [], value = '', label = 'Date', radar = false, busy = false, error = '',
+ /** A day to open on when none is chosen, such as the other side's: passes of a pair are close in time. */
+ near = '',
+ eligible = () => true, onmonth = () => {}, onpick = () => {}, onclose = () => {} } = $props();
+ let cursor = $state('');
+ let selectedDay = $state('');
+ let root;
+ const first = $derived(MISSION_START[radar ? 'sentinel1' : 'sentinel2']);
+ const latest = today();
+ const month = $derived(cursor || monthOf(value || near || today()));
+ const days = $derived(monthDays(month));
+ const entries = (day) => list.filter((pass) => pass.date === day && eligible(pass));
+ const blocked = (day) => list.some((pass) => pass.date === day);
+ const unavailable = (day) => blocked(day)
+ ? (radar ? 'outside date order or radar track' : 'outside date order') : 'no pass';
+ const stamp = (pass) => radar
+ ? `${pass.time?.slice(0, 5) ?? ''} UTC ${orbitMark(pass.orbit)}`
+ : cloudLabel(pass.cloud) || 'cloud unknown';
+
+ onMount(() => {
+ onmonth(month);
+ root?.scrollIntoView({ block: 'nearest' });
+ });
+ function move(step) {
+ cursor = shiftMonth(month, step);
+ selectedDay = '';
+ onmonth(cursor);
+ }
+ function choose(day) {
+ const found = entries(day);
+ if (found.length === 1) onpick(found[0]);
+ else if (found.length > 1) selectedDay = day;
+ }
+</script>
+
+<div bind:this={root} class="pass-calendar" role="group" aria-label={`${label} pass calendar`}>
+ <div class="head">
+ <button class="nav" aria-label="Previous month" title="Previous month"
+ disabled={monthOutOfRange(shiftMonth(month, -1), first, latest)} onclick={() => move(-1)}>
+ <Icon name="chevronLeft" size={12} />
+ </button>
+ <strong>{monthLabel(month)}</strong>
+ <button class="nav" aria-label="Next month" title="Next month"
+ disabled={monthOutOfRange(shiftMonth(month, 1), first, latest)} onclick={() => move(1)}>
+ <Icon name="chevronRight" size={12} />
+ </button>
+ <button class="nav" aria-label="Close calendar" title="Close calendar" onclick={onclose}>
+ <Icon name="x" size={12} />
+ </button>
+ </div>
+ <div class="grid" class:busy>
+ {#each ['M', 'T', 'W', 'T', 'F', 'S', 'S'] as day, index (index)}
+ <span class="dow" aria-hidden="true">{day}</span>
+ {/each}
+ {#each days as day (day.iso)}
+ {@const found = day.inMonth ? entries(day.iso) : []}
+ {@const pass = found[0]}
+ {#if day.inMonth}
+ <button class="day" class:has={!!pass} class:on={day.iso === value || day.iso === selectedDay}
+ class:clear={!!pass && !radar && cloudClass(pass.cloud) === 'clear'}
+ class:part={!!pass && !radar && cloudClass(pass.cloud) === 'part'}
+ class:cloudy={!!pass && !radar && cloudClass(pass.cloud) === 'cloudy'}
+ disabled={!pass || busy} title={pass ? `${day.iso}: ${stamp(pass)}` : `${day.iso}: ${unavailable(day.iso)}`}
+ aria-label={pass ? `${day.iso}: ${stamp(pass)}` : `${day.iso}: ${unavailable(day.iso)}`}
+ onclick={() => choose(day.iso)}>{day.day}</button>
+ {:else}<span class="pad" aria-hidden="true"></span>{/if}
+ {/each}
+ </div>
+ {#if busy}<p class="hint">Reading this month's passes…</p>
+ {:else if error}<p class="warn" role="alert">{error}</p>
+ {:else if selectedDay && entries(selectedDay).length > 1}
+ <div class="times" aria-label={`Passes on ${selectedDay}`}>
+ {#each entries(selectedDay) as pass (pass.time || pass.date)}
+ <button onclick={() => onpick(pass)}>{stamp(pass)}</button>
+ {/each}
+ </div>
+ {:else}<p class="hint">Only days with a pass can be chosen.</p>{/if}
+</div>
+
+<style>
+ .pass-calendar { display: grid; gap: 5px; width: min(100%, 246px); padding: 8px; border: 1px solid var(--border);
+ border-radius: var(--r-sm); background: var(--bg-2); }
+ .head { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
+ .head strong { flex: 1; font-size: var(--fs-xs); text-align: center; }
+ .nav { display: grid; place-items: center; width: 22px; height: 22px; border: 1px solid var(--border);
+ border-radius: var(--r-sm); }
+ .nav:hover:not(:disabled) { border-color: var(--text-3); }
+ .nav:disabled { opacity: .35; }
+ .grid { display: grid; grid-template-columns: repeat(7, minmax(0, 1fr)); gap: 2px; }
+ .grid.busy { opacity: .5; }
+ .dow { text-align: center; font-size: 9px; color: var(--text-3); }
+ .day { display: grid; place-items: center; height: 24px; min-width: 0; border: 1px solid transparent;
+ border-radius: var(--r-sm); color: var(--text-3); font: 10px var(--font-mono); }
+ .day:disabled { opacity: .3; }
+ .day.has { border-color: var(--border); background: var(--bg-2); color: var(--text-1); }
+ .day.clear { border-color: color-mix(in srgb, var(--ok) 65%, transparent); color: var(--ok); }
+ .day.part { border-color: color-mix(in srgb, var(--warn) 55%, transparent); color: var(--warn); }
+ .day.cloudy { color: var(--text-2); }
+ .day.has:hover:not(:disabled) { border-color: var(--text-1); }
+ .day.on { border-color: var(--accent); background: var(--accent); color: var(--accent-text); }
+ .hint, .warn { margin: 0; font-size: 10px; line-height: 1.35; }
+ .hint { color: var(--text-3); }
+ .warn { color: var(--warn); }
+ .times { display: grid; gap: 3px; }
+ .times button { padding: 4px; border: 1px solid var(--border); border-radius: var(--r-sm); font-size: var(--fs-xs); text-align: left; }
+</style>
diff --git a/frontend/src/tools/detect/PassCalendar.test.js b/frontend/src/tools/detect/PassCalendar.test.js
new file mode 100644
index 0000000..eb046c3
--- /dev/null
+++ b/frontend/src/tools/detect/PassCalendar.test.js
@@ -0,0 +1,67 @@
+// @vitest-environment happy-dom
+import { afterEach, expect, it, vi } from 'vitest';
+import { flushSync, mount, unmount } from 'svelte';
+import PassCalendar from './PassCalendar.svelte';
+
+let app;
+afterEach(() => { if (app) unmount(app); document.body.innerHTML = ''; app = null; });
+
+it('shows only actual passes as selectable calendar days and loads each month', async () => {
+ const pass = { date: '2026-09-15', cloud: 12, coverage: 1 };
+ const onmonth = vi.fn();
+ const onpick = vi.fn();
+ const onclose = vi.fn();
+ app = mount(PassCalendar, { target: document.body, props: {
+ list: [pass], value: pass.date, label: 'A', onmonth, onpick, onclose,
+ } });
+ await Promise.resolve(); flushSync();
+ expect(onmonth).toHaveBeenCalledWith('2026-09');
+ const day = document.querySelector('button[aria-label="2026-09-15: 12% cloud"]');
+ expect(day.disabled).toBe(false);
+ expect(day.classList.contains('clear')).toBe(true);
+ expect(document.querySelector('button[aria-label="2026-09-14: no pass"]').disabled).toBe(true);
+ day.click(); flushSync();
+ expect(onpick).toHaveBeenCalledWith(pass);
+ document.querySelector('button[aria-label="Previous month"]').click(); flushSync();
+ expect(onmonth).toHaveBeenCalledWith('2026-08');
+ document.querySelector('button[aria-label="Close calendar"]').click(); flushSync();
+ expect(onclose).toHaveBeenCalledOnce();
+});
+
+it('opens on the month of the day it is told to be near when none is chosen', async () => {
+ const onmonth = vi.fn();
+ app = mount(PassCalendar, { target: document.body, props: { list: [], value: '', near: '2026-03-20', label: 'A', onmonth } });
+ await Promise.resolve(); flushSync();
+ expect(onmonth).toHaveBeenCalledWith('2026-03');
+ unmount(app);
+ app = mount(PassCalendar, { target: document.body, props: { list: [], value: '2026-07-02', near: '2026-03-20', label: 'A', onmonth } });
+ await Promise.resolve(); flushSync();
+ expect(onmonth).toHaveBeenLastCalledWith('2026-07');
+});
+
+it('lets a radar day with two passes choose its time', async () => {
+ const early = { date: '2026-09-15', time: '05:30:00Z', orbit: 'ascending' };
+ const late = { date: '2026-09-15', time: '17:40:00Z', orbit: 'descending' };
+ const onpick = vi.fn();
+ app = mount(PassCalendar, { target: document.body, props: {
+ list: [early, late], value: early.date, label: 'B', radar: true, onpick,
+ } });
+ await Promise.resolve(); flushSync();
+ document.querySelector('button[aria-label^="2026-09-15:"]').click(); flushSync();
+ expect(onpick).not.toHaveBeenCalled();
+ document.querySelectorAll('.times button')[1].click(); flushSync();
+ expect(onpick).toHaveBeenCalledWith(late);
+});
+
+it('disables a real pass when it would put A after B', async () => {
+ const onpick = vi.fn();
+ app = mount(PassCalendar, { target: document.body, props: {
+ list: [{ date: '2026-09-15', cloud: 2 }], value: '2026-09-12', label: 'A',
+ eligible: (pass) => pass.date < '2026-09-12', onpick,
+ } });
+ await Promise.resolve(); flushSync();
+ const day = document.querySelector('button[aria-label="2026-09-15: outside date order"]');
+ expect(day.disabled).toBe(true);
+ day.click(); flushSync();
+ expect(onpick).not.toHaveBeenCalled();
+});
diff --git a/frontend/src/tools/detect/PassDates.svelte b/frontend/src/tools/detect/PassDates.svelte
new file mode 100644
index 0000000..eadd672
--- /dev/null
+++ b/frontend/src/tools/detect/PassDates.svelte
@@ -0,0 +1,79 @@
+<script>
+ /**
+ * The day of a check's passes, picked from a calendar as a routine or a one
+ * pass picks its dates: one button for each side, a month of passes behind it
+ * with the days that have one coloured by their cloud, and a typed date for a
+ * day the calendar does not show.
+ *
+ * The calendar reads the passes over the middle of the map a month at a time,
+ * only for the month in view, and offers only days that keep the two passes in
+ * order.
+ */
+ import PassCalendar from './PassCalendar.svelte';
+ import DateField from '../../components/DateField.svelte';
+ import Icon from '../../components/Icon.svelte';
+
+ let { bench } = $props();
+
+ const check = $derived(bench.check);
+ const sides = $derived(bench.single ? [['b', 'Pass']] : [['a', 'Before'], ['b', 'After']]);
+ const open = $derived(bench.calendar.side);
+ const nameOf = (side) => sides.find(([id]) => id === side)?.[1] ?? '';
+ /** The day of the other side, which a calendar with none chosen opens near. */
+ const otherDay = (side) => (side === 'a' ? check?.b?.date : check?.a?.date) ?? '';
+</script>
+
+<div class="dates">
+ <div class="sides">
+ {#each sides as [side, name] (side)}
+ <div class="side">
+ <strong>{name}</strong>
+ <button type="button" class="date-pick" aria-label={`${name} pass`} aria-expanded={open === side}
+ onclick={() => (open === side ? bench.closeCalendar() : bench.openCalendar(side))}>
+ <Icon name="calendar" size={13} /><span>{check?.[side]?.date || 'Choose a pass'}</span><Icon name="chevronDown" size={12} />
+ </button>
+ </div>
+ {/each}
+ </div>
+ {#if open}
+ <div class="pick">
+ {#key open}
+ <PassCalendar list={bench.calendar.list} value={check?.[open]?.date ?? ''} near={otherDay(open)} label={nameOf(open)} radar={bench.radar}
+ busy={bench.calendar.busy} error={bench.calendar.error} eligible={bench.eligible(open)}
+ onmonth={(month) => bench.loadMonth(month)} onclose={() => bench.closeCalendar()}
+ onpick={(pass) => bench.pickFromCalendar(open, pass)} />
+ {/key}
+ <details class="manual-date">
+ <summary>Enter a date</summary>
+ <DateField day reading={false} label={`${nameOf(open)} date`} value={check?.[open]?.date ?? ''}
+ onchange={(value) => bench.typeDay(open, value ?? '')} />
+ </details>
+ </div>
+ {/if}
+</div>
+
+<style>
+ .dates { display: flex; flex-wrap: wrap; align-items: flex-start; gap: 10px 18px; }
+ .sides { display: grid; gap: 8px; }
+ .side { display: grid; justify-items: start; gap: 3px; font-size: var(--fs-xs); }
+ .side strong { color: var(--text-2); }
+ .date-pick {
+ display: flex;
+ align-items: center;
+ gap: 7px;
+ width: 200px;
+ padding: 6px 8px;
+ border: 1px solid var(--border);
+ border-radius: var(--r-sm);
+ background: var(--bg-2);
+ color: var(--text-1);
+ font-size: var(--fs-xs);
+ text-align: left;
+ }
+ .date-pick:hover, .date-pick[aria-expanded='true'] { border-color: var(--accent); }
+ .date-pick span { flex: 1; }
+ .pick { display: grid; gap: 6px; }
+ .manual-date { color: var(--text-3); font-size: 10px; }
+ .manual-date summary { cursor: pointer; }
+ .pick :global(.date-field) { width: 145px; }
+</style>
diff --git a/frontend/src/tools/detect/PassDates.svelte.test.js b/frontend/src/tools/detect/PassDates.svelte.test.js
new file mode 100644
index 0000000..6056922
--- /dev/null
+++ b/frontend/src/tools/detect/PassDates.svelte.test.js
@@ -0,0 +1,78 @@
+// @vitest-environment happy-dom
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { flushSync, mount, unmount } from 'svelte';
+import { Bench } from '../../lib/map/bench.svelte.js';
+import { newCheck, newRecipe } from '../../lib/map/analyzerRules.js';
+import PassDates from './PassDates.svelte';
+
+const METHODS = [{ id: 'rules', sizes: { all: {} } }];
+const VIEW = { west: 2, south: 48, east: 2.2, north: 48.2 };
+const JUNE = { dates: [{ date: '2026-06-03', cloud: 5, coverage: 1 }, { date: '2026-06-18', cloud: 40, coverage: 1 }] };
+
+let live, bench, target, calls;
+beforeEach(() => { vi.useFakeTimers(); calls = []; });
+afterEach(() => {
+ if (live) unmount(live);
+ bench?.destroy();
+ live = bench = null;
+ target?.remove();
+ vi.useRealTimers();
+});
+
+function open({ dates = 'two', sensor = 'sentinel2', check = {} } = {}) {
+ const recipe = $state({ ...newRecipe(METHODS, { sensor, dates }), name: 'Mine', checks: [] });
+ const api = { post: vi.fn(async (url, body) => { calls.push([url, body]); return JUNE; }) };
+ bench = new Bench({ api, recipe, limits: { max_checks: 12 }, viewBounds: () => VIEW });
+ bench.startDraft();
+ Object.assign(bench.draft.check, check);
+ target = document.createElement('div');
+ document.body.append(target);
+ live = mount(PassDates, { target, props: { bench } });
+ flushSync();
+}
+const settle = async () => { await vi.advanceTimersByTimeAsync(10); flushSync(); };
+const pick = (name) => target.querySelector(`button[aria-label="${name}"]`);
+
+it('has a button for each side of a check of two dates, and one for a single pass', () => {
+ open();
+ expect([...target.querySelectorAll('.side strong')].map((node) => node.textContent)).toEqual(['Before', 'After']);
+ expect(pick('Before pass').textContent).toContain('Choose a pass');
+ unmount(live); bench.destroy(); target.remove();
+ open({ dates: 'one' });
+ expect([...target.querySelectorAll('.side strong')].map((node) => node.textContent)).toEqual(['Pass']);
+});
+
+it('opens a calendar for a side, reads its month once, and picks a day of it', async () => {
+ open({ check: { b: { provider: 'sentinel2', date: '2026-06-18', layer: 'TRUE_COLOR', maxcc: 100 } } });
+ pick('Before pass').click(); await settle();
+ expect(pick('Before pass').getAttribute('aria-expanded')).toBe('true');
+ expect(calls).toHaveLength(1);
+ expect(calls[0][1]).toMatchObject({ collection: 'sentinel2', zones: [expect.objectContaining({ kind: 'rect' })] });
+ // the calendar shows June 2026 when the other side is in June; only days with a pass before B can be picked
+ const days = [...target.querySelectorAll('.pass-calendar .day')];
+ expect(days.filter((day) => !day.disabled).map((day) => day.getAttribute('aria-label').slice(0, 10))).toEqual(['2026-06-03']);
+ target.querySelector('button[aria-label^="2026-06-03"]').click(); await settle();
+ expect(bench.check.a.date).toBe('2026-06-03');
+ expect(bench.calendar.side).toBe('');
+ expect(target.querySelector('.pass-calendar')).toBe(null);
+ expect(pick('Before pass').textContent).toContain('2026-06-03');
+});
+
+it('takes a typed day for one the calendar does not show, and closes from the same button', async () => {
+ open();
+ pick('After pass').click(); await settle();
+ expect(target.querySelector('details.manual-date summary').textContent).toBe('Enter a date');
+ bench.typeDay('b', '2026-06-10'); await settle();
+ expect(bench.check.b.date).toBe('2026-06-10');
+ expect(target.querySelector('.pass-calendar')).not.toBe(null); // still open for the next try
+ pick('After pass').click(); await settle();
+ expect(target.querySelector('.pass-calendar')).toBe(null);
+});
+
+it('moves from one side to the other with the calendar of the side pressed', async () => {
+ open();
+ pick('Before pass').click(); await settle();
+ expect(target.querySelector('.pass-calendar').getAttribute('aria-label')).toBe('Before pass calendar');
+ pick('After pass').click(); await settle();
+ expect(target.querySelector('.pass-calendar').getAttribute('aria-label')).toBe('After pass calendar');
+});
diff --git a/frontend/src/tools/detect/RuleLayers.svelte b/frontend/src/tools/detect/RuleLayers.svelte
index f2e5d97..e4a51b8 100644
--- a/frontend/src/tools/detect/RuleLayers.svelte
+++ b/frontend/src/tools/detect/RuleLayers.svelte
@@ -1,20 +1,42 @@
<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.
+ * What each rule of the analyzer being built keeps, painted on the ground a
+ * test judged. The engine sends one byte a pixel for each tile it read (a bit
+ * per rule, detect_rules.py); this lays each 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.
+ *
+ * The ground a test measured is tinted, so a place no rule kept still reads as
+ * tested, and cloud or missing imagery stays clear. When the map is split
+ * between two passes, what reads the before pass is painted on the before
+ * half, what reads the after pass on the after half, and a change across both.
+ * After the rules or the pins change the picture is dimmed: it answers for
+ * what they were.
*/
+ import { RULE_COLOURS, sideOf } from '../../lib/map/analyzerRules.js';
import { compose, cssMatrix, imageToMercator, invert, screenToMercator } from '../../lib/map/groundFrame.js';
- import { RULE_COLOURS, clipToBounds, paintMask } from '../../lib/map/analyzerRules.js';
+ import RuleTile from './RuleTile.svelte';
- /** `within`: the open check's bounds, past which nothing is painted. */
- let { engine, element, preview = null, shown = [], hover = null, colours = RULE_COLOURS, within = null } = $props();
+ let {
+ engine,
+ element,
+ /** What a test sent back: `{ size, tiles: [{ x, y, box, mask }] }`. */
+ detail = null,
+ rules = [],
+ shown = [],
+ hover = null,
+ colours = RULE_COLOURS,
+ split = false,
+ /** Where the split sits, as a percentage of the map from its left edge. */
+ divider = 50,
+ stale = false,
+ } = $props();
+
+ /** The tint over ground the test measured, out of 255. */
+ const VEIL = 30;
- let canvas = $state(null);
- let bits = $state(null);
let revision = $state(0);
+ let decoded = $state({});
$effect(() => {
if (!engine) return;
@@ -22,65 +44,75 @@
});
/** One byte a pixel out of the PNG the engine sent: its first channel. */
- async function decode(base64, width, height) {
+ async function decode(base64, size) {
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;
+ scratch.width = size;
+ scratch.height = size;
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);
+ const rgba = context.getImageData(0, 0, size, size).data;
+ const out = new Uint8Array(size * size);
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; }
+ const tiles = detail?.tiles ?? [];
+ const size = detail?.size ?? 0;
let cancelled = false;
- decode(mask, width, height)
- .then((decoded) => { if (!cancelled) bits = decoded; })
- .catch(() => { if (!cancelled) bits = null; });
+ Promise.all(tiles.map(async (tile) => [`${tile.x},${tile.y}`, await decode(tile.mask, size)]))
+ .then((pairs) => { if (!cancelled) decoded = Object.fromEntries(pairs); })
+ .catch(() => { if (!cancelled) decoded = {}; });
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;
- const painted = paintMask(bits, { shown, hover, colours });
- const kept = within && preview.box ? clipToBounds(painted, width, height, preview.box, within) : painted;
- canvas.getContext('2d').putImageData(new ImageData(kept, width, height), 0, 0);
- });
-
- const transform = $derived.by(() => {
+ const placed = $derived.by(() => {
revision;
- if (!engine?.frame || !element || !preview?.box) return '';
+ const tiles = detail?.tiles ?? [];
+ if (!engine?.frame || !element || !tiles.length) 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)));
+ const toScreen = invert(screenToMercator(frame));
+ return tiles.filter((tile) => decoded[`${tile.x},${tile.y}`]).map((tile) => ({
+ key: `${tile.x},${tile.y}`,
+ bits: decoded[`${tile.x},${tile.y}`],
+ transform: cssMatrix(compose(toScreen, imageToMercator(tile.box, detail.size, detail.size))),
+ }));
});
+
+ const parts = $derived(split ? ['shared', 'before', 'after'] : ['shared']);
+ /** What a part paints: the rules that belong to it, or none when another rule is hovered. */
+ const shownIn = (part) => rules.map((rule, i) => !!shown[i] && sideOf(rule, split) === part);
+ const hoverIn = (part) => (hover !== null && rules[hover] && sideOf(rules[hover], split) === part ? hover : null);
+ const hoveredElsewhere = (part) => hover !== null && !!rules[hover] && sideOf(rules[hover], split) !== part;
</script>
-{#if preview?.mask}
- <canvas bind:this={canvas} class="rule-layers" style:transform={transform} aria-label="What each rule keeps"></canvas>
+{#if placed.length}
+ <div class="rule-layers" class:stale style:--divider={`${divider}%`} aria-label="What each rule keeps">
+ {#each parts as part (part)}
+ <div class="part {part}">
+ {#each placed as tile (tile.key)}
+ <RuleTile bits={tile.bits} size={detail.size} transform={tile.transform} {colours}
+ shown={hoveredElsewhere(part) ? [] : shownIn(part)} hover={hoverIn(part)} veil={part === 'shared' ? VEIL : 0} />
+ {/each}
+ </div>
+ {/each}
+ </div>
{/if}
<style>
.rule-layers {
position: absolute;
- top: 0;
- left: 0;
+ inset: 0;
z-index: 540;
- transform-origin: 0 0;
- image-rendering: pixelated;
pointer-events: none;
+ transition: opacity 0.15s var(--ease);
}
+ .rule-layers.stale { opacity: 0.4; }
+ .part { position: absolute; inset: 0; }
+ .part.before { clip-path: inset(0 calc(100% - var(--divider)) 0 0); }
+ .part.after { clip-path: inset(0 0 0 var(--divider)); }
</style>
diff --git a/frontend/src/tools/detect/RuleProbe.render.test.js b/frontend/src/tools/detect/RuleProbe.render.test.js
index be16860..ff65f4b 100644
--- a/frontend/src/tools/detect/RuleProbe.render.test.js
+++ b/frontend/src/tools/detect/RuleProbe.render.test.js
@@ -15,6 +15,7 @@ function render(result, extra = {}) {
flushSync();
return { target, done: () => { unmount(live); target.remove(); } };
}
+const press = (target, words) => [...target.querySelectorAll('button')].find((b) => b.textContent.includes(words)).click();
describe('reading the rules at a point', () => {
it('says what every rule read there and which one let it go', () => {
@@ -24,20 +25,31 @@ describe('reading the rules at a point', () => {
] });
expect(target.textContent).toContain('Not kept');
const rows = [...target.querySelectorAll('li')].map((li) => li.textContent.replace(/\s+/g, ' ').trim());
+ expect(rows[0]).toContain('NDVI dropped by 0.25 or more');
expect(rows[0]).toContain('0.72 → 0.31 (−0.41)');
expect(rows[0]).toContain('✓');
+ expect(rows[1]).toContain('B12 (short-wave 2.2 µm) after is at least 25.0%');
expect(rows[1]).toContain('18.0%');
expect(rows[1]).toContain('✗');
+ // each rule wears the number and the colour it has in the list and on the map
+ expect([...target.querySelectorAll('.dot')].map((dot) => dot.textContent)).toEqual(['1', '2']);
// 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', () => {
+ it('leaves out the before and after of an analyzer of one date', () => {
+ const { target, done } = render({ ready: true, imaged: true, measured: true, kept: true, rules: [
+ { passes: true, value: 0.3, before: null, after: null }] }, { single: true, rules: [newRule('band', 'b', { band: 'B12' })] });
+ expect(target.querySelector('li').textContent).toContain('B12 (short-wave 2.2 µm) is at least 25.0%');
+ done();
+ });
+
+ it('says why nothing was read under cloud, off the imagery or outside the ground tested', () => {
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'],
+ [{ ready: false }, 'Outside the ground the test read'],
]) {
const { target, done } = render(result);
expect(target.textContent).toContain(words);
@@ -46,39 +58,46 @@ describe('reading the rules at a point', () => {
}
});
- it('marks the point in the check on the bench, or in a new check of this view', () => {
+ it('drops a pin at the point, unless it is off the imagery or nothing can keep it', () => {
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();
+ const { target, done } = render(read, { onmark });
+ expect(target.textContent).toContain('Drop a pin here');
+ press(target, 'Should stay empty');
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();
- }
+ const off = render({ ...read, imaged: false }, { onmark });
+ expect(off.target.textContent).not.toContain('Should be found');
+ off.done();
+ const nowhere = render(read);
+ expect(nowhere.target.textContent).not.toContain('Should be found');
+ nowhere.done();
});
- it('opens where nothing is read yet, says what is missing, and still takes a mark', () => {
+ it('opens where nothing is read yet, says what is missing, and still takes a pin', () => {
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(frames.target.textContent).toContain('Test the check to read the rules here.');
+ press(frames.target, 'Should be found');
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();
+ });
+
+ it('offers a pin it was opened on to be turned or taken away, and no new pin', () => {
+ const read = { ready: true, imaged: true, measured: true, kept: false, rules: [] };
+ const onturn = vi.fn();
+ const onremove = vi.fn();
+ const { target, done } = render(read, { onmark: vi.fn(), pin: { number: 2, expect: 'found' }, onturn, onremove });
+ expect(target.textContent).toContain('Pin 2: should be found');
+ expect(target.textContent).not.toContain('Drop a pin here');
+ press(target, 'Turn into “Should stay empty”');
+ press(target, 'Remove');
+ expect(onturn).toHaveBeenCalledOnce();
+ expect(onremove).toHaveBeenCalledOnce();
+ done();
});
});
diff --git a/frontend/src/tools/detect/RuleProbe.svelte b/frontend/src/tools/detect/RuleProbe.svelte
index ab93480..d5d2560 100644
--- a/frontend/src/tools/detect/RuleProbe.svelte
+++ b/frontend/src/tools/detect/RuleProbe.svelte
@@ -1,21 +1,23 @@
<script>
/**
- * Every rule read at the point the analyst clicked: the value, the line and
+ * Every rule read at a 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.
+ * become a pin of the check: somewhere a candidate should come out, or none.
+ * Opened on a pin instead, it reads the ground under it and offers to turn
+ * the pin the other way or take it away.
*/
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')`. */
+ engine, probe, rules = [], colours = [], single = false, width = 0, height = 0, onclose = () => {},
+ /** Drop a pin at the point: `onmark('found' | 'empty')`. Left out, the point cannot be kept. */
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,
+ /** The pin the card was opened on, `{ number, expect }`, when it was. */
+ pin = null,
+ onturn = () => {},
+ onremove = () => {},
} = $props();
let revision = $state(0);
@@ -35,16 +37,17 @@
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.unread === 'frames' ? 'Test the check to read the rules here.'
: probe.error ? probe.error
: !result ? 'Reading…'
- : !result.ready ? 'Outside the preview. Read this view first.'
+ : !result.ready ? 'Outside the ground the test read.'
: !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));
+ /** A pin needs no reading, only somewhere to go; off the imagery it says nothing. */
+ const markable = $derived(!!onmark && !pin && !(result?.ready && !result.imaged));
+ const other = $derived(pin?.expect === 'found' ? 'Should stay empty' : 'Should be found');
function reading(rule, row) {
if (rule.measure === 'class') return row.passes ? 'yes' : 'no';
@@ -67,8 +70,8 @@
{#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="dot">{i + 1}</span>
+ <span class="what" title={describeRule(rules[i], { single })}>{describeRule(rules[i], { single })}</span>
<span class="value">{reading(rules[i], row)}</span>
<span class="verdict" class:pass={row.passes}>{row.passes ? '✓' : '✗'}</span>
</li>
@@ -76,17 +79,21 @@
{/each}
</ul>
{/if}
- {#if markable}
+ {#if pin}
<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}
+ <span class="target">Pin {pin.number}: {pin.expect === 'found' ? 'should be found' : 'should stay empty'}</span>
+ <div class="marks">
+ <button class="btn btn-sm" onclick={onturn}>Turn into “{other}”</button>
+ <button class="btn btn-sm" onclick={onremove}>Remove</button>
+ </div>
+ </footer>
+ {:else if markable}
+ <footer>
+ <span class="target">Drop a pin here</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>
</footer>
{/if}
</div>
@@ -116,8 +123,19 @@
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); }
+ li { display: grid; grid-template-columns: 14px 1fr auto 14px; align-items: center; gap: 6px; }
+ .dot {
+ display: grid;
+ place-items: center;
+ width: 14px;
+ height: 14px;
+ border-radius: 50%;
+ background: var(--tint);
+ color: #111;
+ font-size: 9px;
+ font-weight: 800;
+ line-height: 1;
+ }
.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; }
diff --git a/frontend/src/tools/detect/RuleRow.svelte b/frontend/src/tools/detect/RuleRow.svelte
index 1e9a702..4ef40d9 100644
--- a/frontend/src/tools/detect/RuleRow.svelte
+++ b/frontend/src/tools/detect/RuleRow.svelte
@@ -1,24 +1,36 @@
<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.
+ * One rule of an analyzer of your own, written as the sentence it says:
+ * what it measures, the date it is read on, and the line it has to cross.
+ * The dot is the colour its pixels take on the map, with its number, and
+ * hides or shows them. The line is a direction and an amount, and the pins of
+ * the check on the bench sit along the slider where the last test read them,
+ * so the line can be set between the ground that should come out and the
+ * ground that should not.
*/
import {
- BAND_NAMES, CLASS_NAMES, INDICES, L2A_BANDS, MEASURES, PAIRS, POLARISATIONS, formatShare, opsFor,
- retarget, scaleOf, ruleProblem, toEngine,
+ BAND_NAMES, CLASS_NAMES, INDICES, L2A_BANDS, PAIRS, POLARISATIONS, amountOf, describeRule, directionOf,
+ directionsFor, formatShare, lineScale, measuresFor, readsOneDate, retarget, ruleProblem, toEngine, whensFor,
+ withAmount, withDirection,
} from '../../lib/map/analyzerRules.js';
import Icon from '../../components/Icon.svelte';
let {
rule = $bindable(),
+ /** The analyzer, for which measures and dates a rule may use. */
+ recipe,
index = 0,
colour = '#facc15',
/** The first measured rule: candidates are ranked by it. */
signal = false,
- /** `{ share, kept }` from the last preview, or null. */
+ /** `{ share, kept }` from the last test, or null. */
reading = null,
+ /** Where each pin of the check on the bench was read on this rule's line (`pinTicks`). */
+ ticks = [],
+ /** The last test no longer matches the rules, so what it said of this one is dimmed. */
+ stale = false,
+ /** What the last test said taking this rule out would change, in a few words, or ''. */
+ effect = '',
match = 'all',
shown = true,
ontoggle = () => {},
@@ -32,12 +44,25 @@
} = $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 single = $derived(readsOneDate(recipe));
+ const scale = $derived(lineScale(rule));
+ const direction = $derived(directionOf(rule));
+ const between = $derived(rule.op === 'between');
const problem = $derived(ruleProblem(rule));
+ const measures = $derived(measuresFor(recipe));
+ const whens = $derived(whensFor(recipe, 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']];
+ const shownAmount = $derived(Number((amountOf(rule) * scale.factor).toFixed(4)));
+ const shownLower = $derived(Number((rule.value * scale.factor).toFixed(4)));
+ const shownUpper = $derived(Number((rule.upper * scale.factor).toFixed(4)));
+ /** Where the thumb sits along the track, 0 to 1. */
+ const fraction = $derived(Math.min(1, Math.max(0, (shownAmount - scale.min) / (scale.max - scale.min))));
+ /** Whether the ground that passes is above the thumb, as it is for at least, a rise or a drop. */
+ const above = $derived(direction !== 'le');
+ const hint = $derived(rule.on === 'a' ? 'Read on the before pass and painted on the left of the split.'
+ : rule.on === 'b' ? 'Read on the after pass and painted on the right of the split.'
+ : 'Read as after minus before and painted on both sides.');
+ const sentence = $derived(describeRule(rule, { single }));
/** 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`,
@@ -47,8 +72,13 @@
function set(patch) {
rule = retarget(rule, patch);
}
- function setValue(key, shown) {
- const number = Number(shown);
+ function setAmount(text) {
+ const number = Number(text);
+ if (!Number.isFinite(number)) return;
+ rule = { ...rule, value: withAmount(rule, toEngine(rule, number)) };
+ }
+ function setBound(key, text) {
+ const number = Number(text);
if (!Number.isFinite(number)) return;
set({ [key]: toEngine(rule, number) });
}
@@ -56,25 +86,19 @@
const next = rule.classes.includes(id) ? rule.classes.filter((entry) => entry !== id) : [...rule.classes, id];
set({ classes: next });
}
+ const tickWords = (tick) => `${tick.expect === 'found' ? 'Should be found' : 'Should stay empty'}: ${
+ tick.passes ? 'this rule lets it through' : 'this rule turns it away'}`;
</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>
+<div class="rule" class:off={!shown} style={`--tint: ${colour}`} onpointerenter={() => onhover(index)} onpointerleave={() => onhover(null)}>
+ <div class="head">
+ <button class="dot" 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}>{n}</button>
+ <p class="sentence" aria-label={`Rule ${n} says`}>{sentence}</p>
+ <button class="star" class:on={signal} disabled={signal || rule.measure === 'class'}
+ aria-label={signal ? `Rule ${n} ranks the candidates` : `Rank candidates by rule ${n}`}
+ title={signal ? 'Candidates are ranked by this rule' : 'Rank candidates by this rule'} onclick={onsignal}>{signal ? '★' : '☆'}</button>
{#if canRemove}
<button class="cmp-icon" aria-label={`Remove rule ${n}`} title="Remove this rule" onclick={onremove}>
<Icon name="x" size={13} />
@@ -82,132 +106,210 @@
{/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 class="field">
+ <span class="label">Measures</span>
+ <div class="control">
+ {#if measures.length > 1}
+ <select 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} title={measure.hint}>{measure.label}</option>{/each}
+ </select>
+ {/if}
+ {#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="pair">
+ <select 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 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>
- {/if}
+ </div>
- <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}
+ {#if whens.length > 1}
+ <div class="field">
+ <span class="label">Read on</span>
+ <div class="control">
+ <div class="cmp-seg fill" role="group" aria-label={`Rule ${n} reads`}>
+ {#each whens as [id, label] (id)}
+ <button type="button" class:on={rule.on === id} aria-pressed={rule.on === id} onclick={() => set({ on: id })}>{label}</button>
+ {/each}
+ </div>
+ <span class="note">{hint}</span>
+ </div>
</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}
{#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 class="field">
+ <span class="label">Line</span>
+ <div class="control">
+ <div class="cmp-seg fill" role="group" aria-label={`Rule ${n} comparison`}>
+ {#each directionsFor(rule) as [id, label] (id)}
+ <button type="button" class:on={direction === id} aria-pressed={direction === id}
+ onclick={() => (rule = withDirection(rule, id))}>{label}</button>
+ {/each}
+ </div>
+ <div class="value">
+ {#if between}
+ <input type="number" aria-label={`Rule ${n} value`} step={scale.step} value={shownLower}
+ onchange={(event) => setBound('value', event.currentTarget.value)} />
+ <span class="minus">to</span>
+ <input type="number" aria-label={`Rule ${n} upper value`} step={scale.step} value={shownUpper}
+ onchange={(event) => setBound('upper', event.currentTarget.value)} />
+ {:else}
+ <input type="number" aria-label={`Rule ${n} value`} step={scale.step} value={shownAmount}
+ onchange={(event) => setAmount(event.currentTarget.value)} />
+ {/if}
+ <span class="unit">{scale.suffix.trim()}</span>
+ </div>
+ {#if !between}
+ <div class="line" class:stale>
+ <input class="range" class:above type="range" aria-label={`Rule ${n} line`} min={scale.min} max={scale.max} step={scale.step}
+ style={`--fraction: ${fraction}`} value={Math.min(scale.max, Math.max(scale.min, shownAmount))}
+ oninput={(event) => setAmount(event.currentTarget.value)} />
+ {#each ticks as tick (tick.pin)}
+ <i class="tick tick-{tick.expect}" class:passes={tick.passes} class:clipped={tick.clipped}
+ style={`--at: ${tick.at}`} title={tickWords(tick)} role="img" aria-label={tickWords(tick)}></i>
+ {/each}
+ </div>
+ {#if ticks.length}
+ <span class="key" aria-hidden="true"><i class="tick tick-found"></i> should be found <i class="tick tick-empty"></i> should stay empty</span>
+ {/if}
+ {/if}
+ <label class="check" title="Compare with the ground around it, not a fixed value">
+ <input type="checkbox" checked={rule.around > 0}
+ onchange={(event) => set({ around: event.currentTarget.checked ? 150 : 0 })} />
+ Against the ground around it
+ {#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>
+ </div>
+ </div>
+ {:else}
+ <div class="field">
+ <span class="label">Ground is</span>
+ <div class="control">
+ <div class="cmp-seg fill" role="group" aria-label={`Rule ${n} comparison`}>
+ {#each directionsFor(rule) as [id, label] (id)}
+ <button type="button" class:on={direction === id} aria-pressed={direction === id} onclick={() => set({ op: id })}>{label}</button>
+ {/each}
+ </div>
+ </div>
</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>
+ {:else if shareText}
+ <p class="share" class:stale aria-label={`Rule ${n} share`}>{shareText}</p>
+ {/if}
+ {#if effect}
+ <p class="effect" class:stale aria-label={`Rule ${n} effect`}>{effect}</p>
{/if}
</div>
<style>
.rule {
+ container: rule / inline-size;
display: grid;
grid-template-columns: minmax(0, 1fr);
- gap: 6px;
- padding: 8px;
+ gap: 8px;
+ padding: 9px 10px 10px;
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;
+ .rule.off { border-left-color: color-mix(in srgb, var(--tint) 35%, transparent); }
+ .head { display: flex; align-items: flex-start; gap: 7px; }
+ .dot {
+ flex: 0 0 auto;
+ display: grid;
+ place-items: center;
+ width: 20px;
+ height: 20px;
+ margin-top: 0;
+ border-radius: 50%;
+ background: var(--tint);
+ color: #111;
+ font-size: 11px;
+ font-weight: 800;
+ line-height: 1;
+ box-shadow: 0 0 0 1px rgb(0 0 0 / 0.3);
}
- 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); }
+ .dot.off { background: transparent; color: var(--text-2); box-shadow: inset 0 0 0 2px var(--tint); }
+ .sentence {
+ flex: 1;
+ min-width: 0;
+ margin: 1px 0 0;
+ color: var(--text-1);
+ font-size: var(--fs-xs);
+ font-weight: 600;
+ line-height: 1.4;
+ overflow-wrap: anywhere;
+ }
+ .star { flex: 0 0 auto; padding: 0 3px; color: var(--text-3); font-size: 15px; line-height: 20px; }
+ .star:hover:not(:disabled) { color: var(--accent); }
+ .star.on { color: var(--accent); }
+ .star:disabled { cursor: default; }
+ .star:disabled:not(.on) { opacity: 0.35; }
+ .head .cmp-icon { width: 22px; height: 22px; }
+ .field { display: grid; grid-template-columns: 58px minmax(0, 1fr); gap: 8px; align-items: start; }
+ .label { padding-top: 6px; color: var(--text-3); font-size: 10.5px; font-weight: 600; letter-spacing: 0.02em; }
+ .control { display: grid; gap: 6px; min-width: 0; }
+ .control select { width: 100%; min-width: 0; }
+ /* A row of choices that does not fit goes onto a second line rather than out of the card. */
+ .control :global(.cmp-seg.fill) { flex-wrap: wrap; }
+ /* At the dock's narrowest the label goes over its control, which then has the card's whole width. */
+ @container rule (max-width: 300px) {
+ .field { grid-template-columns: minmax(0, 1fr); gap: 3px; }
+ .label { padding-top: 0; }
+ .control :global(.cmp-seg.fill > button) { padding: 0 5px; }
+ }
+ .pair { display: grid; grid-template-columns: minmax(0, 1fr) auto minmax(0, 1fr); align-items: center; gap: 5px; }
+ .note { color: var(--text-3); font-size: 10.5px; line-height: 1.4; }
+ .value { display: flex; align-items: center; gap: 6px; }
.value input[type='number'] { width: 84px; }
+ .minus, .unit { color: var(--text-3); font-size: var(--fs-xs); }
.metres { width: 62px; }
.classes { display: flex; flex-wrap: wrap; gap: 4px; }
.chip {
@@ -218,5 +320,69 @@
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; }
+
+ /* The slider, with the ground that passes in the accent and the pins along it. */
+ .line { position: relative; padding-top: 12px; }
+ .line.stale { opacity: 0.6; }
+ .range {
+ --track: calc(7px + (100% - 14px) * var(--fraction));
+ -webkit-appearance: none;
+ appearance: none;
+ display: block;
+ width: 100%;
+ height: 18px;
+ margin: 0;
+ background: transparent;
+ cursor: pointer;
+ }
+ .range::-webkit-slider-runnable-track {
+ height: 4px;
+ border-radius: 99px;
+ background: linear-gradient(90deg, var(--accent) var(--track), var(--border-strong) var(--track));
+ }
+ .range.above::-webkit-slider-runnable-track {
+ background: linear-gradient(90deg, var(--border-strong) var(--track), var(--accent) var(--track));
+ }
+ .range::-moz-range-track { height: 4px; border-radius: 99px; background: var(--border-strong); }
+ .range::-moz-range-progress { height: 4px; border-radius: 99px; background: var(--accent); }
+ .range.above::-moz-range-progress { background: var(--border-strong); }
+ .range.above::-moz-range-track { background: var(--accent); }
+ .range::-webkit-slider-thumb {
+ -webkit-appearance: none;
+ width: 14px;
+ height: 14px;
+ margin-top: -5px;
+ border: 2px solid var(--bg-2);
+ border-radius: 50%;
+ background: var(--text-1);
+ box-shadow: 0 1px 4px rgb(0 0 0 / 0.5);
+ }
+ .range::-moz-range-thumb { width: 10px; height: 10px; border: 2px solid var(--bg-2); border-radius: 50%; background: var(--text-1); }
+ .range:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; border-radius: 4px; }
+ /* The shapes the map draws: filled where a candidate should come out, struck
+ where none should. */
+ .tick {
+ position: absolute;
+ top: 1px;
+ left: calc(7px + (100% - 14px) * var(--at));
+ width: 9px;
+ height: 9px;
+ transform: translateX(-50%);
+ border: 2px solid var(--text-1);
+ border-radius: 50%;
+ background: var(--bg-2);
+ box-sizing: border-box;
+ }
+ .tick-found { background: var(--text-1); }
+ .tick-empty { border-style: dashed; }
+ .tick.clipped { opacity: 0.6; }
+ .tick.passes { box-shadow: 0 0 0 2px color-mix(in srgb, var(--ok) 70%, transparent); }
+ .key { display: flex; align-items: center; flex-wrap: wrap; gap: 5px; color: var(--text-3); font-size: 10px; }
+ .key .tick { position: static; flex: 0 0 auto; transform: none; margin-left: 4px; }
+ .key .tick:first-child { margin-left: 0; }
+ .check { display: flex; align-items: center; flex-wrap: wrap; gap: 6px; color: var(--text-2); font-size: var(--fs-xs); }
+ .share, .effect { margin: 0; color: var(--text-3); font-size: 10.5px; line-height: 1.4; }
+ .effect { color: var(--text-2); }
+ .share.stale, .effect.stale { opacity: 0.6; }
+ .warn { margin: 0; }
</style>
diff --git a/frontend/src/tools/detect/RuleRow.svelte.test.js b/frontend/src/tools/detect/RuleRow.svelte.test.js
new file mode 100644
index 0000000..ebe0503
--- /dev/null
+++ b/frontend/src/tools/detect/RuleRow.svelte.test.js
@@ -0,0 +1,171 @@
+// @vitest-environment happy-dom
+import { afterEach, expect, it, vi } from 'vitest';
+import { flushSync, mount, unmount } from 'svelte';
+import RuleRow from './RuleRow.svelte';
+import { newRecipe, newRule } from '../../lib/map/analyzerRules.js';
+
+const METHODS = [{ id: 'rules', sizes: { all: {} } }];
+let live, target;
+afterEach(() => { if (live) unmount(live); live = null; target?.remove(); });
+
+/** A row on a rule the test can watch change: the row writes its rule back through the props it was given. */
+function open(rule, extra = {}) {
+ const { recipe, ...rest } = extra;
+ const props = $state({ rule, recipe: newRecipe(METHODS, recipe ?? {}), index: 0, colour: '#facc15', ...rest });
+ target = document.createElement('div');
+ document.body.append(target);
+ live = mount(RuleRow, { target, props });
+ flushSync();
+ return props;
+}
+const query = (selector) => target.querySelector(selector);
+const press = (group, text) => {
+ [...query(`[role="group"][aria-label="${group}"]`).querySelectorAll('button')].find((button) => button.textContent.trim() === text).click();
+ flushSync();
+};
+const type = (input, value, event = 'change') => { input.value = value; input.dispatchEvent(new Event(event, { bubbles: true })); flushSync(); };
+
+it('says the rule as the sentence it is, with the number and colour it wears on the map', () => {
+ open(newRule('index', 'change'));
+ expect(query('.sentence').textContent).toBe('NDVI dropped by 0.25 or more');
+ expect(query('.dot').textContent).toBe('1');
+ expect(query('.rule').getAttribute('style')).toContain('--tint: #facc15');
+});
+
+it('offers before, after and change on two dates, says where each is painted, and nothing on one date', () => {
+ open(newRule('index', 'change'));
+ expect([...query('[aria-label="Rule 1 reads"]').querySelectorAll('button')].map((b) => b.textContent)).toEqual(['Before', 'After', 'Change']);
+ expect(query('.note').textContent).toBe('Read as after minus before and painted on both sides.');
+ unmount(live); target.remove();
+ const props = open(newRule('index', 'a'));
+ expect(query('.note').textContent).toBe('Read on the before pass and painted on the left of the split.');
+ press('Rule 1 reads', 'After');
+ expect(props.rule.on).toBe('b');
+ expect(query('.note').textContent).toBe('Read on the after pass and painted on the right of the split.');
+ unmount(live); target.remove();
+ open(newRule('index', 'b'), { recipe: { dates: 'one' } });
+ expect(query('[aria-label="Rule 1 reads"]')).toBe(null);
+ expect(query('.sentence').textContent).toBe('NDVI is at least 0.40');
+});
+
+it('turns a drop into a rise or a move without losing its size, and a range asks for two values', () => {
+ const props = open(newRule('index', 'change'));
+ expect([...query('[aria-label="Rule 1 comparison"]').querySelectorAll('button')].map((b) => b.textContent)).toEqual(['Dropped', 'Rose', 'Either way', 'Between']);
+ press('Rule 1 comparison', 'Rose');
+ expect(props.rule).toMatchObject({ op: 'ge', value: 0.25 });
+ expect(query('.sentence').textContent).toBe('NDVI rose by 0.25 or more');
+ press('Rule 1 comparison', 'Either way');
+ expect(props.rule).toMatchObject({ op: 'moved', value: 0.25 });
+ press('Rule 1 comparison', 'Between');
+ expect(query('[aria-label="Rule 1 upper value"]')).not.toBe(null);
+ expect(query('input[type="range"]')).toBe(null);
+ press('Rule 1 comparison', 'Dropped');
+ expect(props.rule.op).toBe('le');
+ expect(query('[aria-label="Rule 1 upper value"]')).toBe(null);
+});
+
+it('sets the size of a drop as a positive number, which the rule keeps as a negative one', () => {
+ const props = open(newRule('index', 'change'));
+ expect(query('[aria-label="Rule 1 value"]').value).toBe('0.25');
+ type(query('[aria-label="Rule 1 value"]'), '0.4');
+ expect(props.rule.value).toBe(-0.4);
+ type(query('[aria-label="Rule 1 line"]'), '0.6', 'input');
+ expect(props.rule.value).toBe(-0.6);
+ press('Rule 1 comparison', 'Rose');
+ type(query('[aria-label="Rule 1 value"]'), '0.1');
+ expect(props.rule.value).toBe(0.1);
+});
+
+it('shows reflectance in percent and keeps it in fractions', () => {
+ const props = open(newRule('band', 'b', { band: 'B12' }));
+ expect(query('[aria-label="Rule 1 value"]').value).toBe('25');
+ type(query('[aria-label="Rule 1 value"]'), '30');
+ expect(props.rule.value).toBe(0.3);
+ expect(query('.unit').textContent).toBe('%');
+});
+
+it('puts the ground that passes in the accent: above the line for at least and a drop, below it for at most', () => {
+ open(newRule('index', 'change'));
+ expect(query('input[type="range"]').classList.contains('above')).toBe(true);
+ unmount(live); target.remove();
+ const props = open(newRule('index', 'a'));
+ expect(query('input[type="range"]').classList.contains('above')).toBe(true);
+ press('Rule 1 comparison', 'At most');
+ expect(props.rule.op).toBe('le');
+ expect(query('input[type="range"]').classList.contains('above')).toBe(false);
+});
+
+it('lays the pins along the line where the last test read them, and says which is which', () => {
+ open(newRule('index', 'change'), { ticks: [
+ { pin: 0, expect: 'found', at: 0.6, clipped: false, value: -0.6, passes: true },
+ { pin: 1, expect: 'empty', at: 0.05, clipped: false, value: -0.05, passes: false },
+ ] });
+ const ticks = [...target.querySelectorAll('.line .tick')];
+ expect(ticks.map((tick) => [tick.classList.contains('tick-found'), tick.classList.contains('tick-empty'), tick.classList.contains('passes')]))
+ .toEqual([[true, false, true], [false, true, false]]);
+ expect(ticks[0].getAttribute('style')).toContain('--at: 0.6');
+ expect(ticks[0].getAttribute('aria-label')).toBe('Should be found: this rule lets it through');
+ expect(ticks[1].getAttribute('aria-label')).toBe('Should stay empty: this rule turns it away');
+ expect(query('.key').textContent).toContain('should be found');
+});
+
+it('has no line to lay pins on for a ground class, which is or is not a set of grounds', () => {
+ const props = open(newRule('class', 'b'));
+ expect(query('input[type="range"]')).toBe(null);
+ expect([...query('[aria-label="Rule 1 ground classes"]').querySelectorAll('button')].map((b) => b.textContent)).toContain('water');
+ press('Rule 1 comparison', 'Is not');
+ expect(props.rule.op).toBe('not');
+ expect(query('.sentence').textContent).toBe('ground after is not water');
+});
+
+it('measures only what its satellite reads, and only as many things as there are to choose', () => {
+ open(newRule('radar', 'change'), { recipe: { sensor: 'sentinel1' } });
+ expect(query('[aria-label="Rule 1 measures"]')).toBe(null);
+ expect(query('[aria-label="Rule 1 polarisation"]')).not.toBe(null);
+ unmount(live); target.remove();
+ open(newRule('index', 'change'));
+ const measures = [...query('[aria-label="Rule 1 measures"]').options].map((option) => option.value);
+ expect(measures).toContain('index');
+ expect(measures).not.toContain('radar');
+ expect(measures).toContain('colour');
+ unmount(live); target.remove();
+ open(newRule('index', 'b'), { recipe: { dates: 'one' } });
+ expect([...query('[aria-label="Rule 1 measures"]').options].map((option) => option.value)).not.toContain('colour');
+});
+
+it('says how much of the ground it keeps, and what the pins would come to without it, dimmed once stale', () => {
+ open(newRule('index', 'change'), { index: 1, reading: { share: 0.12, kept: 0.03 }, effect: 'Without it, 1 pin would come out wrong.', match: 'all' });
+ expect(query('[aria-label="Rule 2 share"]').textContent).toBe('12 % of the ground · 3.0 % left with the ones above');
+ expect(query('[aria-label="Rule 2 effect"]').textContent).toBe('Without it, 1 pin would come out wrong.');
+ unmount(live); target.remove();
+ open(newRule('index', 'change'), { reading: { share: 0.12, kept: 0.12 }, stale: true });
+ expect(query('.share').classList.contains('stale')).toBe(true);
+ expect(query('.effect')).toBe(null);
+});
+
+it('shows and hides its pixels, ranks the candidates, is removed, and tells the map when the pointer is on it', () => {
+ const ontoggle = vi.fn();
+ const onsignal = vi.fn();
+ const onremove = vi.fn();
+ const onhover = vi.fn();
+ open(newRule('index', 'change'), { index: 1, ontoggle, onsignal, onremove, onhover, signal: false });
+ query('button.dot').click();
+ query('button.star').click();
+ query('button[aria-label="Remove rule 2"]').click();
+ expect([ontoggle, onsignal, onremove].map((fn) => fn.mock.calls.length)).toEqual([1, 1, 1]);
+ query('.rule').dispatchEvent(new Event('pointerenter'));
+ query('.rule').dispatchEvent(new Event('pointerleave'));
+ expect(onhover.mock.calls).toEqual([[1], [null]]);
+ expect(query('button.star').getAttribute('aria-label')).toBe('Rank candidates by rule 2');
+ unmount(live); target.remove();
+ open(newRule('index', 'change'), { signal: true, canRemove: false });
+ expect(query('button.star').disabled).toBe(true);
+ expect(query('button.star').textContent).toBe('★');
+ expect(query('button[aria-label="Remove rule 1"]')).toBe(null);
+});
+
+it('names what is wrong with a rule in place of its share', () => {
+ open({ ...newRule('nd', 'b'), bands: ['B08', 'B08'] }, { reading: { share: 0.1, kept: 0.1 } });
+ expect(query('.warn').textContent).toBe('Pick two different bands.');
+ expect(query('.share')).toBe(null);
+});
diff --git a/frontend/src/tools/detect/RuleTile.svelte b/frontend/src/tools/detect/RuleTile.svelte
new file mode 100644
index 0000000..5eb559c
--- /dev/null
+++ b/frontend/src/tools/detect/RuleTile.svelte
@@ -0,0 +1,32 @@
+<script>
+ /**
+ * One tile of a test laid on the ground: a canvas of the engine's mask,
+ * painted in the rules' colours and set on the map by the matrix it is given.
+ * It repaints only when a rule is shown, hidden or hovered.
+ */
+ import { paintMask } from '../../lib/map/analyzerRules.js';
+
+ let { bits, size, transform, shown = [], hover = null, colours = [], veil = 0 } = $props();
+ let canvas = $state(null);
+
+ $effect(() => {
+ if (!canvas || !bits || bits.length !== size * size) return;
+ canvas.width = size;
+ canvas.height = size;
+ const painted = paintMask(bits, { shown, hover, colours, veil });
+ canvas.getContext('2d').putImageData(new ImageData(painted, size, size), 0, 0);
+ });
+</script>
+
+<canvas bind:this={canvas} class="rule-tile" style:transform={transform}></canvas>
+
+<style>
+ .rule-tile {
+ position: absolute;
+ top: 0;
+ left: 0;
+ transform-origin: 0 0;
+ image-rendering: pixelated;
+ pointer-events: none;
+ }
+</style>
diff --git a/frontend/src/tools/detect/SecondPass.svelte b/frontend/src/tools/detect/SecondPass.svelte
new file mode 100644
index 0000000..2750bbc
--- /dev/null
+++ b/frontend/src/tools/detect/SecondPass.svelte
@@ -0,0 +1,180 @@
+<script>
+ /**
+ * The second pass of a check with two, on its own map laid over the first and
+ * cut at a line the analyst drags: the before pass shows on the left of it
+ * and the after pass on the right, the same ground in the same frame.
+ *
+ * It is a second surface, as Compare's swipe is, because two dates cannot be
+ * on one map at once. The two cameras are held together (`cameraLink`), so
+ * whichever one the hand is on, the other follows; the pins, the painted
+ * rules and the reading card are drawn over both by Detect.
+ */
+ import { untrack } from 'svelte';
+ import { api } from '../../lib/api.js';
+ import { linkCameras } from '../../lib/map/cameraLink.js';
+ import { RADAR_ID } from '../../lib/radar.js';
+ import { DEFAULT_MAXCC, SENTINEL_ID } from '../../lib/sentinel.js';
+ import { toast } from '../../lib/state.svelte.js';
+ import MapSurface from '../satellite/MapSurface.svelte';
+ import { createRadarState } from '../satellite/state/radar.svelte.js';
+ import { createSentinelState } from '../satellite/state/sentinel.svelte.js';
+ import Icon from '../../components/Icon.svelte';
+
+ let {
+ imagery,
+ /** The engine of the map underneath, whose camera this one follows. */
+ primary,
+ /** The pass to show: `{ provider, date, time, layer }`. */
+ source,
+ view,
+ bearing = 0,
+ home,
+ overlays = [],
+ imperial = false,
+ armed = null,
+ /** Where the cut sits, as a percentage of the map from its left edge. */
+ divider = 50,
+ engine = $bindable(null),
+ element = $bindable(null),
+ onsplit = () => {},
+ onclick = () => {},
+ oncontextmenu = () => {},
+ onusage = () => {},
+ } = $props();
+
+ const place = () => ({ lat: view.lat, lon: view.lon });
+ const s2 = createSentinelState({ place, onBilled: () => onusage(), notify: toast, api });
+ const s1 = createRadarState({ api, place, onBilled: () => onusage() });
+ let providerId = $state(SENTINEL_ID);
+ let stage = $state(null);
+ let ready = $state(false);
+ let dragging = $state(false);
+
+ // The pass asked for, put on this map the way Detect puts one on its own.
+ $effect(() => {
+ const { provider, date, time, layer } = source;
+ untrack(() => {
+ if (provider === 'sentinel1') {
+ providerId = RADAR_ID;
+ s1.pick({ date, time: time ?? '' });
+ } else {
+ providerId = SENTINEL_ID;
+ if (layer) s2.layer = layer;
+ s2.setMaxcc(DEFAULT_MAXCC);
+ s2.date = date;
+ }
+ });
+ });
+
+ // Held on one camera with the map underneath, which leads.
+ $effect(() => {
+ if (!primary || !engine || !ready) return;
+ const link = linkCameras([primary, engine]);
+ untrack(() => link.align());
+ return () => link.dispose();
+ });
+
+ // The column can be dragged wider or narrower; this map has to be told.
+ $effect(() => {
+ if (!stage || typeof ResizeObserver === 'undefined') return;
+ const watch = new ResizeObserver(() => engine?.resize());
+ watch.observe(stage);
+ return () => watch.disconnect();
+ });
+
+ function setAt(clientX) {
+ const box = stage?.getBoundingClientRect();
+ if (box?.width) onsplit(((clientX - box.left) / box.width) * 100);
+ }
+ function press(event) {
+ dragging = true;
+ event.currentTarget.setPointerCapture?.(event.pointerId);
+ setAt(event.clientX);
+ }
+ function drag(event) {
+ if (dragging) setAt(event.clientX);
+ }
+ function release(event) {
+ dragging = false;
+ event.currentTarget.releasePointerCapture?.(event.pointerId);
+ }
+ function key(event) {
+ if (event.key === 'ArrowLeft') onsplit(divider - 2);
+ else if (event.key === 'ArrowRight') onsplit(divider + 2);
+ else if (event.key === 'Home') onsplit(0);
+ else if (event.key === 'End') onsplit(100);
+ else return;
+ event.preventDefault();
+ }
+</script>
+
+<div class="second" bind:this={stage} style:--divider={`${divider}%`}>
+ <div class="clip">
+ <MapSurface bind:engine bind:element bind:ready bind:providerId {imagery} s2={s2} s1={s1} {view} {bearing} {home}
+ resetToHome={false} {imperial} {overlays} {armed} chrome={false} controlsTop={108} {onclick} {oncontextmenu} {onusage} />
+ </div>
+ <button type="button" class="line" class:dragging class:armed={!!armed} role="slider" aria-label="Split between the before and after passes"
+ aria-valuemin="0" aria-valuemax="100" aria-valuenow={Math.round(divider)} tabindex="0"
+ onpointerdown={press} onpointermove={drag} onpointerup={release} onpointercancel={release} onkeydown={key}>
+ <span class="handle" aria-hidden="true">
+ <Icon name="chevronLeft" size={12} stroke={2.4} /><i></i><Icon name="chevronRight" size={12} stroke={2.4} />
+ </span>
+ </button>
+</div>
+
+<style>
+ /* Over the first map and under everything the tool draws on the ground. */
+ .second { position: absolute; inset: 0; z-index: 1; pointer-events: none; }
+ .clip { position: absolute; inset: 0; display: flex; clip-path: inset(0 0 0 var(--divider)); pointer-events: none; }
+ .clip :global(.map-wrap) { pointer-events: auto; }
+ .line {
+ position: absolute;
+ top: 0;
+ bottom: 0;
+ left: var(--divider);
+ z-index: 2;
+ width: 2px;
+ padding: 0;
+ border: 0;
+ transform: translateX(-1px);
+ background: rgb(255 255 255 / 0.92);
+ box-shadow: 0 0 5px rgb(0 0 0 / 0.75);
+ cursor: ew-resize;
+ pointer-events: auto;
+ touch-action: none;
+ }
+ .line::before { position: absolute; inset: 0 -6px; content: ''; }
+ /* With a pin armed the line lets the click through, so a pin can be dropped on the ground it runs
+ over, which is the middle of the map when the map is centred on what is being checked. The
+ handle still takes the drag. */
+ .line.armed { pointer-events: none; }
+ .line:focus-visible { outline: none; }
+ .line:focus-visible .handle { box-shadow: 0 0 0 2px var(--accent), 0 4px 14px rgb(0 0 0 / 0.45); }
+ /* Off the middle of the map, where a click aimed at the place being checked would land on it. */
+ .handle {
+ position: absolute;
+ top: 26%;
+ left: 50%;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ gap: 3px;
+ width: 40px;
+ height: 30px;
+ transform: translate(-50%, -50%);
+ border: 1px solid rgb(255 255 255 / 0.38);
+ border-radius: 9px;
+ background: rgb(24 24 24 / 0.88);
+ backdrop-filter: blur(6px);
+ box-shadow: 0 4px 14px rgb(0 0 0 / 0.45);
+ color: #f8fafc;
+ pointer-events: auto;
+ transition: background 0.12s var(--ease), border-color 0.12s var(--ease), transform 0.12s var(--ease);
+ }
+ .handle i { width: 1px; height: 14px; background: rgb(255 255 255 / 0.28); }
+ .line:hover .handle, .line.dragging .handle {
+ border-color: rgb(255 255 255 / 0.62);
+ background: rgb(12 12 12 / 0.94);
+ transform: translate(-50%, -50%) scale(1.04);
+ }
+</style>
diff --git a/frontend/src/tools/detect/SecondPass.svelte.test.js b/frontend/src/tools/detect/SecondPass.svelte.test.js
new file mode 100644
index 0000000..6416b7d
--- /dev/null
+++ b/frontend/src/tools/detect/SecondPass.svelte.test.js
@@ -0,0 +1,101 @@
+// @vitest-environment happy-dom
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { flushSync, mount, unmount } from 'svelte';
+
+const links = [];
+vi.mock('../../lib/map/cameraLink.js', () => ({
+ linkCameras: (engines) => {
+ const link = { engines, align: vi.fn(), dispose: vi.fn() };
+ links.push(link);
+ return link;
+ },
+}));
+vi.mock('../satellite/MapSurface.svelte', () => import('./MapSurface.stub.svelte'));
+vi.mock('../../lib/api.js', () => ({ api: { get: vi.fn(), post: vi.fn() } }));
+vi.mock('../../lib/state.svelte.js', () => ({ toast: vi.fn() }));
+const { default: SecondPass } = await import('./SecondPass.svelte');
+
+let live, target;
+beforeEach(() => { links.length = 0; });
+afterEach(() => { if (live) unmount(live); live = null; target?.remove(); });
+
+function open(props = {}) {
+ const onsplit = vi.fn();
+ const primary = { fake: 'primary' };
+ target = document.createElement('div');
+ document.body.append(target);
+ live = mount(SecondPass, { target, props: {
+ imagery: {}, primary, source: { provider: 'sentinel2', date: '2026-05-11', layer: 'NDVI' }, view: { lat: 48, lon: 2, zoom: 13 },
+ bearing: 0, home: { lat: 0, lon: 0, zoom: 2 }, divider: 30, onsplit, ...props } });
+ flushSync();
+ return { onsplit, primary };
+}
+const slider = () => target.querySelector('[role="slider"]');
+const press = (key) => { slider().dispatchEvent(new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true })); flushSync(); };
+
+it('lays the cut where the divider says, and says so to a screen reader', () => {
+ open({ divider: 30 });
+ expect(target.querySelector('.second').getAttribute('style')).toContain('--divider: 30%');
+ expect(slider().getAttribute('aria-valuenow')).toBe('30');
+ expect(slider().getAttribute('aria-label')).toBe('Split between the before and after passes');
+});
+
+it('moves the cut from the keys, two points a press, and to either end', () => {
+ const { onsplit } = open({ divider: 30 });
+ press('ArrowRight'); press('ArrowLeft'); press('Home'); press('End'); press('x');
+ expect(onsplit.mock.calls).toEqual([[32], [28], [0], [100]]);
+});
+
+it('moves the cut to where the pointer is over the map, as a share of its width', () => {
+ const { onsplit } = open();
+ target.querySelector('.second').getBoundingClientRect = () => ({ left: 100, width: 400, top: 0, height: 300, right: 500, bottom: 300 });
+ const down = new Event('pointerdown', { bubbles: true });
+ Object.assign(down, { clientX: 300, pointerId: 1 });
+ slider().dispatchEvent(down);
+ const move = new Event('pointermove', { bubbles: true });
+ Object.assign(move, { clientX: 400, pointerId: 1 });
+ slider().dispatchEvent(move);
+ const up = new Event('pointerup', { bubbles: true });
+ Object.assign(up, { clientX: 450, pointerId: 1 });
+ slider().dispatchEvent(up);
+ // a move after the release does nothing
+ const late = new Event('pointermove', { bubbles: true });
+ Object.assign(late, { clientX: 120, pointerId: 1 });
+ slider().dispatchEvent(late);
+ expect(onsplit.mock.calls).toEqual([[50], [75]]);
+});
+
+it('shows the pass it is given on a map of its own, without the map’s chrome', () => {
+ open();
+ const stub = target.querySelector('.stub');
+ expect(stub.dataset.provider).toBe('sentinel2');
+ expect(stub.dataset.chrome).toBe('false');
+});
+
+it('shows a radar pass from the radar basemap', () => {
+ open({ source: { provider: 'sentinel1', date: '2026-05-11', time: '05:30:12' } });
+ expect(target.querySelector('.stub').dataset.provider).toBe('sentinel1');
+});
+
+it('holds its camera to the map underneath once it is up, and lets go with it', () => {
+ const { primary } = open();
+ expect(links).toHaveLength(1);
+ expect(links[0].engines[0]).toBe(primary);
+ expect(links[0].engines[1]).toMatchObject({ fake: true });
+ expect(links[0].align).toHaveBeenCalledOnce();
+ unmount(live); live = null;
+ expect(links[0].dispose).toHaveBeenCalledOnce();
+});
+
+it('hands the cursor mode on to its own map, so a pin can be dropped on either half', () => {
+ open({ armed: 'selecting' });
+ expect(target.querySelector('.stub').dataset.armed).toBe('selecting');
+});
+
+it('lets a click through the line while a pin is armed, and takes it otherwise', () => {
+ open({ armed: 'selecting' });
+ expect(slider().classList.contains('armed')).toBe(true);
+ unmount(live); target.remove();
+ open();
+ expect(slider().classList.contains('armed')).toBe(false);
+});
diff --git a/frontend/src/tools/detect/WhenStep.svelte b/frontend/src/tools/detect/WhenStep.svelte
index 08b5374..d070bb2 100644
--- a/frontend/src/tools/detect/WhenStep.svelte
+++ b/frontend/src/tools/detect/WhenStep.svelte
@@ -6,14 +6,8 @@
* is the newest pass under the cloud ceiling unless a day is chosen, and says
* which day that is once the passes are looked up. A chosen day is read
* whatever its cloud. A routine names no B: each run looks the newest pass up
- * itself, so this only asks what it compares with. The ceiling's slider sits
- * wherever "newest" picks, and says what a ceiling over 30% costs.
- * The passes over the areas are listed under the question, because picking
- * from what exists beats typing a day that may have no picture.
- *
- * One choice stands for every area; the per-area table is for areas far
- * enough apart to sit under different swaths. The pure part is
- * `lib/map/detectWhen.js`. The lookup waits to be pressed.
+ * itself, so this only asks what it compares with. Dates open a calendar of
+ * actual passes; the longer pass list is fetched on request.
*/
import { untrack } from 'svelte';
import { api } from '../../lib/api.js';
@@ -21,14 +15,15 @@
acquisitionQuery, areaKey, cloudWarning, coverageWarning, olderSpan, passKey, withOlder,
} from '../../lib/map/acquisitions.js';
import {
- areaLine, ceilingWarning, newestLabel, newestLine, newestPick, setSide, shadowWarning, sharedSide, uniform,
+ canPickPass, newestLabel, newestLine, newestPick, passBefore, setSide, shadowWarning, sharedSide,
withRule,
} from '../../lib/map/detectWhen.js';
import { isoDay } from '../../lib/sentinel.js';
import AcquisitionPicker from './AcquisitionPicker.svelte';
import AreaDates from './AreaDates.svelte';
+ import PassCalendar from './PassCalendar.svelte';
import DateField from '../../components/DateField.svelte';
- import Modal from '../../components/Modal.svelte';
+ import Icon from '../../components/Icon.svelte';
let {
zones = [],
@@ -37,14 +32,12 @@
/** A vessel or a fire is read on one image; a change needs two. */
single = false,
sensor = 'sentinel2',
- followupId = null,
+ lastPasses = {},
against = $bindable('previous'),
/** A one pass reads B on a day of its own rather than the newest pass. */
chooseB = $bindable(false),
/** The cloud ceiling "newest" is chosen under. A chosen day ignores it. */
maxcc = 100,
- /** Sets the ceiling; without it (radar) no slider is shown. */
- onmaxcc = null,
/** The last lookup, held by the wizard so stepping back does not pay for it twice. */
lookup = $bindable(null),
onshow = () => {},
@@ -59,20 +52,24 @@
let lookback = $state(untrack(() => lookup?.lookback ?? 90));
let busy = $state(false);
let error = $state('');
- let perArea = $state(false);
let generation = 0;
+ let calendarSide = $state('');
+ let calendarPasses = $state([]);
+ let calendarBusy = $state(false);
+ let calendarError = $state('');
+ let calendarGeneration = 0;
+ const calendarCache = new Map();
const key = $derived(areaKey(zones));
// a list looked up another day has missed that day's passes
const fresh = $derived(lookup?.key === key && lookup?.day === isoDay(new Date()) ? lookup : null);
const a = $derived(sharedSide(pairs, 'a'));
const b = $derived(sharedSide(pairs, 'b'));
- const same = $derived(uniform(pairs));
const several = $derived(zones.length > 1);
const ground = $derived(several ? 'these areas' : 'the area');
const heading = $derived(routine ? (single ? 'Which image, each run' : 'Which images, each run')
: single ? 'Which image' : 'Which two images');
- const waived = $derived(routine && !!followupId && against === 'previous');
+ const waived = $derived(routine && against === 'previous' && zones.every((zone) => !!lastPasses[zone.id]));
const aTitle = $derived(!routine ? 'Before' : against === 'previous' ? 'First run compares with' : 'Every run compares with');
const aHint = $derived(
!routine ? 'The picture without the change.'
@@ -91,9 +88,6 @@
.flatMap((entry) => [coverageWarning(entry), radar ? '' : cloudWarning(entry, maxcc)])
.filter(Boolean));
const shadows = $derived(shadowWarning(pairs, zones, { single, radar }));
- // the slider sits where the ceiling is in play: wherever "newest" picks B
- const ceiling = $derived(!radar && !!onmaxcc);
- const ceilingNote = $derived(ceilingWarning(maxcc));
const look = () => search(lookback, false);
const lookOlder = () => search(olderSpan(lookback, fresh?.list), true);
@@ -108,23 +102,50 @@
if (mine !== generation) return;
const list = more ? withOlder(fresh?.list, found.dates) : found.dates ?? [];
lookup = { key, day: isoDay(new Date()), lookback, list, truncated: !!found.truncated };
+ const picked = newestPick(list, { maxcc, radar, track: radar && !single ? a?.time ?? '' : '' });
+ if (picked.pass && zones[0]) onshow({ ...pairs[0]?.b, date: picked.pass.date,
+ time: picked.pass.time ?? '', cloud: picked.pass.cloud, area: zones[0], side: 'B' });
} catch (e) { if (mine === generation) error = e.message; }
finally { if (mine === generation) busy = false; }
}
+ async function loadCalendarMonth(month) {
+ const cacheKey = `${key}:${month}`;
+ const cached = calendarCache.get(cacheKey);
+ const mine = ++calendarGeneration;
+ if (cached) { calendarPasses = cached; calendarBusy = false; calendarError = ''; return; }
+ calendarPasses = []; calendarBusy = true; calendarError = '';
+ const last = new Date(Date.UTC(Number(month.slice(0, 4)), Number(month.slice(5, 7)), 0))
+ .toISOString().slice(0, 10);
+ const end = last < isoDay(new Date()) ? last : isoDay(new Date());
+ try {
+ const found = await api.post('/api/satellite/sentinel/acquisitions',
+ acquisitionQuery(zones, { start: `${month}-01`, end }, new Date(), sensor));
+ calendarCache.set(cacheKey, found.dates ?? []);
+ if (mine === calendarGeneration) calendarPasses = found.dates ?? [];
+ } catch (e) { if (mine === calendarGeneration) calendarError = e.message; }
+ finally { if (mine === calendarGeneration) calendarBusy = false; }
+ }
+
/** One pass on one side of every area, shown on the map as it is chosen,
* with its cloud when the lookup knows it. */
- function pick(letter, date, time = '') {
+ function pick(letter, date, time = '', closeCalendar = true) {
pairs = setSide(pairs, letter, date, time, radar);
if (letter === 'b' && date) chooseB = true;
if (!date || !pairs.length) return;
- const cloud = radar ? null : fresh?.list.find((pass) => pass.date === date)?.cloud ?? null;
- onshow({ ...pairs[0][letter], date, cloud, ...(radar ? { provider: 'sentinel1', time } : {}) });
+ if (closeCalendar) calendarSide = '';
+ const cloud = radar ? null : [...calendarPasses, ...(fresh?.list ?? [])]
+ .find((pass) => pass.date === date)?.cloud ?? null;
+ onshow({ ...pairs[0][letter], date, cloud, area: zones[0], side: letter,
+ ...(radar ? { provider: 'sentinel1', time } : {}) });
}
function takeNewest() {
chooseB = false;
+ calendarSide = '';
pairs = setSide(pairs, 'b', '', '', radar);
+ if (newestNow?.pass && zones[0]) onshow({ ...pairs[0].b, date: newestNow.pass.date,
+ time: newestNow.pass.time ?? '', cloud: newestNow.pass.cloud, area: zones[0], side: 'B' });
}
function compareWith(value) {
@@ -135,22 +156,26 @@
const time = (side) => (radar && side?.time ? `${side.time.slice(0, 5)} UTC` : '');
</script>
-{#snippet ceilingRow()}
- <label class="ceiling" title="The newest pass is taken under this">
- <span>Maximum cloud cover · {maxcc}%</span>
- <input type="range" min="0" max="100" value={maxcc} aria-label="Maximum cloud cover"
- oninput={(e) => onmaxcc(Number(e.currentTarget.value))} />
- </label>
- {#if ceilingNote}<p class="warn" role="note">{ceilingNote}</p>{/if}
-{/snippet}
-
<section class="step" aria-label="Which imagery">
<h3>{heading}</h3>
- {#if routine && single}
+ {#if several}
+ {#if routine && !single}
+ <p class="lead">Each area takes its newest eligible pass as B and compares it with</p>
+ <div class="options" role="radiogroup" aria-label="What each run compares with">
+ {#each AGAINST as [value, title, detail] (value)}
+ <button type="button" role="radio" class="option" class:on={against === value}
+ aria-checked={against === value} onclick={() => compareWith(value)}>
+ <strong>{title}</strong><span>{detail}</span>
+ </button>
+ {/each}
+ </div>
+ {/if}
+ <AreaDates {zones} bind:pairs {single} {routine} baselineOnly={routine} previous={routine && against === 'previous'}
+ {lastPasses} {sensor} {onshow} />
+ {:else if routine && single}
<p class="lead">Each run reads the {newest} over {ground}.</p>
<p class="hint">Nothing to choose now. When you run it, you can keep that pass or name another.</p>
- {#if ceiling}{@render ceilingRow()}{/if}
{:else}
{#if routine}
<p class="lead">Each run takes the {newest} as B and compares it with</p>
@@ -162,7 +187,6 @@
</button>
{/each}
</div>
- {#if ceiling}{@render ceilingRow()}{/if}
{/if}
<div class="slots">
@@ -170,12 +194,31 @@
<div class="slot" class:missing={!a?.date && !waived}>
<span class="tag a" aria-hidden="true">A</span>
<div class="body">
- <span class="k">{aTitle}</span>
+ <span class="k">Date A · {aTitle}</span>
<div class="line">
- <DateField day reading={false} label="Day of A" value={a?.date ?? ''}
- placeholder={same || !several ? 'dd/mm/yyyy' : 'per area'} onchange={(value) => pick('a', value ?? '')} />
+ {#if routine && against === 'previous' && lastPasses[zones[0]?.id]}
+ <button class="link" onclick={() => onshow({ ...lastPasses[zones[0].id], area: zones[0], side: 'A' })}>
+ {lastPasses[zones[0].id].date} · View A</button>
+ {:else}
+ <button class="date-pick" aria-label="Date A" aria-expanded={calendarSide === 'a'}
+ onclick={() => (calendarSide = 'a')}>
+ <Icon name="calendar" size={13} /><span>{a?.date || 'Choose a pass'}</span>
+ <Icon name="chevronDown" size={12} />
+ </button>
+ {/if}
{#if time(a)}<small class="mono">{time(a)}</small>{/if}
</div>
+ {#if calendarSide === 'a'}
+ <PassCalendar list={calendarPasses} value={a?.date ?? ''} label="A" {radar}
+ busy={calendarBusy} error={calendarError} eligible={(pass) => canPickPass('a', pass, a, b, radar)}
+ onmonth={loadCalendarMonth}
+ onclose={() => (calendarSide = '')}
+ onpick={(pass) => pick('a', pass.date, pass.time ?? '')} />
+ <details class="manual-date"><summary>Enter a date</summary>
+ <DateField day reading={false} label="Day of A" value={a?.date ?? ''}
+ onchange={(value) => pick('a', value ?? '', '', false)} />
+ </details>
+ {/if}
<small>{aHint}</small>
</div>
</div>
@@ -184,27 +227,34 @@
<div class="slot" class:missing={chooseB && !b?.date}>
{#if !single}<span class="tag b" aria-hidden="true">B</span>{/if}
<div class="body">
- {#if !single}<span class="k">After</span>{/if}
- <div class="cmp-seg" role="radiogroup" aria-label={single ? 'Which image' : 'Which picture B is'}>
- <button type="button" role="radio" class:on={!chooseB} aria-checked={!chooseB} onclick={takeNewest}>{Newest}</button>
- <button type="button" role="radio" class:on={chooseB} aria-checked={chooseB} onclick={() => (chooseB = true)}>A day I choose</button>
+ <span class="k">{single ? 'Image date' : 'Date B · After'}</span>
+ <div class="line">
+ <button class="date-pick" aria-label={single ? 'Image date' : 'Date B'}
+ aria-expanded={calendarSide === 'b'} onclick={() => (calendarSide = 'b')}>
+ <Icon name="calendar" size={13} /><span>{chooseB && b?.date ? b.date : Newest}</span>
+ <Icon name="chevronDown" size={12} />
+ </button>
+ {#if time(b)}<small class="mono">{time(b)}</small>{/if}
</div>
- {#if chooseB}
- <div class="line">
+ {#if chooseB}<button class="link" onclick={takeNewest}>Use newest pass</button>
+ {:else}<small>{newestNote}</small>{/if}
+ {#if calendarSide === 'b'}
+ <PassCalendar list={calendarPasses} value={b?.date ?? ''} label="B" {radar}
+ busy={calendarBusy} error={calendarError} eligible={(pass) => canPickPass('b', pass, a, b, radar)}
+ onmonth={loadCalendarMonth}
+ onclose={() => (calendarSide = '')}
+ onpick={(pass) => pick('b', pass.date, pass.time ?? '')} />
+ <details class="manual-date"><summary>Enter a date</summary>
<DateField day reading={false} label={single ? 'Day of the image' : 'Day of B'} value={b?.date ?? ''}
- placeholder={same || !several ? 'dd/mm/yyyy' : 'per area'} onchange={(value) => pick('b', value ?? '')} />
- {#if time(b)}<small class="mono">{time(b)}</small>{/if}
- </div>
- <small>Type it, or pick it in the passes below.</small>
- {:else}
- {#if ceiling}{@render ceilingRow()}{/if}
- <small>{newestNote}</small>
+ onchange={(value) => pick('b', value ?? '', '', false)} />
+ </details>
{/if}
</div>
</div>
{/if}
</div>
+ {#if !single && b?.date && !passBefore(a, b, radar)}<p class="warn" role="alert">Date A must be before date B.</p>{/if}
{#if shadows}<p class="warn" role="note">{shadows}</p>{/if}
<p class="passes-title"><strong>Passes over {ground}</strong>
@@ -217,27 +267,8 @@
{#each warnings as warning (warning)}<p class="warn">{warning}</p>{/each}
{/if}
- {#if several && !(routine && single)}
- <p class="hint">{same ? `The same days for all ${zones.length} areas.` : 'The areas have days of their own.'}
- <button class="link" onclick={() => (perArea = true)}>Set them per area…</button></p>
- {#if !same}
- <ul class="dates">
- {#each zones as zone (zone.id)}
- {@const pair = pairs.find((row) => row.area_id === zone.id)}
- <li><span class="who">{zone.name}</span><span class="what">{areaLine(pair, { single, routine, radar })}</span></li>
- {/each}
- </ul>
- {/if}
- {/if}
</section>
-{#if perArea}
- <Modal title="Dates per area" width="760px" onclose={() => (perArea = false)}>
- <AreaDates {zones} bind:pairs {single} baselineOnly={routine} {sensor} {onshow} />
- <button class="btn btn-primary" onclick={() => (perArea = false)}>Done</button>
- </Modal>
-{/if}
-
<style>
.step { display: grid; gap: 9px; }
h3 { margin: 0; font-size: var(--fs-sm); font-weight: 700; }
@@ -280,17 +311,17 @@
.k { color: var(--text-1); font-size: var(--fs-xs); font-weight: 600; }
.line { display: flex; align-items: center; gap: 8px; }
.line :global(.date-field) { width: 145px; }
+ .date-pick { display: flex; align-items: center; gap: 7px; width: min(100%, 246px);
+ padding: 6px 8px; border: 1px solid var(--border); border-radius: var(--r-sm);
+ background: var(--bg-2); color: var(--text-1); font-size: var(--fs-xs); text-align: left; }
+ .date-pick:hover, .date-pick[aria-expanded="true"] { border-color: var(--accent); }
+ .date-pick span { flex: 1; }
+ .manual-date { color: var(--text-3); font-size: 10px; }
+ .manual-date summary { cursor: pointer; }
small { color: var(--text-3); font-size: 10.5px; line-height: 1.35; }
.mono { font-family: var(--font-mono); color: var(--text-2); }
- .cmp-seg { justify-self: start; }
.passes-title { display: flex; flex-wrap: wrap; gap: 6px; align-items: baseline; margin: 2px 0 0; font-size: var(--fs-xs); }
.passes-title span { color: var(--text-3); font-size: 10.5px; }
- .ceiling { display: grid; gap: 3px; color: var(--text-2); font-size: var(--fs-xs); }
- .ceiling input { width: 100%; }
.link { color: var(--accent); font-size: var(--fs-xs); }
.warn { margin: 0; color: var(--warn, #e2a03f); font-size: 10.5px; line-height: 1.35; }
- .dates { display: grid; gap: 3px; margin: 0; padding: 0; list-style: none; }
- .dates li { display: flex; gap: 8px; font-size: var(--fs-xs); }
- .dates .who { flex: 1; min-width: 0; overflow: hidden; color: var(--text-2); text-overflow: ellipsis; white-space: nowrap; }
- .dates .what { color: var(--text-3); font-family: var(--font-mono); font-size: 10.5px; }
</style>
diff --git a/frontend/src/tools/detect/benchHolder.fixture.svelte.js b/frontend/src/tools/detect/benchHolder.fixture.svelte.js
new file mode 100644
index 0000000..33af6da
--- /dev/null
+++ b/frontend/src/tools/detect/benchHolder.fixture.svelte.js
@@ -0,0 +1,6 @@
+/**
+ * Where a test finds the bench the panel builds an analyzer on. The map reads
+ * it through `bind:builder`; `BenchPanel.fixture.svelte` hands it on to here,
+ * so a test can do what the console over the map does: pick a check, drop a pin.
+ */
+export const holder = $state({ bench: null });
diff --git a/frontend/src/tools/inspect/CollageCanvas.svelte b/frontend/src/tools/inspect/CollageCanvas.svelte
index 07fbde6..0c15815 100644
--- a/frontend/src/tools/inspect/CollageCanvas.svelte
+++ b/frontend/src/tools/inspect/CollageCanvas.svelte
@@ -490,7 +490,7 @@
<Icon name="eye" size={14} /> Fit
</button>
{:else}
- <span class="zoom-hint">scroll to zoom · drag background to pan · shift-click to select several</span>
+ <span class="zoom-hint">scroll to zoom · drag background to pan · pull corners to warp · shift-click to select several</span>
{/if}
</div>
diff --git a/frontend/src/tools/inspect/CollageMenu.render.svelte.test.js b/frontend/src/tools/inspect/CollageMenu.render.svelte.test.js
new file mode 100644
index 0000000..bfe3a56
--- /dev/null
+++ b/frontend/src/tools/inspect/CollageMenu.render.svelte.test.js
@@ -0,0 +1,59 @@
+// @vitest-environment happy-dom
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { flushSync, mount, unmount } from 'svelte';
+
+vi.mock('../../lib/api.js', () => ({ api: { post: vi.fn() } }));
+vi.mock('../../lib/state.svelte.js', () => ({ caseState: { current: { id: 'case-a' } }, toast: vi.fn() }));
+
+const { default: CollageMenu } = await import('./CollageMenu.svelte');
+
+const rect = [[0, 0], [80, 0], [80, 60], [0, 60]];
+const node = (id, save, extra = {}) => ({ id, save, quad: rect, w: 80, h: 60, url: `blob:${id}`, ...extra });
+
+let live;
+let target;
+
+function show(nodes, selectedIds) {
+ target = document.createElement('div');
+ document.body.append(target);
+ live = mount(CollageMenu, {
+ target,
+ props: {
+ collage: { width: 1600, height: 800, nodes },
+ selectedIds,
+ requestCrop: vi.fn(),
+ renderPiece: vi.fn(),
+ fileTitles: new Map([['media/clip.mp4', 'Convoy clip']]),
+ },
+ });
+ flushSync();
+}
+
+afterEach(() => {
+ if (live) unmount(live);
+ live = null;
+ target?.remove();
+});
+
+describe('the selected piece', () => {
+ it('says which file it was cut from, and where in it', () => {
+ show([node('nd_1', { path: 'media/clip.mp4', time: 12.4, ops: [] })], ['nd_1']);
+
+ expect(target.querySelector('.identity .source').textContent).toBe('Convoy clip · 0:12.4');
+ expect(target.querySelector('.identity img').getAttribute('src')).toBe('blob:nd_1');
+ });
+
+ it('names an image by its file alone, even one the case no longer lists', () => {
+ show([node('nd_1', { path: 'media/roof.png', time: null, ops: [] })], ['nd_1']);
+
+ expect(target.querySelector('.identity .source').textContent).toBe('roof.png');
+ });
+
+ it('shows nothing of a piece while none is selected, and asks for no canvas size', () => {
+ show([node('nd_1', { path: 'media/roof.png', time: null, ops: [] })], []);
+
+ expect(target.querySelector('.identity')).toBeNull();
+ expect(target.querySelector('input[type="number"]')).toBeNull();
+ expect(target.querySelector('.hint')).toBeNull();
+ });
+});
diff --git a/frontend/src/tools/inspect/CollageMenu.svelte b/frontend/src/tools/inspect/CollageMenu.svelte
index f54c52c..3c83ed0 100644
--- a/frontend/src/tools/inspect/CollageMenu.svelte
+++ b/frontend/src/tools/inspect/CollageMenu.svelte
@@ -1,15 +1,15 @@
<script>
import {
- scaleQuad, rotateQuad, quadCentroid, rotateQuads, scaleQuads, pinholeOps, clampCollageDim,
- stitchCanvas, COLLAGE_MIN_DIM, COLLAGE_MAX_DIM,
+ scaleQuad, rotateQuad, quadCentroid, rotateQuads, scaleQuads, pinholeOps, stitchCanvas, clockTime,
} from '../../lib/inspect.js';
import { api } from '../../lib/api.js';
import { caseState, toast } from '../../lib/state.svelte.js';
import Icon from '../../components/Icon.svelte';
- // 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();
+ // The panel beside the canvas: the selected piece or block, and the auto
+ // panorama. Adding pieces and exporting live in the Collage tool around it.
+ // `fileTitles` names a piece's file as the case names it now.
+ let { collage: active, selectedIds = $bindable([]), requestCrop, renderPiece, fileTitles = new Map() } = $props();
// 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.
@@ -17,14 +17,14 @@
selectedIds.length === 1 ? (active?.nodes.find((n) => n.id === selectedIds[0]) ?? null) : null
);
- // 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.
- function setDim(event, axis) {
- const next = clampCollageDim(event.currentTarget.value, active[axis]);
- active[axis] = next;
- event.currentTarget.value = next;
- }
+ // Which file the selected piece was cut from, and where in it.
+ const source = $derived.by(() => {
+ if (!selected) return null;
+ const path = selected.save?.path ?? '';
+ const name = fileTitles.get(path) ?? path.split('/').pop();
+ const time = selected.save?.time;
+ return time == null ? name : `${name} · ${clockTime(time)}`;
+ });
function removeNode(id) {
active.nodes = active.nodes.filter((n) => n.id !== id);
@@ -97,9 +97,9 @@
// into each piece's recipe — bounded and undistorted however far you panned, at
// the cost of the corner handles.
const MODES = [
- { id: 'planar', label: 'Planar', hint: 'One flat surface such as a facade, the ground or a map. Pieces stay warpable.' },
- { id: 'cylindrical', label: 'Cylindrical', hint: 'A camera panning sideways. Bounded and even end to end.' },
- { id: 'spherical', label: 'Spherical', hint: 'A camera that pans *and* tilts. Same, over both axes.' },
+ { id: 'planar', label: 'Planar', hint: 'One flat surface, such as a facade or the ground. Pieces stay warpable.' },
+ { id: 'cylindrical', label: 'Cylindrical', hint: 'A camera panning sideways.' },
+ { id: 'spherical', label: 'Spherical', hint: 'A camera that pans and tilts.' },
];
let mode = $state('cylindrical');
let stitching = $state(false);
@@ -185,50 +185,21 @@
</script>
<div class="module">
- <p class="hint">Drag pieces to arrange them, pull corners to warp; shift-click selects several.</p>
-
- <div class="section">
- <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>
- </div>
-
{#if selected}
<div class="section">
- <div class="section-head"><span>Selected piece</span></div>
- <div class="scale-row">
- <span class="lbl">Scale</span>
- <button class="btn btn-sm sq" onclick={() => scaleBy(selected, 1 / 1.1)} aria-label="Shrink piece">−</button>
- <button class="btn btn-sm sq" onclick={() => scaleBy(selected, 1.1)} aria-label="Enlarge piece">+</button>
- <span class="sub">or drag a square side handle</span>
+ <div class="identity" title={source}>
+ <span class="mini">
+ {#if selected.url}<img src={selected.url} alt="" />{:else}<Icon name={selected.missing ? 'alert' : 'image'} size={14} />{/if}
+ </span>
+ <span class="source">{source}</span>
</div>
<div class="scale-row">
- <span class="lbl">Rotate</span>
- <button class="btn btn-sm sq" onclick={() => rotateByDeg(selected, -15)} aria-label="Rotate left">↺</button>
- <button class="btn btn-sm sq" onclick={() => rotateByDeg(selected, 15)} aria-label="Rotate right">↻</button>
- <span class="sub">or drag the ↻ handle above the piece</span>
+ <span class="lbl">Scale</span>
+ <button class="btn btn-sm sq" onclick={() => scaleBy(selected, 1 / 1.1)} aria-label="Shrink piece" title="Shrink, or drag a side handle">−</button>
+ <button class="btn btn-sm sq" onclick={() => scaleBy(selected, 1.1)} aria-label="Enlarge piece" title="Enlarge, or drag a side handle">+</button>
+ <span class="lbl gap">Rotate</span>
+ <button class="btn btn-sm sq" onclick={() => rotateByDeg(selected, -15)} aria-label="Rotate left" title="Turn 15° left, or drag the ↻ handle">↺</button>
+ <button class="btn btn-sm sq" onclick={() => rotateByDeg(selected, 15)} aria-label="Rotate right" title="Turn 15° right, or drag the ↻ handle">↻</button>
</div>
<div class="actions">
<button class="btn btn-sm" onclick={() => requestCrop?.(selected)}><Icon name="crop" size={13} /> Crop</button>
@@ -245,19 +216,16 @@
{#if selectedGroup.length > 1}
<div class="section">
- <div class="section-head"><span>Selected block <span class="count">{selectedGroup.length}</span></span></div>
- <p class="hint">Moves as one block; shift-click a piece to add or drop it.</p>
- <div class="scale-row">
- <span class="lbl">Scale</span>
- <button class="btn btn-sm sq" onclick={() => scaleGroupBy(1 / 1.1)} aria-label="Shrink block">−</button>
- <button class="btn btn-sm sq" onclick={() => scaleGroupBy(1.1)} aria-label="Enlarge block">+</button>
- <span class="sub">or drag a block corner</span>
+ <div class="section-head" title="Moves as one block; shift-click a piece to add or drop it">
+ <span>{selectedGroup.length} pieces selected</span>
</div>
<div class="scale-row">
- <span class="lbl">Rotate</span>
- <button class="btn btn-sm sq" onclick={() => rotateGroupByDeg(-15)} aria-label="Rotate block left">↺</button>
- <button class="btn btn-sm sq" onclick={() => rotateGroupByDeg(15)} aria-label="Rotate block right">↻</button>
- <span class="sub">or drag the ↻ knob</span>
+ <span class="lbl">Scale</span>
+ <button class="btn btn-sm sq" onclick={() => scaleGroupBy(1 / 1.1)} aria-label="Shrink block" title="Shrink, or drag a block corner">−</button>
+ <button class="btn btn-sm sq" onclick={() => scaleGroupBy(1.1)} aria-label="Enlarge block" title="Enlarge, or drag a block corner">+</button>
+ <span class="lbl gap">Rotate</span>
+ <button class="btn btn-sm sq" onclick={() => rotateGroupByDeg(-15)} aria-label="Rotate block left" title="Turn 15° left, or drag the ↻ knob">↺</button>
+ <button class="btn btn-sm sq" onclick={() => rotateGroupByDeg(15)} aria-label="Rotate block right" title="Turn 15° right, or drag the ↻ knob">↻</button>
</div>
<div class="actions">
<button class="btn btn-sm danger" onclick={removeGroup} title="or press Delete">
@@ -268,12 +236,9 @@
{/if}
<div class="section">
- <div class="section-head"><span>Auto panorama</span></div>
- <p class="hint">
- Solves the layout from the overlapping imagery itself, then drops the pieces back on the
- canvas, which grows to hold them at full resolution. You can still drag pieces to correct
- the result.
- </p>
+ <div class="section-head" title="Places the pieces from the imagery they share. You can still drag them after.">
+ <span>Auto panorama</span>
+ </div>
<div class="modes">
{#each MODES as m (m.id)}
<button class="mode" class:on={mode === m.id} onclick={() => (mode = m.id)} title={m.hint}>
@@ -281,7 +246,6 @@
</button>
{/each}
</div>
- <p class="hint sub-hint">{MODES.find((m) => m.id === mode).hint}</p>
<button
class="btn btn-sm w-full"
disabled={stitching || !active || active.nodes.length < 2}
@@ -307,20 +271,47 @@
flex-direction: column;
gap: 12px;
}
- .hint {
- color: var(--text-3);
- font-size: var(--fs-xs);
- margin: 0;
- }
.section {
display: flex;
flex-direction: column;
gap: 8px;
}
- .hint + .section {
+ .section + .section {
border-top: 1px solid var(--border);
padding-top: 12px;
}
+ .identity {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ min-width: 0;
+ }
+ .mini {
+ flex-shrink: 0;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ width: 40px;
+ height: 30px;
+ border-radius: var(--r-sm);
+ overflow: hidden;
+ background: var(--bg-0);
+ color: var(--text-3);
+ }
+ .mini img {
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ }
+ .source {
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ font-size: var(--fs-sm);
+ font-weight: 600;
+ color: var(--text-1);
+ }
.section-head {
font-weight: 600;
font-size: var(--fs-sm);
@@ -349,9 +340,6 @@
background: var(--bg-3);
color: var(--accent);
}
- .sub-hint {
- margin-top: -2px;
- }
.scale-row {
display: flex;
align-items: center;
@@ -361,14 +349,8 @@
font-size: var(--fs-sm);
color: var(--text-2);
}
- .scale-row .sub {
- font-size: var(--fs-xs);
- color: var(--text-3);
- }
- .dim {
- width: 5.5em;
- padding: 4px 6px;
- font-size: var(--fs-xs);
+ .scale-row .gap {
+ margin-left: 10px;
}
.btn.sq {
min-width: 30px;
diff --git a/frontend/src/tools/inspect/CollageMenu.test.js b/frontend/src/tools/inspect/CollageMenu.test.js
index afe200d..1c079ca 100644
--- a/frontend/src/tools/inspect/CollageMenu.test.js
+++ b/frontend/src/tools/inspect/CollageMenu.test.js
@@ -5,24 +5,15 @@ const source = readFileSync(new URL('./CollageMenu.svelte', import.meta.url), 'u
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).toContain('let { collage: active, selectedIds = $bindable([]), requestCrop, renderPiece, fileTitles = new Map() } = $props();');
expect(source).not.toContain('session.');
expect(source).not.toContain('addCollage');
});
});
describe('CollageMenu canvas', () => {
- it('holds a typed side inside the bounds compose accepts, in the field too', () => {
- expect(source).toContain(` const next = clampCollageDim(event.currentTarget.value, active[axis]);
- active[axis] = next;
- event.currentTarget.value = next;`);
- expect(source).toContain('min={COLLAGE_MIN_DIM}');
- expect(source).toContain('max={COLLAGE_MAX_DIM}');
- });
-
- it('names both fields for a screen reader, which has no × to read', () => {
- expect(source).toContain('aria-label="Canvas width in pixels"');
- expect(source).toContain('aria-label="Canvas height in pixels"');
+ it('leaves the size to the export rather than asking for one', () => {
+ expect(source).not.toContain('Canvas width in pixels');
});
it('resizes the canvas to what the solver asked for', () => {
diff --git a/frontend/src/tools/inspect/CollagePreview.svelte b/frontend/src/tools/inspect/CollagePreview.svelte
new file mode 100644
index 0000000..39f3b74
--- /dev/null
+++ b/frontend/src/tools/inspect/CollagePreview.svelte
@@ -0,0 +1,53 @@
+<script>
+ import { fileUrl } from '../../lib/fileUrl.js';
+ import Icon from '../../components/Icon.svelte';
+
+ // What a collage looks like in its list: the preview the tool drew, or the
+ // pieces' outlines until it has drawn one.
+ let { row, caseId, iconSize = 18 } = $props();
+
+ const src = $derived(row.thumb ? `${fileUrl(caseId, row.thumb)}?v=${row.thumb_v ?? ''}` : null);
+</script>
+
+<span class="preview">
+ {#if src}
+ <img {src} alt="" loading="lazy" draggable="false" />
+ {:else if row.outline}
+ <svg viewBox={`0 0 ${row.outline.width} ${row.outline.height}`} preserveAspectRatio="xMidYMid meet" aria-hidden="true">
+ {#each row.outline.quads as quad, i (i)}
+ <polygon points={quad.map(([x, y]) => `${x},${y}`).join(' ')} vector-effect="non-scaling-stroke" />
+ {/each}
+ </svg>
+ {:else}
+ <Icon name="grid" size={iconSize} />
+ {/if}
+</span>
+
+<style>
+ /* The frame sets the size and the picture fits inside it, so a tall collage
+ cannot stretch its card. */
+ .preview {
+ position: relative;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ width: 100%;
+ height: 100%;
+ overflow: hidden;
+ color: var(--text-3);
+ background: var(--bg-0);
+ }
+ img,
+ svg {
+ position: absolute;
+ inset: 6%;
+ width: 88%;
+ height: 88%;
+ object-fit: contain;
+ }
+ polygon {
+ fill: color-mix(in srgb, var(--accent) 12%, transparent);
+ stroke: var(--text-3);
+ stroke-width: 1;
+ }
+</style>
diff --git a/frontend/src/tools/inspect/PiecePicker.svelte b/frontend/src/tools/inspect/PiecePicker.svelte
index 038d15b..b3bc989 100644
--- a/frontend/src/tools/inspect/PiecePicker.svelte
+++ b/frontend/src/tools/inspect/PiecePicker.svelte
@@ -2,8 +2,10 @@
import { untrack } from 'svelte';
import { api } from '../../lib/api.js';
import { fileUrl } from '../../lib/fileUrl.js';
- import { buildFrameOps } from '../../lib/inspect.js';
+ import { buildFrameOps, clockTime } from '../../lib/inspect.js';
+ import { foldTerms, foldText } from '../../lib/textFold.js';
import Icon from '../../components/Icon.svelte';
+ import SearchInput from '../../components/SearchInput.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,
@@ -11,6 +13,17 @@
let { caseId, filters, works, images, used, rev = 0, onadd } = $props();
let tab = $state('frames');
+ let query = $state('');
+
+ // Both lists keep the order they arrive in, the files last worked on and the
+ // images last added first, and the search box only narrows them.
+ const matches = (text) => {
+ const terms = foldTerms(query);
+ const folded = foldText(text);
+ return terms.every((term) => folded.includes(term));
+ };
+ const shownWorks = $derived(works.filter((w) => w.frames && matches(w.title)));
+ const shownImages = $derived(images.filter((item) => matches(item.title || item.filename)));
let open = $state({}); // work name -> expanded
let frames = $state({}); // work name -> [{ frame, thumb }] once fetched
const blobs = new Set();
@@ -38,8 +51,9 @@
}
}
+ // One file unfolded at a time, so the list stays a list of files.
function toggle(name) {
- open[name] = !open[name];
+ open = open[name] ? {} : { [name]: true };
if (open[name] && !frames[name]) load(name).catch(() => (frames[name] = []));
}
@@ -59,8 +73,6 @@
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) } });
}
@@ -71,24 +83,29 @@
</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 class="bar">
+ <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>
+ <div class="find"><SearchInput bind:value={query} placeholder="Search…" width="100%" /></div>
</div>
+ <div class="list">
{#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>
+ <p class="hint">Frames cut in Inspect show up here.</p>
{/if}
- {#each works.filter((w) => w.frames) as w (w.name)}
+ {#each shownWorks 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} />
+ <button class="group-head" class:open={open[w.name]} onclick={() => toggle(w.name)} aria-expanded={!!open[w.name]} title={w.title}>
+ <span class="file">
+ {#if w.thumb}<img src={fileUrl(caseId, w.thumb)} alt="" loading="lazy" />{:else}<Icon name={w.kind === 'video' ? 'video' : 'image'} size={13} />{/if}
+ </span>
<span class="name">{w.title}</span>
<span class="count">{w.frames}</span>
</button>
@@ -104,7 +121,7 @@
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}
+ {#if entry.frame.time != null}<span class="num">{clockTime(entry.frame.time)}</span>{/if}
<span class="tag">{#if times}×{times}{:else}<Icon name="plus" size={10} />{/if}</span>
</button>
{:else}
@@ -118,12 +135,18 @@
{/if}
</div>
{/each}
+ {#if query.trim() && works.some((w) => w.frames) && !shownWorks.length}
+ <p class="hint">No file named “{query.trim()}”.</p>
+ {/if}
{:else}
{#if !images.length}
<p class="hint">No images in the case yet.</p>
{/if}
+ {#if query.trim() && images.length && !shownImages.length}
+ <p class="hint">No image named “{query.trim()}”.</p>
+ {/if}
<div class="thumbs">
- {#each images as item (item.path)}
+ {#each shownImages 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>
@@ -131,6 +154,7 @@
{/each}
</div>
{/if}
+ </div>
</div>
<style>
@@ -139,6 +163,29 @@
flex-direction: column;
gap: 8px;
}
+ .bar {
+ display: flex;
+ gap: 6px;
+ align-items: stretch;
+ }
+ .find {
+ flex: 1;
+ min-width: 0;
+ display: flex;
+ flex-direction: column;
+ }
+ .find :global(.search-box) {
+ flex: 1;
+ }
+ /* The files scroll on their own, so the controls below stay in reach. */
+ .list {
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ max-height: 38vh;
+ overflow: auto;
+ padding-right: 2px;
+ }
.tabs {
display: flex;
flex-shrink: 0;
@@ -147,8 +194,7 @@
overflow: hidden;
}
.tabs button {
- flex: 1;
- padding: 5px 4px;
+ padding: 5px 9px;
font-size: var(--fs-xs);
color: var(--text-2);
background: transparent;
@@ -169,15 +215,37 @@
.group-head {
display: flex;
align-items: center;
- gap: 6px;
+ gap: 8px;
width: 100%;
- padding: 4px 2px;
+ padding: 3px;
background: none;
border: 0;
+ border-radius: var(--r-sm);
color: var(--text-1);
font-size: var(--fs-sm);
text-align: left;
}
+ .group-head:hover,
+ .group-head.open {
+ background: var(--bg-2);
+ }
+ .file {
+ flex-shrink: 0;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ width: 36px;
+ height: 26px;
+ border-radius: 3px;
+ overflow: hidden;
+ background: var(--bg-0);
+ color: var(--text-3);
+ }
+ .file img {
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ }
.name {
flex: 1;
min-width: 0;
diff --git a/frontend/src/tools/satellite/AddedLayers.render.test.js b/frontend/src/tools/satellite/AddedLayers.render.test.js
index 19c66dc..2208509 100644
--- a/frontend/src/tools/satellite/AddedLayers.render.test.js
+++ b/frontend/src/tools/satellite/AddedLayers.render.test.js
@@ -33,6 +33,13 @@ const text = () => document.body.textContent ?? '';
const rows = (selector) => [...document.body.querySelectorAll(selector)];
const byText = (selector, label) =>
rows(selector).find((node) => node.textContent.trim().startsWith(label));
+const byLabel = (label) => document.body.querySelector(`[aria-label="${label}"]`);
+
+/** Every row opens folded: this is the press that shows the rest of one. */
+function unfold(title) {
+ byText('.fold', title).click();
+ flushSync();
+}
const LAYER = {
name: 'Sightings',
@@ -74,8 +81,34 @@ describe('before anything is added', () => {
});
describe('a row', () => {
+ it('opens folded to one line: the eye, the name, and its acts', () => {
+ show({ rows: [LAYER] });
+
+ expect(text()).toContain('Sightings');
+ expect(text()).not.toContain('sightings.kml');
+ expect(document.querySelector('.fold').getAttribute('aria-expanded')).toBe('false');
+ expect(byLabel('Remove Sightings')).toBeTruthy();
+ });
+
+ it('unfolds the layer just added, since it was added to be read', () => {
+ show({ rows: [LAYER, followed()], opened: 'Roadblocks' });
+
+ const [first, second] = rows('.fold');
+ expect(first.getAttribute('aria-expanded')).toBe('false');
+ expect(second.getAttribute('aria-expanded')).toBe('true');
+ });
+
+ it('folds the layer just added when asked, and keeps it folded', () => {
+ show({ rows: [followed()], opened: 'Roadblocks' });
+
+ unfold('Roadblocks');
+
+ expect(document.querySelector('.fold').getAttribute('aria-expanded')).toBe('false');
+ });
+
it('renders from state, with where it came from and how fresh it is', () => {
show({ rows: [LAYER] });
+ unfold('Sightings');
expect(text()).toContain('Sightings');
expect(text()).toContain('sightings.kml');
@@ -84,6 +117,7 @@ describe('a row', () => {
it('states what is loaded and what is drawn, separately', () => {
show({ rows: [{ ...LAYER, hidden: ['Damage'] }] });
+ unfold('Sightings');
// never the drawn count passing for the loaded one
expect(text()).toMatch(/3.200 features · 2.788 shown/);
@@ -91,6 +125,7 @@ describe('a row', () => {
it('links a followed map back to the page it was published on', () => {
show({ rows: [followed()] });
+ unfold('Roadblocks');
const link = document.querySelector('.from');
expect(link.getAttribute('href')).toBe('https://example.test/r.kml');
@@ -102,34 +137,39 @@ describe('a row', () => {
it('leaves a file as plain text, having nowhere to send anybody', () => {
show({ rows: [LAYER] });
+ unfold('Sightings');
expect(document.querySelector('.from')).toBeNull();
expect(text()).toContain('sightings.kml');
});
- it('says a stale snapshot is stale, and marks it for the eye', () => {
+ it('says a stale snapshot is stale, folded or not', () => {
show({ rows: [followed({ stale: true, checked_at: '2020-01-01T00:00:00Z' })] });
+ // folded, the name and a mark say it before anything is read
+ expect(document.querySelector('.name.stale')).toBeTruthy();
+ expect(document.querySelector('.stale-mark').title).toContain('out of date');
+
+ unfold('Roadblocks');
expect(text()).toContain('out of date');
- expect(document.querySelector('.stale')).toBeTruthy();
});
it('offers Refresh only to a layer that has somewhere to refresh from', () => {
show({ rows: [LAYER] });
- expect(byText('button', 'Refresh')).toBeFalsy();
+ expect(byLabel('Refresh Sightings')).toBeNull();
unmount(held);
held = null;
document.body.innerHTML = '';
show({ rows: [followed()] });
- expect(byText('button', 'Refresh')).toBeTruthy();
+ expect(byLabel('Refresh Roadblocks')).toBeTruthy();
});
it('owns its layer the way a curated row does not: it can be removed', () => {
show({ rows: [LAYER] });
- expect(byText('button', 'Remove')).toBeTruthy();
+ expect(byLabel('Remove Sightings')).toBeTruthy();
// no way to reach the saved copy on disk: it is stored under an extension
// no other program opens, in a folder the analyst never sees
expect(byText('button', 'Reveal file')).toBeFalsy();
@@ -145,6 +185,7 @@ describe('a row', () => {
describe('the legend is the filter', () => {
it('opens to one row per category, with its colour and its count', () => {
show({ rows: [LAYER] });
+ unfold('Sightings');
byText('.legend-head', '2 groups').click();
flushSync();
@@ -159,6 +200,7 @@ describe('the legend is the filter', () => {
it('reports a hidden category as off rather than dropping it from the legend', () => {
show({ rows: [{ ...LAYER, hidden: ['Damage'] }] });
+ unfold('Sightings');
byText('.legend-head', '2 groups').click();
flushSync();
@@ -171,6 +213,7 @@ describe('the legend is the filter', () => {
it('asks for exactly the category that was clicked', () => {
const oncategory = vi.fn();
show({ rows: [LAYER], oncategory });
+ unfold('Sightings');
byText('.legend-head', '2 groups').click();
flushSync();
@@ -203,6 +246,7 @@ describe('finding a pin', () => {
function opened(props = {}) {
show({ rows: [LAYER], ...props });
+ unfold('Sightings');
byText('.legend-head', '2 groups').click();
flushSync();
}
@@ -216,6 +260,7 @@ describe('finding a pin', () => {
it('offers nothing to search on a layer that is switched off', () => {
// a match is somewhere to go, and a layer nobody is drawing has nowhere
show({ rows: [{ ...LAYER, enabled: false }], search: finder(null) });
+ unfold('Sightings');
byText('.legend-head', '2 groups').click();
flushSync();
@@ -302,8 +347,8 @@ describe('the acts', () => {
show({ rows: [followed()], ...handlers });
document.querySelector('.eye').click();
- byText('button', 'Refresh').click();
- byText('button', 'Remove').click();
+ byLabel('Refresh Roadblocks').click();
+ byLabel('Remove Roadblocks').click();
byText('button', 'Add a layer').click();
for (const handler of Object.values(handlers)) expect(handler).toHaveBeenCalled();
@@ -312,7 +357,144 @@ describe('the acts', () => {
it('says a refresh is running on the row it is running on', () => {
show({ rows: [followed()], busy: 'Roadblocks' });
- expect(byText('button', 'Reading…')).toBeTruthy();
- expect(byText('button', 'Reading…').disabled).toBe(true);
+ const button = byLabel('Refresh Roadblocks');
+ expect(button.title).toBe('Reading…');
+ expect(button.disabled).toBe(true);
+ });
+
+ it('refreshes every followed layer from the head, and only offers it when there is one', () => {
+ show({ rows: [LAYER] });
+ expect(byLabel('Refresh every followed layer')).toBeNull();
+
+ unmount(held);
+ held = null;
+ document.body.innerHTML = '';
+
+ const onrefreshall = vi.fn();
+ show({ rows: [LAYER, followed()], onrefreshall });
+ byLabel('Refresh every followed layer').click();
+ expect(onrefreshall).toHaveBeenCalled();
+ });
+
+ it('holds the head button while it is going through them', () => {
+ show({ rows: [followed()], refreshing: true });
+
+ expect(byLabel('Refresh every followed layer').disabled).toBe(true);
+ });
+});
+
+/** The list is the stack, top first, and the grip is how it changes. */
+describe('restacking', () => {
+ const three = () => [
+ LAYER,
+ followed(),
+ { ...LAYER, name: 'Damage', title: 'Damage' },
+ ];
+
+ /** happy-dom has no DataTransfer, so the drag carries a stand-in. */
+ function dragEvent(type, { x = 100, y = 0 } = {}) {
+ const event = new Event(type, { bubbles: true, cancelable: true });
+ event.dataTransfer = {
+ setData() {},
+ setDragImage() {},
+ effectAllowed: '',
+ dropEffect: '',
+ };
+ event.clientX = x;
+ event.clientY = y;
+ return event;
+ }
+
+ /** …and no layout: each row 26px tall, the list 300px wide from x 0. */
+ const ROW = 26;
+ function laidOut() {
+ const list = document.querySelector('ul.layers');
+ const items = [...list.children];
+ const rect = (top, height) => ({ top, bottom: top + height, height, left: 0, right: 300, width: 300 });
+ list.getBoundingClientRect = () => rect(0, items.length * ROW);
+ items.forEach((item, index) => (item.getBoundingClientRect = () => rect(index * ROW, ROW)));
+ return items;
+ }
+
+ it('has nothing to drag in a list of one', () => {
+ show({ rows: [LAYER] });
+
+ expect(document.querySelector('.grip')).toBeNull();
+ });
+
+ it('drops a row below the one it was let go over the lower half of', () => {
+ const onreorder = vi.fn();
+ show({ rows: three(), onreorder });
+ const items = laidOut();
+ rows('.grip')[0].dispatchEvent(dragEvent('dragstart'));
+ // the lower half of the second row
+ items[1].dispatchEvent(dragEvent('dragover', { y: ROW + 20 }));
+ flushSync();
+ expect(items[2].classList.contains('gap-above')).toBe(true);
+ items[1].dispatchEvent(dragEvent('drop', { y: ROW + 20 }));
+
+ expect(onreorder).toHaveBeenCalledWith(['Roadblocks', 'Sightings', 'Damage']);
+ });
+
+ it('still takes the drop when the pointer drifted off the row beside the list', () => {
+ // the grip sits on the row's left edge, and a hand moving down drifts off it
+ const onreorder = vi.fn();
+ show({ rows: three(), onreorder });
+ laidOut();
+ rows('.grip')[2].dispatchEvent(dragEvent('dragstart'));
+ const over = dragEvent('dragover', { x: -12, y: 4 });
+ document.body.dispatchEvent(over);
+ expect(over.defaultPrevented).toBe(true);
+ document.body.dispatchEvent(dragEvent('drop', { x: -12, y: 4 }));
+
+ expect(onreorder).toHaveBeenCalledWith(['Damage', 'Sightings', 'Roadblocks']);
+ });
+
+ it('refuses a drop far from the list, so the row goes back where it was', () => {
+ const onreorder = vi.fn();
+ show({ rows: three(), onreorder });
+ laidOut();
+ rows('.grip')[0].dispatchEvent(dragEvent('dragstart'));
+ const over = dragEvent('dragover', { x: 600, y: 40 });
+ document.body.dispatchEvent(over);
+ flushSync();
+
+ expect(over.defaultPrevented).toBe(false);
+ expect(document.querySelector('.gap-above, .gap-below')).toBeNull();
+ document.body.dispatchEvent(dragEvent('drop', { x: 600, y: 40 }));
+ expect(onreorder).not.toHaveBeenCalled();
+ });
+
+ it('asks for nothing when a row is let go where it was', () => {
+ const onreorder = vi.fn();
+ show({ rows: three(), onreorder });
+ const items = laidOut();
+ const own = items[1];
+ // a drop that never passed over the list…
+ rows('.grip')[1].dispatchEvent(dragEvent('dragstart'));
+ own.dispatchEvent(dragEvent('drop', { y: ROW + 20 }));
+ // …and one let go over itself
+ rows('.grip')[1].dispatchEvent(dragEvent('dragstart'));
+ own.dispatchEvent(dragEvent('dragover', { y: ROW + 20 }));
+ own.dispatchEvent(dragEvent('drop', { y: ROW + 20 }));
+
+ expect(onreorder).not.toHaveBeenCalled();
+ });
+
+ it('moves one place at a time with the arrow keys, and not past either end', () => {
+ const onreorder = vi.fn();
+ show({ rows: three(), onreorder });
+ const press = (grip, key) =>
+ grip.dispatchEvent(new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true }));
+
+ press(rows('.grip')[0], 'ArrowDown');
+ expect(onreorder).toHaveBeenLastCalledWith(['Roadblocks', 'Sightings', 'Damage']);
+ press(rows('.grip')[2], 'ArrowUp');
+ expect(onreorder).toHaveBeenLastCalledWith(['Sightings', 'Damage', 'Roadblocks']);
+
+ onreorder.mockClear();
+ press(rows('.grip')[0], 'ArrowUp');
+ press(rows('.grip')[2], 'ArrowDown');
+ expect(onreorder).not.toHaveBeenCalled();
});
});
diff --git a/frontend/src/tools/satellite/AddedLayers.svelte b/frontend/src/tools/satellite/AddedLayers.svelte
index 8a655ab..28be9d6 100644
--- a/frontend/src/tools/satellite/AddedLayers.svelte
+++ b/frontend/src/tools/satellite/AddedLayers.svelte
@@ -19,6 +19,11 @@
* - **Refresh and Remove**, because the analyst owns this layer in a way
* they do not own the borders overlay.
*
+ * A row opens folded to one line: the eye, the name, and the two acts as
+ * icons. Unfolding it shows the rest. Staleness is the one thing a folded row
+ * still says, because it is said before a mark is read. The rows are in the
+ * order the map stacks them, top first, and the grip drags them into another.
+ *
* Everything a row states is computed in `lib/map/addedLayers.js`, so the
* rules are read off a test rather than off a screen.
*
@@ -29,6 +34,7 @@
* what the map draws. One slot is also what keeps a row this tall from growing
* a third thing to unfold.
*/
+ import { tick, untrack } from 'svelte';
import Icon from '../../components/Icon.svelte';
import SearchInput from '../../components/SearchInput.svelte';
import LayerTimeStrip from './LayerTimeStrip.svelte';
@@ -38,6 +44,7 @@
freshness,
grouped,
legend,
+ moveName,
sourceLabel,
} from '../../lib/map/addedLayers.js';
@@ -46,6 +53,10 @@
rows = [],
/** The layer an act is running on, so its buttons can say so. */
busy = '',
+ /** The head's Refresh is going through every followed layer. */
+ refreshing = false,
+ /** The layer just added, which opens unfolded since it was added to be read. */
+ opened = '',
open = $bindable(true),
/** `(layer, query) => { total, results, ready }`, over features already in
* memory. Nothing here fetches. */
@@ -53,7 +64,10 @@
ontoggle,
oncategory,
onrefresh,
+ onrefreshall,
onremove,
+ /** `(names)`: every row's name in its new order, top of the map first. */
+ onreorder,
onpick,
onadd,
/** `(layer) => index | null`, the days its features carry (`layerDates.js`). */
@@ -63,6 +77,96 @@
} = $props();
const live = $derived(rows.filter((row) => row.enabled).length);
+ const anyFollowed = $derived(rows.some(followed));
+ const names = $derived(rows.map((row) => row.name));
+
+ /** Unfolded rows, by layer name. Every row starts folded, on every visit. */
+ let unfolded = $state(new Set());
+
+ /** Once per added layer: folding it afterwards must keep it folded. */
+ let unfoldedOnAdd = '';
+ $effect(() => {
+ if (!opened || opened === unfoldedOnAdd) return;
+ unfoldedOnAdd = opened;
+ untrack(() => (unfolded = new Set(unfolded).add(opened)));
+ });
+
+ function toggleRow(name) {
+ const next = new Set(unfolded);
+ if (next.has(name)) next.delete(name);
+ else next.add(name);
+ unfolded = next;
+ }
+
+ /** The row being dragged, and the gap it would land in (a place in the list). */
+ let dragged = $state('');
+ let gap = $state(-1);
+ let list = $state(null);
+
+ /**
+ * How far past the list a drag still counts as over it. The grip sits on the
+ * row's left edge, so a hand moving down it drifts off the row within pixels,
+ * and a drop the browser refuses snaps the row back to where it was.
+ */
+ const SLACK_X = 32;
+ const SLACK_Y = 16;
+
+ /** The gap under the pointer, by height alone, or -1 away from the list. */
+ function gapAt(x, y) {
+ const box = list?.getBoundingClientRect();
+ if (!box) return -1;
+ if (x < box.left - SLACK_X || x > box.right + SLACK_X) return -1;
+ if (y < box.top - SLACK_Y || y > box.bottom + SLACK_Y) return -1;
+ const items = [...list.children];
+ const at = items.findIndex((item) => {
+ const rect = item.getBoundingClientRect();
+ return y < rect.top + rect.height / 2;
+ });
+ return at < 0 ? items.length : at;
+ }
+
+ function dragStart(event, row) {
+ dragged = row.name;
+ event.dataTransfer.effectAllowed = 'move';
+ event.dataTransfer.setData('text/plain', row.title);
+ const item = event.currentTarget.closest('li');
+ if (item) event.dataTransfer.setDragImage(item, 12, 12);
+ }
+
+ /** On the window, so the pointer need not stay on a row for the drop to take. */
+ function dragOver(event) {
+ if (!dragged) return;
+ gap = gapAt(event.clientX, event.clientY);
+ if (gap < 0) return;
+ event.preventDefault();
+ event.dataTransfer.dropEffect = 'move';
+ }
+
+ function drop(event) {
+ if (!dragged) return;
+ event.preventDefault();
+ if (gap < 0) return dragEnd();
+ const next = moveName(names, dragged, gap);
+ dragEnd();
+ if (next.join('\n') !== names.join('\n')) onreorder?.(next);
+ }
+
+ function dragEnd() {
+ dragged = '';
+ gap = -1;
+ }
+
+ /** The same move from the keyboard, one place at a time, focus kept on the grip. */
+ async function nudge(event, row, index) {
+ const step = event.key === 'ArrowUp' ? -1 : event.key === 'ArrowDown' ? 1 : 0;
+ if (!step) return;
+ event.preventDefault();
+ const to = index + step;
+ if (to < 0 || to >= names.length) return;
+ onreorder?.(moveName(names, row.name, step > 0 ? to + 1 : to));
+ await tick();
+ document.querySelector(`[data-grip="${CSS.escape(row.name)}"]`)?.focus();
+ }
/** Expanded legends, by layer name. A layer's categories are its own list and
* three of them open at once would push the case's own panel off screen. */
@@ -80,21 +184,61 @@
}
</script>
-<button type="button" class="sub-head" onclick={() => (open = !open)}>
- <Icon name={open ? 'chevronDown' : 'chevronRight'} size={12} />
- <Icon name="compass" size={13} />
- <span>Added layers</span>
- <span class="count">{live}</span>
-</button>
+<svelte:window ondragover={dragOver} ondrop={drop} />
+
+<div class="head">
+ <button type="button" class="sub-head" onclick={() => (open = !open)}>
+ <Icon name={open ? 'chevronDown' : 'chevronRight'} size={12} />
+ <Icon name="compass" size={13} />
+ <span>Added layers</span>
+ <span class="count">{live}</span>
+ </button>
+ {#if anyFollowed}
+ <button
+ type="button"
+ class="icon-act"
+ class:spin={refreshing}
+ disabled={refreshing}
+ aria-label="Refresh every followed layer"
+ title={refreshing ? 'Reading…' : 'Refresh every followed layer'}
+ onclick={() => onrefreshall?.()}
+ >
+ <Icon name="reset" size={13} />
+ </button>
+ {/if}
+</div>
{#if open}
{#if !rows.length}
<p class="empty">Nothing added yet.</p>
{/if}
- <ul class="layers">
- {#each rows as row (row.name)}
- <li>
+ <ul class="layers" class:stackable={rows.length > 1} bind:this={list}>
+ {#each rows as row, index (row.name)}
+ {@const unfold = unfolded.has(row.name)}
+ <li
+ class:dragged={dragged === row.name}
+ class:gap-above={dragged && gap === index}
+ class:gap-below={dragged && gap === index + 1 && index === rows.length - 1}
+ >
<div class="row">
+ {#if rows.length > 1}
+ <!-- A span rather than a button: Firefox starts no drag from a button. -->
+ <span
+ role="button"
+ tabindex="0"
+ class="grip"
+ draggable="true"
+ data-grip={row.name}
+ aria-label={`Move ${row.title}`}
+ aria-keyshortcuts="ArrowUp ArrowDown"
+ title="Drag to restack"
+ ondragstart={(event) => dragStart(event, row)}
+ ondragend={dragEnd}
+ onkeydown={(event) => nudge(event, row, index)}
+ >
+ <Icon name="grip" size={14} />
+ </span>
+ {/if}
<button
type="button"
class="eye"
@@ -106,8 +250,46 @@
>
<Icon name="eye" size={13} />
</button>
- <span class="name" class:off={!row.enabled}>{row.title}</span>
+ <button
+ type="button"
+ class="fold"
+ aria-expanded={unfold}
+ aria-label={`${row.title}, details`}
+ title={unfold ? 'Fold this layer' : 'Show its details'}
+ onclick={() => toggleRow(row.name)}
+ >
+ <Icon name={unfold ? 'chevronDown' : 'chevronRight'} size={11} />
+ <span class="name" class:off={!row.enabled} class:stale={row.stale}>{row.title}</span>
+ </button>
+ {#if row.stale && !unfold}
+ <span class="stale-mark" title={freshness(row)}>
+ <Icon name="alert" size={12} />
+ </span>
+ {/if}
+ {#if followed(row)}
+ <button
+ type="button"
+ class="icon-act"
+ class:spin={busy === row.name}
+ disabled={busy === row.name}
+ aria-label={`Refresh ${row.title}`}
+ title={busy === row.name ? 'Reading…' : 'Read it again from its source'}
+ onclick={() => onrefresh?.(row)}
+ >
+ <Icon name="reset" size={13} />
+ </button>
+ {/if}
+ <button
+ type="button"
+ class="icon-act danger"
+ aria-label={`Remove ${row.title}`}
+ title="Remove this layer"
+ onclick={() => onremove?.(row)}
+ >
+ <Icon name="trash" size={13} />
+ </button>
</div>
+ {#if unfold}
<p class="meta">
<!-- A followed map is a page somebody publishes, so where it came
from is a way of getting there: this is the one thing on the row
@@ -235,16 +417,7 @@
{/if}
{/if}
- <nav class="acts" aria-label={row.title}>
- {#if followed(row)}
- <button
- class="btn btn-sm"
- disabled={busy === row.name}
- onclick={() => onrefresh?.(row)}
- >{busy === row.name ? 'Reading…' : 'Refresh'}</button>
- {/if}
- <button class="btn btn-sm quiet" onclick={() => onremove?.(row)}>Remove</button>
- </nav>
+ {/if}
</li>
{/each}
</ul>
@@ -256,20 +429,125 @@
<style>
.layers {
+ --indent: 30px;
margin: 0;
padding: 0 4px;
list-style: none;
}
+ .layers.stackable {
+ --indent: 46px;
+ }
+ .head {
+ display: flex;
+ align-items: center;
+ gap: 2px;
+ }
+ .head .icon-act {
+ margin-top: 6px;
+ }
.layers > li {
- padding-bottom: 6px;
+ position: relative;
+ padding-bottom: 2px;
+ }
+ .layers > li.dragged {
+ opacity: 0.45;
+ }
+ /* Where the dragged row would land: a line in the gap, above this row or,
+ past the last one, below it. */
+ .layers > li.gap-above::before,
+ .layers > li.gap-below::after {
+ content: '';
+ position: absolute;
+ left: 4px;
+ right: 4px;
+ height: 2px;
+ border-radius: 1px;
+ background: var(--accent);
+ }
+ .layers > li.gap-above::before {
+ top: -1px;
+ }
+ .layers > li.gap-below::after {
+ bottom: -1px;
}
.row {
display: flex;
align-items: center;
- gap: 8px;
+ gap: 4px;
min-height: 26px;
}
+ /* Always shown once there is something to reorder, and the details below
+ move right by its width so they stay under the name. */
+ .grip {
+ display: grid;
+ flex: none;
+ place-items: center;
+ width: 14px;
+ height: 22px;
+ margin-right: 2px;
+ border-radius: var(--radius-1);
+ color: var(--text-3);
+ cursor: grab;
+ }
+ .grip:hover,
+ .grip:focus-visible {
+ color: var(--text-1);
+ background: var(--bg-3);
+ }
+ .grip:active {
+ cursor: grabbing;
+ }
+ .fold {
+ display: flex;
+ flex: 1;
+ align-items: center;
+ gap: 4px;
+ min-width: 0;
+ padding: 2px 0;
+ color: var(--text-3);
+ text-align: left;
+ cursor: pointer;
+ }
+ .fold:hover,
+ .fold:hover .name {
+ color: var(--text-1);
+ }
+ .stale-mark {
+ display: grid;
+ place-items: center;
+ color: var(--warn);
+ }
+ .icon-act {
+ display: grid;
+ flex: none;
+ place-items: center;
+ width: 22px;
+ height: 22px;
+ border-radius: var(--radius-1);
+ color: var(--text-3);
+ cursor: pointer;
+ }
+ .icon-act:hover:not(:disabled) {
+ color: var(--text-1);
+ background: var(--bg-3);
+ }
+ .icon-act.danger:hover {
+ color: var(--danger);
+ }
+ .icon-act:disabled {
+ cursor: default;
+ }
+ .icon-act.spin :global(svg) {
+ animation: spin 0.9s linear infinite;
+ }
+ @keyframes spin {
+ to {
+ transform: rotate(360deg);
+ }
+ }
.eye {
+ flex: none;
+ margin-right: 4px;
display: grid;
place-items: center;
width: 22px;
@@ -287,6 +565,10 @@
}
.name {
flex: 1;
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
font-size: var(--fs-sm);
color: var(--text-1);
}
@@ -297,7 +579,7 @@
display: flex;
gap: 6px;
margin: 0;
- padding-left: 30px;
+ padding-left: var(--indent, 30px);
font-size: 10px;
color: var(--text-3);
}
@@ -326,7 +608,7 @@
display: flex;
align-items: center;
gap: 4px;
- padding: 3px 0 2px 26px;
+ padding: 3px 0 2px calc(var(--indent, 30px) - 4px);
color: var(--text-3);
font-size: 10px;
cursor: pointer;
@@ -336,7 +618,7 @@
}
.legend {
margin: 0;
- padding: 0 0 2px 30px;
+ padding: 0 0 2px var(--indent, 30px);
list-style: none;
}
.cat {
@@ -390,17 +672,11 @@
color: var(--text-3);
}
.find {
- padding: 2px 4px 4px 30px;
- }
- .acts {
- display: flex;
- flex-wrap: wrap;
- gap: 4px;
- padding: 4px 0 0 30px;
+ padding: 2px 4px 4px var(--indent, 30px);
}
.empty {
margin: 0;
- padding: 2px 0 4px 30px;
+ padding: 2px 0 4px var(--indent, 30px);
font-size: 10px;
color: var(--text-3);
}
diff --git a/frontend/src/tools/satellite/AddedLayersOverlay.svelte b/frontend/src/tools/satellite/AddedLayersOverlay.svelte
index e8a6375..94daabc 100644
--- a/frontend/src/tools/satellite/AddedLayersOverlay.svelte
+++ b/frontend/src/tools/satellite/AddedLayersOverlay.svelte
@@ -63,6 +63,23 @@
live.delete(name);
}
+ /**
+ * Stack the drawn layers as the panel lists them, the first on top.
+ *
+ * The block stays where the first one sits, and each next one goes just under
+ * the one before, so what the case draws itself keeps its place around them.
+ * Run again whenever a layer finishes building, since a late one lands on top.
+ */
+ function restack() {
+ let above = null;
+ for (const row of layers) {
+ const layer = live.get(row.name)?.layer;
+ if (!layer?.floor()) continue;
+ if (above) layer.stackUnder(above);
+ above = layer;
+ }
+ }
+
$effect(() => {
if (!engine || !caseId) return;
const wanted = new Set(layers.map((row) => row.name));
@@ -94,9 +111,11 @@
period: row.period,
attribution: attribution(row),
});
+ restack();
})
.catch(() => drop(row.name));
}
+ restack();
});
/**
diff --git a/frontend/src/tools/satellite/TemporalPopup.svelte b/frontend/src/tools/satellite/TemporalPopup.svelte
index c17536b..cfa195a 100644
--- a/frontend/src/tools/satellite/TemporalPopup.svelte
+++ b/frontend/src/tools/satellite/TemporalPopup.svelte
@@ -24,7 +24,7 @@
const TOOL = {
media: 'Media', proof: 'Proof', place: 'Map', post: 'Post',
'inspect-session': 'Inspect', collage: 'Collage', note: 'Notebook', bookmark: 'the source',
- capture: 'Map',
+ capture: 'Map', claim: 'Timeline',
};
const ordered = $derived(
@@ -60,7 +60,7 @@
*/
function when(item) {
if (!item.raw) return '';
- if (!item.raw.includes('T')) return formatTemporalValue(item.raw).label;
+ if (!item.raw.includes('T')) return formatTemporalValue(item.raw, item.tz).label;
const stamp = zonedStamp(item.earliest);
return stamp ? `${stamp.slice(8, 10)} ${stamp.slice(5, 7)} · ${stamp.slice(11, 16)}` : '';
}
diff --git a/frontend/src/tools/satellite/state/addedLayers.svelte.js b/frontend/src/tools/satellite/state/addedLayers.svelte.js
index e7e3c8d..02b4821 100644
--- a/frontend/src/tools/satellite/state/addedLayers.svelte.js
+++ b/frontend/src/tools/satellite/state/addedLayers.svelte.js
@@ -25,6 +25,8 @@
*/
import {
drawable,
+ followed,
+ refreshedLabel,
renewsOnShow,
searchFeatures,
toggleCategory,
@@ -35,6 +37,8 @@ export function createAddedLayersState({ api, notify, ensureCase, reloadCase })
let rows = $state([]);
let open = $state(true);
let busy = $state(''); // the layer name an act is running on
+ let refreshing = $state(false); // the head's Refresh is going through every layer
+ let justAdded = $state(''); // the layer the + just filed, which opens unfolded
let adding = $state(false); // the + dialog is up
let saving = $state(false); // …and it is reading a file or an address
let geoconfirmed = $state(false); // the GeoConfirmed dialog the + led to
@@ -186,6 +190,21 @@ export function createAddedLayersState({ api, notify, ensureCase, reloadCase })
return data;
}
+ /**
+ * Fetch one followed layer again: `'moved'` when the bytes changed, `'same'`
+ * when they did not. A failure throws, with the reason the backend gave.
+ */
+ function reread(caseId, layer) {
+ return act(layer.name, async () => {
+ const row = await api.post(`/api/cases/${caseId}/map-layers/${encodeURIComponent(layer.name)}/refresh`);
+ if (loadedFor !== caseId) return 'same';
+ const moved = row.sha256 !== layer.sha256;
+ if (moved) forget(row.name);
+ replace(row);
+ return moved ? 'moved' : 'same';
+ });
+ }
+
async function act(name, run) {
busy = name;
try {
@@ -211,6 +230,7 @@ export function createAddedLayersState({ api, notify, ensureCase, reloadCase })
replace(row);
// on, since it was added to be looked at, and just read
show(row.name, true);
+ justAdded = row.name;
renewed.add(row.name);
adding = false;
geoconfirmed = false;
@@ -283,6 +303,12 @@ export function createAddedLayersState({ api, notify, ensureCase, reloadCase })
get busy() {
return busy;
},
+ get refreshing() {
+ return refreshing;
+ },
+ get justAdded() {
+ return justAdded;
+ },
get adding() {
return adding;
},
@@ -399,20 +425,62 @@ export function createAddedLayersState({ api, notify, ensureCase, reloadCase })
},
/** The explicit press. The second of this feature's three network calls. */
- refresh(caseId, layer) {
- return act(layer.name, async () => {
- try {
- const row = await api.post(`/api/cases/${caseId}/map-layers/${encodeURIComponent(layer.name)}/refresh`);
- if (row.sha256 !== layer.sha256) forget(row.name);
- replace(row);
- notify(
- row.sha256 === layer.sha256 ? 'Unchanged since last read' : `${row.title} updated`,
- 'ok'
- );
- } catch (error) {
- notify(error?.message || 'That source could not be reached', 'error');
+ async refresh(caseId, layer) {
+ try {
+ const result = await reread(caseId, layer);
+ notify(result === 'same' ? 'Unchanged since last read' : `${layer.title} updated`, 'ok');
+ } catch (error) {
+ notify(error?.message || 'That source could not be reached', 'error');
+ }
+ },
+
+ /**
+ * The same press on every followed layer, one after the other so each row
+ * says when its own turn comes, and one toast at the end rather than one
+ * per layer. A file has nothing to read and is left alone.
+ */
+ async refreshAll(caseId) {
+ const due = rows.filter(followed);
+ if (!due.length || refreshing) return;
+ refreshing = true;
+ let moved = 0;
+ let failed = 0;
+ try {
+ for (const layer of due) {
+ try {
+ if ((await reread(caseId, layer)) === 'moved') moved += 1;
+ } catch {
+ failed += 1;
+ }
}
- });
+ } finally {
+ refreshing = false;
+ }
+ const kind = failed === due.length ? 'error' : failed ? 'warn' : 'ok';
+ notify(refreshedLabel({ moved, failed, total: due.length }), kind);
+ },
+
+ /**
+ * The rows as they were dragged, top of the map first. The list moves at
+ * once, and a failed save puts it back.
+ */
+ async reorder(caseId, names) {
+ const before = rows;
+ const at = new Map(rows.map((row) => [row.name, row]));
+ const kept = names.filter((name) => at.has(name));
+ rows = [
+ ...kept.map((name) => at.get(name)),
+ ...rows.filter((row) => !kept.includes(row.name)),
+ ];
+ try {
+ const list = await api.put(`/api/cases/${caseId}/map-layers/order`, {
+ names: rows.map((row) => row.name),
+ });
+ if (loadedFor === caseId && Array.isArray(list)) rows = list;
+ } catch (error) {
+ if (loadedFor === caseId) rows = before;
+ notify(error?.message || 'That order could not be kept', 'error');
+ }
},
async remove(caseId, layer) {
diff --git a/frontend/src/tools/satellite/state/addedLayers.svelte.test.js b/frontend/src/tools/satellite/state/addedLayers.svelte.test.js
index e41787d..5b7ce25 100644
--- a/frontend/src/tools/satellite/state/addedLayers.svelte.test.js
+++ b/frontend/src/tools/satellite/state/addedLayers.svelte.test.js
@@ -272,6 +272,80 @@ describe('the acts on a row', () => {
expect(layers.rows).toHaveLength(1);
});
+ it('reads every followed layer again in turn, and says what it found once', async () => {
+ rows = [FILE_LAYER, followed(), followed({ name: 'Convoys', title: 'Convoys', sha256: 'ddd' })];
+ api.post = vi.fn(async (path) => {
+ calls.push(['POST', path]);
+ if (path.includes('Convoys')) throw new Error('that source answered 503');
+ return { ...followed(), sha256: 'ccc' };
+ });
+ const layers = store();
+ layers.load('c1');
+ await settle();
+ calls.length = 0;
+ notify.mockClear();
+
+ await layers.refreshAll('c1');
+
+ // a file has nothing to read and is left alone
+ expect(calls).toEqual([
+ ['POST', '/api/cases/c1/map-layers/Roadblocks/refresh'],
+ ['POST', '/api/cases/c1/map-layers/Convoys/refresh'],
+ ]);
+ expect(notify).toHaveBeenCalledTimes(1);
+ expect(notify).toHaveBeenCalledWith('1 updated, 1 could not be reached', 'warn');
+ expect(layers.refreshing).toBe(false);
+ });
+
+ it('asks nothing when no layer is followed', async () => {
+ const layers = store();
+ layers.load('c1');
+ await settle();
+ calls.length = 0;
+
+ await layers.refreshAll('c1');
+
+ expect(calls).toEqual([]);
+ expect(notify).not.toHaveBeenCalled();
+ });
+
+ it('moves the rows at once and keeps the order the backend answers with', async () => {
+ rows = [FILE_LAYER, followed()];
+ api.put = vi.fn(async (path, body) => {
+ calls.push(['PUT', path, body]);
+ return [followed(), FILE_LAYER];
+ });
+ const layers = store();
+ layers.load('c1');
+ await settle();
+ calls.length = 0;
+
+ const saving = layers.reorder('c1', ['Roadblocks', 'Sightings']);
+ // before the answer: the list and what is drawn already follow the drag
+ expect(layers.rows.map((row) => row.name)).toEqual(['Roadblocks', 'Sightings']);
+ await saving;
+
+ expect(calls).toEqual([
+ ['PUT', '/api/cases/c1/map-layers/order', { names: ['Roadblocks', 'Sightings'] }],
+ ]);
+ expect(layers.rows.map((row) => row.name)).toEqual(['Roadblocks', 'Sightings']);
+ });
+
+ it('puts the order back when it could not be kept', async () => {
+ rows = [FILE_LAYER, followed()];
+ api.put = vi.fn(async () => {
+ throw new Error('disk full');
+ });
+ const layers = store();
+ layers.load('c1');
+ await settle();
+
+ await layers.reorder('c1', ['Roadblocks', 'Sightings']);
+
+ expect(layers.rows.map((row) => row.name)).toEqual(['Sightings', 'Roadblocks']);
+ expect(notify).toHaveBeenCalledWith('disk full', 'error');
+ });
+
it('takes a removed layer off the list and out of what is drawn', async () => {
const layers = store();
layers.load('c1');
@@ -340,6 +414,15 @@ describe('adding', () => {
expect(calls).toEqual([]);
});
+ it('names what was just added, so its row opens unfolded', async () => {
+ const layers = store();
+ expect(layers.justAdded).toBe('');
+
+ await layers.subscribe('https://example.test/roadblocks.kml');
+
+ expect(layers.justAdded).toBe('Roadblocks');
+ });
+
it('leaves the dialog open when the source was refused, with the reason', async () => {
// the backend's sentence is something to act on, and closing the dialog
// would take the input away with it
diff --git a/frontend/src/tools/settings/TemplatesTab.render.test.js b/frontend/src/tools/settings/TemplatesTab.render.test.js
new file mode 100644
index 0000000..880d684
--- /dev/null
+++ b/frontend/src/tools/settings/TemplatesTab.render.test.js
@@ -0,0 +1,124 @@
+// @vitest-environment happy-dom
+/**
+ * The Templates section, actually mounted.
+ *
+ * Each row offers a copy, and a post row also says whether new posts start with
+ * it. Both are answers the parent acts on, so what is checked here is what a row
+ * hands up when pressed and what it shows for the current default.
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { flushSync, mount, unmount } from 'svelte';
+import TemplatesTab from './TemplatesTab.svelte';
+import { prefs, templatesState } from '../../lib/state.svelte.js';
+
+const PROOF = { id: 'pf_1', name: 'House proof', data: { legend: true } };
+const CLASSIC = { id: 'po_1', name: 'Classic', data: { body: '#place' } };
+const SHORT = { id: 'po_2', name: 'Short', data: { body: '#coordinates' } };
+
+let target;
+let app;
+let props;
+
+function open() {
+ target = document.createElement('div');
+ document.body.append(target);
+ props = {
+ newTemplate: vi.fn(),
+ editTemplate: vi.fn(),
+ duplicateTemplate: vi.fn(),
+ savePrefs: vi.fn(),
+ deleteTpl: null,
+ };
+ app = mount(TemplatesTab, { target, props });
+ flushSync();
+}
+
+beforeEach(() => {
+ templatesState.proof = [PROOF];
+ templatesState.post = [CLASSIC, SHORT];
+ prefs.postTemplate = '';
+});
+
+afterEach(() => {
+ if (app) unmount(app);
+ target?.remove();
+ app = null;
+ templatesState.proof = [];
+ templatesState.post = [];
+ prefs.postTemplate = '';
+});
+
+const rows = () => [...target.querySelectorAll('.tpl-row')];
+const rowOf = (name) => rows().find((row) => row.querySelector('.tpl-name').textContent === name);
+const button = (row, text) =>
+ [...row.querySelectorAll('button')].find((b) => b.textContent.trim() === text);
+const toggle = (name) => rowOf(name).querySelector('button[aria-pressed]');
+
+describe('Duplicate', () => {
+ it('is on every row of both kinds, and hands up the kind and the template', () => {
+ open();
+ expect(rows()).toHaveLength(3);
+ for (const row of rows()) expect(button(row, 'Duplicate')).toBeTruthy();
+
+ button(rowOf('House proof'), 'Duplicate').click();
+ expect(props.duplicateTemplate).toHaveBeenLastCalledWith('proof', PROOF);
+ button(rowOf('Short'), 'Duplicate').click();
+ expect(props.duplicateTemplate).toHaveBeenLastCalledWith('post', SHORT);
+ expect(props.editTemplate).not.toHaveBeenCalled();
+ });
+});
+
+describe('the template new posts start with', () => {
+ it('is offered on post rows only', () => {
+ open();
+ expect(toggle('House proof')).toBeNull();
+ expect(toggle('Classic')).not.toBeNull();
+ expect(toggle('Short')).not.toBeNull();
+ expect(toggle('Short').getAttribute('title')).toBe('Start new posts with this template');
+ });
+
+ it('is none until one is chosen', () => {
+ open();
+ expect(target.querySelectorAll('.tpl-tag')).toHaveLength(0);
+ expect(toggle('Classic').getAttribute('aria-pressed')).toBe('false');
+ expect(toggle('Short').getAttribute('aria-pressed')).toBe('false');
+ });
+
+ it('asks the parent to save the one pressed', () => {
+ open();
+ toggle('Short').click();
+ expect(props.savePrefs).toHaveBeenCalledWith({ post_template: 'po_2' });
+ });
+
+ it('marks the default row, and only that one', () => {
+ prefs.postTemplate = 'po_2';
+ open();
+ expect(toggle('Short').getAttribute('aria-pressed')).toBe('true');
+ expect(toggle('Classic').getAttribute('aria-pressed')).toBe('false');
+ const tags = [...target.querySelectorAll('.tpl-tag')];
+ expect(tags.map((tag) => tag.textContent)).toEqual(['Default']);
+ expect(rowOf('Short').contains(tags[0])).toBe(true);
+ });
+
+ it('is cleared by pressing it again', () => {
+ prefs.postTemplate = 'po_2';
+ open();
+ toggle('Short').click();
+ expect(props.savePrefs).toHaveBeenCalledWith({ post_template: '' });
+ });
+
+ it('moves to another row when that one is pressed', () => {
+ prefs.postTemplate = 'po_2';
+ open();
+ toggle('Classic').click();
+ expect(props.savePrefs).toHaveBeenCalledWith({ post_template: 'po_1' });
+ });
+
+ it('follows the saved preference when it changes', () => {
+ open();
+ prefs.postTemplate = 'po_1';
+ flushSync();
+ expect(toggle('Classic').getAttribute('aria-pressed')).toBe('true');
+ expect(target.querySelectorAll('.tpl-tag')).toHaveLength(1);
+ });
+});
diff --git a/frontend/src/tools/settings/TemplatesTab.svelte b/frontend/src/tools/settings/TemplatesTab.svelte
index d5ae610..40a6425 100644
--- a/frontend/src/tools/settings/TemplatesTab.svelte
+++ b/frontend/src/tools/settings/TemplatesTab.svelte
@@ -3,12 +3,19 @@
* Reusable proof styles and report structures, shared across cases.
*
* Content-free presets: a template carries house style, never a case's
- * material. Editing one opens the parent's editor modal.
+ * material. Editing or duplicating one opens the parent's editor modal. One
+ * post template can be the one new posts start with (`post_template`).
*/
import Icon from '../../components/Icon.svelte';
- import { templatesState } from '../../lib/state.svelte.js';
+ import { templatesState, prefs } from '../../lib/state.svelte.js';
- let { newTemplate, editTemplate, deleteTpl = $bindable() } = $props();
+ let { newTemplate, editTemplate, duplicateTemplate, savePrefs, deleteTpl = $bindable() } = $props();
+
+ // Pressing the template that is already the default clears it, which brings
+ // back the classic layout.
+ function toggleDefault(id) {
+ savePrefs({ post_template: prefs.postTemplate === id ? '' : id });
+ }
</script>
<section class="group">
@@ -24,6 +31,9 @@
<button class="btn btn-sm" onclick={() => editTemplate('proof', t)}>
<Icon name="edit" size={13} /> Edit
</button>
+ <button class="btn btn-sm" onclick={() => duplicateTemplate('proof', t)}>
+ <Icon name="copy" size={13} /> Duplicate
+ </button>
<button class="btn btn-sm" title="Delete"
onclick={() => (deleteTpl = { kind: 'proof', id: t.id, name: t.name })}>
<Icon name="trash" size={13} />
@@ -47,12 +57,23 @@
</p>
<div class="tpl-list">
{#each templatesState.post as t (t.id)}
+ {@const isDefault = prefs.postTemplate === t.id}
<div class="tpl-row">
- <span class="tpl-name">{t.name}</span>
+ <span class="tpl-label">
+ <span class="tpl-name">{t.name}</span>
+ {#if isDefault}<span class="tpl-tag">Default</span>{/if}
+ </span>
<div class="tpl-actions">
+ <button class="btn btn-sm" class:on={isDefault} aria-pressed={isDefault}
+ title="Start new posts with this template" onclick={() => toggleDefault(t.id)}>
+ <Icon name="bookmark" size={13} />
+ </button>
<button class="btn btn-sm" onclick={() => editTemplate('post', t)}>
<Icon name="edit" size={13} /> Edit
</button>
+ <button class="btn btn-sm" onclick={() => duplicateTemplate('post', t)}>
+ <Icon name="copy" size={13} /> Duplicate
+ </button>
<button class="btn btn-sm" title="Delete"
onclick={() => (deleteTpl = { kind: 'post', id: t.id, name: t.name })}>
<Icon name="trash" size={13} />
@@ -90,6 +111,13 @@
background: var(--bg-2);
}
+ .tpl-label {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ min-width: 0;
+ }
+
.tpl-name {
font-size: var(--fs-sm);
color: var(--text-1);
@@ -98,6 +126,23 @@
white-space: nowrap;
}
+ .tpl-tag {
+ flex-shrink: 0;
+ padding: 1px 7px;
+ border-radius: 999px;
+ background: var(--accent);
+ color: var(--accent-text);
+ font-size: var(--fs-xs);
+ font-weight: 600;
+ }
+
+ .btn.on,
+ .btn.on:hover:not(:disabled) {
+ background: var(--accent);
+ border-color: var(--accent);
+ color: var(--accent-text);
+ }
+
.tpl-actions {
display: flex;
gap: 6px;
diff --git a/frontend/src/tools/textDirection.test.js b/frontend/src/tools/textDirection.test.js
new file mode 100644
index 0000000..334eec3
--- /dev/null
+++ b/frontend/src/tools/textDirection.test.js
@@ -0,0 +1,44 @@
+/**
+ * Every surface that shows or takes the analyst's own words reads them in their own
+ * direction: an Arabic label, a Hebrew note, a Persian statement start on the right
+ * wherever they sit in an English interface. HTML gets `dir="auto"`; a canvas node
+ * name and an SVG plate, which no attribute reaches, get `bidiIsolate`.
+ */
+import { describe, expect, it } from 'vitest';
+import { readFileSync } from 'node:fs';
+
+const read = (path) => readFileSync(new URL(path, import.meta.url), 'utf8');
+
+describe('text direction on the surfaces that hold the analyst\'s words', () => {
+ it.each([
+ ['./Timeline.svelte', [
+ 'dir="auto"\n >{item.label}</span>',
+ '<strong dir="auto">{item.label}</strong>\n <small>',
+ 'class="list-links" dir="auto">{names(item.subject_entities)}',
+ '<h2 dir="auto">{selected.label}</h2>',
+ '<blockquote dir="auto">{inspectorChain.entity.attrs.verbatim}</blockquote>',
+ '<strong dir="auto">{track.label}</strong>',
+ ]],
+ ['./Board.svelte', [
+ '<span class="name" dir="auto">{row.label}</span>',
+ '<span class="name" dir="auto">{entity.label}</span>',
+ ]],
+ ['../components/EntityDetails.svelte', [
+ 'class="input"\n dir="auto"\n bind:value={infoTitle}',
+ 'dir="auto" bind:value={infoNotes}',
+ ]],
+ ['../components/TemporalClaimEditor.svelte', [
+ 'id="temporal-statement"\n class="textarea"\n dir="auto"',
+ 'dir="auto" bind:value={method}',
+ 'dir="auto" bind:value={verbatim}',
+ ]],
+ ])('%s', (path, expected) => {
+ const source = read(path);
+ for (const line of expected) expect(source).toContain(line);
+ });
+
+ it('isolates what a canvas or a plate draws', () => {
+ expect(read('./Graph.svelte')).toContain('text: bidiIsolate(shortLabel(data.label)),');
+ expect(read('../lib/plate.js')).toContain('const clean = bidiIsolate(text);');
+ });
+});
diff --git a/src/azimut/api/analyzers.py b/src/azimut/api/analyzers.py
index e2e0b9c..372325c 100644
--- a/src/azimut/api/analyzers.py
+++ b/src/azimut/api/analyzers.py
@@ -22,8 +22,8 @@ from ..engine import (
)
from ..engine.analysis_models import (
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, stored, unreadable,
+ AreaGeometry, AreaGroup, Check, Colour, Latitude, Longitude, Model, Recipe, RunInput, SceneClass, ShortId,
+ Source, Zone, is_single, stored, unreadable,
)
from ..workspace import Case
from .cases import delete_by_path, delete_entities_deep, get_case
@@ -54,7 +54,7 @@ def recipes() -> dict[str, Any]:
"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},
+ "max_check_tiles": detect_rules.MAX_CHECK_TILES},
# 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))},
@@ -85,36 +85,32 @@ 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."""
+class CheckInput(Model):
+ """An analyzer of your own as it stands, and one of its checks to try it on."""
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
+ check: Check
-class ProbeInput(PreviewInput):
- #: Longitude and latitude, inside the grid the preview reads.
- point: tuple[Longitude, Latitude]
+class TestInput(CheckInput):
+ #: Fetch the frames the cache lacks. Only the analyst's Test sets it.
+ read: bool = False
+ #: Send what the map draws as well: each tile's mask, the candidates and
+ #: what every rule read at every pin.
+ detail: bool = False
-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
+class ProbeInput(CheckInput):
+ #: Longitude and latitude, inside the ground the check was tested on.
+ point: tuple[Longitude, Latitude]
-def _rules_only(body: PreviewInput | CheckInput) -> None:
+def _rules_only(body: CheckInput) -> None:
if body.recipe.method != "rules":
- raise HTTPException(422, "only an analyzer of your own rules has a live preview")
+ raise HTTPException(422, "only an analyzer of your own rules has checks to test")
-def _previewing(work: Any) -> dict[str, Any]:
- """Run a preview step, saying what went wrong in words an analyst can act on."""
+def _testing(work: Any) -> dict[str, Any]:
+ """Run a step of a test, saying what went wrong in words an analyst can act on."""
try:
result: dict[str, Any] = work()
return result
@@ -126,34 +122,32 @@ def _previewing(work: Any) -> dict[str, Any]:
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.
[email protected]("/compare/analyzers/check/plan")
+def plan_check(body: CheckInput) -> dict[str, Any]:
+ """What testing a check would read: its tiles, and how many frames the cache lacks.
- Reads the tile cache only unless `read` is set, which fetches the missing
- frames: one metered Sentinel Hub request each, for each date read.
+ Each missing frame is one metered Sentinel Hub request. Nothing is fetched.
"""
_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))
+ return _testing(lambda: detect_rules.plan(body.recipe, body.check))
@router.post("/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.
+def test_check(body: TestInput) -> dict[str, Any]:
+ """One check tried with the rules as they stand: what came out on each pin.
Reads the tile cache only unless `read` is set, which fetches the missing
- frames the way the preview's Read does.
+ frames: one metered Sentinel Hub request each, for each date read.
"""
_rules_only(body)
- return _previewing(lambda: detect_rules.check(body.recipe, body.check, read=body.read))
+ return _testing(lambda: detect_rules.check(body.recipe, body.check, read=body.read, detail=body.detail))
+
+
[email protected]("/compare/analyzers/probe")
+def probe_rules(body: ProbeInput) -> dict[str, Any]:
+ """Every rule's reading at one point of a tested check. Never fetches."""
+ _rules_only(body)
+ return _testing(lambda: detect_rules.probe(body.recipe, body.check, body.point))
Kind = Literal["areas", "zones", "followups", "runs"]
@@ -186,20 +180,32 @@ def save_area(case_id: str, body: Area) -> dict[str, Any]:
@router.put("/cases/{case_id}/analysis/areas/{ident}")
def update_area(case_id: str, ident: str, body: Area) -> dict[str, Any]:
case = get_case(case_id)
- read(case, "areas", ident)
- return engine.save(case, "areas", body.model_dump(), ident)
+ old = read(case, "areas", ident)
+ position = old.get("position") if body.position is None else body.position
+ return engine.save(case, "areas", body.model_copy(update={"position": position}).model_dump(), ident)
@router.post("/cases/{case_id}/analysis/zones")
-def save_zones(case_id: str, body: ZoneSet) -> dict[str, Any]:
- return engine.save(get_case(case_id), "zones", body.model_dump())
+def save_zones(case_id: str, body: AreaGroup) -> dict[str, Any]:
+ case = get_case(case_id)
+ for area_id in body.area_ids:
+ read(case, "areas", area_id)
+ position = body.position
+ if position is None:
+ positions = [row["position"] for row in engine.listing(case, "zones") if row["position"] is not None]
+ position = max(positions, default=-1) + 1
+ return engine.save(case, "zones", body.model_copy(update={"position": position}).model_dump())
@router.put("/cases/{case_id}/analysis/zones/{ident}")
-def update_zones(case_id: str, ident: str, body: ZoneSet) -> dict[str, Any]:
+def update_zones(case_id: str, ident: str, body: AreaGroup) -> dict[str, Any]:
case = get_case(case_id)
- read(case, "zones", ident)
- return engine.save(case, "zones", body.model_dump(), ident)
+ old = read(case, "zones", ident)
+ for area_id in body.area_ids:
+ if area_id not in old["area_ids"]:
+ read(case, "areas", area_id)
+ position = old.get("position") if body.position is None else body.position
+ return engine.save(case, "zones", body.model_copy(update={"position": position}).model_dump(), ident)
@router.post("/cases/{case_id}/analysis/followups")
@@ -216,6 +222,49 @@ def update_followup(case_id: str, ident: str, body: RunInput) -> dict[str, Any]:
return engine.save(case, "followups", body.model_dump(), ident)
+class RoutineColour(Model):
+ colour: Colour
+
+
[email protected]("/cases/{case_id}/analysis/followups/{ident}/colour")
+def update_followup_colour(case_id: str, ident: str, body: RoutineColour) -> dict[str, Any]:
+ case = get_case(case_id)
+ with engine.LOCK, case._lock:
+ saved = read(case, "followups", ident)
+ saved["recipe"] = {**saved["recipe"], "colour": body.colour}
+ return engine.save(case, "followups", saved, ident)
+
+
[email protected]("/cases/{case_id}/analysis/runs/{ident}/colour")
+def update_run_colour(case_id: str, ident: str, body: RoutineColour) -> dict[str, Any]:
+ case = get_case(case_id)
+ with engine.LOCK, case._lock:
+ saved = read(case, "runs", ident)
+ if saved["status"] in engine.ACTIVE:
+ raise HTTPException(409, "wait for this run to finish before changing its colour")
+ saved["display_colour"] = body.colour
+ return engine.save(case, "runs", saved, ident)
+
+
[email protected]("/cases/{case_id}/analysis/followups/{ident}/last-passes")
+def followup_last_passes(case_id: str, ident: str) -> dict[str, dict[str, Any]]:
+ """The last successfully swept pass for each area, without a network lookup."""
+ case = get_case(case_id)
+ saved = read(case, "followups", ident)
+ fields = {key: saved[key] for key in RunInput.model_fields if key in saved}
+ try:
+ body = engine.hydrate(case, stored(RunInput, {**fields, "followup_id": ident}))
+ except (FileNotFoundError, ValidationError, ValueError) as exc:
+ raise HTTPException(422, "this detection needs editing before it can run") from exc
+ found: dict[str, dict[str, Any]] = {}
+ for zone in body.zones:
+ local = engine._sensed_by(engine.for_area(body, zone))
+ last = engine.last_successful_pass(case, local)
+ if last:
+ found[zone.id] = last.model_dump()
+ return found
+
+
def start(case: Any, body: RunInput) -> dict[str, Any]:
"""Queue one run. Runs of a case wait their turn behind each other, so a
whole list of saved detections can be started at once; only the same
@@ -231,14 +280,24 @@ def start(case: Any, body: RunInput) -> dict[str, Any]:
if any(row.get("status") in engine.ACTIVE and row.get("followup_id") == body.followup_id
for row in engine.listing(case, "runs")):
raise HTTPException(409, "this detection is already queued or running")
+ prepared, area_runs = engine.prepare_areas(case, body)
+ bad_order = next((row for row in area_runs if row["status"] == "failed"
+ and "date A must be before date B" in row["message"]), None)
+ if bad_order:
+ raise HTTPException(422, bad_order["message"])
+ if body.followup_id and not any(row["status"] == "pending" for row in area_runs):
+ failed = any(row["status"] == "failed" for row in area_runs)
+ return {"status": "failed" if failed else "no_new_imagery", "area_runs": area_runs,
+ "message": " · ".join(row["message"] for row in area_runs if row.get("message"))}
try:
- plans = [engine.plan(engine.for_area(body, zone)) for zone in body.zones]
+ active_zones = [zone for zone, outcome in zip(prepared.zones, area_runs)
+ if outcome["status"] == "pending"]
+ plans = [engine.plan(engine.for_area(prepared, zone)) for zone in active_zones]
if sum(map(len, plans)) > engine.MAX_TILES:
raise ValueError("areas exceed the tile limit; split them into smaller runs")
except ValueError as exc:
raise HTTPException(422, str(exc)) from exc
- prepared, area_runs = engine.prepare_areas(case, body)
- duplicates = engine.duplicates(case, prepared, area_runs)
+ duplicates = [] if body.followup_id else engine.duplicates(case, prepared, area_runs)
if duplicates and not body.run_anyway:
return {"duplicates": duplicates, "input": prepared.model_dump()}
# Store the resolved pairs, not the launch request or its confirmation flag.
diff --git a/src/azimut/api/cases/__init__.py b/src/azimut/api/cases/__init__.py
index 3fbdaa7..1cc9613 100644
--- a/src/azimut/api/cases/__init__.py
+++ b/src/azimut/api/cases/__init__.py
@@ -29,6 +29,7 @@ from .graph import router as _graph
from .lifecycle import router as _lifecycle
from .lifecycle import workspace_router
from .links import router as _links
+from .merges import router as _merges
from .registry import router as _registry
from .timeline import router as _timeline
from .timeline import timeline
@@ -44,6 +45,7 @@ for _sub in (
_lifecycle,
_catalog,
_graph,
+ _merges,
_entities,
_entity_images,
_links,
diff --git a/src/azimut/api/cases/catalog.py b/src/azimut/api/cases/catalog.py
index edb8da1..19b827d 100644
--- a/src/azimut/api/cases/catalog.py
+++ b/src/azimut/api/cases/catalog.py
@@ -10,11 +10,13 @@ from __future__ import annotations
from typing import Any, cast
from fastapi import APIRouter, HTTPException
+from pydantic import BaseModel, Field
from ...engine import analysis_views as analysis_view_engine
from ...engine import entities as entity_engine
from ...engine import tally as tally_engine
from ...repository import EntityStatus
+from ...store.filters import lacking
from ...workspace import CaseError
from .common import _temporal_filter_args, get_case
@@ -44,6 +46,7 @@ def catalog_entities(
value: str | None = None,
linked: str | None = None,
unlinked: bool = False,
+ lacks: str | None = None,
since: str | None = None,
until: str | None = None,
by: str | None = None,
@@ -52,6 +55,8 @@ def catalog_entities(
temporal_category: str | None = None,
order: str = "",
view: str | None = None,
+ previews: bool = False,
+ counts: str | None = None,
) -> dict[str, Any]:
"""A bounded page of the entity catalog (Step 5, "Bounded loading").
@@ -74,9 +79,20 @@ def catalog_entities(
``attr`` without ``value`` is not a term — it is the analyst having chosen which
field they are about to ask about, and answering it as "holds nothing" would empty
the table between two clicks of one act.
+
+ ``previews`` also joins the picture a file, a capture, a proof or a collage already has, for
+ a picker that has to tell twenty sources apart at a glance. Only what is cached
+ or recorded: nothing is made, and the table, which draws its own, does not ask.
+
+ ``counts=type`` adds ``by_type``, the matching count per type, so the Board can
+ say how much of the answer each of its groups holds in the one request.
"""
case = get_case(case_id)
limit = max(1, min(limit, 500))
+ if counts not in (None, "", "type"):
+ raise HTTPException(status_code=400, detail=f"'{counts}' is not a count")
+ by_type = counts == "type"
+ types = [t.strip() for t in type.split(",") if t.strip()] if type else None
if view:
saved = case.get_analysis_view(view)
if saved is None:
@@ -85,13 +101,13 @@ def catalog_entities(
try:
return _explain_catalog_matches(
analysis_view_engine.snapshot_page(
- saved, limit=limit, cursor=cursor, order=order
+ saved, limit=limit, cursor=cursor, order=order,
+ types=types, count_by_type=by_type,
),
q,
)
except CaseError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
- types = [t.strip() for t in type.split(",") if t.strip()] if type else None
filed_by = [name.strip() for name in by.split(",") if name.strip()] if by else None
temporal_since, temporal_until, temporal_categories = _temporal_filter_args(
temporal_from, temporal_to, temporal_category
@@ -104,11 +120,19 @@ def catalog_entities(
limit=limit, cursor=cursor, types=types, status=valid_status,
query=q, folder=folder, unfiled=unfiled, recursive=recursive,
attr=attr, attr_value=value, linked=linked, unlinked=unlinked,
+ lacks=lacking(lacks),
since=since, until=until, filed_by=filed_by, order=order,
temporal_since=temporal_since, temporal_until=temporal_until,
- temporal_categories=temporal_categories,
+ temporal_categories=temporal_categories, count_by_type=by_type,
)
thumbs = case.entity_image_thumbs([entity["id"] for entity in page["items"]])
+ if previews:
+ files = [entity["id"] for entity in page["items"] if entity["type"] == "media"]
+ thumbs = {**case.media_thumbs(files), **thumbs}
+ for entity in page["items"]:
+ recorded = (entity.get("attrs") or {}).get("thumb")
+ if entity["type"] in ("capture", "proof", "collage") and isinstance(recorded, str):
+ thumbs.setdefault(entity["id"], recorded)
for entity in page["items"]:
if thumb := thumbs.get(entity["id"]):
entity["thumb"] = thumb
@@ -116,6 +140,25 @@ def catalog_entities(
except CaseError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
+#: The most rows one events read covers: a Board page, with room for the pinned row.
+MAX_EVENT_ROWS = 200
+
+
+class EventRowsIn(BaseModel):
+ ids: list[str] = Field(default_factory=list, max_length=MAX_EVENT_ROWS)
+
+
[email protected]("/{case_id}/catalog/events")
+def catalog_events(case_id: str, body: EventRowsIn) -> dict[str, Any]:
+ """What the case's Claims say about these rows: how many name each one, when the
+ dated ones fall, how many sources and places they reach, and a density over the
+ case's own span of dated Claims (``engine`` side: ``event_summaries``).
+
+ A POST because it carries a page of ids, and bounded to one page of them: the Board
+ reads it once per page it shows, never once per row.
+ """
+ return get_case(case_id).event_summaries(body.ids)
+
@router.get("/{case_id}/catalog/summary")
def catalog_summary(case_id: str) -> dict[str, Any]:
"""Counts per type, status, folder and filer, plus how many the case connects to
@@ -153,6 +196,7 @@ def catalog_tally(
value: str | None = None,
linked: str | None = None,
unlinked: bool = False,
+ lacks: str | None = None,
since: str | None = None,
until: str | None = None,
by: str | None = None,
@@ -178,6 +222,7 @@ def catalog_tally(
get_case(case_id), types=types, status=status, query=q,
folder=folder, unfiled=unfiled, recursive=recursive,
attr=attr, attr_value=value, linked=linked, unlinked=unlinked,
+ lacks=lacking(lacks),
since=since, until=until, filed_by=filed_by,
temporal_since=temporal_since, temporal_until=temporal_until,
temporal_categories=temporal_categories,
diff --git a/src/azimut/api/cases/doctor.py b/src/azimut/api/cases/doctor.py
index a618dcd..7ca03ef 100644
--- a/src/azimut/api/cases/doctor.py
+++ b/src/azimut/api/cases/doctor.py
@@ -57,6 +57,9 @@ def doctor_repair(case_id: str, body: DoctorRepair) -> dict[str, Any]:
elif body.action == "drop" and body.entity_id:
doctor_engine.require_missing_media(case, body.entity_id)
result = delete_entity_deep(case, body.entity_id)
+ elif body.action == "drop-redirect" and body.entity_id:
+ doctor_engine.require_dangling_redirect(case, body.entity_id)
+ result = {"status": "dropped", "redirects": case.drop_redirects([body.entity_id])}
elif body.action == "relink" and body.entity_id and body.replacement:
doctor_engine.require_missing_media(case, body.entity_id)
doctor_engine.require_unknown_media(case, body.replacement)
diff --git a/src/azimut/api/cases/entities.py b/src/azimut/api/cases/entities.py
index 4fb9a73..d8b27c3 100644
--- a/src/azimut/api/cases/entities.py
+++ b/src/azimut/api/cases/entities.py
@@ -13,6 +13,8 @@ from pydantic import BaseModel, Field
from ...engine import entities as entity_engine
from ...engine import links as link_engine
+from ...engine import merge as merge_engine
+from ...engine import retype as retype_engine
from ...engine import satellite as satellite_engine
from ...engine import tally as tally_engine
from ...repository import EntityStatus
@@ -108,27 +110,44 @@ def add_entity(case_id: str, body: EntityIn) -> dict[str, Any]:
@router.patch("/{case_id}/entities/{entity_id}")
def update_entity(case_id: str, entity_id: str, body: EntityPatch) -> dict[str, Any]:
case = get_case(case_id)
- current = case.get_entity(entity_id)
- if current is None:
- raise HTTPException(status_code=404, detail=f"entity '{entity_id}' not found")
- patch = {k: v for k, v in body.model_dump().items() if v is not None}
- if body.attrs is not None:
- # Against the type it will have once patched, and the entity has to exist
- # before its fields can be judged.
- _check_attrs(
- body.type or str(current["type"]),
- body.attrs,
- current=current.get("attrs") or {},
- )
- try:
- entity = case.update_entity(entity_id, patch)
- if body.status == "confirmed":
- link_engine.confirm_incident_relations(case, entity_id)
- if current.get("type") in MAPPED_TYPES or entity.get("type") in MAPPED_TYPES:
- events.publish({"type": "saved", "case_id": case.id})
- return entity
- except CaseError as exc:
- raise HTTPException(status_code=404, detail=str(exc)) from exc
+ with case.lock:
+ current = case.get_entity(entity_id)
+ if current is None:
+ raise HTTPException(status_code=404, detail=f"entity '{entity_id}' not found")
+ patch = {k: v for k, v in body.model_dump().items() if v is not None}
+ retyped = body.type is not None and body.type != current["type"]
+ if retyped:
+ # A change of type is checked before anything is written, and refused with
+ # everything that stands in its way (`engine/retype.py`). A route that wrote
+ # the column and nothing else let a subject keep relations its new type
+ # cannot hold.
+ reasons = retype_engine.problems(case, {**current, "attrs": {**current["attrs"], **(body.attrs or {})}}, str(body.type))
+ if reasons:
+ raise HTTPException(status_code=409, detail=reasons)
+ if body.attrs is not None:
+ # Against the type it will have once patched, and the entity has to exist
+ # before its fields can be judged.
+ _check_attrs(
+ body.type or str(current["type"]),
+ body.attrs,
+ current=current.get("attrs") or {},
+ )
+ if retyped:
+ patch["attrs"] = retype_engine.retained_fields(current, str(body.type), body.attrs or {})
+ try:
+ entity = case.update_entity(entity_id, patch)
+ if body.status == "confirmed":
+ link_engine.confirm_incident_relations(case, entity_id)
+ if current.get("type") in MAPPED_TYPES or entity.get("type") in MAPPED_TYPES:
+ events.publish({"type": "saved", "case_id": case.id})
+ if retyped:
+ # Into an identifier, the value the case already holds under that type is
+ # reported and never refused: two records of one value are a merge to make.
+ twin = retype_engine.twin(case, entity, str(entity["type"]))
+ return {**entity, "twin": twin}
+ return entity
+ except CaseError as exc:
+ raise HTTPException(status_code=404, detail=str(exc)) from exc
@router.get("/{case_id}/entities/{entity_id}/dependents")
def entity_dependents(case_id: str, entity_id: str) -> dict[str, Any]:
@@ -154,7 +173,12 @@ def entity_chain(case_id: str, entity_id: str) -> dict[str, Any]:
case = get_case(case_id)
chain = link_engine.chain_of(case, entity_id)
if chain is None:
- raise HTTPException(status_code=404, detail=f"entity '{entity_id}' not found")
+ # An id a merge absorbed answers with the entity that took it in, saying so.
+ target, merged_from = merge_engine.resolve(case, entity_id)
+ chain = link_engine.chain_of(case, target) if merged_from else None
+ if chain is None:
+ raise HTTPException(status_code=404, detail=f"entity '{entity_id}' not found")
+ return {**chain, "merged_from": merged_from}
return chain
@router.get("/{case_id}/entities/{entity_id}/placement")
@@ -217,7 +241,7 @@ def remove_entities(case_id: str, body: EntityDeleteIn) -> dict[str, Any]:
raise HTTPException(status_code=404, detail=str(exc)) from exc
@router.post("/{case_id}/entities/missing")
-def missing_entities(case_id: str, body: EntityIdsIn) -> dict[str, list[str]]:
+def missing_entities(case_id: str, body: EntityIdsIn) -> dict[str, Any]:
"""Which of these ids the case no longer holds.
A sidecar keeps ids and only ids — a sheet cell's link, the files a row carries —
@@ -227,4 +251,12 @@ def missing_entities(case_id: str, body: EntityIdsIn) -> dict[str, list[str]]:
"""
case = get_case(case_id)
held = {str(entity["id"]) for entity in case.entities_by_ids(body.ids)}
- return {"missing": [row for row in dict.fromkeys(body.ids) if row not in held]}
+ absent = [row for row in dict.fromkeys(body.ids) if row not in held]
+ # An absorbed id is not missing: it answers with the entity that took it in.
+ redirects = case.entity_redirects(absent) if absent else {}
+ live = {entity["id"] for entity in case.entities_by_ids([target["id"] for target in redirects.values()])}
+ redirects = {old: target for old, target in redirects.items() if target["id"] in live}
+ return {
+ "missing": [row for row in absent if row not in redirects],
+ "redirects": redirects,
+ }
diff --git a/src/azimut/api/cases/graph.py b/src/azimut/api/cases/graph.py
index 3659c7c..cd4c05e 100644
--- a/src/azimut/api/cases/graph.py
+++ b/src/azimut/api/cases/graph.py
@@ -15,6 +15,7 @@ from pydantic import BaseModel, Field
from ...engine import artifacts as artifact_engine
from ...engine import graph as graph_engine
+from ...store.filters import lacking
from ...workspace import Case, CaseError
from .common import _temporal_filter_args, get_case
@@ -68,6 +69,7 @@ def graph_view(
value: str | None = None,
linked: str | None = None,
unlinked: bool = False,
+ lacks: str | None = None,
since: str | None = None,
until: str | None = None,
by: str | None = None,
@@ -119,6 +121,7 @@ def graph_view(
case, lens_id=lens, limit=limit, types=types, status=status,
query=q, folder=folder, unfiled=unfiled, recursive=recursive, order=order,
attr=attr, attr_value=value, linked=linked, unlinked=unlinked,
+ lacks=lacking(lacks),
since=since, until=until, filed_by=filed_by,
temporal_since=temporal_since, temporal_until=temporal_until,
temporal_categories=temporal_categories,
diff --git a/src/azimut/api/cases/merges.py b/src/azimut/api/cases/merges.py
new file mode 100644
index 0000000..685e2a0
--- /dev/null
+++ b/src/azimut/api/cases/merges.py
@@ -0,0 +1,71 @@
+"""Merging two subjects, and undoing it (`engine/merge.py` holds the rules).
+
+A preview first, written nowhere, then the merge, then an undo for as long as the
+record exists. The redirects the merges leave are read here too, so a note or a
+sheet naming an absorbed id can show the entity that took it in.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+from fastapi import APIRouter, HTTPException
+from pydantic import BaseModel, Field
+
+from ...engine import merge as merge_engine
+from ...workspace import CaseError
+from .common import get_case
+from .. import events
+
+router = APIRouter(prefix="/api/cases", tags=["cases"])
+
+
+class MergeIn(BaseModel):
+ other: str = Field(min_length=1, max_length=64)
+
+
+class RedirectIds(BaseModel):
+ ids: list[str] = Field(min_length=1, max_length=2000)
+
+
[email protected]("/{case_id}/entities/redirects")
+def entity_redirects(case_id: str, body: RedirectIds) -> dict[str, Any]:
+ """Resolve only the ids a document actually references."""
+ return {"redirects": get_case(case_id).entity_redirects(body.ids)}
+
+
[email protected]("/{case_id}/entities/{survivor_id}/merge-preview")
+def merge_preview(case_id: str, survivor_id: str, other: str) -> dict[str, Any]:
+ """What folding `other` into this entity would do. Nothing is written."""
+ try:
+ return merge_engine.preview(get_case(case_id), survivor_id, other)
+ except CaseError as exc:
+ raise HTTPException(status_code=409, detail=str(exc)) from exc
+
+
[email protected]("/{case_id}/entities/{survivor_id}/merge")
+def merge_entities(case_id: str, survivor_id: str, body: MergeIn) -> dict[str, Any]:
+ """Fold `other` into this entity, in one transaction."""
+ try:
+ result = merge_engine.merge(get_case(case_id), survivor_id, body.other)
+ events.publish({"type": "saved", "case_id": case_id})
+ return result
+ except CaseError as exc:
+ raise HTTPException(status_code=409, detail=str(exc)) from exc
+
+
[email protected]("/{case_id}/entities/{survivor_id}/merges")
+def entity_merges(case_id: str, survivor_id: str) -> dict[str, Any]:
+ """The merges this entity took in that can still be undone, newest first."""
+ return {"merges": get_case(case_id).merges_into(survivor_id)}
+
+
[email protected]("/{case_id}/merges/{merge_id}/undo")
+def undo_merge(case_id: str, merge_id: str) -> dict[str, Any]:
+ """Take one merge back out, listing whatever could not come back."""
+ try:
+ result = merge_engine.undo(get_case(case_id), merge_id)
+ events.publish({"type": "saved", "case_id": case_id})
+ return result
+ except CaseError as exc:
+ raise HTTPException(status_code=409, detail=str(exc)) from exc
diff --git a/src/azimut/api/cases/registry.py b/src/azimut/api/cases/registry.py
index 5d90b4c..8598bc4 100644
--- a/src/azimut/api/cases/registry.py
+++ b/src/azimut/api/cases/registry.py
@@ -16,6 +16,8 @@ from ...engine import entities as entity_engine
from ...engine import graph as graph_engine
from ...engine import links as link_engine
from ...engine import sheetpromote as promote_engine
+from ...engine import retype as retype_engine
+from ...engine import merge as merge_engine
router = APIRouter(prefix="/api/cases", tags=["cases"])
@@ -126,6 +128,8 @@ def entity_types() -> list[dict[str, Any]]:
"family_reads": entity_engine.FAMILY_READS.get(entry.family, ""),
"icon": entry.icon,
"manual": entry.manual,
+ "retypable": retype_engine.retypable(entry.type),
+ "mergeable": entry.family in merge_engine.MERGE_FAMILIES,
# Whether a sheet row may become one. Not the same question as ``manual``
# and it drifted the moment it was assumed to be: a ``place`` is never
# created by hand because it is born from the map, yet a column of
diff --git a/src/azimut/api/cases/timeline.py b/src/azimut/api/cases/timeline.py
index 97a2b17..cdca916 100644
--- a/src/azimut/api/cases/timeline.py
+++ b/src/azimut/api/cases/timeline.py
@@ -14,6 +14,7 @@ from typing import Any, Literal
from fastapi import APIRouter, HTTPException, Query
from pydantic import BaseModel, Field, StrictInt
+from ...engine import entities as entity_engine
from ...engine import links as link_engine
from ...engine import timeline as timeline_engine
from ...repository import EntityStatus
@@ -23,9 +24,18 @@ from .common import _check_attrs, _timeline_bound, delete_entity_deep, get_case
router = APIRouter(prefix="/api/cases", tags=["cases"])
+class NewSubjectIn(BaseModel):
+ """A subject the entry line names for the first time, created with the Claim."""
+
+ slot: Literal["about", "at", "cites"]
+ type: str = Field(min_length=1, max_length=40)
+ label: str = Field(min_length=1, max_length=300)
+
class TemporalClaimIn(BaseModel):
statement: str = Field(min_length=1, max_length=300)
when: str | None = None
+ #: The IANA zone `when` was stated in: a day then spans that zone's day.
+ when_zone: str | None = Field(default=None, max_length=64)
time_role: Literal["occurred", "observed", "valid"] | None = None
confidence: Literal["certain", "probable", "possible", "refuted"] | None = None
method: str | None = None
@@ -35,10 +45,14 @@ class TemporalClaimIn(BaseModel):
about: list[str] = Field(default_factory=list, max_length=200)
at: list[str] = Field(default_factory=list, max_length=50)
cites: list[str] = Field(default_factory=list, max_length=200)
+ #: Subjects named for the first time on this line. They are created in the same
+ #: transaction as the Claim, so abandoning or failing the line leaves nothing.
+ create: list[NewSubjectIn] = Field(default_factory=list, max_length=10)
class TemporalClaimPatch(BaseModel):
statement: str | None = Field(default=None, min_length=1, max_length=300)
when: str | None = None
+ when_zone: str | None = Field(default=None, max_length=64)
time_role: Literal["occurred", "observed", "valid"] | None = None
confidence: Literal["certain", "probable", "possible", "refuted"] | None = None
method: str | None = None
@@ -93,8 +107,87 @@ def timeline(
)
except (CaseError, json.JSONDecodeError) as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
+ # A file's row carries the preview the case already cached for it, so a card on a
+ # zoomed axis can show the picture. One indexed read per page, and nothing is made.
+ media_owners = [
+ str(item["owner_id"]) for item in page["items"]
+ if item.get("category") == timeline_engine.MEDIA
+ ]
+ if media_owners:
+ thumbs = get_case(case_id).media_thumbs(media_owners)
+ for item in page["items"]:
+ thumb = thumbs.get(str(item["owner_id"]))
+ if thumb and item.get("category") == timeline_engine.MEDIA:
+ item["thumb"] = thumb
+ lane = (track_query or {}).get("as_files")
+ if lane in ("sources", "imagery"):
+ _situate_files(get_case(case_id), page["items"], from_above=lane == "imagery")
return {**page, "window": {"from": since, "to": until}}
+
+#: What an event can put at its date: a picture or a video, or a picture from orbit.
+_SITUATED = ("media", "capture")
+
+
+def _situate_files(case: Case, items: list[dict[str, Any]], *, from_above: bool) -> None:
+ """Name, on each event of a file lane, the file it puts at its date, with its preview.
+
+ A file's own dates are what it says about itself; the date an analyst gives it is
+ an event about it or citing it: a proof's date stated for its footage, a
+ correction, "seen in" a video. That event is what places the file in time, so the
+ lane draws the file itself there. The sources' lane draws a picture or a video the
+ case collected, the imagery lane one the app pictured from above (`FROM_ABOVE`),
+ so an event about a video that cites a Compare render is the video on one and the
+ render on the other. The file the event is *about* comes first, since a proof's
+ date is about the footage and cites the proof. Two indexed reads per page.
+ """
+ named = {
+ str(entry["id"]): entry
+ for item in items if item.get("category") == timeline_engine.STATEMENT
+ for key in ("subject_entities", "source_entities")
+ for entry in item.get(key) or [] if entry.get("type") in _SITUATED
+ }
+ if not named:
+ return
+ ids = sorted(named)
+ origins = case.media_origins(ids)
+
+ def above(entry: dict[str, Any]) -> bool:
+ route = (origins.get(str(entry["id"])) or {}).get("type")
+ return entry.get("type") == "capture" or route in link_engine.FROM_ABOVE
+
+ chosen: dict[str, dict[str, Any]] = {}
+ for item in items:
+ if item.get("category") != timeline_engine.STATEMENT:
+ continue
+ for key in ("subject_entities", "source_entities"):
+ entry = next(
+ (e for e in item.get(key) or []
+ if e.get("type") in _SITUATED and above(e) == from_above),
+ None,
+ )
+ if entry is not None:
+ chosen[str(item["id"])] = entry
+ break
+ if not chosen:
+ return
+ ids = sorted({str(entry["id"]) for entry in chosen.values()})
+ thumbs = dict(case.media_thumbs(ids))
+ for entity in case.entities_by_ids(ids):
+ # A capture records its own preview rather than owning an indexed media row.
+ recorded = (entity.get("attrs") or {}).get("thumb")
+ if recorded and entity["id"] not in thumbs:
+ thumbs[entity["id"]] = recorded
+ for item in items:
+ entry = chosen.get(str(item.get("id")))
+ if entry is not None:
+ item["file"] = {
+ "id": entry["id"],
+ "label": entry.get("label", ""),
+ "type": entry.get("type"),
+ **({"thumb": thumbs[entry["id"]]} if thumbs.get(entry["id"]) else {}),
+ }
+
# Every way the case puts something on the map. A Claim says where it happened with
# `at`, and that was the only one this layer knew — so a window full of photographs
# recorded somewhere, captures showing somewhere, or a structure standing somewhere
@@ -232,8 +325,16 @@ def timeline_map(
}
_TEMPORAL_CLAIM_ATTRS = (
- "when", "time_role", "confidence", "method", "verbatim", "count", "condition"
+ "when", "when_zone", "time_role", "confidence", "method", "verbatim", "count",
+ "condition",
)
+
+
+def _without_orphan_zone(attrs: dict[str, Any]) -> dict[str, Any]:
+ """A zone says how a date reads, so it leaves with the date it read."""
+ if not attrs.get("when"):
+ attrs.pop("when_zone", None)
+ return attrs
_TEMPORAL_CONNECTORS = ("about", "at", "cites")
def _temporal_item(case: Case, claim_id: str) -> dict[str, Any]:
@@ -284,6 +385,16 @@ def _check_claim_connectors(
except CaseError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
[email protected]("/{case_id}/timeline/claims/{claim_id}")
+def read_temporal_claim(case_id: str, claim_id: str) -> dict[str, Any]:
+ """Where one Claim sits on the Timeline: its own row, dated, undated or off the
+ UTC axis. What opening a Claim from anywhere reads, so it lands on its entry."""
+ case = get_case(case_id)
+ entity = case.get_entity(claim_id)
+ if entity is None or entity["type"] != "claim":
+ raise HTTPException(status_code=404, detail=f"claim '{claim_id}' not found")
+ return {"item": _temporal_item(case, claim_id)}
+
@router.post("/{case_id}/timeline/claims")
def create_temporal_claim(case_id: str, body: TemporalClaimIn) -> dict[str, Any]:
"""Create the statement, date and all of its connectors in one transaction."""
@@ -296,20 +407,49 @@ def create_temporal_claim(case_id: str, body: TemporalClaimIn) -> dict[str, Any]
for key in _TEMPORAL_CLAIM_ATTRS
if getattr(body, key) is not None
}
+ _without_orphan_zone(attrs)
_check_attrs("claim", attrs)
- connectors = {key: getattr(body, key) for key in _TEMPORAL_CONNECTORS}
- _check_claim_connectors(case, {"type": "claim"}, connectors)
+ connectors = {key: list(getattr(body, key)) for key in _TEMPORAL_CONNECTORS}
+ new_subjects = [_new_subject(entry) for entry in body.create]
+ created: list[dict[str, Any]] = []
try:
- saved = case.save_temporal_claim(
- entity_id=None,
- label=statement,
- attrs=attrs,
- connectors=connectors,
- by="user",
- )
+ # One transaction for the subjects and the Claim: a connector the vocabulary
+ # refuses rolls the new subjects back with it.
+ with case.batch():
+ for entry, label in new_subjects:
+ entity = case.add_entity(entry.type, label, {}, by="user")
+ connectors[entry.slot].append(entity["id"])
+ created.append({"id": entity["id"], "type": entry.type,
+ "label": label, "slot": entry.slot})
+ _check_claim_connectors(case, {"type": "claim"}, connectors)
+ saved = case.save_temporal_claim(
+ entity_id=None,
+ label=statement,
+ attrs=attrs,
+ connectors=connectors,
+ by="user",
+ )
except CaseError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
- return {**saved, "temporal": _temporal_item(case, saved["entity"]["id"])}
+ return {
+ **saved,
+ "created": created,
+ "temporal": _temporal_item(case, saved["entity"]["id"]),
+ }
+
+def _new_subject(entry: NewSubjectIn) -> tuple[NewSubjectIn, str]:
+ """A new subject checked before anything is written: a type an analyst makes by
+ hand, and a name that is more than spaces. A Claim is not a subject here, since a
+ line that names one files a second statement rather than a subject of this one."""
+ declared = entity_engine.entity_type(entry.type)
+ if declared is None or not declared.manual or entry.type == "claim":
+ raise HTTPException(
+ status_code=400, detail=f"a new subject cannot be a '{entry.type}'"
+ )
+ label = entry.label.strip()
+ if not label:
+ raise HTTPException(status_code=400, detail="a new subject needs a name")
+ return entry, label
@router.patch("/{case_id}/timeline/claims/{claim_id}")
def update_temporal_claim(
@@ -334,6 +474,7 @@ def update_temporal_claim(
for key in _TEMPORAL_CLAIM_ATTRS:
if key in body.model_fields_set:
attrs[key] = getattr(body, key)
+ _without_orphan_zone(attrs)
_check_attrs("claim", attrs, current=current.get("attrs") or {})
connector_keys = set(_TEMPORAL_CONNECTORS) & body.model_fields_set
connectors = (
diff --git a/src/azimut/api/compare.py b/src/azimut/api/compare.py
index 4285298..e65d95b 100644
--- a/src/azimut/api/compare.py
+++ b/src/azimut/api/compare.py
@@ -83,10 +83,12 @@ _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)?)$"
#: The colours a GIF keeps exactly, comma-separated: the marks drawn on the
-#: pictures and the export's own inks. Median cut spends a palette on the
-#: imagery, so a thin red outline over fields came out a dull brown and a green
-#: and a blue mark came out one teal.
-GIF_COLOURS = 192
+#: pictures and the export's own inks. A palette quantizer can spend its entries
+#: on the common sand tones and turn rare dark pixels into grey-brown ones. Use
+#: an octree palette with every GIF entry so the imagery loses as little colour
+#: information as GIF allows after visible overlay colours have been reserved.
+GIF_COLOURS = 256
+GIF_QUANTIZE_METHOD = Image.Quantize.FASTOCTREE
MAX_KEPT_COLOURS = 32
_KEPT_COLOURS = r"^(#[0-9a-fA-F]{6}(,#[0-9a-fA-F]{6}){0,31})?$"
@@ -576,15 +578,16 @@ def _kept_colours(text: str) -> list[tuple[int, int, int]]:
def _quantize(frame: Image.Image, kept: list[tuple[int, int, int]]) -> Image.Image:
- """One frame in 192 colours, the kept ones among them exactly.
+ """One frame in 256 colours, the kept ones among them exactly.
- The rest of the palette is median cut's answer for the imagery. Mapping onto a
- fixed palette dithers by default, which would speckle the marks' edges and change
- how the imagery has always looked, so it maps to the nearest entry instead.
+ The rest of the palette is the octree quantizer's answer for the imagery.
+ Mapping onto a fixed palette dithers by default, which would speckle the marks'
+ edges and change how the imagery has always looked, so it maps to the nearest
+ entry instead.
"""
if not kept:
- return frame.quantize(colors=GIF_COLOURS, method=Image.Quantize.MEDIANCUT)
- base = frame.quantize(colors=GIF_COLOURS - len(kept), method=Image.Quantize.MEDIANCUT)
+ return frame.quantize(colors=GIF_COLOURS, method=GIF_QUANTIZE_METHOD)
+ base = frame.quantize(colors=GIF_COLOURS - len(kept), method=GIF_QUANTIZE_METHOD)
ground = (base.getpalette() or [])[: 3 * (GIF_COLOURS - len(kept))]
entries = [channel for rgb in kept for channel in rgb] + ground
# A palette image holds 256 entries; the spare ones repeat the first kept colour.
diff --git a/src/azimut/api/inspect.py b/src/azimut/api/inspect.py
index 3d6fe0f..d95a5f6 100644
--- a/src/azimut/api/inspect.py
+++ b/src/azimut/api/inspect.py
@@ -9,7 +9,7 @@ from __future__ import annotations
from typing import Any, Literal
-from fastapi import APIRouter, HTTPException, Response
+from fastapi import APIRouter, HTTPException, Response, UploadFile
from pydantic import BaseModel, Field
from .. import jobs
@@ -346,6 +346,20 @@ def save_collage(case_id: str, body: CollageIn) -> dict[str, Any]:
raise HTTPException(status_code=400, detail=str(exc)) from exc
[email protected]("/cases/{case_id}/collages/{name}/thumb")
+async def save_collage_thumb(case_id: str, name: str, file: UploadFile) -> dict[str, Any]:
+ """The picture the collage list shows for it, drawn by the browser from the layout."""
+ case = get_case(case_id)
+ raw = await file.read(inspectwork.MAX_THUMB_BYTES + 1)
+ try:
+ saved = inspectwork.save_collage_thumb(case, name, raw)
+ except CaseError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+ if saved is None:
+ raise HTTPException(status_code=404, detail="collage not found")
+ return saved
+
+
@router.delete("/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."""
diff --git a/src/azimut/api/maplayers.py b/src/azimut/api/maplayers.py
index 38cce96..cd8d2df 100644
--- a/src/azimut/api/maplayers.py
+++ b/src/azimut/api/maplayers.py
@@ -24,7 +24,7 @@ Google for the one it pointed at.
from __future__ import annotations
-from typing import Any
+from typing import Annotated, Any
from fastapi import APIRouter, Form, HTTPException, UploadFile
from fastapi.responses import FileResponse, Response
@@ -251,6 +251,18 @@ def layer_icon(case_id: str, name: str, key: str) -> Response:
)
+class OrderIn(BaseModel):
+ #: Every layer's name, top of the map first.
+ names: list[Annotated[str, Field(max_length=200)]] = Field(max_length=2000)
+
+
[email protected]("/{case_id}/map-layers/order")
+def order_layers(case_id: str, body: OrderIn) -> list[dict[str, Any]]:
+ """The rows as they were dragged, which is also how the map stacks them.
+ Answers with the whole list in its new order. Touches no network."""
+ return layer_engine.reorder(get_case(case_id), [_stem(name) for name in body.names])
+
+
@router.patch("/{case_id}/map-layers/{name}")
def update_layer(case_id: str, name: str, body: UpdateIn) -> dict[str, Any]:
"""The legend, the time filter, the refresh policy and the title. Touches no
diff --git a/src/azimut/api/proofs.py b/src/azimut/api/proofs.py
index 4920e17..e887310 100644
--- a/src/azimut/api/proofs.py
+++ b/src/azimut/api/proofs.py
@@ -29,6 +29,7 @@ from .. import config
from ..engine import artifacts as artifact_engine
from ..engine import exportdir
from ..engine import links as link_engine
+from ..engine import localtime
from ..engine import media as media_engine
from ..engine import reveal as reveal_engine
from ..engine import satellite as satellite_engine
@@ -112,7 +113,35 @@ def _write_spec(path: Path, spec: dict[str, Any]) -> None:
_STATED_TEXT_MAX = 2000
-def _stated_when(spec: dict[str, Any]) -> str:
+def _chosen_zone(spec: dict[str, Any]) -> str | None:
+ """The zone the analyst picked for the proof's date, or None for *at the point*."""
+ raw = spec.get("whenZone")
+ if raw in (None, ""):
+ return None
+ if not temporal.valid_zone(raw):
+ raise HTTPException(status_code=422, detail="unknown time zone")
+ return str(raw)
+
+
+def _point_zone(spec: dict[str, Any]) -> str | None:
+ """The zone of the proof's first point, the one every single-answer surface reads.
+
+ A date read off footage is read on the clock of the place it shows, so that is
+ where the day begins. No point, no zone: the date then spans UTC's day, as a
+ date stated before zones existed always has.
+ """
+ points = satellite_engine.spec_points(spec)
+ if not points:
+ return None
+ return localtime.zone_for(float(points[0]["lat"]), float(points[0]["lon"]))
+
+
+def _stated_zone(spec: dict[str, Any]) -> str | None:
+ """The zone the proof's date is read in: the analyst's pick, else its point's."""
+ return _chosen_zone(spec) or _point_zone(spec)
+
+
+def _stated_when(spec: dict[str, Any], zone: str | None = None) -> str:
"""The date the proof states, checked against the profile the case stores.
Refused here rather than stored and puzzled over later: a value the temporal
@@ -128,7 +157,7 @@ def _stated_when(spec: dict[str, Any]) -> str:
if not value:
return ""
try:
- temporal.parse_temporal(value)
+ temporal.parse_temporal(value, tz=zone)
except temporal.TemporalError as exc:
raise HTTPException(status_code=422, detail=f"unsupported date: {exc}") from exc
return value
@@ -311,6 +340,19 @@ def load_proof(case_id: str, name: str) -> dict[str, Any]:
if attr in attrs:
stated = attrs[attr]
opened[key] = (stated.strip() or None) if isinstance(stated, str) else None
+ # The zone too, but only where it says something the spec does not: the
+ # composer leaves it at *the point's* by default, and a zone the case holds
+ # that the point would give anyway is that default, not a pick. One set in
+ # Details that differs from it is the analyst's, and opens as their choice.
+ held = attrs.get("when_zone")
+ implied = _chosen_zone(opened) or _point_zone(opened)
+ if isinstance(held, str) and held and held != implied and temporal.valid_zone(held):
+ opened["whenZone"] = held
+ # What the date is read in, whichever way it was chosen, for the reader that
+ # only shows it (a post naming the offset).
+ opened["whenZoneStated"] = (held if isinstance(held, str) and held else None) or (
+ implied if opened.get("when") else None
+ )
return opened
return spec
@@ -373,7 +415,10 @@ def save_proof(case_id: str, body: ProofIn) -> dict[str, Any]:
incoming = _decode_assets(body.assets)
# Read up front for the same reason: a date outside the profile is refused
# before the rename below moves this proof's export and its pasted images.
- when = _stated_when(body.spec)
+ zone = _stated_zone(body.spec)
+ when = _stated_when(body.spec, zone)
+ # A zone only means something beside the date it reads.
+ when_zone = zone if when else None
description = _stated_description(body.spec)
# The export too, and for a stronger reason — the rename below deletes the
# old PNG and moves the assets folder, so a payload refused after that point
@@ -427,6 +472,9 @@ def save_proof(case_id: str, body: ProofIn) -> dict[str, Any]:
spec["azimut_proof"] = 1
spec["title"] = name
spec["when"] = when or None
+ # The pick, not the answer: left empty, the zone follows the point each save.
+ spec["whenZone"] = _chosen_zone(body.spec)
+ spec.pop("whenZoneStated", None)
spec["description"] = description or None
previous = case.resolve_inside(layout.proof_spec_rel(name if recased else old or name))
spec.setdefault("created_at", read_created_at(previous) or _now())
@@ -466,6 +514,8 @@ def save_proof(case_id: str, body: ProofIn) -> dict[str, Any]:
# since clearing the field is the analyst taking the statement back.
if existing["attrs"].get("when", "") != when:
attrs["when"] = when
+ if existing["attrs"].get("when_zone") != when_zone:
+ attrs["when_zone"] = when_zone
if existing["attrs"].get("notes", "") != description:
attrs["notes"] = description
if attrs:
@@ -481,6 +531,7 @@ def save_proof(case_id: str, body: ProofIn) -> dict[str, Any]:
**({"path": png_rel} if png_rel else {}),
**({"thumb": thumb_rel} if thumb_rel else {}),
**({"when": when} if when else {}),
+ **({"when_zone": when_zone} if when_zone else {}),
**({"notes": description} if description else {}),
},
by="proof-composer",
@@ -517,6 +568,7 @@ def save_proof(case_id: str, body: ProofIn) -> dict[str, Any]:
rel=rel,
old_rel=old_rel,
when=when,
+ when_zone=when_zone,
spec=spec,
)
@@ -528,6 +580,8 @@ def save_proof(case_id: str, body: ProofIn) -> dict[str, Any]:
"thumb": thumb_rel,
"spec_path": rel,
"place": place,
+ # The zone the date was read in, so a post handed this proof names its clock.
+ "when_zone": when_zone,
# The files this save stated the date for, so the composer can say so. A
# save that writes into the graph announces it; it just does not ask.
"dated": dated,
@@ -544,7 +598,7 @@ _STATED_BY = "proof"
#: What the statement holds when nothing but this save has touched it. A Claim that
#: has grown reasoning, a quote or a confidence is the analyst's own work by then,
#: and clearing a date in the composer must not delete it.
-_OURS = {"when", "time_role", _STATED_BY}
+_OURS = {"when", "when_zone", "time_role", _STATED_BY}
def _source_material(case: Case, spec: dict[str, Any]) -> list[dict[str, Any]]:
@@ -600,6 +654,7 @@ def _date_the_material(
old_rel: str | None,
when: str,
spec: dict[str, Any],
+ when_zone: str | None = None,
) -> list[str]:
"""State the proof's date for the footage it rests on, and answer with what it hit.
@@ -640,6 +695,9 @@ def _date_the_material(
if key not in _OURS
},
"when": when,
+ # Read on the same clock the proof states it on, so the footage's day
+ # is the day of the place it shows.
+ **({"when_zone": when_zone} if when_zone else {}),
# What the file shows, as read by whoever composed the proof. The same
# role the Timeline's own "this media was captured" correction uses.
"time_role": "observed",
diff --git a/src/azimut/api/satellite.py b/src/azimut/api/satellite.py
index ad66835..818a1f6 100644
--- a/src/azimut/api/satellite.py
+++ b/src/azimut/api/satellite.py
@@ -1250,6 +1250,19 @@ def _instant(value: str, field: str) -> datetime:
return parsed if parsed.tzinfo else parsed.replace(tzinfo=timezone.utc)
[email protected]("/geo/zone")
+def zone_at(
+ lat: float = Query(ge=-90, le=90),
+ lon: float = Query(ge=-180, le=180),
+) -> dict[str, str]:
+ """The civil zone at a point, for a time typed as the local time there.
+
+ Only the name: the offset depends on the instant, daylight saving included, and
+ the browser that holds the instant computes it.
+ """
+ return {"name": localtime.zone_for(lat, lon)}
+
+
@router.get("/geo/daylight")
def daylight_for_window(
lat: float = Query(ge=-90, le=90),
diff --git a/src/azimut/api/settings.py b/src/azimut/api/settings.py
index 6f5738c..b0e1e34 100644
--- a/src/azimut/api/settings.py
+++ b/src/azimut/api/settings.py
@@ -52,6 +52,7 @@ ECO_TUNABLE = ("mapbox", "google", "sentinelhub")
DEFAULT_HOME_VIEW = config.DEFAULT_SETTINGS["home_view"]
DEFAULT_POST_MENTION = config.DEFAULT_SETTINGS["post_mention"]
DEFAULT_POST_TARGET = config.DEFAULT_SETTINGS["post_target"]
+DEFAULT_POST_TEMPLATE = config.DEFAULT_SETTINGS["post_template"]
DEFAULT_SIGNATURE_HANDLE = config.DEFAULT_SETTINGS["signature_handle"]
@@ -112,6 +113,8 @@ class PrefsIn(BaseModel):
proof_place_auto: bool | None = None
post_mention: str | None = None # handle a new post draft is addressed to
post_target: str | None = None # social composer a new post draft starts with
+ # id of the post template a new draft starts with; "" is the classic layout
+ post_template: str | None = Field(default=None, pattern=r"^$|^[A-Za-z0-9_-]{1,64}$")
post_prefill: bool | None = None # let the extension fill that composer
reverse_prefill: bool | None = None # let it open an engine with the image
signature_handle: str | None = None # account handle stamped on opted-in proofs
@@ -153,6 +156,7 @@ def _prefs(settings: dict[str, Any]) -> dict[str, Any]:
"proof_place_auto": bool(settings.get("proof_place_auto", True)),
"post_mention": settings.get("post_mention", DEFAULT_POST_MENTION),
"post_target": settings.get("post_target", DEFAULT_POST_TARGET),
+ "post_template": settings.get("post_template", DEFAULT_POST_TEMPLATE),
"post_prefill": bool(settings.get("post_prefill", True)),
"reverse_prefill": bool(settings.get("reverse_prefill", True)),
"signature_handle": settings.get("signature_handle", DEFAULT_SIGNATURE_HANDLE),
@@ -292,6 +296,8 @@ def _apply_prefs(settings: dict[str, Any], body: PrefsIn) -> None:
settings["post_mention"] = body.post_mention.strip()[:64]
if body.post_target is not None:
settings["post_target"] = body.post_target
+ if body.post_template is not None:
+ settings["post_template"] = body.post_template
if body.post_prefill is not None:
settings["post_prefill"] = bool(body.post_prefill)
if body.reverse_prefill is not None:
@@ -655,6 +661,7 @@ class ImportedSettings(BaseModel):
proof_place_auto: bool = True
post_mention: str = Field(default=DEFAULT_POST_MENTION, max_length=64)
post_target: str = DEFAULT_POST_TARGET
+ post_template: str = DEFAULT_POST_TEMPLATE
post_prefill: bool = True
reverse_prefill: bool = True
signature_handle: str = Field(default=DEFAULT_SIGNATURE_HANDLE, max_length=64)
@@ -728,6 +735,12 @@ class ImportedSettings(BaseModel):
"""
return value if value in config.POST_TARGETS else DEFAULT_POST_TARGET
+ @field_validator("post_template")
+ @classmethod
+ def readable_template_id(cls, value: str) -> str:
+ """An id no template carries reads as none rather than failing the backup."""
+ return value if re.fullmatch(r"[A-Za-z0-9_-]{1,64}", value) else DEFAULT_POST_TEMPLATE
+
class ImportIn(BaseModel):
"""A previously exported backup. Only keys Azimut recognises are applied —
diff --git a/src/azimut/casestore.py b/src/azimut/casestore.py
index 965ac31..c2e804c 100644
--- a/src/azimut/casestore.py
+++ b/src/azimut/casestore.py
@@ -52,6 +52,7 @@ class CaseStore:
attr_value: str | None = None,
linked: str | None = None,
unlinked: bool = False,
+ lacks: list[str] | None = None,
since: str | None = None,
until: str | None = None,
filed_by: list[str] | None = None,
@@ -59,6 +60,7 @@ class CaseStore:
temporal_until: str | None = None,
temporal_categories: list[str] | None = None,
order: str = "",
+ count_by_type: bool = False,
) -> dict[str, Any]:
"""A bounded, filtered page of the catalog (Step 5), paged with an indexed
keyset over the ordering asked for."""
@@ -75,6 +77,7 @@ class CaseStore:
attr_value=attr_value,
linked=linked,
unlinked=unlinked,
+ lacks=lacks,
since=since,
until=until,
filed_by=filed_by,
@@ -82,8 +85,13 @@ class CaseStore:
temporal_until=temporal_until,
temporal_categories=temporal_categories,
order=order,
+ count_by_type=count_by_type,
)
+ def event_summaries(self, entity_ids: list[str], *, buckets: int = 12) -> dict[str, Any]:
+ """What the case's Claims say about each of these entities (Board rows)."""
+ return self._graph().event_summaries(entity_ids, buckets=buckets)
+
def catalog_summary(self) -> dict[str, Any]:
"""Total plus per-type, per-status, per-folder and per-filer counts."""
return self._graph().catalog_summary()
@@ -238,6 +246,7 @@ class CaseStore:
attr_value: str | None = None,
linked: str | None = None,
unlinked_only: bool = False,
+ lacks: list[str] | None = None,
since: str | None = None,
until: str | None = None,
filed_by: list[str] | None = None,
@@ -251,6 +260,7 @@ class CaseStore:
limit=limit, types=types, exclude_types=exclude_types, status=status,
query=query, folder=folder, unfiled=unfiled, recursive=recursive,
attr=attr, attr_value=attr_value, linked=linked, unlinked_only=unlinked_only,
+ lacks=lacks,
since=since, until=until, filed_by=filed_by,
temporal_since=temporal_since, temporal_until=temporal_until,
temporal_categories=temporal_categories,
@@ -483,6 +493,57 @@ class CaseStore:
) -> dict[str, int]:
return self._graph().reinsert(entities, links)
+ # -- merges and redirects ----------------------------------------------
+
+ def merge_entities(
+ self,
+ survivor_id: str,
+ merged_id: str,
+ *,
+ survivor_attrs: dict[str, Any],
+ survivor_status: str,
+ old_key: str | None,
+ by: str,
+ dry_run: bool = False,
+ ) -> dict[str, Any]:
+ return self._graph().merge_entities(
+ survivor_id, merged_id, survivor_attrs=survivor_attrs,
+ survivor_status=survivor_status, old_key=old_key, by=by, dry_run=dry_run,
+ )
+
+ def unmerge(self, merge_id: str) -> dict[str, Any]:
+ return self._graph().unmerge(merge_id)
+
+ def pending_merge_work(self) -> list[dict[str, Any]]:
+ return self._graph().pending_merge_work()
+
+ def finish_merge_work(self, merge_id: str) -> None:
+ self._graph().finish_merge_work(merge_id)
+
+ def get_merge(self, merge_id: str) -> dict[str, Any] | None:
+ return self._graph().get_merge(merge_id)
+
+ def merges_into(self, survivor_id: str) -> list[dict[str, Any]]:
+ return self._graph().merges_into(survivor_id)
+
+ def set_merge_sheets(self, merge_id: str, sheets: list[dict[str, Any]]) -> None:
+ self._graph().set_merge_sheets(merge_id, sheets)
+
+ def entity_redirects(self, ids: list[str] | None = None) -> dict[str, dict[str, str]]:
+ return self._graph().entity_redirects(ids)
+
+ def redirect_by_key(self, key: str) -> str | None:
+ return self._graph().redirect_by_key(key)
+
+ def dangling_redirects(self, keep: set[str]) -> list[dict[str, str]]:
+ return self._graph().dangling_redirects(keep)
+
+ def drop_redirects(self, old_ids: list[str]) -> int:
+ return self._graph().drop_redirects(old_ids)
+
+ def forget_merges_of(self, entity_ids: list[str]) -> None:
+ self._graph().forget_merges_of(entity_ids)
+
# -- durable jobs (thumbnail and background-job model) -------------------
def enqueue_job(
diff --git a/src/azimut/config.py b/src/azimut/config.py
index afb5f70..0f38330 100644
--- a/src/azimut/config.py
+++ b/src/azimut/config.py
@@ -52,7 +52,8 @@ DEFAULT_SETTINGS: dict[str, Any] = {
# their configuration with Sentinel-1 as its source. Empty until found.
"sentinel1_layer": "",
"detect_view": {
- "collapsed": False, "basemap": "esri-world-imagery", "overlays": ["boundaries", "placenames"], "saved": True,
+ "collapsed": False, "width": 380, "basemap": "esri-world-imagery",
+ "overlays": ["boundaries", "placenames"], "saved": True,
},
# Schema version this build writes. Read back through _settings_schema() so
# a future breaking rename is migrated rather than silently dropped.
@@ -128,6 +129,10 @@ DEFAULT_SETTINGS: dict[str, Any] = {
# The social composer a new post draft starts with. A saved draft keeps its
# own target so a later preference change never rewrites it.
"post_target": "x",
+ # The post template a new post draft starts with, by id. Empty means the
+ # classic layout. An id whose template has since been deleted is ignored
+ # where it is read, so nothing here needs cleaning up after a delete.
+ "post_template": "",
# Whether Publish lets the capture extension fill that composer — the thread
# typed in, the proof and the media attached, nothing posted. The only switch
# for it: the extension keeps none of its own, so this is where the answer
diff --git a/src/azimut/engine/analysis_examples.py b/src/azimut/engine/analysis_examples.py
index 53f3fe0..47ae6cb 100644
--- a/src/azimut/engine/analysis_examples.py
+++ b/src/azimut/engine/analysis_examples.py
@@ -10,8 +10,8 @@ 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`, then every check was run again through
Copernicus itself, which is what an analyst's run reads. Marks sit at least 64
-pixels inside the grid tile they fall in, since a check reads each mark on its
-own tile.
+pixels inside the grid tile they fall in, so a check reads each mark on its own
+tile and nothing beside it.
"""
from __future__ import annotations
@@ -33,15 +33,14 @@ class Example:
def _checks(a: str, b: str, layer: str,
- *rows: tuple[str, str, tuple[float, float, float, float], list[Point], list[Point]]) -> list[Check]:
+ *rows: tuple[str, str, 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]
+ }) for ident, name, found, empty in rows]
def _example(ident: str, place: str, when: str, size: str, **fields: Any) -> Example:
@@ -65,13 +64,13 @@ EXAMPLES: list[Example] = [
Rule(measure="band", band="B08", on="b", op="ge", value=0.04)],
checks=_checks(
"2023-08-08", "2023-08-13", "SWIR",
- ("town", "The town and hills that burned", (-156.68747, 20.86409, -156.66278, 20.90174),
+ ("town", "The town and hills that burned",
[(-156.67478, 20.87209), (-156.67547, 20.89374)], []),
- ("spared", "Homes and dry grass that did not", (-156.66095, 20.85149, -156.63523, 20.88217),
+ ("spared", "Homes and dry grass that did not",
[], [(-156.64723, 20.87417), (-156.64895, 20.85949)]),
- ("reef", "The reef off the town", (-156.6873, 20.85703, -156.6633, 20.87303),
+ ("reef", "The reef off the town",
[], [(-156.6753, 20.86503)]),
- ("cloud", "A cloud the mask missed", (-156.64644, 20.88862, -156.62244, 20.90462),
+ ("cloud", "A cloud the mask missed",
[], [(-156.63444, 20.89662)]),
)),
# The pine forest cleared for the Grünheide factory in early 2020. Mown
@@ -86,11 +85,11 @@ EXAMPLES: list[Example] = [
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),
+ ("site", "The factory site, cleared",
[(13.79269, 52.39574), (13.79235, 52.39359)], []),
- ("forest", "Pine forest still standing", (13.73383, 52.37376, 13.75783, 52.38976),
+ ("forest", "Pine forest still standing",
[], [(13.74583, 52.38176)]),
- ("meadows", "Meadows mown between the passes", (13.72499, 52.38203, 13.77723, 52.41856),
+ ("meadows", "Meadows mown between the passes",
[], [(13.76523, 52.39003), (13.73699, 52.41056)]),
)),
# The Kakhovka reservoir after the dam broke on 6 June 2023. Water that
@@ -105,11 +104,11 @@ EXAMPLES: list[Example] = [
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),
+ ("bed", "The reservoir bed, exposed",
[(34.46845, 47.55171), (34.46845, 47.52969)], []),
- ("river", "The river channel, still water", (34.41497, 47.55378, 34.45497, 47.57778),
+ ("river", "The river channel, still water",
[], [(34.43497, 47.56578)]),
- ("pond", "The power plant cooling pond", (34.51557, 47.50111, 34.55557, 47.52511),
+ ("pond", "The power plant cooling pond",
[], [(34.53454, 47.51311)]),
)),
# Panel fields laid in the Dubai desert between 2019 and 2023. Dunes the
@@ -124,11 +123,11 @@ EXAMPLES: list[Example] = [
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),
+ ("panels", "New panel fields",
[(55.40435, 24.72138), (55.40401, 24.70438)], []),
- ("old", "Panels already there on A", (55.36832, 24.74976, 55.39832, 24.77376),
+ ("old", "Panels already there on A",
[], [(55.38332, 24.76176)]),
- ("dunes", "Dunes the wind moved", (55.32893, 24.64411, 55.35893, 24.66811),
+ ("dunes", "Dunes the wind moved",
[], [(55.34393, 24.65611)]),
)),
# The anchorage off Fujairah, on one pass. Near infrared alone takes the
@@ -143,11 +142,11 @@ EXAMPLES: list[Example] = [
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),
+ ("ships", "Ships at anchor",
[(56.57259, 25.17166), (56.57311, 25.14571)], []),
- ("town", "Fujairah town, on land", (56.32643, 25.1332, 56.36643, 25.1632),
+ ("town", "Fujairah town, on land",
[], [(56.34643, 25.1482)]),
- ("water", "Open water", (56.51818, 25.13242, 56.55818, 25.16242),
+ ("water", "Open water",
[], [(56.53818, 25.14742)]),
)),
]
diff --git a/src/azimut/engine/analysis_models.py b/src/azimut/engine/analysis_models.py
index 944c218..886a19a 100644
--- a/src/azimut/engine/analysis_models.py
+++ b/src/azimut/engine/analysis_models.py
@@ -35,6 +35,7 @@ Band = Literal["B01", "B02", "B03", "B04", "B05", "B06", "B07", "B08", "B8A", "B
#: 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}$")]
+AreaId = Annotated[str, Field(pattern=r"^[0-9a-f]{12}$")]
Colour = Annotated[str, Field(pattern=r"^#[0-9a-fA-F]{6}$")]
# Methods that read one image instead of a pair. A vessel or a fire is a thing
@@ -114,6 +115,7 @@ RETIRED_OVERLAYS = frozenset({"labels"})
class DetectPrefs(Model):
collapsed: bool = False
+ width: int = Field(default=380, ge=300, le=720)
basemap: str = Field(default="esri-world-imagery", max_length=120, pattern=r"^[a-zA-Z0-9_-]+$")
overlays: list[Literal["boundaries", "placenames", "roads", "railway", "power", "seamarks", "gpstraces"]] = (
Field(default=["boundaries", "placenames"], max_length=7))
@@ -354,6 +356,15 @@ class Source(Model):
return data
+def ordered_pair(a: Source, b: Source) -> bool:
+ """Whether a dated comparison reads A strictly before B."""
+ if not a.date or not b.date:
+ return True
+ if a.date != b.date:
+ return a.date < b.date
+ return bool(a.provider == b.provider == "sentinel1" and a.time and b.time and a.time < b.time)
+
+
#: How many checks one analyzer keeps, and how many marks one check holds.
MAX_CHECKS = 12
MAX_MARKS = 20
@@ -361,13 +372,6 @@ 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."""
@@ -391,16 +395,16 @@ class CheckResult(Model):
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.
+ It is a pair of passes and the marks laid on them: where a candidate must
+ come out and where none may. It keeps the exact passes it was saved on, so
+ a rerun reads the same images, and it reads the ground under its marks and
+ nothing else, so there is no frame to set.
"""
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
@@ -408,8 +412,6 @@ class Check(Model):
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
@@ -429,6 +431,12 @@ class Recipe(Model):
#: to pass all of them or any one.
rules: list[Rule] = Field(default_factory=list, max_length=MAX_RULES)
match: Literal["all", "any"] = "all"
+ #: What an analyzer of your own reads, chosen when it is made: which
+ #: satellite, and whether it judges one date or the change between two. The
+ #: rules have to agree. One saved before it was declared gets it worked out
+ #: from its rules, once, and keeps it from then on.
+ sensor: Literal["sentinel2", "sentinel1"] | None = None
+ dates: Literal["one", "two"] | None = None
#: Places the analyst trusts, rerun after each change (`Check`).
checks: list[Check] = Field(default_factory=list, max_length=MAX_CHECKS)
@@ -447,8 +455,8 @@ class Recipe(Model):
@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")
+ if self.rules or self.checks or self.sensor or self.dates:
+ raise ValueError("only an analyzer of your own rules carries rules, checks and what it reads")
return self
if not self.rules:
raise ValueError("add at least one rule")
@@ -457,18 +465,62 @@ class Recipe(Model):
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")
+ single = all(rule.on == "b" for rule in self.rules)
+ if self.sensor is None:
+ self.sensor = "sentinel1" if True in radar else "sentinel2"
+ if self.dates is None:
+ self.dates = "one" if single else "two"
+ if (self.sensor == "sentinel1") != (True in radar):
+ raise ValueError("a radar analyzer reads radar rules and a Sentinel-2 one optical rules; "
+ "start another analyzer for the other satellite")
+ if (self.dates == "one") != single:
+ raise ValueError("an analyzer of one date reads the pass itself, and one of two dates needs a rule "
+ "on the change or on the before date")
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
+ @model_serializer(mode="wrap")
+ def compact(self, handler: SerializerFunctionWrapHandler) -> dict[str, Any]:
+ # A calibrated method says what it reads in `METHODS`; only the rules
+ # declare it, so everything else is written as it always was.
+ data: dict[str, Any] = handler(self)
+ for key in ("sensor", "dates"):
+ if data.get(key) is None:
+ data.pop(key, None)
+ return data
+
class ZoneSet(Model):
+ """Shape snapshots written by Detect before area groups existed."""
title: str = Field(min_length=1, max_length=120)
zones: list[Zone] = Field(min_length=1, max_length=32)
+class AreaGroupReview(Model):
+ saved_area_id: AreaId
+ current_area_id: AreaId
+ name: str = Field(min_length=1, max_length=120)
+
+
+class AreaGroup(Model):
+ title: str = Field(min_length=1, max_length=120)
+ area_ids: list[AreaId] = Field(default_factory=list, max_length=1000)
+ position: int | None = Field(default=None, ge=0, le=100_000)
+ pending_review: list[AreaGroupReview] = Field(default_factory=list, max_length=32)
+
+ @model_validator(mode="after")
+ def unique_areas(self) -> AreaGroup:
+ if len(self.area_ids) != len(set(self.area_ids)):
+ raise ValueError("an area can appear only once in a group")
+ reviewed = [item.saved_area_id for item in self.pending_review]
+ if len(reviewed) != len(set(reviewed)) or any(area_id not in self.area_ids for area_id in reviewed):
+ raise ValueError("reviewed shapes must belong to this group")
+ return self
+
+
class AreaGeometry(Model):
type: Literal["Polygon"] = "Polygon"
coordinates: list[list[tuple[FiniteFloat, FiniteFloat]]] = Field(min_length=1, max_length=1)
@@ -486,6 +538,7 @@ class Area(Model):
name: str = Field(min_length=1, max_length=120)
colour: Colour = "#38bdf8"
geometry: AreaGeometry
+ position: int | None = Field(default=None, ge=0, le=100_000)
class AreaDates(Model):
@@ -527,6 +580,8 @@ class RunInput(Model):
pair.date_rule == "latest_previous" and self.followup_id
):
raise ValueError("choose a reference date for each area")
+ if not is_single(self.recipe) and not ordered_pair(pair.a, pair.b):
+ raise ValueError("date A must be before date B for each comparison")
return self
if not self.zones:
raise ValueError("choose at least one area")
@@ -539,6 +594,8 @@ class RunInput(Model):
required.append(self.a)
if any(not source.date for source in required):
raise ValueError("choose a dated Copernicus acquisition")
+ if not is_single(self.recipe) and self.date_rule == "manual" and not ordered_pair(self.a, self.b):
+ raise ValueError("date A must be before date B for each comparison")
return self
@@ -559,18 +616,18 @@ 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.sensor == "sentinel1"
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.
+ An analyzer of one date needs 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.dates == "one"
return recipe.method in SINGLE_METHODS
@@ -757,10 +814,10 @@ def frames_per_tile(method: str) -> int:
#: 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.
+# `rules` is the one method whose answers depend on the recipe: which dates and
+# which satellite are what the analyzer declares (`Recipe.dates`, `Recipe.sensor`),
+# and the panel works the frames out from them (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 or method == "rules", "sensor": sensor_for(method),
diff --git a/src/azimut/engine/analysis_views.py b/src/azimut/engine/analysis_views.py
index 0d5991f..17e0ded 100644
--- a/src/azimut/engine/analysis_views.py
+++ b/src/azimut/engine/analysis_views.py
@@ -62,7 +62,7 @@ def _query_terms(spec: dict[str, Any]) -> dict[str, str]:
return {}
allowed = {
"type", "status", "q", "folder", "unfiled", "recursive", "attr",
- "value", "linked", "unlinked", "since", "until", "by",
+ "value", "linked", "unlinked", "lacks", "since", "until", "by",
}
return {
key: _short(value, 1000)
@@ -134,6 +134,13 @@ def _clean_track(value: Any, index: int) -> dict[str, Any]:
"label": _short(query.get("label"), 300),
"relation": relation,
"roles": roles,
+ # Written only when set, so a track saved before the switch reads back
+ # exactly as it was stored.
+ **({"collected_only": True} if query.get("collected_only") is True else {}),
+ # A lane that draws each event as the file it dates: the sources' files
+ # (the Media track) or the imagery the app made (the Imagery track).
+ **({"as_files": query["as_files"]}
+ if query.get("as_files") in {"sources", "imagery"} else {}),
},
"collapsed": bool(value.get("collapsed")),
"hidden": _string_list(value.get("hidden"), limit=500),
@@ -145,11 +152,12 @@ _ZONE_NAME = re.compile(r"[A-Za-z0-9+\-_/]{1,64}")
def _valid_zone_choice(choice: str) -> bool:
- """Which clock the axis was read on: UTC, this machine, a saved point, or a zone
- named outright. The last one has to travel — a view made on `zone:Asia/Tokyo` must
- not come back on UTC — so the name is kept whether or not the machine reopening it
- can load the name; the axis asks that when it draws."""
- if choice in {"utc", "machine"}:
+ """Which clock the axis was read on: the zone of the case's places, UTC, this
+ machine, a saved point, or a zone named outright. The last one has to travel — a
+ view made on `zone:Asia/Tokyo` must not come back on UTC — so the name is kept
+ whether or not the machine reopening it can load the name; the axis asks that when
+ it draws. `case` is found again from the places wherever the view is opened."""
+ if choice in {"utc", "case", "machine"}:
return True
if choice.startswith("place:"):
rest = choice.removeprefix("place:")
@@ -299,6 +307,7 @@ def _capture(case: Case, spec: dict[str, Any]) -> dict[str, Any]:
attr_value=terms.get("value"),
linked=terms.get("linked"),
unlinked=terms.get("unlinked") == "true",
+ lacks=[part for part in terms.get("lacks", "").split(",") if part] or None,
since=terms.get("since"),
until=terms.get("until"),
filed_by=filed_by or None,
@@ -476,11 +485,13 @@ def _clean_snapshot(value: Any) -> dict[str, Any]:
"uncertain": bool(item.get("uncertain")),
"approximate": bool(item.get("approximate")),
"zone": _short(item.get("zone"), 24) or None,
+ "tz": _short(item.get("tz"), 64) or None,
"sortable": bool(item.get("sortable")),
"status": _short(item.get("status"), 24) or None,
"confidence": _short(item.get("confidence"), 24) or None,
"parse_error": _short(item.get("parse_error"), 500) or None,
"owner_type": _short(item.get("owner_type"), 40),
+ "produced_here": bool(item.get("produced_here")),
"subjects": _string_list(item.get("subjects"), item_limit=64),
"places": _string_list(item.get("places"), item_limit=64),
"sources": _string_list(item.get("sources"), item_limit=64),
@@ -595,11 +606,37 @@ def prepare(
return spec
-def snapshot_page(view: dict[str, Any], *, limit: int, cursor: str | None, order: str) -> dict[str, Any]:
- """A bounded Board page over immutable captured rows."""
+def snapshot_page(
+ view: dict[str, Any],
+ *,
+ limit: int,
+ cursor: str | None,
+ order: str,
+ types: list[str] | None = None,
+ count_by_type: bool = False,
+) -> dict[str, Any]:
+ """A bounded Board page over immutable captured rows.
+
+ ``types`` narrows the frozen rows the way it narrows a live page, which is what a
+ Board group asks for, and ``count_by_type`` counts every captured row per type.
+ ``events`` orders by the Claims the snapshot itself captured naming a row: a frozen
+ reading is not re-read against the live case.
+ """
snapshot = view.get("spec", {}).get("snapshot") or {}
- rows = list(snapshot.get("entities") or [])
- if order in {"label", "-label"}:
+ captured = list(snapshot.get("entities") or [])
+ rows = [row for row in captured if not types or row.get("type") in types]
+ if order in {"events", "-events"}:
+ claims = {row.get("id") for row in captured if row.get("type") == "claim"}
+ named: dict[str, set[str]] = {}
+ for link in snapshot.get("links") or []:
+ if link.get("type") in {"about", "at", "cites"} and link.get("from") in claims:
+ named.setdefault(str(link.get("to")), set()).add(str(link.get("from")))
+ # Stable, so rows naming the same count keep the order they were captured in.
+ rows.sort(
+ key=lambda row: len(named.get(str(row.get("id")), ())),
+ reverse=order.startswith("-"),
+ )
+ elif order in {"label", "-label"}:
rows.sort(key=lambda row: str(row.get("label") or "").casefold(), reverse=order.startswith("-"))
elif order in {"created", "-created"}:
rows.sort(
@@ -616,4 +653,11 @@ def snapshot_page(view: dict[str, Any], *, limit: int, cursor: str | None, order
raise CaseError(f"invalid snapshot cursor '{cursor}'")
page = rows[start : start + limit]
next_cursor = str(start + limit) if start + limit < len(rows) else None
- return {"items": page, "next_cursor": next_cursor, "total": len(rows)}
+ result: dict[str, Any] = {"items": page, "next_cursor": next_cursor, "total": len(rows)}
+ if count_by_type:
+ by_type: dict[str, int] = {}
+ for row in rows:
+ kind = str(row.get("type") or "")
+ by_type[kind] = by_type.get(kind, 0) + 1
+ result["by_type"] = by_type
+ return result
diff --git a/src/azimut/engine/analyzers.py b/src/azimut/engine/analyzers.py
index 4243a59..524e29b 100644
--- a/src/azimut/engine/analyzers.py
+++ b/src/azimut/engine/analyzers.py
@@ -40,6 +40,8 @@ from .analysis_models import (
SMOOTHING_M,
Area,
AreaDates,
+ AreaGroup,
+ AreaGroupReview,
AreaGeometry,
Model,
Parameters,
@@ -47,8 +49,10 @@ from .analysis_models import (
RunInput,
Source,
Zone,
+ ZoneSet,
is_radar,
is_single,
+ ordered_pair,
recipe_products,
recipe_sensor,
stored,
@@ -260,6 +264,14 @@ def read(case: Case, kind: str, ident: str) -> dict[str, Any]:
if path.stat().st_size > 16_000_000:
raise ValueError("analysis record is too large")
saved = json.loads(path.read_text(encoding="utf-8"))
+ if kind == "zones" and "area_ids" not in saved:
+ with LOCK, case._lock:
+ # A set stored copies of shapes. Promote those copies before
+ # replacing the set, so an old drawing or changed outline survives.
+ saved = json.loads(path.read_text(encoding="utf-8"))
+ if "area_ids" not in saved:
+ saved = migrate_area_group(case, saved)
+ media.write_json_atomic(path, saved)
if kind == "followups":
with LOCK, case._lock:
if not saved.get("area_dates"):
@@ -283,6 +295,42 @@ def read(case: Case, kind: str, ident: str) -> dict[str, Any]:
return saved
+def migrate_area_group(case: Case, saved: dict[str, Any]) -> dict[str, Any]:
+ legacy = stored(ZoneSet, saved)
+ area_ids: list[str] = []
+ reviews: dict[str, AreaGroupReview] = {}
+ for zone in legacy.zones:
+ ring = zone.ring()
+ geometry = AreaGeometry(coordinates=[ring + [ring[0]]]).model_dump(mode="json")
+ changed_id = None
+ if len(zone.id) == 12 and all(c in "0123456789abcdef" for c in zone.id):
+ try:
+ existing = read(case, "areas", zone.id)
+ if existing["geometry"] == geometry:
+ area_ids.append(zone.id)
+ continue
+ changed_id = zone.id
+ except FileNotFoundError:
+ pass
+ fingerprint = json.dumps(zone.model_dump(), sort_keys=True)
+ derived = hashlib.sha256(fingerprint.encode()).hexdigest()[:12]
+ path = case.resolve_inside(relpath("areas", derived))
+ if path.exists() and read(case, "areas", derived)["geometry"] != geometry:
+ raise ValueError("saved area id collision")
+ if not path.exists():
+ save(case, "areas", Area(name=zone.name, geometry=AreaGeometry.model_validate(geometry)).model_dump(),
+ new_id=derived)
+ area_ids.append(derived)
+ if changed_id:
+ reviews[derived] = AreaGroupReview(saved_area_id=derived, current_area_id=changed_id,
+ name=zone.name)
+ converted = AreaGroup(title=legacy.title, area_ids=list(dict.fromkeys(area_ids)),
+ pending_review=list(reviews.values())).model_dump()
+ return converted | {
+ key: saved[key] for key in ("id", "created_at", "updated_at", "version") if key in saved
+ }
+
+
#: The parts of a saved detection that editing it sends back as they were read.
PARTS: dict[str, type[Model]] = {"recipe": Recipe, "a": Source, "b": Source}
LISTS: dict[str, type[Model]] = {"zones": Zone, "area_dates": AreaDates}
@@ -394,11 +442,16 @@ def summary(kind: str, saved: dict[str, Any]) -> dict[str, Any]:
("id", "title", "created_at", "updated_at", "status", "progress",
"total", "count", "message", "completed_at") if key in saved}
body = saved.get("input", saved)
- row["areas"] = len(body.get("zones") or [])
+ row["areas"] = len(body.get("area_ids") or []) if kind == "zones" else len(body.get("zones") or [])
if kind == "zones":
+ row["area_ids"] = body["area_ids"]
+ row["position"] = body.get("position")
+ row["pending_review"] = body.get("pending_review", [])
return row
recipe = body.get("recipe") or {}
- row.update(analyzer=recipe.get("name", ""), colour=recipe.get("colour", ""),
+ row.update(analyzer=recipe.get("name", ""),
+ colour=saved.get("display_colour", recipe.get("colour", "")) if kind == "runs"
+ else 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.
@@ -430,6 +483,20 @@ def listing(case: Case, kind: str) -> list[dict[str, Any]]:
rows.append(summary(kind, read(case, kind, path.stem.split("-", 1)[1])))
except (OSError, ValueError, KeyError):
continue
+ if kind in {"zones", "areas"}:
+ ordered = sorted(rows, key=lambda row: (row.get("position") is None,
+ row.get("position") or 0,
+ -datetime.fromisoformat(row["created_at"]).timestamp()))
+ if kind == "zones" and any(row.get("position") is None for row in ordered):
+ with LOCK, case._lock:
+ for position, row in enumerate(ordered):
+ if row.get("position") == position:
+ continue
+ path = case.resolve_inside(relpath("zones", row["id"]))
+ saved = read(case, "zones", row["id"])
+ media.write_json_atomic(path, {**saved, "position": position})
+ row["position"] = position
+ return ordered
return sorted(rows, key=lambda row: row["created_at"], reverse=True)
@@ -1531,13 +1598,12 @@ def prune_frames(case: Case, run: dict[str, Any]) -> None:
del run["frames"][key]
-def previous_pass(case: Case, body: RunInput) -> Source:
- """The pass this routine's last finished run swept, which the next one
- compares against. Falls back to the reference the routine was saved with."""
+def last_successful_pass(case: Case, body: RunInput) -> Source | None:
+ """Newest pass this routine finished for this area and radar track."""
if not body.followup_id:
- return body.a
- best: tuple[tuple[str, str], Source] | None = None
- for summary, previous in ready_runs(case, body.followup_id):
+ return None
+ best: Source | None = None
+ for _, previous in ready_runs(case, body.followup_id):
area_id = body.zones[0].id
try:
if previous.get("area_runs"):
@@ -1554,21 +1620,24 @@ def previous_pass(case: Case, body: RunInput) -> Source:
candidate = stored(Source, previous["input"]["b"])
except (KeyError, ValueError):
continue
- if candidate.layer != body.b.layer or not candidate.date:
- continue
- if body.b.date and candidate.date >= body.b.date:
+ if candidate.provider != body.b.provider or candidate.layer != body.b.layer or not candidate.date:
continue
# Radar compares like with like: a pass from another track sees the
# same ground at another angle, and that difference is not change.
if candidate.provider == "sentinel1" and body.b.time and not sentinel.same_track(
candidate.time, body.b.time):
continue
- # Runs of one routine can share a timestamp, which is only seconds deep,
- # so the pass they swept settles the order between them.
- key = (str(summary.get("created_at", "")), candidate.date)
- if best is None or key > best[0]:
- best = (key, candidate)
- return best[1] if best else body.a
+ if best is None or (candidate.date, candidate.time) > (best.date, best.time):
+ best = candidate
+ return best
+
+
+def previous_pass(case: Case, body: RunInput) -> Source:
+ """The last successful pass before B, or the first-run reference."""
+ last = last_successful_pass(case, body)
+ if last and (not body.b.date or (last.date, last.time) < (body.b.date, body.b.time)):
+ return last
+ return body.a
def _lookup(body: RunInput, start: str, end: str) -> list[dict[str, Any]]:
@@ -1656,7 +1725,8 @@ def _timed(body: RunInput) -> RunInput:
return body.model_copy(update={"a": a, "b": b})
-def resolve_dates(case: Case, body: RunInput, *, selected: bool = False) -> RunInput:
+def resolve_dates(case: Case, body: RunInput, *, selected: bool = False,
+ notes: list[str] | None = None) -> RunInput:
body = _sensed_by(body)
single = is_single(body.recipe)
radar = is_radar(body.recipe)
@@ -1691,6 +1761,12 @@ def resolve_dates(case: Case, body: RunInput, *, selected: bool = False) -> RunI
whole = [entry for entry in allowed if entry["coverage"] >= FULL_COVER]
if not whole:
best = max((entry["coverage"] for entry in allowed), default=0)
+ cloudy = next((entry for entry in found if not radar and entry["coverage"] >= FULL_COVER
+ and entry.get("cloud") is not None and entry["cloud"] > source.maxcc), None)
+ if cloudy:
+ raise ValueError(f"latest pass {cloudy['date']} has {round(cloudy['cloud'])}% cloud, "
+ f"above the {source.maxcc}% limit; no eligible pass in the last "
+ f"{LOOKBACK_DAYS} days")
raise ValueError(
(f"no recent Sentinel-1 pass{' on this track' if track else ''} covers the whole area"
if radar else "no recent pass covers the whole area under the cloud limit")
@@ -1700,6 +1776,13 @@ def resolve_dates(case: Case, body: RunInput, *, selected: bool = False) -> RunI
source.date = whole[0]["date"] # newest first
if radar:
source.time = whole[0]["time"]
+ elif notes is not None:
+ cloudy = next((entry for entry in found if entry["date"] > source.date
+ and entry["coverage"] >= FULL_COVER and entry.get("cloud") is not None
+ and entry["cloud"] > source.maxcc), None)
+ if cloudy:
+ notes.append(f"Skipped {cloudy['date']} ({round(cloudy['cloud'])}% cloud, "
+ f"limit {source.maxcc}%); using {source.date}.")
reference = (source if single else
body.a if body.date_rule != "latest_previous" else
previous_pass(case, body.model_copy(update={"b": source})))
@@ -1724,8 +1807,17 @@ def prepare_areas(case: Case, body: RunInput) -> tuple[RunInput, list[dict[str,
local = for_area(body, zone)
outcome: dict[str, Any] = {"area_id": zone.id, "name": zone.name}
try:
- local = resolve_dates(case, local, selected=bool(body.area_dates))
- outcome.update(status="pending", a=local.a.model_dump(), b=local.b.model_dump(), message="")
+ notes: list[str] = []
+ local = resolve_dates(case, local, selected=bool(body.area_dates), notes=notes)
+ if not is_single(local.recipe) and not ordered_pair(local.a, local.b):
+ raise ValueError("date A must be before date B for each comparison")
+ last = last_successful_pass(case, local) if body.followup_id and not body.run_anyway else None
+ current = (local.b.date, local.b.time)
+ already_seen = last is not None and current <= (last.date, last.time)
+ status = "no_new_imagery" if already_seen else "pending"
+ message = f"{zone.name}: No new pass since {last.date}" if already_seen and last else ""
+ message = " ".join(part for part in [*notes, message] if part)
+ outcome.update(status=status, a=local.a.model_dump(), b=local.b.model_dump(), message=message)
pairs.append(AreaDates(area_id=zone.id, a=local.a, b=local.b, date_rule="manual"))
except Exception as exc:
message = str(exc) if isinstance(exc, ValueError) else "Imagery could not be read"
@@ -1795,7 +1887,7 @@ def execute(case: Case, job: dict[str, Any]) -> None:
resolved = []
for outcome in outcomes:
check_active(case, ident)
- if outcome["status"] == "failed":
+ if outcome["status"] != "pending":
continue
zone = next(zone for zone in original.zones if zone.id == outcome["area_id"])
body = for_area(original, zone).model_copy(update={
diff --git a/src/azimut/engine/artifacts.py b/src/azimut/engine/artifacts.py
index 2ec2d30..c2f74af 100644
--- a/src/azimut/engine/artifacts.py
+++ b/src/azimut/engine/artifacts.py
@@ -131,8 +131,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"),
+ # already rest on it, so it outlives the layout. The preview travels because
+ # only the open collage can draw it again.
+ "collage": Kind(path_attr="spec", companions=(Named(layout.collage_thumb_rel),)),
# 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/bundles.py b/src/azimut/engine/bundles.py
index ae331ba..456e685 100644
--- a/src/azimut/engine/bundles.py
+++ b/src/azimut/engine/bundles.py
@@ -464,6 +464,12 @@ def _clean_database(source: Path, target: Path) -> None:
# Downloads folder a bundle came from), which is the account's own name.
# An import rebuilds what it needs, thumbnails first.
conn.execute("DELETE FROM jobs")
+ # A merge's undo record is local state like the Trash, and names what the
+ # Trash would restore: after an import a merge is final. The redirects travel,
+ # so the ids it absorbed keep answering in the imported case.
+ conn.execute("DELETE FROM entity_merges")
+ conn.execute("DELETE FROM entity_redirects WHERE new_id NOT IN (SELECT id FROM entities)")
+ conn.execute("UPDATE entity_redirects SET merge_id = NULL")
conn.commit()
conn.execute("VACUUM")
finally:
@@ -622,6 +628,8 @@ def export_case(
output: Path | None = None,
) -> Path:
"""Write one complete bundle atomically and return its path."""
+ if case.pending_merge_work():
+ raise BundleError("a merge still needs to update a sheet; reopen the case once the sheet is writable")
config.bundles_dir().mkdir(parents=True, exist_ok=True)
output = Path(output) if output is not None else bundle_path(case, sealed=bool(password))
if output.parent.resolve() != config.bundles_dir().resolve():
diff --git a/src/azimut/engine/detect_rules.py b/src/azimut/engine/detect_rules.py
index 194acc6..ebe3f0a 100644
--- a/src/azimut/engine/detect_rules.py
+++ b/src/azimut/engine/detect_rules.py
@@ -1,4 +1,4 @@
-"""Analyzers made of the analyst's own rules, and the preview that tunes them.
+"""Analyzers made of the analyst's own rules, and the checks that tune 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
@@ -6,13 +6,14 @@ 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.
+A check is a pair of passes and the pins laid on them, and testing it runs
+`evaluate` on the tiles under the pins and the ones beside them. That is the
+frames a sweep of the same ground would read, so what the test shows there is
+what a run returns: the same rules, cleanup, sizes, shape and grouping. It
+hands back what each rule kept, the candidates, whether one came out on each
+pin and what every rule read there. Testing reads the tile cache, and
+fetching the frames it lacks is a separate act, which the analyst asks for and
+which is metered like any other.
"""
from __future__ import annotations
@@ -22,6 +23,7 @@ import io
import math
import threading
from collections import OrderedDict
+from collections.abc import Sequence
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass
from typing import Any
@@ -51,18 +53,22 @@ UNITS = {"index": 0.1, "nd": 0.1, "band": 0.02, "brightness": 0.02, "colour": 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.
+#: How many grid tiles one check may read, the ones beside a pin near an edge
+#: included. Past that the frames to fetch stop being a figure an analyst can
+#: weigh before pressing Test.
+MAX_CHECK_TILES = 12
+#: How near to its tile's edge a pin may come, in pixels, before the tile across
+#: the edge is read as well. The examples keep their marks at least 64 pixels
+#: inside, so each of them reads one tile.
+EDGE_PX = 48
+TEST_CANDIDATES = 300
+#: Bits of a tile's 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 frames a test has read lately, so testing again after a change to a
+# rule re-reads nothing from disk. A frame is 2.6 MB decoded; this holds a check
+# of a few tiles on two dates with room to spare.
_DECODED: OrderedDict[tuple[str, int, int], Any] = OrderedDict()
_DECODED_MAX = 40
_DECODED_LOCK = threading.Lock()
@@ -247,20 +253,35 @@ def _past(rule: Rule, value: Any) -> Any:
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)
+@dataclass
+class Measured:
+ """One tile with every rule of the recipe read on it, before they are put together.
+ Kept apart from the verdict so that a question about the rules (what do the
+ pins make of them without this one?) is answered from the same reading
+ instead of measuring the tile again.
+ """
-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.
+ recipe: Recipe
+ shape: tuple[int, int]
+ core: tuple[slice, slice]
+ measured: Any
+ imaged: Any
+ passes: list[Any]
+ values: list[Any]
+ before: list[Any]
+ after: list[Any]
+ distances: list[Any]
+
+
+def measure(products: dict[str, tuple[Any, Any]], mask: Any, recipe: Recipe,
+ days: tuple[str, str], lat: float) -> Measured:
+ """Read every rule of the recipe on one tile.
`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
@@ -303,27 +324,44 @@ def evaluate(products: dict[str, tuple[Any, Any]], mask: Any, recipe: Recipe,
befores.append(before)
afters.append(after)
distances.append(distance)
+ return Measured(recipe=recipe, shape=shape, core=core, measured=measured, imaged=imaged, passes=passes,
+ values=values, before=befores, after=afters, distances=distances)
+
+def judge(tile: Measured, keep: Sequence[int] | None = None) -> analyzers.Reading:
+ """What the rules make of a measured tile: the pixels kept, cleaned, and how far past the line.
+
+ `keep` names the rules to put together, in place of all of them, to ask what
+ the tile would have given without one.
+ """
+ import cv2
+ import numpy as np
+
+ recipe = tile.recipe
+ options = recipe.parameters
+ used = list(range(len(recipe.rules))) if keep is None else list(keep)
+ passes = [tile.passes[i] for i in used]
if recipe.match == "all":
combined = np.logical_and.reduce(passes)
else:
combined = np.logical_or.reduce(passes)
- binary = measured & combined
+ binary = tile.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
+ binary = cleaned.astype(bool) & tile.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)
+ # under "any" the best of whichever rules it passed. 1 is on the line. The
+ # signal is the first rule that measures something.
+ ranked = next((i for i in used if recipe.rules[i].measure != "class"), None)
if recipe.match == "all":
- past = distances[ranked] if ranked is not None else np.zeros(shape)
+ past = tile.distances[ranked] if ranked is not None else np.zeros(tile.shape)
else:
- past = np.fmax.reduce(np.stack(distances), axis=0)
+ past = np.fmax.reduce(np.stack([tile.distances[i] for i in used]), 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]] = {}
@@ -331,17 +369,30 @@ def evaluate(products: dict[str, tuple[Any, Any]], mask: Any, recipe: Recipe,
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")}
+ measures = {"before": (clean(tile.before[ranked]), "mean"), "after": (clean(tile.after[ranked]), "mean"),
+ "signed": (clean(tile.values[ranked]), "mean")}
else:
- measures = {"value": (clean(values[ranked]), "mean")}
+ measures = {"value": (clean(tile.values[ranked]), "mean")}
+ core = tile.core
+ return 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()})
+
+
+def evaluation(tile: Measured, reading: analyzers.Reading) -> Evaluation:
+ """A measured tile with its verdict, cropped back to the tile."""
+ core = tile.core
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])
+ return Evaluation(reading=reading, passes=[crop(p) for p in tile.passes], values=[crop(v) for v in tile.values],
+ before=[crop(b) for b in tile.before], after=[crop(a) for a in tile.after],
+ measured=tile.measured[core], imaged=tile.imaged[core])
+
+
+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."""
+ tile = measure(products, mask, recipe, days, lat)
+ return evaluation(tile, judge(tile))
class _Classes(dict[tuple[str, ...], tuple[int, ...]]):
@@ -356,11 +407,11 @@ class _Classes(dict[tuple[str, ...], tuple[int, ...]]):
SCENE_CLASSES_FLAT = _Classes()
-# -- the preview ---------------------------------------------------------------------
+# -- the frames a check reads ----------------------------------------------------------
-def preview_sources(recipe: Recipe, a: Source, b: Source) -> tuple[Source, Source]:
- """The sources a preview reads, named for the satellite the rules use.
+def check_sources(recipe: Recipe, a: Source, b: Source) -> tuple[Source, Source]:
+ """The sources a check 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.
@@ -371,38 +422,25 @@ def preview_sources(recipe: Recipe, a: Source, b: Source) -> tuple[Source, Sourc
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")
+ raise ValueError("choose the pass this check is read 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")
+ raise ValueError("these rules read the before date as well; choose its 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")
+ raise ValueError("the before and after passes 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")
+def tile_box(x: int, y: int) -> dict[str, float]:
+ """A grid tile's extent in metres of the Mercator plane, where the map lays its image."""
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
+ world = analyzers.WORLD
+ return {"west": x / count * world - world / 2, "east": (x + 1) / count * world - world / 2,
+ "north": world / 2 - y / count * world, "south": world / 2 - (y + 1) / count * world}
def held(source: Source, x: int, y: int, product: str) -> Any | None:
@@ -442,9 +480,9 @@ def missing(recipe: Recipe, a: Source, b: Source,
def fetch(frames: list[tuple[Source, int, int, str]]) -> None:
- """Read the frames a preview lacks from Copernicus into the tile cache.
+ """Read the frames a test lacks from Copernicus into the tile cache.
- Only ever called because the analyst pressed Read. Each frame is one
+ Only ever called because the analyst pressed Test. Each frame is one
request on the Sentinel Hub meter, counted whether it succeeds or not.
"""
if not frames:
@@ -469,7 +507,7 @@ def fetch(frames: list[tuple[Source, int, int, str]]) -> None:
list(pool.map(one, frames))
-def _tile(recipe: Recipe, a: Source, b: Source, x: int, y: int) -> Evaluation:
+def _measure_tile(recipe: Recipe, a: Source, b: Source, x: int, y: int) -> Measured:
import numpy as np
z, size = analyzers.GRID
@@ -478,10 +516,15 @@ def _tile(recipe: Recipe, a: Source, b: Source, x: int, y: int) -> Evaluation:
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")
+ raise ValueError("test the check to read its 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)
+ return measure(read, np.ones((size, size), np.uint8), recipe, (a.date, b.date), lat)
+
+
+def _tile(recipe: Recipe, a: Source, b: Source, x: int, y: int) -> Evaluation:
+ tile = _measure_tile(recipe, a, b, x, y)
+ return evaluation(tile, judge(tile))
def _png(mask: Any) -> str:
@@ -490,91 +533,75 @@ def _png(mask: Any) -> str:
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.
+# -- checks ---------------------------------------------------------------------------------
- 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
+#: How close a candidate has to come to a mark to be on it: a pixel and a half.
+MARK_REACH_M = 15.0
- a, b = preview_sources(recipe, a, b)
- tiles, clipped = preview_tiles(bounds)
+
+def pixel_of(point: tuple[float, float]) -> tuple[int, int, int, int]:
+ """The grid tile under a point, and the pixel of that tile the point falls on."""
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]]}
+ gx, gy = (value * count for value in analyzers.mercator(*point))
+ x, y = min(count - 1, int(gx)), min(count - 1, int(gy))
+ return x, y, min(size - 1, int((gx - x) * size)), min(size - 1, int((gy - y) * size))
-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
+def check_tiles(check: Check) -> list[tuple[int, int]]:
+ """The grid tiles a check reads: the ones under its marks, then the ones beside them.
- a, b = preview_sources(recipe, a, b)
+ A mark is read on its own tile, so a candidate cut by the tile's edge is
+ judged on the part inside it, and two halves that are each too small to
+ keep would both be lost. A mark within EDGE_PX of an edge therefore reads
+ the tile across it as well, and the seam is joined the way a sweep joins it.
+ """
+ if not check.marks:
+ raise ValueError("drop a pin on the ground this check should read")
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))
+ edge = EDGE_PX / size
+ under: list[tuple[int, int]] = []
+ beside: list[tuple[int, int]] = []
+ for mark in check.marks:
+ gx, gy = (value * count for value in analyzers.mercator(*mark.point))
+ x, y = min(count - 1, int(gx)), min(count - 1, int(gy))
+ if (x, y) not in under:
+ under.append((x, y))
+ dx = -1 if gx - x < edge else 1 if gx - x > 1 - edge else 0
+ dy = -1 if gy - y < edge else 1 if gy - y > 1 - edge else 0
+ for step in ((dx, 0), (0, dy), (dx, dy)):
+ tile = (x + step[0], y + step[1])
+ if step != (0, 0) and 0 <= tile[0] < count and 0 <= tile[1] < count and tile not in beside:
+ beside.append(tile)
+ tiles = under + [tile for tile in beside if tile not in under]
+ if len(tiles) > MAX_CHECK_TILES:
+ raise ValueError(f"these pins reach {len(tiles)} tiles and a check reads at most {MAX_CHECK_TILES}: "
+ "keep the pins of one place in a check and start another for ground further away")
+ return tiles
+
+
+def _satellite(recipe: Recipe, check: Check) -> None:
+ 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")
+
+
+def plan(recipe: Recipe, check: Check) -> dict[str, int]:
+ """What testing a check would read: its tiles, and how many frames the cache lacks.
+
+ Each missing frame is one request on the Sentinel Hub meter, so this is
+ what the Test button says before it is pressed. Nothing is fetched.
+ """
+ _satellite(recipe, check)
+ a, b = check_sources(recipe, check.a, check.b)
+ tiles = check_tiles(check)
+ return {"tiles": len(tiles), "missing": len(missing(recipe, a, b, tiles))}
+
+
+def _reading(recipe: Recipe, evaluation: Evaluation, px: int, py: int) -> dict[str, Any]:
+ """What every rule read at one pixel of a tile, and whether it passed."""
+ import numpy as np
def number(array: Any) -> float | None:
if array is None:
@@ -582,51 +609,100 @@ def probe(recipe: Recipe, a: Source, b: Source, point: tuple[float, float]) -> d
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]),
+ return {"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 probe(recipe: Recipe, check: Check, point: tuple[float, float]) -> dict[str, Any]:
+ """What every rule read at one point of the ground a check was tested on."""
+ a, b = check_sources(recipe, check.a, check.b)
+ x, y, px, py = pixel_of(point)
+ if missing(recipe, a, b, [(x, y)]):
+ return {"ready": False}
+ return {"ready": True, **_reading(recipe, _tile(recipe, a, b, x, y), px, py)}
-def check_tiles(check: Check) -> list[tuple[int, int]]:
- """The grid tiles a check reads: the ones under its marks, else its view's.
+def _detail(recipe: Recipe, check: Check, tiles: list[tuple[int, int]],
+ evaluations: dict[tuple[int, int], Evaluation], candidates: list[dict[str, Any]]) -> dict[str, Any]:
+ """What the map draws of a test: each tile's mask, the candidates, and every pin's reading."""
+ import numpy as np
- 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]] = []
+ _, size = analyzers.GRID
+ measured_total = kept_total = 0
+ own = [0] * len(recipe.rules)
+ running = [0] * len(recipe.rules)
+ grid: list[dict[str, Any]] = []
+ for x, y in tiles:
+ evaluation = evaluations[(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())
+ grid.append({"x": x, "y": y, "box": tile_box(x, y), "mask": _png(bits)})
+ share = lambda value: round(value / measured_total, 5) if measured_total else 0.0 # noqa: E731
+ readings = []
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
+ x, y, px, py = pixel_of(mark.point)
+ readings.append(_reading(recipe, evaluations[(x, y)], px, py))
+ return {"size": size, "tiles": grid,
+ "measured": round(measured_total / (len(tiles) * size * size), 5),
+ "rules": [{"share": share(own[i]), "kept": share(running[i])} for i in range(len(recipe.rules))],
+ "kept": share(kept_total), "readings": readings,
+ "candidates": [{key: value for key, value in row.items() if key != "parts"}
+ for row in candidates[:TEST_CANDIDATES]]}
+
+
+def _candidates_of(recipe: Recipe, tiles: list[tuple[int, int]],
+ readings: dict[tuple[int, int], analyzers.Reading]) -> list[dict[str, Any]]:
+ """What a run of the recipe would return over these tiles: outlined, joined across seams, sized."""
+ rows: list[dict[str, Any]] = []
+ for part, tile in enumerate(tiles):
+ rows.extend(analyzers._candidates(readings[tile], recipe.phenomenon, tile[0], tile[1], part, []))
+ options = recipe.parameters
+ return [row for row in analyzers.merge(rows, options.merge_metres) if analyzers.keeps(row, options)]
+
+def _covered(check: Check, candidates: list[dict[str, Any]]) -> list[bool]:
+ return [any(analysis_geometry.near(row["geometry"], mark.point, MARK_REACH_M) for row in candidates)
+ for mark in check.marks]
-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.
+def _without(recipe: Recipe, check: Check, tiles: list[tuple[int, int]],
+ measured: dict[tuple[int, int], Measured], skip: int) -> list[bool]:
+ """Whether each mark would be on a candidate if the recipe had not had one rule.
+
+ The rules were read once; only what they make of it is done again.
"""
- 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)
+ keep = [i for i in range(len(recipe.rules)) if i != skip]
+ try:
+ readings = {tile: judge(measured[tile], keep) for tile in tiles}
+ return _covered(check, _candidates_of(recipe, tiles, readings))
+ except ValueError:
+ # So many fragments that a run would refuse them: without this rule everything is flagged.
+ return [True] * len(check.marks)
+
+
+def check(recipe: Recipe, check: Check, *, read: bool = False, detail: bool = False) -> dict[str, Any]:
+ """A check tested with the recipe as it stands: what came out on each mark.
+
+ It reads the tile cache, 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. `detail` adds what the
+ map draws: each tile's mask, the candidates and what every rule read at
+ every mark, and with several rules what the marks would have come to
+ without each one (`without`), which is how an analyst sees which rules help.
+ """
+ _satellite(recipe, check)
+ a, b = check_sources(recipe, check.a, check.b)
tiles = check_tiles(check)
lacking = missing(recipe, a, b, tiles)
if lacking and read:
@@ -634,15 +710,17 @@ def check(recipe: Recipe, check: Check, *, read: bool = False) -> dict[str, Any]
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}
+ measured = {tile: _measure_tile(recipe, a, b, *tile) for tile in tiles}
+ evaluations = {tile: evaluation(measured[tile], judge(measured[tile])) for tile in tiles}
+ candidates = _candidates_of(recipe, tiles, {tile: evaluations[tile].reading for tile in tiles})
+ answer: dict[str, Any] = {"ready": True, "missing": 0, "count": len(candidates), "covered": _covered(check, candidates)}
+ if detail:
+ candidates.sort(key=lambda row: row["margin"], reverse=True)
+ answer.update(_detail(recipe, check, tiles, evaluations, candidates))
+ if len(recipe.rules) > 1:
+ answer["without"] = [{"covered": _without(recipe, check, tiles, measured, skip)}
+ for skip in range(len(recipe.rules))]
+ return answer
# -- built-ins as rules --------------------------------------------------------------
diff --git a/src/azimut/engine/doctor.py b/src/azimut/engine/doctor.py
index 59816d7..0e8e46e 100644
--- a/src/azimut/engine/doctor.py
+++ b/src/azimut/engine/doctor.py
@@ -19,6 +19,7 @@ DATABASE_UNREADABLE = "database-unreadable"
MEDIA_MISSING = "media-missing"
MEDIA_UNKNOWN = "media-unknown"
TEMPORAL_INDEX_STALE = "temporal-index-stale"
+REDIRECT_DANGLING = "redirect-dangling"
def _media_files(case: Case) -> Iterator[Path]:
@@ -143,6 +144,19 @@ def scan(case: Case) -> dict[str, Any]:
}
)
+ for redirect in _dangling_redirects(case):
+ issues.append(
+ {
+ "id": f"{REDIRECT_DANGLING}:{redirect['old_id']}",
+ "kind": REDIRECT_DANGLING,
+ "severity": "info",
+ "title": f"{redirect['label']} was merged into something no longer in the case",
+ "detail": "Its id no longer leads anywhere, in the case or in the Trash.",
+ "entity_id": redirect["old_id"],
+ "actions": [{"id": "drop-redirect", "label": "Drop redirect", "tone": "danger"}],
+ }
+ )
+
for rel_path in unknown_paths:
issues.append(
{
@@ -158,6 +172,27 @@ def scan(case: Case) -> dict[str, Any]:
return _report(case, manifest, issues)
+def _dangling_redirects(case: Case) -> list[dict[str, str]]:
+ """Merge redirects to an entity that is neither in the case nor in the Trash.
+
+ A survivor in the Trash is not dangling: restoring it brings the redirect back to
+ life. One gone for good takes its redirects with it (`trash.purge`), so this only
+ finds what an older build or a hand edit left behind.
+ """
+ trashed: set[str] = set()
+ for group in case.list_trash():
+ held = case.get_trash_group(str(group["id"])) or {}
+ trashed.update(
+ str(entity.get("id")) for entity in (held.get("payload") or {}).get("entities") or []
+ )
+ return case.dangling_redirects(trashed)
+
+
+def require_dangling_redirect(case: Case, old_id: str) -> None:
+ if not any(redirect["old_id"] == old_id for redirect in _dangling_redirects(case)):
+ raise CaseError("this redirect still leads somewhere")
+
+
def _report(case: Case, manifest: dict[str, Any], issues: list[dict[str, Any]]) -> dict[str, Any]:
return {
"case_id": case.id,
diff --git a/src/azimut/engine/entities.py b/src/azimut/engine/entities.py
index 6e4d14e..a4318ac 100644
--- a/src/azimut/engine/entities.py
+++ b/src/azimut/engine/entities.py
@@ -105,7 +105,7 @@ from dataclasses import dataclass
from typing import Any
from ..workspace import CaseError
-from .temporal import TemporalError, parse_temporal
+from .temporal import TemporalError, parse_temporal, valid_zone
#: The families, in the order a menu should show them.
ACTOR = "actor"
@@ -156,8 +156,10 @@ FAMILY_READS: dict[str, str] = {
#: says is that the field expects sentences. A quoted source and the reasoning behind
#: a claim run to paragraphs, and a one-line box that scrolls sideways at eighty
#: characters is a field nobody fills — the reason those two exist at all.
+#:
+#: `timezone` is an IANA zone name, the one a date beside it was stated in.
ATTR_KINDS: tuple[str, ...] = (
- "text", "longtext", "number", "url", "geojson", "choice", "temporal",
+ "text", "longtext", "number", "url", "geojson", "choice", "temporal", "timezone",
)
#: Longest a declared text field may be. Generous: `verbatim` quotes a source and
@@ -368,6 +370,8 @@ ENTITY_TYPES: tuple[EntityType, ...] = (
# is what lets an order of battle render and sort — brigade above battalion
# above company — and the tree itself is `part-of` edges.
attrs=(
+ Attr("aliases", "Other names",
+ hint="former names, acronyms or the name in another script"),
Attr("echelon", "Echelon",
hint="brigade, battalion, company: what lets an order of battle sort"),
Attr("country", "Country"),
@@ -399,6 +403,8 @@ ENTITY_TYPES: tuple[EntityType, ...] = (
# fields of the vessel: an identifier entity is only worth minting the day
# a value turns up without its object, which is the AIS tracker's problem.
attrs=(
+ Attr("aliases", "Former names",
+ hint="the names this hull sailed under, since a renamed ship keeps its IMO"),
Attr("imo", "IMO number", hint="permanent, unlike the MMSI"),
Attr("mmsi", "MMSI", hint="changes with the flag"),
Attr("flag", "Flag state"),
@@ -430,6 +436,7 @@ ENTITY_TYPES: tuple[EntityType, ...] = (
# A building, and also a bridge, a mast, a dam. Its position is stated by
# `sited-at` rather than held here, so only `place` carries geometry.
attrs=(
+ Attr("aliases", "Other names", hint="local names or the name in another script"),
Attr("kind", "Kind"),
Attr("address", "Address"),
_CONDITION,
@@ -541,6 +548,11 @@ ENTITY_TYPES: tuple[EntityType, ...] = (
attrs=(
Attr("when", "Taken", kind="temporal",
hint="when the material this proof rests on was taken"),
+ # The clock that date was read on. The composer states it from
+ # the proof's first point unless the analyst picks another, and
+ # it is what makes a stated day that place's day on the Timeline.
+ Attr("when_zone", "Time zone", kind="timezone",
+ hint="the zone the date was stated in"),
)),
EntityType("post", "Post", DOCUMENT, "post", DELIVERABLE,
hint="a prepared thread or report, saved rather than published"),
@@ -564,8 +576,8 @@ ENTITY_TYPES: tuple[EntityType, ...] = (
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,
- hint="saved geographic areas reusable by any Detect analyzer"),
+ EntityType("analysis-zones", "Area group", DOCUMENT, "polygon", ANNEX,
+ hint="an ordered group of case areas used in Detect"),
EntityType("analysis-area", "Area", DOCUMENT, "mapArea", ANNEX,
hint="a named area shared by detections in this case"),
# Named "routine" everywhere a user reads it: the type id is storage, and
@@ -609,6 +621,8 @@ ENTITY_TYPES: tuple[EntityType, ...] = (
"place", "Place", PLACE, "pin", SUBJECT,
hint="a saved point, as exact or as vague as the evidence allows",
attrs=(
+ Attr("aliases", "Other names",
+ hint="local, older or transliterated names, so a search finds either"),
# Darwin Core's rule, kept verbatim: this is the radius of the smallest
# circle containing the whole location, not a standard deviation — so
# two analysts write the same number. And **zero is not valid**: an
@@ -662,6 +676,10 @@ ENTITY_TYPES: tuple[EntityType, ...] = (
hint="when this claim applies",
group="When",
),
+ Attr(
+ "when_zone", "Time zone", kind="timezone",
+ hint="the zone the date was stated in",
+ ),
Attr(
"time_role", "Time role", kind="choice",
hint="what this value means for the claim",
@@ -1076,6 +1094,11 @@ def _check_temporal(attr: Attr, value: Any) -> None:
raise CaseError(f"'{attr.key}' {exc}") from exc
+def _check_timezone(attr: Attr, value: Any) -> None:
+ if not valid_zone(value):
+ raise CaseError(f"'{attr.key}' must be a time zone name such as Europe/Kyiv, or nothing")
+
+
_CHECKS: dict[str, Callable[[Attr, Any], None]] = {
"text": _check_text,
"longtext": _check_text,
@@ -1084,4 +1107,5 @@ _CHECKS: dict[str, Callable[[Attr, Any], None]] = {
"geojson": _check_geojson,
"choice": _check_choice,
"temporal": _check_temporal,
+ "timezone": _check_timezone,
}
diff --git a/src/azimut/engine/graph.py b/src/azimut/engine/graph.py
index 5b490d0..ea36bee 100644
--- a/src/azimut/engine/graph.py
+++ b/src/azimut/engine/graph.py
@@ -305,6 +305,7 @@ def view(
attr_value: str | None = None,
linked: str | None = None,
unlinked: bool = False,
+ lacks: list[str] | None = None,
since: str | None = None,
until: str | None = None,
filed_by: list[str] | None = None,
@@ -369,6 +370,7 @@ def view(
limit=bounded, types=types, exclude_types=hidden, status=_status(status),
query=query, folder=folder, unfiled=unfiled, recursive=recursive,
attr=attr, attr_value=attr_value, linked=linked, unlinked_only=unlinked,
+ lacks=lacks,
since=since, until=until, filed_by=filed_by,
temporal_since=temporal_since, temporal_until=temporal_until,
temporal_categories=temporal_categories,
diff --git a/src/azimut/engine/inspectwork.py b/src/azimut/engine/inspectwork.py
index be0a086..b50407f 100644
--- a/src/azimut/engine/inspectwork.py
+++ b/src/azimut/engine/inspectwork.py
@@ -24,17 +24,22 @@ cannot be taken back, so every session it rewrites is first copied, byte for byt
from __future__ import annotations
+import io
import json
import re
import shutil
+import warnings
from datetime import datetime, timezone
from pathlib import Path
from typing import TYPE_CHECKING, Any
+from PIL import Image
+
from .. import layout
from ..workspace import CaseError
from . import links as link_engine
from . import media as media_engine
+from .sheets import replace_atomic
if TYPE_CHECKING:
from ..workspace import Case
@@ -50,6 +55,11 @@ COLLAGE_VERSION = 1
MAX_SPEC_BYTES = 2_000_000
MAX_FRAMES = 500
MAX_PIECES = 200
+#: The collage list's preview: the browser draws it no wider than this, and a
+#: larger one is shrunk rather than stored.
+THUMB_EDGE = 480
+MAX_THUMB_BYTES = 4_000_000
+MAX_THUMB_PIXELS = 1024 * 1024
WORK_TYPE = "inspect-session"
COLLAGE_TYPE = "collage"
@@ -351,16 +361,76 @@ def _collage_specs(case: "Case") -> list[tuple[str, dict[str, Any]]]:
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,
+ stem = Path(rel).stem
+ row: dict[str, Any] = {
+ "name": stem,
+ "title": stem,
"pieces": len(spec.get("nodes") or []),
"updated_at": spec.get("updated_at"),
- })
+ "filed": _export_current(case, spec),
+ }
+ thumb = case.resolve_inside(layout.collage_thumb_rel(stem))
+ # Emptied since it was drawn, the preview would show pieces no longer there.
+ if row["pieces"] and thumb.is_file():
+ # The route revalidates by ETag, so the version only has to change
+ # the URL the list hands out when the picture changed.
+ row["thumb"] = layout.collage_thumb_rel(stem)
+ row["thumb_v"] = thumb.stat().st_mtime_ns
+ else:
+ row["outline"] = _outline(spec)
+ rows.append(row)
rows.sort(key=lambda row: row.get("updated_at") or "", reverse=True)
return rows
+def _export_current(case: "Case", spec: dict[str, Any]) -> bool:
+ """Whether the picture last exported is still in the case and still this layout.
+
+ The signature is the browser's JSON of each piece's recipe and corners, so it is
+ compared parsed rather than as text: the two sides need not print a number alike.
+ """
+ exported = spec.get("exported")
+ if not isinstance(exported, dict):
+ return False
+ path, signature = exported.get("path"), exported.get("signature")
+ if not isinstance(path, str) or not isinstance(signature, str):
+ return False
+ try:
+ recorded = json.loads(signature)
+ except ValueError:
+ return False
+ nodes = [n for n in spec.get("nodes") or [] if isinstance(n, dict)]
+ if recorded != [[n.get("save"), n.get("quad")] for n in nodes]:
+ return False
+ try:
+ return media_engine.read_item(case, path) is not None
+ except (CaseError, OSError, ValueError):
+ return False
+
+
+def _outline(spec: dict[str, Any]) -> dict[str, Any] | None:
+ """The pieces' corners trimmed to their bounds, for a collage with no preview yet."""
+ quads = []
+ for node in spec.get("nodes") or []:
+ quad = node.get("quad") if isinstance(node, dict) else None
+ if not isinstance(quad, list):
+ continue
+ try:
+ quads.append([(float(x), float(y)) for x, y in quad])
+ except (TypeError, ValueError):
+ continue
+ if not quads:
+ return None
+ xs = [x for quad in quads for x, _ in quad]
+ ys = [y for quad in quads for _, y in quad]
+ x0, y0 = min(xs), min(ys)
+ return {
+ "width": round(max(xs) - x0, 1),
+ "height": round(max(ys) - y0, 1),
+ "quads": [[[round(x - x0, 1), round(y - y0, 1)] for x, y in quad] for quad in quads],
+ }
+
+
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))
@@ -440,15 +510,17 @@ def save_collage(
media_engine.rename_path(source, source.with_name(Path(rel).name))
_write(case.resolve_inside(rel), written)
existing = case.find_entity(attr="spec", value=old_rel)
+ renamed = {"spec": rel, **_carry_thumb(case, current, final)}
if existing:
- case.update_entity(existing["id"], {"label": final, "attrs": {"spec": rel}})
+ case.update_entity(existing["id"], {"label": final, "attrs": renamed})
elif 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)
+ renamed = {"spec": rel, **_carry_thumb(case, current, final)}
if existing:
- case.update_entity(existing["id"], {"label": final, "attrs": {"spec": rel}})
+ case.update_entity(existing["id"], {"label": final, "attrs": renamed})
case.resolve_inside(old_rel).unlink(missing_ok=True)
else:
_write(case.resolve_inside(rel), written)
@@ -457,6 +529,56 @@ def save_collage(
return {"name": final, "title": final}
+def _carry_thumb(case: "Case", old: str, new: str) -> dict[str, str]:
+ """Move a renamed collage's preview along, and say where it went."""
+ source = case.resolve_inside(layout.collage_thumb_rel(old))
+ if not source.is_file():
+ return {}
+ target = layout.collage_thumb_rel(new)
+ # Not resolved: on Windows a path resolves to the case on disk, which is the old one.
+ media_engine.rename_path(source, source.with_name(Path(target).name))
+ return {"thumb": target}
+
+
+def _preview_image(raw: bytes) -> "Image.Image":
+ """A PNG the browser drew, checked by its header before a pixel is decoded."""
+ if len(raw) > MAX_THUMB_BYTES:
+ raise CaseError("that preview is too large")
+ try:
+ with warnings.catch_warnings():
+ warnings.simplefilter("error", Image.DecompressionBombWarning)
+ opened = Image.open(io.BytesIO(raw))
+ if opened.format != "PNG" or opened.width * opened.height > MAX_THUMB_PIXELS:
+ raise ValueError("not a preview")
+ image = opened.convert("RGBA")
+ except Exception as exc:
+ raise CaseError("that preview is not a picture the list can show") from exc
+ image.thumbnail((THUMB_EDGE, THUMB_EDGE), Image.Resampling.LANCZOS)
+ return image
+
+
+def save_collage_thumb(case: "Case", name: str, raw: bytes) -> dict[str, Any] | None:
+ """File the preview of a saved collage, or None when no collage has that name.
+
+ Written as WebP whatever arrived, so what sits in the case is always pixels this
+ side re-encoded, and the entity points at it for the graph and the Timeline.
+ """
+ image = _preview_image(raw)
+ buf = io.BytesIO()
+ image.save(buf, "WEBP", quality=80)
+ stem = layout.slugify(name, "Collage")
+ rel = layout.collage_rel(stem)
+ thumb = layout.collage_thumb_rel(stem)
+ with case.lock:
+ if not case.resolve_inside(rel).is_file():
+ return None
+ replace_atomic(case.resolve_inside(thumb), buf.getvalue())
+ entity = case.find_entity(attr="spec", value=rel)
+ if entity and (entity.get("attrs") or {}).get("thumb") != thumb:
+ case.update_entity(entity["id"], {"attrs": {"thumb": thumb}})
+ return {"thumb": thumb}
+
+
# -- 0.3.1: one work per file, collages on their own ------------------------------
diff --git a/src/azimut/engine/links.py b/src/azimut/engine/links.py
index 29ffd60..67534ad 100644
--- a/src/azimut/engine/links.py
+++ b/src/azimut/engine/links.py
@@ -84,7 +84,13 @@ MADE_HERE: tuple[str, ...] = ("inspect",)
#: grabbed on purpose, filed as a capture — so it is held back with them, and so is the
#: image a saved Compare session renders of two such views. What stays out
#: is material that came from outside: an upload, a paste, a download.
-PRODUCED_HERE: tuple[str, ...] = (*MADE_HERE, "satellite", "screenshot", "compare")
+#:
+#: Of those, the routes that picture the ground from above (the capture, the map
+#: screenshot, the Compare render and the picture Detect keeps under that name) are
+#: imagery rather than footage: the Timeline draws the files they made on a lane of
+#: their own, apart from the sources' pictures and videos and what Inspect cut from them.
+FROM_ABOVE: tuple[str, ...] = ("satellite", "screenshot", "compare")
+PRODUCED_HERE: tuple[str, ...] = (*MADE_HERE, *FROM_ABOVE)
#: Exact artifact contract. These are not ordinary relations: producing tools
#: record them, and the pair decides delete behaviour. A file path resolving to an
diff --git a/src/azimut/engine/maplayers.py b/src/azimut/engine/maplayers.py
index dae3b1f..21bd7c2 100644
--- a/src/azimut/engine/maplayers.py
+++ b/src/azimut/engine/maplayers.py
@@ -2109,16 +2109,42 @@ def _update_locked(
return row(name, spec)
+def reorder(case: "Case", names: list[str]) -> list[dict[str, Any]]:
+ """Keep the order the analyst dragged the rows into, the first drawn on top.
+
+ Each named layer stores its place in its own spec, so the order travels with
+ the layer through a bundle and the Trash. A name the case does not hold is
+ skipped, and a layer left unnamed goes back to the top with the new ones.
+ """
+ with case.lock:
+ place = 0
+ for name in names:
+ try:
+ spec = _read_spec(case, name)
+ except LayerError:
+ continue
+ spec["position"] = place
+ place += 1
+ _write_spec(case, name, spec)
+ return listing(case)
+
+
def listing(case: "Case") -> list[dict[str, Any]]:
- """Every layer this case holds, newest first."""
+ """Every layer this case holds, top of the map first.
+
+ A layer never reordered sits above the reordered ones, newest first, which
+ is where a layer just added lands.
+ """
rows = []
for path in sorted(case.subdir(layout.LAYERS_DIR).glob("*.json")):
try:
- rows.append(row(path.stem, _read_spec(case, path.stem)))
+ spec = _read_spec(case, path.stem)
except LayerError:
continue
- rows.sort(key=lambda entry: entry.get("created_at") or "", reverse=True)
- return rows
+ rows.append((spec.get("position"), row(path.stem, spec)))
+ rows.sort(key=lambda entry: entry[1].get("created_at") or "", reverse=True)
+ rows.sort(key=lambda entry: entry[0] if isinstance(entry[0], int) else -1)
+ return [entry for _, entry in rows]
def read(case: "Case", name: str) -> dict[str, Any]:
diff --git a/src/azimut/engine/merge.py b/src/azimut/engine/merge.py
new file mode 100644
index 0000000..7a52133
--- /dev/null
+++ b/src/azimut/engine/merge.py
@@ -0,0 +1,296 @@
+"""Folding one subject into another: two records the analyst says are one thing.
+
+Quick entry makes duplicates cheap, so this makes them cheap to fix. It is always
+the analyst's gesture and never automatic: a name is not an identity, and the app
+proposes a duplicate at most (`/entities/twin`), it never folds one.
+
+**What can merge.** Two entities of one type, in the families that name something
+(`MERGE_FAMILIES`): people, groups, objects, models, identifiers, places. Not files
+(`same-image-as` says two files are one picture), not claims (two observations of
+one thing stay two observations), not documents. Two types are two questions:
+change one type first (`engine/retype.py`).
+
+**What the survivor keeps.** Its own values. A field it leaves empty takes the other
+one's value; a field both fill differently keeps the survivor's, and the other value
+goes into the notes, attributed. The absorbed name goes into the other names when
+the type declares them, into the notes otherwise. Either being confirmed confirms
+the survivor, since the merge is the analyst's own act.
+
+**What moves** is in `store/merges.py`, one transaction; the sheets' sidecars follow
+once it has committed. The absorbed id keeps answering through a redirect
+(``entity_redirects``), so a note, a frozen view or a Trash restore naming it lands
+on the survivor, and the merge record undoes it all while it exists. A bundle keeps
+the redirects and leaves the records behind, as it does the Trash.
+"""
+
+from __future__ import annotations
+
+import json
+from typing import Any
+
+from ..workspace import Case, CaseError
+from . import entities as entity_engine
+from .textfold import fold_text
+from . import satellite as satellite_engine
+from . import sheets as sheet_engine
+
+#: The families whose entities can be folded together.
+MERGE_FAMILIES = frozenset({
+ entity_engine.ACTOR, entity_engine.ASSET, entity_engine.CLASS,
+ entity_engine.IDENTIFIER, entity_engine.PLACE,
+})
+
+#: Fields a merge settles by its own rules rather than as an ordinary value.
+_OWN_RULES = frozenset({"notes", "aliases", "folder", "_retained_fields", satellite_engine.COORD_KEY})
+
+
+def refusals(survivor: dict[str, Any] | None, other: dict[str, Any] | None) -> list[str]:
+ """Why these two cannot merge, one line each; empty when they can."""
+ if survivor is None or other is None:
+ return ["both entities have to be in the case"]
+ if survivor["id"] == other["id"]:
+ return ["an entity cannot be merged into itself"]
+ reasons: list[str] = []
+ if survivor["type"] != other["type"]:
+ reasons.append("two different types: change one type first")
+ entry = entity_engine.entity_type(str(survivor["type"]))
+ if entry is None or entry.family not in MERGE_FAMILIES:
+ label = entry.label.lower() if entry else survivor["type"]
+ reasons.append(f"a {label} is never merged")
+ return reasons
+
+
+def _declared(type_: str) -> dict[str, entity_engine.Attr]:
+ entry = entity_engine.entity_type(type_)
+ return {attr.key: attr for attr in entry.attrs} if entry else {}
+
+
+def _shown(value: Any) -> str:
+ if isinstance(value, (dict, list)):
+ return json.dumps(value, ensure_ascii=False, sort_keys=True)
+ return str(value)
+
+
+def _filled(value: Any) -> bool:
+ return value is not None and value != "" and value != [] and value != {}
+
+
+def _names(value: Any) -> list[str]:
+ return [part.strip() for part in str(value or "").replace("\n", ";").replace(",", ";").split(";") if part.strip()]
+
+
+def combine(survivor: dict[str, Any], other: dict[str, Any]) -> dict[str, Any]:
+ """What the survivor holds after the merge, and how each field was settled.
+
+ Pure: ``{attrs, status, old_key, kept, added, conflicts}``. ``kept`` are the
+ survivor's own values, ``added`` fill a field it left empty, ``conflicts`` are
+ the other's differing values, written into the notes.
+ """
+ ours: dict[str, Any] = dict(survivor.get("attrs") or {})
+ theirs: dict[str, Any] = dict(other.get("attrs") or {})
+ declared = _declared(str(survivor["type"]))
+ attrs = dict(ours)
+ added: dict[str, Any] = {}
+ conflicts: list[dict[str, Any]] = []
+ for key, value in theirs.items():
+ if key in _OWN_RULES or not _filled(value):
+ continue
+ if not _filled(ours.get(key)):
+ attrs[key] = value
+ added[key] = value
+ elif ours[key] != value:
+ label = declared[key].label if key in declared else key
+ conflicts.append({"key": key, "label": label, "kept": ours[key], "other": value})
+
+ if not _filled(ours.get("folder")) and _filled(theirs.get("folder")):
+ attrs["folder"] = theirs["folder"]
+ added["folder"] = theirs["folder"]
+
+ old_key = theirs.get(satellite_engine.COORD_KEY) or None
+ if not old_key and survivor["type"] == "place" and theirs.get("lat") is not None and theirs.get("lon") is not None:
+ old_key = satellite_engine.coord_key(theirs["lat"], theirs["lon"])
+ retained = {**(theirs.get("_retained_fields") or {}), **(ours.get("_retained_fields") or {})}
+ if retained:
+ attrs["_retained_fields"] = retained
+
+ lines: list[str] = []
+ other_label = str(other.get("label") or "")
+ alias_values = _names(ours.get("aliases"))
+ if "aliases" in declared:
+ for name in [other_label, *_names(theirs.get("aliases"))]:
+ if name and fold_text(name) != fold_text(str(survivor.get("label") or "")) and fold_text(name) not in {
+ fold_text(alias) for alias in alias_values
+ }:
+ alias_values.append(name)
+ if alias_values != _names(ours.get("aliases")):
+ attrs["aliases"] = "; ".join(alias_values)
+ added["aliases"] = attrs["aliases"]
+ elif fold_text(other_label) != fold_text(str(survivor.get("label") or "")):
+ lines.append(f"Also filed as: {other_label}")
+
+ # Other names retained after a type change are still case data.
+ if "aliases" not in declared and _filled(theirs.get("aliases")):
+ if not _filled(ours.get("aliases")):
+ attrs["aliases"] = theirs["aliases"]
+ added["aliases"] = theirs["aliases"]
+ elif ours["aliases"] != theirs["aliases"]:
+ conflicts.append({"key": "aliases", "label": "Other names", "kept": ours["aliases"], "other": theirs["aliases"]})
+
+ theirs_notes = str(theirs.get("notes") or "").strip()
+ ours_notes = str(ours.get("notes") or "").strip()
+ if theirs_notes and theirs_notes not in ours_notes:
+ lines.append(f"From {other_label}: {theirs_notes}")
+ for conflict in conflicts:
+ lines.append(f"From {other_label}, {conflict['label']}: {_shown(conflict['other'])}")
+ if lines:
+ attrs["notes"] = "\n\n".join(part for part in (ours_notes, "\n".join(lines)) if part)
+
+ confirmed = "confirmed" in (
+ survivor.get("provenance", {}).get("status"), other.get("provenance", {}).get("status")
+ )
+ status = "confirmed" if confirmed else str(survivor.get("provenance", {}).get("status") or "confirmed")
+ if attrs.get("notes") != ours.get("notes"):
+ added["notes"] = attrs["notes"]
+ entity_engine.check_attrs(str(survivor["type"]), attrs, current=ours)
+ kept = {key: value for key, value in ours.items() if key not in added}
+ return {
+ "attrs": attrs,
+ "status": status,
+ "old_key": old_key,
+ "kept": kept,
+ "added": added,
+ "conflicts": conflicts,
+ }
+
+
+def _notes_naming(case: Case, entity_id: str) -> int:
+ """How many notes mention this entity in their text. Read, never rewritten: the
+ text is the analyst's, and the redirect resolves it."""
+ token = f"[[entity:{entity_id}|"
+ count = 0
+ cursor: str | None = None
+ while True:
+ page = case.page_entities(limit=200, cursor=cursor, types=["note"])
+ for note in page.get("items", []):
+ path = (note.get("attrs") or {}).get("path")
+ if not path:
+ continue
+ try:
+ text = case.resolve_inside(str(path)).read_text(encoding="utf-8")
+ except (CaseError, OSError, ValueError):
+ continue
+ count += token in text
+ cursor = page.get("next_cursor")
+ if not cursor:
+ return count
+
+
+def _sidecar(case: Case, sheet: dict[str, Any]) -> dict[str, Any] | None:
+ try:
+ _, meta_path = sheet_engine._paths(case, sheet)
+ meta = json.loads(meta_path.read_text(encoding="utf-8"))
+ except (CaseError, OSError, ValueError):
+ return None
+ return meta if isinstance(meta, dict) else None
+
+
+def _sheets_naming(case: Case, entity_id: str) -> int:
+ count = 0
+ cursor: str | None = None
+ while True:
+ page = case.page_entities(limit=sheet_engine.SHEET_PAGE, cursor=cursor, types=["sheet"])
+ for sheet in page.get("items", []):
+ meta = _sidecar(case, sheet)
+ if meta is not None and entity_id in sheet_engine.linked_entity_ids(meta):
+ count += 1
+ cursor = page.get("next_cursor")
+ if not cursor:
+ return count
+
+
+def _checked(case: Case, survivor_id: str, other_id: str) -> tuple[dict[str, Any], dict[str, Any]]:
+ survivor, other = case.get_entity(survivor_id), case.get_entity(other_id)
+ reasons = refusals(survivor, other)
+ if reasons:
+ raise CaseError("; ".join(reasons))
+ assert survivor is not None and other is not None
+ return survivor, other
+
+
+def preview(case: Case, survivor_id: str, other_id: str) -> dict[str, Any]:
+ """What merging `other_id` into `survivor_id` would do, written nowhere.
+
+ The database half is the merge itself, rolled back; the sheets and notes that
+ name the absorbed entity are counted from disk.
+ """
+ survivor, other = _checked(case, survivor_id, other_id)
+ fields = combine(survivor, other)
+ report = case.merge_entities(
+ survivor_id, other_id,
+ survivor_attrs=fields["attrs"], survivor_status=fields["status"],
+ old_key=fields["old_key"], by="user", dry_run=True,
+ )
+ return {
+ "survivor": survivor,
+ "other": other,
+ "fields": {key: fields[key] for key in ("kept", "added", "conflicts")},
+ "links": report["links"],
+ "refused": report["refused"],
+ "images": report["images"],
+ "pins": report["pins"],
+ "views": report["views"],
+ "sheets": _sheets_naming(case, other_id),
+ "notes": _notes_naming(case, other_id),
+ }
+
+
+def merge(case: Case, survivor_id: str, other_id: str, *, by: str = "user") -> dict[str, Any]:
+ """Fold `other_id` into `survivor_id`. Returns the report and the merge id."""
+ with case.lock:
+ survivor, other = _checked(case, survivor_id, other_id)
+ fields = combine(survivor, other)
+ recover(case)
+ if case.pending_merge_work():
+ raise CaseError("a previous merge still needs to update a sheet; make it writable first")
+ sheets = sheet_engine.plan_entity_move(case, other_id, survivor_id)
+ with case.batch():
+ report = case.merge_entities(
+ survivor_id, other_id,
+ survivor_attrs=fields["attrs"], survivor_status=fields["status"],
+ old_key=fields["old_key"], by=by,
+ )
+ case.set_merge_sheets(report["merge"], sheets)
+ warnings = recover(case)
+ return {**report, "sheets": len(sheets), "warnings": warnings, "fields": {k: fields[k] for k in ("added", "conflicts")}}
+
+
+def undo(case: Case, merge_id: str) -> dict[str, Any]:
+ """Undo database changes once; replay sidecars from the durable journal."""
+ with case.lock:
+ recover(case)
+ if case.pending_merge_work():
+ raise CaseError("a previous merge still needs to update a sheet; make it writable first")
+ result = case.unmerge(merge_id)
+ lost = [*result["lost"], *recover(case)]
+ return {"restored": result["restored"], "survivor": result["survivor"], "lost": lost}
+
+
+def recover(case: Case) -> list[str]:
+ """Finish interrupted sidecar writes on case open, including interrupted Undo."""
+ warnings: list[str] = []
+ with case.lock:
+ for record in case.pending_merge_work():
+ payload = record["payload"]
+ lost, retry = sheet_engine.apply_entity_move(case, payload.get("sheets", []), undo=bool(payload.get("undo_result")))
+ warnings.extend(lost)
+ if not retry:
+ case.finish_merge_work(record["id"])
+ return warnings
+
+
+def resolve(case: Case, entity_id: str) -> tuple[str, dict[str, str] | None]:
+ """The id an entity answers to now, and where it came from when it was absorbed."""
+ redirect = case.entity_redirects([entity_id]).get(entity_id)
+ if redirect is None:
+ return entity_id, None
+ return str(redirect["id"]), {"id": entity_id, "label": str(redirect["label"])}
diff --git a/src/azimut/engine/retype.py b/src/azimut/engine/retype.py
new file mode 100644
index 0000000..42e2be4
--- /dev/null
+++ b/src/azimut/engine/retype.py
@@ -0,0 +1,136 @@
+"""Changing what a subject is, without losing anything on the way.
+
+A quick entry guesses a type (`frontend/src/lib/entryLine.js`), and a guess is
+sometimes wrong: a unit filed as a person, a handle filed as an organization. The
+type is one column, and writing it used to be all a change did, so a change could
+leave a subject holding relations its new type cannot hold. Every rule is checked
+here, before anything is written, and a change that would lose something is
+refused with what stands in the way. The analyst removes it themselves and asks
+again: nothing is dropped behind them.
+
+- **Which types.** Between types an analyst makes by hand that own no files, in the
+ families that name something (`RETYPE_FAMILIES`). A place is a point and a claim
+ is a statement, so neither changes, into or out of.
+- **Relations.** Every relation touching the subject is checked against the new
+ type, as `links.set_relation_type` checks a verb that changes.
+- **Photos.** A type with no gallery cannot take a subject that has photos.
+- **Fields.** Kept. A value the new type does not declare stays in ``attrs``, where
+ Details shows it as kept from the earlier type; changing back makes it editable
+ again. A declared value the new type reads differently is refused.
+- **Identity.** Into an identifier, a value the case already holds is reported, and
+ never refused: two records of one value are a merge to make, not an error.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+from ..repository import CaseRepository
+from ..workspace import CaseError
+from . import artifacts as artifact_engine
+from . import entities as entity_engine
+from . import links as link_engine
+
+#: The families whose types can change into one another.
+RETYPE_FAMILIES = frozenset({
+ entity_engine.ACTOR, entity_engine.ASSET, entity_engine.CLASS, entity_engine.IDENTIFIER,
+})
+
+
+def retypable(type_: str) -> bool:
+ """Whether a subject of this type can change type, and be changed into it."""
+ entry = entity_engine.entity_type(type_)
+ return (
+ entry is not None
+ and entry.manual
+ and entry.family in RETYPE_FAMILIES
+ and type_ in artifact_engine.NO_FILES
+ )
+
+
+def _a(word: str) -> str:
+ """The word with its article, as a reason is read aloud: an account, a person."""
+ return f"{'an' if word[:1] in 'aeiou' else 'a'} {word}"
+
+
+def _reading(entity: dict[str, Any]) -> str:
+ return f"“{entity.get('label') or entity.get('id')}”"
+
+
+def problems(case: CaseRepository, entity: dict[str, Any], new_type: str) -> list[str]:
+ """What stands in the way of this entity becoming a ``new_type``, one line each.
+
+ Empty when the change can go ahead. Nothing is written either way.
+ """
+ old_type = str(entity["type"])
+ if new_type == old_type:
+ return []
+ new_entry = entity_engine.entity_type(new_type)
+ if new_entry is None:
+ return [f"'{new_type}' is not a type this case knows"]
+ reasons: list[str] = []
+ if not retypable(old_type):
+ old_entry = entity_engine.entity_type(old_type)
+ reasons.append(f"{_a(old_entry.label.lower() if old_entry else old_type)} keeps its type")
+ if not retypable(new_type):
+ reasons.append(f"nothing can become {_a(new_entry.label.lower())}")
+ if reasons:
+ return reasons
+
+ changed = {**entity, "type": new_type}
+ for link in case.links_of(str(entity["id"])):
+ spec = link_engine.relation_type(link["type"])
+ if spec is None:
+ reasons.append(f"it is joined by '{link['type']}', which only a tool writes")
+ continue
+ ours_from = link["from"] == entity["id"]
+ other_id = link["to"] if ours_from else link["from"]
+ other = changed if other_id == entity["id"] else case.get_entity(other_id)
+ if other is None:
+ continue
+ source, target = (changed, other) if ours_from else (other, changed)
+ if source["type"] not in spec.from_types or target["type"] not in spec.to_types:
+ verb = spec.label
+ reasons.append(
+ f"it {verb} {_reading(target)}" if ours_from
+ else f"{_reading(source)} {verb} it"
+ )
+
+ if not new_entry.image_gallery:
+ photos = len(case.entity_images(str(entity["id"])))
+ if photos:
+ reasons.append(
+ f"{_a(new_entry.label.lower())} has no photos, and this one has {photos}"
+ )
+
+ attrs = entity.get("attrs") or {}
+ try:
+ entity_engine.check_attrs(new_type, attrs, current=attrs)
+ except CaseError as exc:
+ reasons.append(f"a field does not fit {_a(new_entry.label.lower())}: {exc}")
+ return reasons
+
+
+def twin(case: CaseRepository, entity: dict[str, Any], new_type: str) -> dict[str, Any] | None:
+ """The entity already holding this value as a ``new_type`` identifier, or None."""
+ key = entity_engine.identity_key(new_type, str(entity.get("label") or ""))
+ if not key:
+ return None
+ for entity_id, label in case.labels_of_type(new_type):
+ if entity_id != entity["id"] and entity_engine.identity_key(new_type, label) == key:
+ return case.get_entity(entity_id)
+ return None
+
+
+def retained_fields(entity: dict[str, Any], new_type: str, patch: dict[str, Any]) -> dict[str, Any]:
+ """Remember the source type of fields kept outside the new type's editor."""
+ attrs = {**entity.get("attrs", {}), **patch}
+ old = entity_engine.entity_type(entity["type"])
+ new = entity_engine.entity_type(new_type)
+ declared = {field.key for field in new.attrs} if new else set()
+ held = dict(attrs.get("_retained_fields") or {})
+ for field in old.attrs if old else ():
+ if field.key not in declared and attrs.get(field.key) not in (None, ""):
+ held.setdefault(field.key, entity["type"])
+ held = {key: type_ for key, type_ in held.items() if key not in declared and attrs.get(key) not in (None, "")}
+ return {**patch, "_retained_fields": held or None}
diff --git a/src/azimut/engine/satellite.py b/src/azimut/engine/satellite.py
index 50ee237..e62a96a 100644
--- a/src/azimut/engine/satellite.py
+++ b/src/azimut/engine/satellite.py
@@ -124,6 +124,11 @@ def place_at(
"""
key = coord_key(lat, lon)
found = case.find_entity(attr=COORD_KEY, value=key)
+ if found is None:
+ # A place merged into another is found where it went, or enrichment would
+ # file the same point again as a new place (`engine/merge.py`).
+ survivor = case.redirect_by_key(key)
+ found = case.get_entity(survivor) if survivor else None
if found is not None or keyed_only:
return found
for place in _page_all(case, ["place"]):
diff --git a/src/azimut/engine/sheets.py b/src/azimut/engine/sheets.py
index c654f2c..958e8da 100644
--- a/src/azimut/engine/sheets.py
+++ b/src/azimut/engine/sheets.py
@@ -685,7 +685,8 @@ def sync_mentions(case: "Case", sheet_id: str, meta: dict[str, Any]) -> None:
if source is None:
return
wanted: list[str] = []
- for entity_id in linked_entity_ids(meta):
+ resolved = drop_dead_links(case, meta)
+ for entity_id in linked_entity_ids(resolved):
try:
link_engine.check_relation_target(case, source, entity_id, link_engine.MENTIONS)
except CaseError:
@@ -1044,9 +1045,123 @@ def drop_dead_links(case: "Case", meta: dict[str, Any]) -> dict[str, Any]:
return meta
held = {str(entity["id"]) for entity in case.entities_by_ids(wanted)}
gone = {entity_id for entity_id in wanted if entity_id not in held}
+ # An id a merge absorbed is not dead: it points where its entity went.
+ redirects = case.entity_redirects(sorted(gone)) if gone else {}
+ if redirects:
+ live = {entity["id"] for entity in case.entities_by_ids([target["id"] for target in redirects.values()])}
+ moves = {old: str(target["id"]) for old, target in redirects.items() if target["id"] in live}
+ moved, _ = _with_entities_moved(meta, moves)
+ meta = moved or meta
+ gone -= set(moves)
return _without_entities(meta, gone) or meta
+def _with_entities_moved(
+ meta: dict[str, Any], moves: dict[str, str]
+) -> tuple[dict[str, Any] | None, list[list[str]]]:
+ """The sidecar with ids moved (``{old: new}``), and where each move happened.
+
+ A location is a path into the sidecar — ``["links", row, column]``, ``["values",
+ column, word]`` or ``["attachments", row, "replaced" | "joined"]`` — so an undone
+ merge puts back exactly those cells and no other. None when nothing moved. A row
+ already carrying the new id does not carry it twice.
+ """
+ out = json.loads(json.dumps(meta))
+ where: list[list[str]] = []
+ for identity, cells in (out.get("links") or {}).items():
+ if isinstance(cells, dict):
+ for name, value in cells.items():
+ if value in moves:
+ cells[name] = moves[value]
+ where.append(["links", identity, name])
+ for column, words in (out.get("values") or {}).items():
+ if isinstance(words, dict):
+ for word, value in words.items():
+ if value in moves:
+ words[word] = moves[value]
+ where.append(["values", column, word])
+ for identity, held in (out.get("attachments") or {}).items():
+ if isinstance(held, list):
+ kept: list[Any] = []
+ for value in held:
+ target = moves.get(value, value)
+ if target != value:
+ # "joined" when the row already carried the new id, which then
+ # stays after an undo; "replaced" when the old one gives way to it.
+ how = "joined" if target in held else "replaced"
+ where.append(["attachments", identity, how])
+ if target not in kept:
+ kept.append(target)
+ out["attachments"][identity] = kept
+ return (out if where else None), where
+
+
+def plan_entity_move(case: "Case", old: str, new: str) -> list[dict[str, Any]]:
+ """Read the sheet cells to move before the merge transaction records its journal."""
+ plans: list[dict[str, Any]] = []
+ cursor: str | None = None
+ while True:
+ page = case.page_entities(limit=SHEET_PAGE, cursor=cursor, types=["sheet"])
+ for entity in page["items"]:
+ _, path = _paths(case, entity)
+ try:
+ before = json.loads(path.read_text(encoding="utf-8"))
+ except (OSError, ValueError) as exc:
+ raise CaseError(f"cannot read sheet '{entity['label']}' before merging") from exc
+ if not isinstance(before, dict):
+ raise CaseError(f"invalid sheet '{entity['label']}'")
+ after, where = _with_entities_moved(before, {old: new})
+ if after is None:
+ continue
+ changes: list[dict[str, Any]] = []
+ for section, first, second in where:
+ key = [section, first] if section == "attachments" else [section, first, second]
+ if any(change["key"] == key for change in changes):
+ continue
+ left, right = before, after
+ for part in key:
+ left, right = left[part], right[part]
+ changes.append({"key": key, "before": left, "after": right})
+ plans.append({"sheet": entity["id"], "changes": changes})
+ cursor = page.get("next_cursor")
+ if not cursor:
+ return plans
+
+
+def apply_entity_move(case: "Case", records: list[dict[str, Any]], *, undo: bool = False) -> tuple[list[str], bool]:
+ """Replay a durable merge journal, preserving later edits and reporting conflicts."""
+ lost: list[str] = []
+ retry = False
+ for record in records:
+ sheet = case.get_entity(record["sheet"])
+ if sheet is None:
+ lost.append("a sheet used by the merge is no longer in the case")
+ continue
+ try:
+ _, path = _paths(case, sheet)
+ meta = json.loads(path.read_text(encoding="utf-8"))
+ for change in record["changes"]:
+ expected = change["after" if undo else "before"]
+ desired = change["before" if undo else "after"]
+ holder = meta
+ for part in change["key"][:-1]:
+ holder = holder.get(part, {}) if isinstance(holder, dict) else {}
+ key = change["key"][-1]
+ if holder.get(key) == desired:
+ continue
+ if holder.get(key) != expected:
+ lost.append(f"a cell in '{sheet['label']}' was changed since and keeps its value")
+ continue
+ holder[key] = desired
+ # Write only the sidecar; CSV bytes and its edit stamp stay untouched.
+ write_atomic(path, json.dumps(meta, ensure_ascii=False, indent=2), encoding="utf-8")
+ sync_mentions(case, sheet["id"], meta)
+ except (CaseError, OSError, ValueError) as exc:
+ lost.append(f"sheet '{sheet['label']}' could not be updated: {exc}")
+ retry = True
+ return lost, retry
+
+
def _without_entities(meta: dict[str, Any], gone: set[str]) -> dict[str, Any] | None:
"""The sidecar with every pointer at *gone* removed, or None when it held none.
diff --git a/src/azimut/engine/tally.py b/src/azimut/engine/tally.py
index 8810145..e276a49 100644
--- a/src/azimut/engine/tally.py
+++ b/src/azimut/engine/tally.py
@@ -76,6 +76,7 @@ def tally(
attr_value: str | None = None,
linked: str | None = None,
unlinked: bool = False,
+ lacks: list[str] | None = None,
since: str | None = None,
until: str | None = None,
filed_by: list[str] | None = None,
@@ -104,6 +105,7 @@ def tally(
limit=bounded, types=wanted, status=_status(status), query=query,
folder=folder, unfiled=unfiled, recursive=recursive,
attr=attr, attr_value=attr_value, linked=linked, unlinked=unlinked,
+ lacks=lacks,
since=since, until=until, filed_by=filed_by,
temporal_since=temporal_since, temporal_until=temporal_until,
temporal_categories=temporal_categories,
diff --git a/src/azimut/engine/temporal.py b/src/azimut/engine/temporal.py
index b481c68..e87f701 100644
--- a/src/azimut/engine/temporal.py
+++ b/src/azimut/engine/temporal.py
@@ -4,14 +4,21 @@ Reduced dates, date intervals and their final qualifiers follow EDTF's familiar
surface. Exact timestamps follow ISO 8601. This module deliberately implements
neither full EDTF nor timestamp intervals: every accepted value must yield honest,
exclusive search bounds, or be marked as a local value that cannot join a UTC axis.
+
+A value may be stated in a named zone, stored beside it rather than inside it. A civil
+date then spans that zone's days: the 12th of March in Kyiv starts two hours before
+the 12th in UTC, and reading it as UTC's would put the event on the wrong side of a
+satellite pass. A local timestamp gains its bounds the same way.
"""
from __future__ import annotations
from dataclasses import dataclass
-from datetime import UTC, datetime, timedelta, timezone
+from datetime import UTC, datetime, timedelta, timezone, tzinfo
import re
+from .localtime import known_zone, zone_info
+
class TemporalError(ValueError):
"""A temporal value is outside Azimut's announced profile."""
@@ -29,6 +36,10 @@ class TemporalEndpoint:
approximate: bool
zone: str
sortable: bool
+ #: The IANA zone the bounds were read in, when the value was stated in one and
+ #: the endpoint left it room to apply: a `Z` or an offset already says where
+ #: it stands.
+ tz: str | None = None
@dataclass(frozen=True)
@@ -79,6 +90,10 @@ class TemporalValue:
def sortable(self) -> bool:
return self.start.sortable and bool(self.end is None or self.end.sortable)
+ @property
+ def tz(self) -> str | None:
+ return self.start.tz or (self.end.tz if self.end is not None else None)
+
_DATE = re.compile(
r"(?P<year>\d{4})"
@@ -93,21 +108,28 @@ _TIMESTAMP = re.compile(
)
-def parse_temporal(raw: object) -> TemporalValue:
+def parse_temporal(raw: object, *, tz: str | None = None) -> TemporalValue:
"""Parse one supported temporal value without rewriting what the analyst typed.
Bounds are half-open: ``earliest`` is inclusive and ``latest`` is exclusive.
A reduced month therefore ends at the start of the next month, and a timestamp
written to seconds ends one second later. Local timestamps remain valid but have
no UTC bounds until a timezone is known.
+
+ ``tz`` is the IANA zone the value was stated in. Dates are then bounded by that
+ zone's midnights, across a daylight-saving change included, and a local
+ timestamp is read on its clock. Without it a date spans UTC's days, as it always
+ has, so a value stored before zones existed keeps its place.
"""
if not isinstance(raw, str):
raise TemporalError("a temporal value must be text")
if not raw or raw != raw.strip():
raise TemporalError("a temporal value cannot be empty or padded with spaces")
+ if tz is not None and not valid_zone(tz):
+ raise TemporalError("the timezone is not one this installation knows")
if "/" not in raw:
- return TemporalValue(raw=raw, start=_parse_endpoint(raw))
+ return TemporalValue(raw=raw, start=_parse_endpoint(raw, tz))
if raw.count("/") != 1:
raise TemporalError("an interval must contain exactly two dates")
@@ -119,8 +141,8 @@ def parse_temporal(raw: object) -> TemporalValue:
timestamps = bool(_TIMESTAMP.fullmatch(start_raw) and _TIMESTAMP.fullmatch(end_raw))
if not dates and not timestamps:
raise TemporalError("an interval needs two dates or two timestamps")
- start = _parse_date(start_raw) if dates else _parse_timestamp(start_raw)
- end = _parse_date(end_raw) if dates else _parse_timestamp(end_raw)
+ start = _parse_date(start_raw, tz) if dates else _parse_timestamp(start_raw, tz)
+ end = _parse_date(end_raw, tz) if dates else _parse_timestamp(end_raw, tz)
if start.earliest is None or end.earliest is None:
raise TemporalError("a timestamp interval needs a timezone on both bounds")
upper = end.latest if dates else end.earliest
@@ -129,6 +151,16 @@ def parse_temporal(raw: object) -> TemporalValue:
return TemporalValue(raw=raw, start=start, end=end)
+def valid_zone(name: object) -> bool:
+ """Whether ``name`` is an IANA zone a value can be stated in here.
+
+ Checked before it is stored, not only when it is read: a name another machine's
+ database held would otherwise leave a value placed on one install and not on
+ the next, with nothing on screen saying why.
+ """
+ return isinstance(name, str) and 0 < len(name) <= 64 and name == name.strip() and known_zone(name)
+
+
def window_bound(raw: str, *, upper: bool) -> str:
"""One end of a search window, read from a value the analyst may have typed short.
@@ -148,15 +180,20 @@ def window_bound(raw: str, *, upper: bool) -> str:
return bound
-def _parse_endpoint(raw: str) -> TemporalEndpoint:
+def _parse_endpoint(raw: str, tz: str | None = None) -> TemporalEndpoint:
if _DATE.fullmatch(raw):
- return _parse_date(raw)
+ return _parse_date(raw, tz)
if _TIMESTAMP.fullmatch(raw):
- return _parse_timestamp(raw)
+ return _parse_timestamp(raw, tz)
raise TemporalError("the temporal value is outside the supported date and timestamp profile")
-def _parse_date(raw: str) -> TemporalEndpoint:
+def _civil(year: int, month: int, day: int, where: tzinfo) -> datetime:
+ """Midnight opening a civil day in a zone, as the UTC instant it is."""
+ return datetime(year, month, day, tzinfo=where).astimezone(UTC)
+
+
+def _parse_date(raw: str, tz: str | None = None) -> TemporalEndpoint:
match = _DATE.fullmatch(raw)
if match is None:
raise TemporalError("date intervals accept dates, not timestamps or open bounds")
@@ -165,25 +202,30 @@ def _parse_date(raw: str) -> TemporalEndpoint:
month_text = match.group("month")
day_text = match.group("day")
qualifier = match.group("qualifier")
+ # Each end is the midnight opening a civil day, never a fixed 24 hours on from
+ # the start: a day that crosses a clock change is 23 or 25 hours long.
+ where: tzinfo = zone_info(tz) if tz else UTC
try:
if day_text is not None:
month = int(month_text or 0)
day = int(day_text)
- earliest = datetime(year, month, day, tzinfo=UTC)
- latest = earliest + timedelta(days=1)
+ first = datetime(year, month, day)
+ following = first + timedelta(days=1)
+ earliest = _civil(year, month, day, where)
+ latest = _civil(following.year, following.month, following.day, where)
precision = "day"
elif month_text is not None:
month = int(month_text)
- earliest = datetime(year, month, 1, tzinfo=UTC)
+ earliest = _civil(year, month, 1, where)
if month == 12:
- latest = datetime(year + 1, 1, 1, tzinfo=UTC)
+ latest = _civil(year + 1, 1, 1, where)
else:
- latest = datetime(year, month + 1, 1, tzinfo=UTC)
+ latest = _civil(year, month + 1, 1, where)
precision = "month"
else:
- earliest = datetime(year, 1, 1, tzinfo=UTC)
- latest = datetime(year + 1, 1, 1, tzinfo=UTC)
+ earliest = _civil(year, 1, 1, where)
+ latest = _civil(year + 1, 1, 1, where)
precision = "year"
except (OverflowError, ValueError) as exc:
raise TemporalError("the date is not a valid Gregorian date with representable bounds") from exc
@@ -197,10 +239,11 @@ def _parse_date(raw: str) -> TemporalEndpoint:
approximate=qualifier in ("~", "%"),
zone="date-only",
sortable=True,
+ tz=tz,
)
-def _parse_timestamp(raw: str) -> TemporalEndpoint:
+def _parse_timestamp(raw: str, tz: str | None = None) -> TemporalEndpoint:
match = _TIMESTAMP.fullmatch(raw)
if match is None: # guarded by `_parse_endpoint`, useful for direct maintenance
raise TemporalError("the timestamp is outside the supported ISO profile")
@@ -209,10 +252,10 @@ def _parse_timestamp(raw: str) -> TemporalEndpoint:
microsecond = int(fraction.ljust(6, "0")) if fraction else 0
zone_text = match.group("zone")
- tz = None
+ where: tzinfo | None = None
zone = "local"
if zone_text == "Z":
- tz = UTC
+ where = UTC
zone = "utc"
elif zone_text:
offset_hour = int(match.group("offset_hour") or 0)
@@ -222,8 +265,13 @@ def _parse_timestamp(raw: str) -> TemporalEndpoint:
offset = timedelta(hours=offset_hour, minutes=offset_minute)
if match.group("sign") == "-":
offset = -offset
- tz = timezone(offset)
+ where = timezone(offset)
zone = "offset"
+ elif tz:
+ # A wall-clock reading with no offset of its own, stated in a named zone:
+ # that zone's clock on that day, summer time included.
+ where = zone_info(tz)
+ zone = "named"
try:
instant = datetime(
@@ -234,12 +282,12 @@ def _parse_timestamp(raw: str) -> TemporalEndpoint:
int(match.group("minute")),
int(match.group("second")),
microsecond,
- tzinfo=tz,
+ tzinfo=where,
)
except ValueError as exc:
raise TemporalError("the timestamp is not a valid Gregorian date and time") from exc
- if tz is None:
+ if where is None:
return TemporalEndpoint(
raw=raw,
earliest=None,
@@ -268,6 +316,7 @@ def _parse_timestamp(raw: str) -> TemporalEndpoint:
approximate=False,
zone=zone,
sortable=True,
+ tz=tz if zone == "named" else None,
)
diff --git a/src/azimut/engine/textfold.py b/src/azimut/engine/textfold.py
new file mode 100644
index 0000000..5d706eb
--- /dev/null
+++ b/src/azimut/engine/textfold.py
@@ -0,0 +1,52 @@
+"""How a search compares text: without case, and without the marks a reader skips.
+
+``fold_text`` is applied to the stored search index and to every term typed against
+it, so a search for ``Kyiv`` in Cyrillic, ``Cafe`` or ``محمد`` finds the label written
+with its accents, its stress marks or its vowels. The browser holds the same fold
+(``frontend/src/lib/textFold.js``) for a case small enough to search in memory, and
+``tests/fixtures/fold_cases.json`` holds both to one list.
+
+Marks go only where a reader would skip them: on a Latin, Greek or Cyrillic letter,
+Arabic harakat and the tatweel, Hebrew points. Everywhere else a combining mark is
+part of the letter: a Devanagari sign changes the syllable and a dakuten changes the
+sound, so they stay. Punctuation is never touched, because an address, an email or a
+handle is looked for by it. ``identity_key`` does not fold: that is identity, and this
+is recall.
+
+``lower`` rather than ``casefold``, with the two differences that matter spelled out,
+because ``casefold`` has no counterpart in JavaScript and the two sides must agree.
+"""
+
+from __future__ import annotations
+
+import unicodedata
+
+#: Case differences ``lower`` leaves that a reader does not see.
+_SAME_LETTER = str.maketrans({"ß": "ss", "ς": "σ"})
+
+
+def _skipped_on(base: int) -> bool:
+ """Whether a mark on this letter is one a reader of its script skips."""
+ return base <= 0x052F or 0x1E00 <= base <= 0x1FFF
+
+
+def _skipped(mark: int) -> bool:
+ """Arabic harakat and superscript alef, then the Hebrew points."""
+ return 0x064B <= mark <= 0x065F or mark == 0x0670 or 0x0591 <= mark <= 0x05C7
+
+
+def fold_text(text: str) -> str:
+ """``text`` as a search compares it."""
+ out: list[str] = []
+ base = 0
+ for char in unicodedata.normalize("NFD", text.lower().translate(_SAME_LETTER)):
+ code = ord(char)
+ if unicodedata.category(char) == "Mn":
+ if not (_skipped_on(base) or _skipped(code)):
+ out.append(char)
+ continue
+ if code == 0x0640: # the tatweel, which only stretches a word
+ continue
+ base = code
+ out.append(char)
+ return unicodedata.normalize("NFC", "".join(out))
diff --git a/src/azimut/engine/timeline.py b/src/azimut/engine/timeline.py
index 67a334f..e9a6377 100644
--- a/src/azimut/engine/timeline.py
+++ b/src/azimut/engine/timeline.py
@@ -43,6 +43,8 @@ class ProjectionRow:
status: str | None
confidence: str | None
parse_error: str | None
+ #: The IANA zone the value was stated in, when one was and it applied.
+ tz: str | None = None
def record(self) -> dict[str, Any]:
return asdict(self)
@@ -59,15 +61,17 @@ def _project_value(
time_role: str | None = None,
status: str | None = None,
confidence: str | None = None,
+ tz: object = None,
) -> ProjectionRow:
text = raw if isinstance(raw, str) and raw else None
+ stated_in = tz if isinstance(tz, str) and tz else None
if text is None:
return ProjectionRow(
id, owner_id, authority, category, kind, None, None, None, None,
None, time_role, False, False, None, False, status, confidence, None,
)
try:
- value = parse_temporal(text)
+ value = parse_temporal(text, tz=stated_in)
except TemporalError as exc:
# Old cases may contain a field that predates the declared Claim contract.
# Keep it visible as unplaced and explain why it cannot be placed; a derived
@@ -95,6 +99,9 @@ def _project_value(
status=status,
confidence=confidence,
parse_error=None,
+ # The clock the value was stated on, kept even where the value writes its own
+ # offset: a time picked on Kyiv's clock says Kyiv, not only `+03:00`.
+ tz=stated_in,
)
@@ -121,6 +128,7 @@ def project_entity(entity: dict[str, Any]) -> list[ProjectionRow]:
kind="claim",
raw=attrs.get("when"),
time_role=role if isinstance(role, str) else None,
+ tz=attrs.get("when_zone"),
status=(
provenance.get("status")
if isinstance(provenance.get("status"), str)
@@ -158,6 +166,7 @@ def project_entity(entity: dict[str, Any]) -> list[ProjectionRow]:
kind="taken",
raw=attrs.get("when"),
time_role="occurred",
+ tz=attrs.get("when_zone"),
)
)
return rows
diff --git a/src/azimut/engine/trash.py b/src/azimut/engine/trash.py
index 6b78b48..e3088e2 100644
--- a/src/azimut/engine/trash.py
+++ b/src/azimut/engine/trash.py
@@ -292,6 +292,15 @@ def purge(case: Case, group_id: str) -> None:
raise CaseError(f"trash group '{group_id}' not found")
_drop_dir(case, group_id)
case.remove_trash_group(group_id)
+ # Gone for good now: the redirects to these entities and the merges they took
+ # in go with them, as they would have with a case that never held them.
+ gone = [
+ str(entity["id"])
+ for entity in (group.get("payload") or {}).get("entities") or []
+ if entity.get("id")
+ ]
+ if gone:
+ case.forget_merges_of(gone)
inspectwork.forget_legacy(case)
diff --git a/src/azimut/layout.py b/src/azimut/layout.py
index 6e29d16..7172e67 100644
--- a/src/azimut/layout.py
+++ b/src/azimut/layout.py
@@ -499,6 +499,11 @@ def collage_rel(name: str) -> str:
return f"{COLLAGE_DIR}/{name}.json"
+def collage_thumb_rel(name: str) -> str:
+ """The preview the collage list shows, drawn by the browser from the open layout."""
+ return f"{COLLAGE_DIR}/{name}.webp"
+
+
def compare_session_rel(name: str) -> str:
return f"{COMPARE_DIR}/{name}.json"
diff --git a/src/azimut/repository.py b/src/azimut/repository.py
index 667e335..1ca3ee6 100644
--- a/src/azimut/repository.py
+++ b/src/azimut/repository.py
@@ -59,6 +59,7 @@ class CaseRepository(Protocol):
attr_value: str | None = None,
linked: str | None = None,
unlinked: bool = False,
+ lacks: list[str] | None = None,
since: str | None = None,
until: str | None = None,
filed_by: list[str] | None = None,
@@ -66,6 +67,7 @@ class CaseRepository(Protocol):
temporal_until: str | None = None,
temporal_categories: list[str] | None = None,
order: str = "",
+ count_by_type: bool = False,
) -> dict[str, Any]:
"""A bounded, filtered slice of the catalog (Step 5, "Bounded loading").
@@ -86,7 +88,17 @@ class CaseRepository(Protocol):
``total`` counts the whole filtered set, so the narrowing terms answer a
question rather than only shortening a list: *how many videos have
- coordinates* is that number, and the page is which ones.
+ coordinates* is that number, and the page is which ones. ``count_by_type``
+ adds ``by_type``, the same count split per type.
+ """
+ ...
+
+ def event_summaries(self, entity_ids: list[str], *, buckets: int = 12) -> dict[str, Any]:
+ """Per entity: how many Claims name it, when the dated ones fall, and how many
+ sources and places they reach, with ``buckets`` counts over one shared range.
+
+ ``{"range": {"from", "to"} | None, "rows": {id: {events, first, last,
+ sources, places, buckets}}}``.
"""
...
@@ -178,6 +190,7 @@ class CaseRepository(Protocol):
attr_value: str | None = None,
linked: str | None = None,
unlinked_only: bool = False,
+ lacks: list[str] | None = None,
since: str | None = None,
until: str | None = None,
filed_by: list[str] | None = None,
@@ -603,6 +616,57 @@ class CaseRepository(Protocol):
whose two endpoints still exist."""
...
+ # -- merges and redirects ----------------------------------------------
+
+ def merge_entities(
+ self,
+ survivor_id: str,
+ merged_id: str,
+ *,
+ survivor_attrs: dict[str, Any],
+ survivor_status: str,
+ old_key: str | None,
+ by: str,
+ dry_run: bool = False,
+ ) -> dict[str, Any]:
+ """Fold one entity into another in one transaction (``store/merges.py``)."""
+ ...
+
+ def unmerge(self, merge_id: str) -> dict[str, Any]:
+ """Take one merge back out, reporting what could not come back."""
+ ...
+
+ def pending_merge_work(self) -> list[dict[str, Any]]:
+ ...
+
+ def finish_merge_work(self, merge_id: str) -> None:
+ ...
+
+ def get_merge(self, merge_id: str) -> dict[str, Any] | None:
+ ...
+
+ def merges_into(self, survivor_id: str) -> list[dict[str, Any]]:
+ ...
+
+ def set_merge_sheets(self, merge_id: str, sheets: list[dict[str, Any]]) -> None:
+ ...
+
+ def entity_redirects(self, ids: list[str] | None = None) -> dict[str, dict[str, str]]:
+ """Where absorbed ids now answer, ``{old: {id, label}}``."""
+ ...
+
+ def redirect_by_key(self, key: str) -> str | None:
+ ...
+
+ def dangling_redirects(self, keep: set[str]) -> list[dict[str, str]]:
+ ...
+
+ def drop_redirects(self, old_ids: list[str]) -> int:
+ ...
+
+ def forget_merges_of(self, entity_ids: list[str]) -> None:
+ ...
+
# -- durable jobs ------------------------------------------------------
#
# Local background work (thumbnails today; EXIF, OCR, transcripts later) that
diff --git a/src/azimut/sqlite_backend.py b/src/azimut/sqlite_backend.py
index 9601775..7974da6 100644
--- a/src/azimut/sqlite_backend.py
+++ b/src/azimut/sqlite_backend.py
@@ -31,9 +31,11 @@ from typing import TYPE_CHECKING, Any, Callable, Iterator, TypeVar
from .engine import links as link_engine
from .engine import timeline as timeline_engine
+from .engine.textfold import fold_text
from . import layout
from .repository import EntityStatus
from .store.cursors import (
+ _COUNTED_ORDERS,
_PAGE_ORDERS,
_page_cursor,
_parse_timeline_cursor,
@@ -42,16 +44,21 @@ from .store.cursors import (
_timeline_phase_cursor,
)
from .store.filters import (
+ LACKS,
MAX_ATTR_VALUES,
_entity_filters,
_facet_value,
_holds_number,
_link_scope,
_linked_at_all,
+ lacking,
)
+from .store import merges as merge_store
from .store.migrations import _SQLITE_MIGRATIONS
from .store.rows import (
+ _FROM_ABOVE_FILE_SQL,
_PRODUCED_HERE_SQL,
+ _PRODUCED_HERE_ROW_SQL,
_MEDIA_CATEGORIES,
_MEDIA_CATEGORY_SQL,
_entity_search_text,
@@ -122,7 +129,13 @@ if TYPE_CHECKING:
# Schema 18 rebuilds it again, now that a proof's stated date is projected as a
# statement: proofs dated before the projection could read them still reach the
# Timeline, without re-saving each one.
-SQLITE_SCHEMA = 18
+# Schema 19 rebuilds both search indexes folded (`engine/textfold.py`): a search
+# finds a label whatever accents, stress marks or Arabic and Hebrew vowels it was
+# written with, and a term is folded the same way as it is typed. It also adds the
+# two tables a merge writes (`engine/merge.py`): `entity_redirects`, so an id that was
+# absorbed still answers with the entity that took it in, and `entity_merges`, the
+# record that undoes one.
+SQLITE_SCHEMA = 19
_SCHEMA = """
CREATE TABLE meta (
@@ -273,8 +286,36 @@ CREATE TABLE temporal_items (
sortable INTEGER NOT NULL DEFAULT 0 CHECK (sortable IN (0, 1)),
status TEXT,
confidence TEXT,
- parse_error TEXT
+ parse_error TEXT,
+ tz TEXT
);
+-- An id a merge absorbed, and the entity that took it in. Chains are compressed as
+-- they are written, so an old id always names a survivor in one step. No foreign
+-- key: the survivor may be in the Trash, and its restore must find the redirect.
+-- `old_key` is the coordinate key a merged place was found by, so enrichment does
+-- not file the same point again as a new place.
+CREATE TABLE entity_redirects (
+ old_id TEXT PRIMARY KEY,
+ new_id TEXT NOT NULL,
+ old_label TEXT NOT NULL,
+ old_key TEXT,
+ merge_id TEXT,
+ at TEXT NOT NULL
+);
+CREATE INDEX idx_entity_redirects_new ON entity_redirects(new_id);
+CREATE INDEX idx_entity_redirects_key ON entity_redirects(old_key) WHERE old_key IS NOT NULL;
+-- One merge, and everything needed to undo it. Local state, like the Trash: a
+-- bundle leaves these behind, and after an import the merge is final.
+CREATE TABLE entity_merges (
+ id TEXT PRIMARY KEY,
+ survivor_id TEXT NOT NULL,
+ merged_id TEXT NOT NULL,
+ merged_label TEXT NOT NULL,
+ at TEXT NOT NULL,
+ by TEXT NOT NULL,
+ payload_json TEXT NOT NULL
+);
+CREATE INDEX idx_entity_merges_survivor ON entity_merges(survivor_id);
CREATE INDEX idx_entities_type ON entities(type);
CREATE INDEX idx_entities_status ON entities(prov_status);
CREATE INDEX idx_entities_folder ON entities(folder);
@@ -405,6 +446,28 @@ class SqliteCase:
)
if version < SQLITE_SCHEMA:
store._upgrade()
+ if version == 19:
+ # Development cases may already carry an earlier cut of the unshipped 19.
+ with store._connect() as conn:
+ merges_missing = conn.execute("SELECT 1 FROM sqlite_master WHERE name = 'entity_merges'").fetchone() is None
+ zones_missing = "tz" not in {
+ col["name"] for col in conn.execute("PRAGMA table_info(temporal_items)").fetchall()
+ }
+ if merges_missing or zones_missing:
+ from .store.migrations import _MERGE_TABLES, _add_temporal_zones
+ with store._connect() as conn:
+ conn.execute("BEGIN IMMEDIATE")
+ try:
+ if merges_missing:
+ for statement in _MERGE_TABLES.split(";"):
+ if statement.strip():
+ conn.execute(statement)
+ if zones_missing:
+ _add_temporal_zones(conn)
+ conn.execute("COMMIT")
+ except BaseException:
+ conn.execute("ROLLBACK")
+ raise
if media_dir is not None:
store._ensure_media_index(media_dir)
return store
@@ -789,6 +852,7 @@ class SqliteCase:
attr_value: str | None = None,
linked: str | None = None,
unlinked_only: bool = False,
+ lacks: list[str] | None = None,
since: str | None = None,
until: str | None = None,
filed_by: list[str] | None = None,
@@ -829,6 +893,7 @@ class SqliteCase:
types=types, exclude_types=exclude_types, status=status, query=query,
folder=folder, unfiled=unfiled, recursive=recursive,
attr=attr, attr_value=attr_value, linked=linked, unlinked=unlinked_only,
+ lacks=lacks,
since=since, until=until, filed_by=filed_by,
temporal_since=temporal_since, temporal_until=temporal_until,
temporal_categories=temporal_categories,
@@ -1237,6 +1302,7 @@ class SqliteCase:
attr_value: str | None = None,
linked: str | None = None,
unlinked: bool = False,
+ lacks: list[str] | None = None,
since: str | None = None,
until: str | None = None,
filed_by: list[str] | None = None,
@@ -1244,6 +1310,7 @@ class SqliteCase:
temporal_until: str | None = None,
temporal_categories: list[str] | None = None,
order: str = "",
+ count_by_type: bool = False,
) -> dict[str, Any]:
"""A bounded, cursor-paginated slice of entities, in insertion order or sorted.
@@ -1266,25 +1333,40 @@ class SqliteCase:
``total`` counts every row matching the same terms, which is what makes the
narrowing terms answer a question rather than only shorten a list: *how many
- videos have coordinates* is that number.
+ videos have coordinates* is that number. ``count_by_type`` adds ``by_type``,
+ the same count split per type, which is what lets the Board say how much of
+ the answer each of its groups holds without asking once per group.
"""
- if order and order not in _PAGE_ORDERS:
+ orders = {**_PAGE_ORDERS, **_COUNTED_ORDERS}
+ if order and order not in orders:
raise CaseError(f"'{order}' is not an ordering")
+ if order in _COUNTED_ORDERS and not types:
+ raise CaseError(f"'{order}' orders a set of types, not the whole case")
filter_clause, filter_params = _entity_filters(
types=types, status=status, query=query,
folder=folder, unfiled=unfiled, recursive=recursive,
attr=attr, attr_value=attr_value, linked=linked, unlinked=unlinked,
+ lacks=lacks,
since=since, until=until, filed_by=filed_by,
temporal_since=temporal_since, temporal_until=temporal_until,
temporal_categories=temporal_categories,
)
clause, params = filter_clause, list(filter_params)
sort_key = ""
+ computed = ""
if order:
- expression, sort_key, descending = _PAGE_ORDERS[order]
+ expression, sort_key, descending = orders[order]
way = "<" if descending else ">"
+ if sort_key == "_sort":
+ computed = f", {expression} AS _sort"
if cursor is not None:
- seat, key = _page_cursor(cursor)
+ seat, raw_key = _page_cursor(cursor)
+ key: Any = raw_key
+ if order in _COUNTED_ORDERS:
+ try:
+ key = int(raw_key)
+ except ValueError:
+ raise CaseError(f"invalid cursor '{cursor}'") from None
joiner = " AND " if clause else " WHERE "
clause = (
f"{clause}{joiner}({expression} {way} ?"
@@ -1308,10 +1390,22 @@ class SqliteCase:
).fetchone()[0]
)
rows = conn.execute(
- f"SELECT rowid AS _rowid, * FROM entities{clause}"
+ f"SELECT rowid AS _rowid, *{computed} FROM entities{clause}"
f" ORDER BY {ordering} LIMIT ?",
params,
).fetchall()
+ by_type = (
+ {
+ r["type"]: int(r["n"])
+ for r in conn.execute(
+ f"SELECT type, COUNT(*) AS n FROM entities{filter_clause}"
+ " GROUP BY type",
+ filter_params,
+ )
+ }
+ if count_by_type
+ else None
+ )
has_more = len(rows) > limit
rows = rows[:limit]
next_cursor = None
@@ -1320,11 +1414,109 @@ class SqliteCase:
next_cursor = (
f"{tail['_rowid']}:{tail[sort_key]}" if sort_key else str(tail["_rowid"])
)
- return {
+ page: dict[str, Any] = {
"items": [self._entity(r) for r in rows],
"next_cursor": next_cursor,
"total": total,
}
+ if by_type is not None:
+ page["by_type"] = by_type
+ return page
+
+ def event_summaries(self, entity_ids: list[str], *, buckets: int = 12) -> dict[str, Any]:
+ """What the case's Claims say about each of these entities, in a few grouped reads.
+
+ Per id: how many Claims name it (``events``, through ``about``, ``at`` or
+ ``cites``), the first and last instant the dated ones cover, how many distinct
+ sources those Claims cite and how many places they put it at, and ``buckets``
+ counts of their midpoints across ``range``.
+
+ **One range for every row**, the case's own span of dated Claims, so a column
+ of these reads as *when each one was active* rather than as twelve shapes that
+ cannot be compared. Undated Claims count as events and draw nothing.
+
+ Bounded by the ids asked for, which the route caps at a page: the Board asks
+ once per page, never once per row.
+ """
+ ids = list(dict.fromkeys(entity_ids))
+ if not ids:
+ return {"range": None, "rows": {}}
+ marks = ",".join("?" for _ in ids)
+ named = (
+ "WITH named(eid, cid) AS ("
+ " SELECT DISTINCT n.to_id, n.from_id FROM links n"
+ " JOIN entities c ON c.id = n.from_id"
+ f" WHERE n.to_id IN ({marks}) AND c.type = 'claim'"
+ " AND n.type IN ('about', 'at', 'cites'))"
+ )
+ dated = (
+ " FROM named JOIN temporal_items t ON t.owner_id = named.cid"
+ " WHERE t.category = 'statement' AND t.sortable = 1"
+ " AND t.earliest IS NOT NULL AND t.latest IS NOT NULL"
+ )
+ rows: dict[str, dict[str, Any]] = {
+ one: {
+ "events": 0, "first": None, "last": None,
+ "sources": 0, "places": 0, "buckets": [0] * buckets,
+ }
+ for one in ids
+ }
+ with self._connect() as conn:
+ span = conn.execute(
+ "SELECT MIN(earliest) AS lo, MAX(latest) AS hi,"
+ " MIN(julianday(earliest)) AS jlo, MAX(julianday(latest)) AS jhi"
+ " FROM temporal_items WHERE category = 'statement' AND sortable = 1"
+ " AND earliest IS NOT NULL AND latest IS NOT NULL"
+ " AND owner_id IN (SELECT id FROM entities WHERE type = 'claim')"
+ ).fetchone()
+ for r in conn.execute(
+ f"{named} SELECT eid, COUNT(*) AS n FROM named GROUP BY eid", ids
+ ):
+ rows[r["eid"]]["events"] = int(r["n"])
+ for r in conn.execute(
+ f"{named} SELECT named.eid AS eid, MIN(t.earliest) AS first,"
+ f" MAX(t.latest) AS last{dated} GROUP BY named.eid",
+ ids,
+ ):
+ rows[r["eid"]]["first"] = r["first"]
+ rows[r["eid"]]["last"] = r["last"]
+ for r in conn.execute(
+ f"{named} SELECT named.eid AS eid, COUNT(DISTINCT s.to_id) AS n FROM named"
+ " JOIN links s ON s.from_id = named.cid AND s.type = 'cites'"
+ " AND s.to_id != named.eid GROUP BY named.eid",
+ ids,
+ ):
+ rows[r["eid"]]["sources"] = int(r["n"])
+ # A place is reached two ways: a Claim that puts the entity at it, and a
+ # relation the entity states itself (`located-at`, `sited-at`). One count,
+ # distinct, so a place reached both ways is one place.
+ for r in conn.execute(
+ f"{named}, reached(eid, pid) AS ("
+ " SELECT named.eid, a.to_id FROM named"
+ " JOIN links a ON a.from_id = named.cid AND a.type = 'at'"
+ " AND a.to_id != named.eid"
+ " UNION"
+ " SELECT d.from_id, d.to_id FROM links d JOIN entities p ON p.id = d.to_id"
+ f" WHERE d.from_id IN ({marks}) AND p.type = 'place')"
+ " SELECT eid, COUNT(DISTINCT pid) AS n FROM reached GROUP BY eid",
+ [*ids, *ids],
+ ):
+ rows[r["eid"]]["places"] = int(r["n"])
+ low, high = span["jlo"], span["jhi"]
+ if low is not None and high is not None:
+ width = max(high - low, 1e-9)
+ for r in conn.execute(
+ f"{named} SELECT named.eid AS eid, MIN(?, MAX(0, CAST("
+ " ((julianday(t.earliest) + julianday(t.latest)) / 2 - ?) / ? * ?"
+ f" AS INTEGER))) AS bucket, COUNT(*) AS n{dated}"
+ " GROUP BY named.eid, bucket",
+ [*ids, buckets - 1, low, width, buckets],
+ ):
+ rows[r["eid"]]["buckets"][int(r["bucket"])] = int(r["n"])
+ timespan = (
+ {"from": span["lo"], "to": span["hi"]} if span["lo"] is not None else None
+ )
+ return {"range": timespan, "rows": rows}
def catalog_summary(self) -> dict[str, Any]:
"""Total plus per-type, per-status, per-folder and per-filer counts in grouped
@@ -1405,6 +1597,17 @@ class SqliteCase:
(link_engine.ABOUT,),
).fetchone()[0]
)
+ # What the Claims are missing, priced for the same reason `unlinked` is:
+ # the Board offers "No source" and "Not assessed" as standing questions,
+ # and a question that says how many it would answer is one worth asking.
+ lacks = {
+ what: int(
+ conn.execute(
+ f"SELECT COUNT(*) FROM entities e WHERE {predicate.format(alias='e')}"
+ ).fetchone()[0]
+ )
+ for what, predicate in LACKS.items()
+ }
return {
"total": total,
"by_type": by_type,
@@ -1414,6 +1617,7 @@ class SqliteCase:
"linked_to": linked_to,
"unlinked": unlinked,
"countable": countable,
+ "lacks": lacks,
}
def attr_facets(
@@ -2024,7 +2228,7 @@ class SqliteCase:
base_params.append(folder)
else:
base_where.append("folder IS NULL")
- for term in (q or "").casefold().split():
+ for term in fold_text(q or "").split():
base_where.append("search_text LIKE ? ESCAPE '\\'")
base_params.append(_like_contains(term))
@@ -2166,6 +2370,20 @@ class SqliteCase:
" AND temporal_link.type IN ('about', 'at', 'cites')))"
)
params.extend((entity_id, entity_id))
+ # A proof's date is stated for the footage it rests on, as a Claim about that
+ # footage which cites the proof (`api/proofs.py`, `_date_the_material`). While
+ # that Claim still says the proof's date, the proof's own row is the same date
+ # a second time, so it is the Claim alone that is drawn and counted. A proof
+ # with no collected footage under it has no such Claim and keeps its row.
+ where.append(
+ "NOT (t.category = 'statement' AND t.kind = 'taken' AND EXISTS ("
+ "SELECT 1 FROM links proof_date"
+ " JOIN temporal_items stated ON stated.owner_id = proof_date.from_id"
+ " WHERE proof_date.to_id = t.owner_id AND proof_date.type = 'cites'"
+ " AND stated.kind = 'claim' AND stated.time_role = 'observed'"
+ # The same day in another zone is another span, so both are drawn.
+ " AND stated.raw = t.raw AND stated.tz IS t.tz))"
+ )
query: dict[str, Any] = track if isinstance(track, dict) else {}
roles = [
value for value in query.get("roles", [])
@@ -2210,6 +2428,7 @@ class SqliteCase:
attr_value=term("value") or None,
linked=term("linked") or None,
unlinked=term("unlinked").lower() == "true",
+ lacks=lacking(term("lacks")),
since=term("since") or None,
until=term("until") or None,
filed_by=filed_by or None,
@@ -2244,6 +2463,30 @@ class SqliteCase:
" WHERE track_link.from_id = t.owner_id AND track_link.type = ?)"
)
params.append(connector)
+ if query.get("collected_only") is True:
+ # The Media Library's switch, on a track: the files the case produced
+ # itself stay off it. The one a reading is focused on shows whatever made
+ # it, or opening a frame's own dates would land on an empty axis.
+ held = f"NOT {_PRODUCED_HERE_ROW_SQL}"
+ if entity_id:
+ held = f"(t.owner_id = ? OR {held})"
+ params.append(entity_id)
+ where.append(held)
+ as_files = query.get("as_files")
+ if as_files in {"sources", "imagery"}:
+ # A file lane holds the events about a file or citing it. The sources'
+ # pictures and videos (and what Inspect cut from them) are one lane; what
+ # the app pictured from above, Compare and Detect among it, is the other.
+ kind = (
+ _FROM_ABOVE_FILE_SQL if as_files == "imagery"
+ else f"(file.type = 'media' AND NOT {_FROM_ABOVE_FILE_SQL})"
+ )
+ where.append(
+ "EXISTS (SELECT 1 FROM links file_link"
+ " JOIN entities file ON file.id = file_link.to_id"
+ " WHERE file_link.from_id = t.owner_id"
+ f" AND file_link.type IN ('about', 'cites') AND {kind})"
+ )
hidden_raw: list[Any] = (
query["hidden"] if isinstance(query.get("hidden"), list) else []
)
@@ -2274,11 +2517,13 @@ class SqliteCase:
"uncertain": bool(row["uncertain"]),
"approximate": bool(row["approximate"]),
"zone": row["zone"],
+ "tz": row["tz"],
"sortable": bool(row["sortable"]),
"status": row["status"],
"confidence": row["confidence"],
"parse_error": row["parse_error"],
"owner_type": row["owner_type"],
+ "produced_here": bool(row["produced_here"]),
"subjects": [entry["id"] for entry in joined.get("about", [])],
"places": [entry["id"] for entry in joined.get("at", [])],
"sources": [entry["id"] for entry in joined.get("cites", [])],
@@ -2391,7 +2636,8 @@ class SqliteCase:
"WITH ranked AS (SELECT t.id AS ranked_id,"
f" ROW_NUMBER() OVER (ORDER BY {group_sql}, {stamp_sql}, t.id) - 1 AS rn"
f" FROM temporal_items t{clause})"
- " SELECT t.*, e.label, e.type AS owner_type FROM ranked"
+ " SELECT t.*, e.label, e.type AS owner_type,"
+ f" {_PRODUCED_HERE_ROW_SQL} AS produced_here FROM ranked"
" JOIN temporal_items t ON t.id = ranked.ranked_id"
" JOIN entities e ON e.id = t.owner_id"
" WHERE ranked.rn % ? = ? ORDER BY ranked.rn LIMIT ?",
@@ -2399,7 +2645,8 @@ class SqliteCase:
).fetchall()
else:
rows = conn.execute(
- "SELECT t.*, e.label, e.type AS owner_type FROM temporal_items t"
+ "SELECT t.*, e.label, e.type AS owner_type,"
+ f" {_PRODUCED_HERE_ROW_SQL} AS produced_here FROM temporal_items t"
" JOIN entities e ON e.id = t.owner_id"
f"{clause} ORDER BY {group_sql}, {stamp_sql}, t.id LIMIT ?",
(*params, limit + 1),
@@ -2580,7 +2827,13 @@ class SqliteCase:
if key in patch:
entity[key] = patch[key]
if "attrs" in patch:
- entity["attrs"].update(patch["attrs"])
+ # Remove retained fields explicitly. Ordinary nulls remain tombstones:
+ # file editors use their presence to override older sidecar values.
+ for key, value in patch["attrs"].items():
+ if value is None and (key == "_retained_fields" or key in (entity["attrs"].get("_retained_fields") or {})):
+ entity["attrs"].pop(key, None)
+ else:
+ entity["attrs"][key] = value
if patch.get("status") in ("confirmed", "suggested"):
entity["provenance"]["status"] = patch["status"]
conn.execute(
@@ -3109,6 +3362,213 @@ class SqliteCase:
"size_bytes": int(row["size"]),
}
+ # -- merges and redirects (store/merges.py) ------------------------------
+
+ def merge_entities(
+ self,
+ survivor_id: str,
+ merged_id: str,
+ *,
+ survivor_attrs: dict[str, Any],
+ survivor_status: str,
+ old_key: str | None,
+ by: str,
+ dry_run: bool = False,
+ ) -> dict[str, Any]:
+ """Fold one entity into another in one transaction, or report what it would do.
+
+ A dry run is the same transaction rolled back at its end, so a preview cannot
+ say anything the merge would not do.
+ """
+ merge_id = _new_id("m")
+
+ def op(conn: sqlite3.Connection) -> dict[str, Any]:
+ conn.execute("SAVEPOINT merge_attempt")
+ try:
+ report = merge_store.merge_rows(
+ conn,
+ survivor_id=survivor_id,
+ merged_id=merged_id,
+ survivor_attrs=survivor_attrs,
+ survivor_status=survivor_status,
+ old_key=old_key,
+ merge_id=merge_id,
+ by=by,
+ at=_now(),
+ entity_row=self._entity,
+ link_row=self._link,
+ sync_temporal=_sync_entity_temporal,
+ search_text=_entity_search_text,
+ folder_of=_folder_of,
+ )
+ if dry_run:
+ raise merge_store.DryRun(report)
+ self._touch(conn)
+ conn.execute("RELEASE merge_attempt")
+ return report
+ except BaseException:
+ conn.execute("ROLLBACK TO merge_attempt")
+ conn.execute("RELEASE merge_attempt")
+ raise
+
+ try:
+ return self._write(op)
+ except merge_store.DryRun as preview:
+ if not dry_run:
+ raise CaseError("merge refused: " + "; ".join(link.get("reason", "invalid relation") for link in preview.report["refused"])) from preview
+ return preview.report
+
+ def unmerge(self, merge_id: str) -> dict[str, Any]:
+ """Take one merge back out, saying what could not come back."""
+
+ def op(conn: sqlite3.Connection) -> dict[str, Any]:
+ result = merge_store.unmerge_rows(
+ conn,
+ merge_id,
+ entity_row=self._entity,
+ sync_temporal=_sync_entity_temporal,
+ search_text=_entity_search_text,
+ folder_of=_folder_of,
+ ensure_primary=self._ensure_entity_image_primary,
+ )
+ self._touch(conn)
+ return result
+
+ return self._write(op)
+
+ def get_merge(self, merge_id: str) -> dict[str, Any] | None:
+ with self._connect() as conn:
+ row = conn.execute("SELECT * FROM entity_merges WHERE id = ?", (merge_id,)).fetchone()
+ return self._merge(row, payload=True) if row is not None else None
+
+ def merges_into(self, survivor_id: str) -> list[dict[str, Any]]:
+ """The merges this entity took in, newest first, without their payloads."""
+ with self._connect() as conn:
+ rows = conn.execute(
+ "SELECT * FROM entity_merges WHERE survivor_id = ? OR survivor_id IN"
+ " (SELECT old_id FROM entity_redirects WHERE new_id = ?) ORDER BY rowid DESC",
+ (survivor_id, survivor_id),
+ ).fetchall()
+ return [self._merge(row, payload=False) for row in rows]
+
+ def set_merge_sheets(self, merge_id: str, sheets: list[dict[str, Any]]) -> None:
+ """Record the sheet cells a merge rewrote on disk, once they are written."""
+
+ def op(conn: sqlite3.Connection) -> None:
+ row = conn.execute(
+ "SELECT payload_json FROM entity_merges WHERE id = ?", (merge_id,)
+ ).fetchone()
+ if row is None:
+ return
+ payload = json.loads(row["payload_json"])
+ payload["sheets"] = sheets
+ payload["pending_sheets"] = True
+ conn.execute(
+ "UPDATE entity_merges SET payload_json = ? WHERE id = ?",
+ (json.dumps(payload, ensure_ascii=False), merge_id),
+ )
+
+ self._write(op)
+
+ def pending_merge_work(self) -> list[dict[str, Any]]:
+ with self._connect() as conn:
+ rows = conn.execute("SELECT * FROM entity_merges ORDER BY rowid").fetchall()
+ return [self._merge(row, payload=True) for row in rows if json.loads(row["payload_json"]).get("pending_sheets")]
+
+ def finish_merge_work(self, merge_id: str) -> None:
+ def op(conn: sqlite3.Connection) -> None:
+ row = conn.execute("SELECT payload_json FROM entity_merges WHERE id = ?", (merge_id,)).fetchone()
+ if row is None:
+ return
+ payload = json.loads(row["payload_json"])
+ if payload.get("undo_result"):
+ conn.execute("DELETE FROM entity_merges WHERE id = ?", (merge_id,))
+ else:
+ payload.pop("pending_sheets", None)
+ conn.execute("UPDATE entity_merges SET payload_json = ? WHERE id = ?", (json.dumps(payload, ensure_ascii=False), merge_id))
+ self._write(op)
+
+ @staticmethod
+ def _merge(row: sqlite3.Row, *, payload: bool) -> dict[str, Any]:
+ merge: dict[str, Any] = {
+ "id": row["id"],
+ "survivor_id": row["survivor_id"],
+ "merged_id": row["merged_id"],
+ "merged_label": row["merged_label"],
+ "at": row["at"],
+ "by": row["by"],
+ }
+ if payload:
+ merge["payload"] = json.loads(row["payload_json"])
+ return merge
+
+ def entity_redirects(self, ids: list[str] | None = None) -> dict[str, dict[str, str]]:
+ """Where absorbed ids now answer: ``{old: {id, label}}``, for these ids or all."""
+ with self._connect() as conn:
+ if ids is None:
+ rows = conn.execute(
+ "SELECT old_id, new_id, old_label FROM entity_redirects"
+ " ORDER BY at DESC"
+ ).fetchall()
+ else:
+ rows = []
+ for chunk in _chunks(list(dict.fromkeys(ids))):
+ rows.extend(conn.execute(
+ "SELECT old_id, new_id, old_label FROM entity_redirects"
+ f" WHERE old_id IN ({_marks(chunk)})",
+ chunk,
+ ).fetchall())
+ return {row["old_id"]: {"id": row["new_id"], "label": row["old_label"]} for row in rows}
+
+ def redirect_by_key(self, key: str) -> str | None:
+ """The survivor of a merged place that was found by this coordinate key."""
+ with self._connect() as conn:
+ row = conn.execute(
+ "SELECT new_id FROM entity_redirects WHERE old_key = ? LIMIT 1", (key,)
+ ).fetchone()
+ return row["new_id"] if row is not None else None
+
+ def dangling_redirects(self, keep: set[str]) -> list[dict[str, str]]:
+ """Redirects to an entity neither in the case nor among ``keep`` (the Trash)."""
+ with self._connect() as conn:
+ rows = conn.execute(
+ "SELECT r.old_id, r.new_id, r.old_label FROM entity_redirects r"
+ " LEFT JOIN entities e ON e.id = r.new_id WHERE e.id IS NULL"
+ ).fetchall()
+ return [
+ {"old_id": row["old_id"], "new_id": row["new_id"], "label": row["old_label"]}
+ for row in rows if row["new_id"] not in keep
+ ]
+
+ def drop_redirects(self, old_ids: list[str]) -> int:
+ def op(conn: sqlite3.Connection) -> int:
+ dropped = 0
+ for chunk in _chunks(list(dict.fromkeys(old_ids))):
+ dropped += conn.execute(
+ f"DELETE FROM entity_redirects WHERE old_id IN ({_marks(chunk)})", chunk
+ ).rowcount
+ if dropped:
+ self._touch(conn)
+ return dropped
+
+ return self._write(op)
+
+ def forget_merges_of(self, entity_ids: list[str]) -> None:
+ """An entity gone for good takes the redirects to it and its merge records."""
+
+ def op(conn: sqlite3.Connection) -> None:
+ for chunk in _chunks(list(dict.fromkeys(entity_ids))):
+ conn.execute(
+ f"DELETE FROM entity_merges WHERE survivor_id IN ({_marks(chunk)})"
+ f" OR survivor_id IN (SELECT old_id FROM entity_redirects WHERE new_id IN ({_marks(chunk)}))",
+ [*chunk, *chunk],
+ )
+ conn.execute(
+ f"DELETE FROM entity_redirects WHERE new_id IN ({_marks(chunk)})", chunk
+ )
+
+ self._write(op)
+
def reinsert(
self, entities: list[dict[str, Any]], links: list[dict[str, Any]]
) -> dict[str, int]:
@@ -3148,10 +3608,23 @@ class SqliteCase:
r["id"]
for r in conn.execute("SELECT id FROM entities")
}
+ # An end merged into another entity since the delete is found where it
+ # went: restoring a Claim about an absorbed subject lands on its survivor.
+ redirected = {
+ r["old_id"]: r["new_id"]
+ for r in conn.execute("SELECT old_id, new_id FROM entity_redirects")
+ }
kept = 0
for link in links:
+ link = {
+ **link,
+ "from": redirected.get(link["from"], link["from"]),
+ "to": redirected.get(link["to"], link["to"]),
+ }
if link["from"] not in present or link["to"] not in present:
continue
+ if not merge_store.valid_restored_link(conn, link["from"], link["to"], link["type"]):
+ continue
prov = link.get("provenance") or {}
conn.execute(
"INSERT OR REPLACE INTO links"
diff --git a/src/azimut/store/cursors.py b/src/azimut/store/cursors.py
index 212842a..4903731 100644
--- a/src/azimut/store/cursors.py
+++ b/src/azimut/store/cursors.py
@@ -28,6 +28,16 @@ from ..workspace import CaseError, _parse_cursor
#: entities filed in the same second, or two people with one name — so the rowid
#: breaks it. That is what makes "newest first" an answer about the case rather than
#: about the hundred rows a table happened to have loaded.
+#: How many Claims name an entity through a connector (`about`, `at` or `cites`),
+#: which is what the Board's "Most noted" reads: the subjects the analyst keeps
+#: writing about come first. Correlated on the outer ``entities`` row, and distinct
+#: per Claim, since one Claim placing *and* citing a thing is one event about it.
+EVENTS_SQL = (
+ "(SELECT COUNT(DISTINCT n.from_id) FROM links n JOIN entities c ON c.id = n.from_id"
+ " WHERE n.to_id = entities.id AND c.type = 'claim'"
+ " AND n.type IN ('about', 'at', 'cites'))"
+)
+
_PAGE_ORDERS: dict[str, tuple[str, str, bool]] = {
"label": ("label COLLATE NOCASE", "label", False),
"-label": ("label COLLATE NOCASE", "label", True),
@@ -35,6 +45,18 @@ _PAGE_ORDERS: dict[str, tuple[str, str, bool]] = {
"-created": ("prov_at", "prov_at", True),
}
+#: Orderings computed per row rather than walked off an index, and therefore asked
+#: of a **type set** only, never of the whole case: the Board's "Most noted" orders
+#: one group of subjects, and what it costs is that group's rows, each one an index
+#: search on `links.to_id`. A count has no column to read the key back from, so the
+#: page selects it as `_sort`, and its cursor key is parsed back as a number: SQLite
+#: ranks every integer below every string, so a text key would resume at the wrong
+#: row.
+_COUNTED_ORDERS: dict[str, tuple[str, str, bool]] = {
+ "events": (EVENTS_SQL, "_sort", False),
+ "-events": (EVENTS_SQL, "_sort", True),
+}
+
def _page_cursor(cursor: str) -> tuple[int, str]:
"""An ordered page's cursor: the rowid it stopped on, and that row's sort key.
diff --git a/src/azimut/store/filters.py b/src/azimut/store/filters.py
index b6ab0a5..e0cbf1d 100644
--- a/src/azimut/store/filters.py
+++ b/src/azimut/store/filters.py
@@ -16,6 +16,7 @@ from functools import lru_cache
from typing import Any
from ..engine import timeline as timeline_engine
+from ..engine.textfold import fold_text
from ..workspace import CaseError
from .sql import _like_contains, _like_prefix, _marks
@@ -148,6 +149,29 @@ def _linked_at_all(alias: str) -> str:
f" OR l.to_id = {alias}.id)"
)
+#: What a Claim can be missing, as the catalog asks it. A Claim that cites nothing
+#: rests on the analyst's word alone, and one with no confidence has not been graded.
+#: Both ask of Claims only: a file is its own source, and nothing else is graded.
+LACKS = {
+ "source": (
+ "{alias}.type = 'claim' AND NOT EXISTS (SELECT 1 FROM links l"
+ " WHERE l.from_id = {alias}.id AND l.type = 'cites')"
+ ),
+ "assessment": (
+ # The stored text as `json.dumps` writes it, so no JSON1 is needed: a grade
+ # is always a string, and a null or absent one is not a grade.
+ "{alias}.type = 'claim'"
+ " AND {alias}.attrs_json NOT LIKE '%\"confidence\": \"%'"
+ ),
+}
+
+
+def lacking(raw: str | None) -> list[str] | None:
+ """A comma-separated ``lacks`` parameter as the list the store takes."""
+ parts = [part.strip() for part in (raw or "").split(",") if part.strip()]
+ return list(dict.fromkeys(parts)) or None
+
+
#: The character that sorts after every other, appended to an inclusive upper bound.
#: ``prov_at`` holds a full ISO instant and a date range is asked in days, so
#: ``until='2026-08-10'`` has to reach the whole of that day rather than stopping at
@@ -168,6 +192,7 @@ def _entity_filters(
attr_value: str | None = None,
linked: str | None = None,
unlinked: bool = False,
+ lacks: list[str] | None = None,
since: str | None = None,
until: str | None = None,
filed_by: list[str] | None = None,
@@ -194,6 +219,8 @@ def _entity_filters(
statement being built, because the one-hop test has to correlate to the outer row
and the two callers spell that table differently.
+ ``lacks`` asks what a Claim is missing (``LACKS``): a source, an assessment.
+
``unlinked`` is that sentence's other half — *connected to nothing* — and
``since``/``until``/``filed_by`` are the three terms about how a row got here
rather than about what it says: when it was filed, and by which tool or by hand.
@@ -220,7 +247,7 @@ def _entity_filters(
else:
where.append("folder = ?")
params.append(folder)
- for term in (query or "").casefold().split():
+ for term in fold_text(query or "").split():
where.append("search_text LIKE ? ESCAPE '\\'")
params.append(_like_contains(term))
# A field with no value chosen is not a term: it is the analyst having picked which
@@ -236,6 +263,10 @@ def _entity_filters(
params.extend(bound)
if unlinked:
where.append(f" NOT{_linked_at_all(alias)}")
+ for missing in lacks or ():
+ if missing not in LACKS:
+ raise CaseError(f"unknown lacks term '{missing}'")
+ where.append(LACKS[missing].format(alias=alias))
if since:
where.append("prov_at >= ?")
params.append(since)
diff --git a/src/azimut/store/merges.py b/src/azimut/store/merges.py
new file mode 100644
index 0000000..b677b6f
--- /dev/null
+++ b/src/azimut/store/merges.py
@@ -0,0 +1,532 @@
+"""The database half of a merge, and of its undo (`engine/merge.py` holds the rules).
+
+One merge is one transaction over every table that names an entity by id: links,
+photos, graph positions, saved live views, the redirect that keeps the absorbed id
+answering, and the record that undoes it all. A preview runs the same code and
+rolls it back, so what the dialog shows is what the merge writes.
+
+Nothing on disk is touched here. A sheet's sidecar is the one file that holds ids,
+and `engine/sheets.py` rewrites it once this has committed.
+"""
+
+from __future__ import annotations
+
+import json
+import sqlite3
+from collections.abc import Callable
+from typing import Any
+
+from ..engine import links as link_engine
+from ..engine import entities as entity_engine
+from ..workspace import CaseError
+
+#: The verbs that must not close on themselves (`links._check_relation_cycle`).
+CYCLE_TYPES = (link_engine.PART_OF, link_engine.IN_NETWORK, link_engine.CITES)
+
+EntityRow = Callable[[sqlite3.Row], dict[str, Any]]
+LinkRow = Callable[[sqlite3.Row], dict[str, Any]]
+SyncTemporal = Callable[[sqlite3.Connection, dict[str, Any]], None]
+SearchText = Callable[[str, str, dict[str, Any]], str]
+FolderOf = Callable[[dict[str, Any]], str | None]
+
+
+class DryRun(Exception): # noqa: N818 - control flow, not an error
+ """Raised at the end of a previewed merge, to roll it back with its report."""
+
+ def __init__(self, report: dict[str, Any]) -> None:
+ super().__init__("preview")
+ self.report = report
+
+
+def repoint_row_id(value: str, old: str, new: str) -> str:
+ """A timeline row id (`temporal:<kind>:<owner>[:…]`) moved to another owner.
+
+ By its parts, never by substring: an id that merely contains the old one is a
+ different row.
+ """
+ parts = value.split(":")
+ if len(parts) >= 3 and parts[0] == "temporal" and parts[2] == old:
+ parts[2] = new
+ return ":".join(parts)
+ return value
+
+
+def _moved_list(values: Any, old: str, new: str, *, rows: bool = False) -> tuple[Any, bool]:
+ if not isinstance(values, list):
+ return values, False
+ out: list[Any] = []
+ changed = False
+ for value in values:
+ if not isinstance(value, str):
+ out.append(value)
+ continue
+ moved = repoint_row_id(value, old, new) if rows else (new if value == old else value)
+ changed = changed or moved != value
+ if moved not in out:
+ out.append(moved)
+ return out, changed
+
+
+def rewrite_view_spec(spec: dict[str, Any], old: str, new: str, label: str = "") -> tuple[dict[str, Any], bool]:
+ """A live view's recipe with the absorbed id moved onto the survivor.
+
+ What a live view names by id: the entity a Timeline is scoped to, the rows its
+ tracks pin or hide, and the nodes a Graph leaves out, folds or has placed. A
+ snapshot is never passed here: a frozen reading stays what it was.
+ """
+ out = json.loads(json.dumps(spec))
+ changed = False
+ timeline = out.get("timeline") if isinstance(out.get("timeline"), dict) else None
+ if timeline:
+ scope = timeline.get("entity")
+ if isinstance(scope, dict) and scope.get("id") == old:
+ scope["id"] = new
+ if label:
+ scope["label"] = label
+ changed = True
+ for track in timeline.get("tracks") or []:
+ if not isinstance(track, dict):
+ continue
+ for key in ("hidden", "pinned"):
+ if key not in track:
+ continue
+ track[key], moved = _moved_list(track.get(key), old, new, rows=True)
+ changed = changed or moved
+ graph = out.get("graph") if isinstance(out.get("graph"), dict) else None
+ if graph:
+ if graph.get("root") == old:
+ graph["root"] = new
+ changed = True
+ for key in ("omitted", "collapsed", "kept", "expanded"):
+ if key not in graph:
+ continue
+ graph[key], moved = _moved_list(graph.get(key), old, new)
+ changed = changed or moved
+ put_away = graph.get("putAway")
+ if isinstance(put_away, dict):
+ rewritten: dict[str, list[Any]] = {}
+ for owner, ids in put_away.items():
+ key = new if owner == old else owner
+ values, moved = _moved_list(ids, old, new)
+ changed = changed or moved or key != owner
+ rewritten[key] = list(dict.fromkeys([*rewritten.get(key, []), *values]))
+ graph["putAway"] = rewritten
+ arrangement = graph.get("arrangement")
+ if isinstance(arrangement, list):
+ placed = {item.get("id") for item in arrangement if isinstance(item, dict)}
+ kept: list[Any] = []
+ for item in arrangement:
+ if isinstance(item, dict) and item.get("id") == old:
+ changed = True
+ if new in placed:
+ continue # the survivor's own position wins
+ item = {**item, "id": new}
+ kept.append(item)
+ graph["arrangement"] = kept
+ return out, changed
+
+
+def _reaches(conn: sqlite3.Connection, start: str, target: str, type_: str) -> bool:
+ """Whether `start` leads to `target` along links of one type."""
+ frontier = [start]
+ seen: set[str] = set()
+ while frontier:
+ current = frontier.pop()
+ if current == target:
+ return True
+ if current in seen:
+ continue
+ seen.add(current)
+ frontier.extend(
+ row["to_id"] for row in conn.execute(
+ "SELECT to_id FROM links WHERE from_id = ? AND type = ?", (current, type_)
+ )
+ )
+ return False
+
+
+def merge_rows(
+ conn: sqlite3.Connection,
+ *,
+ survivor_id: str,
+ merged_id: str,
+ survivor_attrs: dict[str, Any],
+ survivor_status: str,
+ old_key: str | None,
+ merge_id: str,
+ by: str,
+ at: str,
+ entity_row: EntityRow,
+ link_row: LinkRow,
+ sync_temporal: SyncTemporal,
+ search_text: SearchText,
+ folder_of: FolderOf,
+) -> dict[str, Any]:
+ """Fold `merged_id` into `survivor_id`, recording how to take it back out."""
+ survivor_row = conn.execute("SELECT * FROM entities WHERE id = ?", (survivor_id,)).fetchone()
+ merged_row = conn.execute("SELECT * FROM entities WHERE id = ?", (merged_id,)).fetchone()
+ if survivor_row is None or merged_row is None:
+ raise CaseError("both entities have to be in the case")
+ survivor = entity_row(survivor_row)
+ merged = entity_row(merged_row)
+ entry = entity_engine.entity_type(survivor["type"])
+ if survivor_id == merged_id or survivor["type"] != merged["type"] or entry is None or entry.family not in {"actor", "asset", "class", "identifier", "place"}:
+ raise CaseError("only two different subjects of the same type can merge")
+
+ moved: list[dict[str, Any]] = []
+ loops: list[dict[str, Any]] = []
+ twins: list[dict[str, Any]] = []
+ refused: list[dict[str, Any]] = []
+ for row in conn.execute(
+ "SELECT * FROM links WHERE from_id = ? OR to_id = ? ORDER BY rowid", (merged_id, merged_id)
+ ).fetchall():
+ start = survivor_id if row["from_id"] == merged_id else row["from_id"]
+ end = survivor_id if row["to_id"] == merged_id else row["to_id"]
+ link = link_row(row)
+ spec = link_engine.relation_type(row["type"])
+ if spec is not None:
+ source = entity_row(conn.execute("SELECT * FROM entities WHERE id = ?", (start,)).fetchone())
+ target = entity_row(conn.execute("SELECT * FROM entities WHERE id = ?", (end,)).fetchone())
+ if source["type"] not in spec.from_types or target["type"] not in spec.to_types:
+ refused.append({**link, "reason": "incompatible endpoints"})
+ continue
+ elif row["type"] not in link_engine.CHAIN_TYPES:
+ refused.append({**link, "reason": "unknown relation"})
+ continue
+ if start == end:
+ loops.append(link)
+ elif conn.execute(
+ "SELECT 1 FROM links WHERE from_id = ? AND to_id = ? AND type = ? AND id != ?"
+ " AND confidence IS ? AND nature IS ? AND prov_status = ? AND prov_by = ? AND prov_source IS ?",
+ (start, end, row["type"], row["id"], row["confidence"], row["nature"], row["prov_status"], row["prov_by"], row["prov_source"]),
+ ).fetchone() is not None:
+ twins.append(link)
+ elif row["type"] in CYCLE_TYPES and _reaches(conn, end, start, row["type"]):
+ refused.append({**link, "reason": "would create a cycle"})
+ continue
+ else:
+ conn.execute(
+ "UPDATE links SET from_id = ?, to_id = ? WHERE id = ?", (start, end, row["id"])
+ )
+ moved.append({"id": row["id"], "from": row["from_id"], "to": row["to_id"], "type": row["type"]})
+ continue
+ conn.execute("DELETE FROM links WHERE id = ?", (row["id"],))
+
+ if refused:
+ raise DryRun({"blocked": True, "refused": refused, "links": {"moved": len(moved), "twins": len(twins), "loops": len(loops), "refused": len(refused)}, "images": {}, "pins": {}, "views": []})
+
+ held_media = {
+ row["media_id"] for row in conn.execute(
+ "SELECT media_id FROM entity_images WHERE entity_id = ? AND media_id IS NOT NULL",
+ (survivor_id,),
+ )
+ }
+ has_primary = conn.execute(
+ "SELECT 1 FROM entity_images WHERE entity_id = ? AND is_primary = 1", (survivor_id,)
+ ).fetchone() is not None
+ position = int(conn.execute(
+ "SELECT COALESCE(MAX(position), -1) FROM entity_images WHERE entity_id = ?", (survivor_id,)
+ ).fetchone()[0]) + 1
+ images_moved: list[dict[str, Any]] = []
+ images_dropped: list[dict[str, Any]] = []
+ for row in conn.execute(
+ "SELECT * FROM entity_images WHERE entity_id = ? ORDER BY position, image_id", (merged_id,)
+ ).fetchall():
+ if row["media_id"] is not None and row["media_id"] in held_media:
+ images_dropped.append(dict(row))
+ continue # the same picture twice; the entity's delete takes this row
+ primary = bool(row["is_primary"]) and not has_primary
+ has_primary = has_primary or primary
+ conn.execute(
+ "UPDATE entity_images SET entity_id = ?, position = ?, is_primary = ?"
+ " WHERE entity_id = ? AND image_id = ?",
+ (survivor_id, position, int(primary), merged_id, row["image_id"]),
+ )
+ images_moved.append({
+ "image_id": row["image_id"], "position": row["position"],
+ "is_primary": bool(row["is_primary"]), "primary_here": primary,
+ })
+ position += 1
+
+ pins: list[dict[str, Any]] = []
+ for row in conn.execute("SELECT * FROM graph_pins WHERE entity_id = ?", (merged_id,)).fetchall():
+ taken = conn.execute(
+ "SELECT 1 FROM graph_pins WHERE entity_id = ? AND lens = ?", (survivor_id, row["lens"])
+ ).fetchone() is not None
+ if not taken:
+ conn.execute(
+ "UPDATE graph_pins SET entity_id = ? WHERE entity_id = ? AND lens = ?",
+ (survivor_id, merged_id, row["lens"]),
+ )
+ pins.append({"lens": row["lens"], "x": row["x"], "y": row["y"], "moved": not taken})
+
+ views: list[dict[str, Any]] = []
+ for row in conn.execute(
+ "SELECT id, name, spec_json FROM analysis_views WHERE mode = 'live' ORDER BY id"
+ ).fetchall():
+ before = json.loads(row["spec_json"])
+ after, changed = rewrite_view_spec(before, merged_id, survivor_id, survivor["label"])
+ if changed:
+ conn.execute(
+ "UPDATE analysis_views SET spec_json = ? WHERE id = ?",
+ (json.dumps(after, ensure_ascii=False), row["id"]),
+ )
+ views.append({"id": row["id"], "name": row["name"], "before": before, "after": after})
+
+ survivor_after = {
+ **survivor,
+ "attrs": survivor_attrs,
+ "provenance": {**survivor["provenance"], "status": survivor_status},
+ }
+ conn.execute(
+ "UPDATE entities SET attrs_json = ?, folder = ?, search_text = ?, prov_status = ?"
+ " WHERE id = ?",
+ (
+ json.dumps(survivor_attrs, ensure_ascii=False),
+ folder_of(survivor_attrs),
+ search_text(survivor["type"], survivor["label"], survivor_attrs),
+ survivor_status,
+ survivor_id,
+ ),
+ )
+ sync_temporal(conn, survivor_after)
+ conn.execute("DELETE FROM links WHERE from_id = ? OR to_id = ?", (merged_id, merged_id))
+ conn.execute("DELETE FROM entities WHERE id = ?", (merged_id,))
+
+ compressed = [
+ row["old_id"] for row in conn.execute(
+ "SELECT old_id FROM entity_redirects WHERE new_id = ?", (merged_id,)
+ )
+ ]
+ conn.execute("UPDATE entity_redirects SET new_id = ? WHERE new_id = ?", (survivor_id, merged_id))
+ conn.execute(
+ "INSERT OR REPLACE INTO entity_redirects(old_id, new_id, old_label, old_key, merge_id, at)"
+ " VALUES(?, ?, ?, ?, ?, ?)",
+ (merged_id, survivor_id, merged["label"], old_key, merge_id, at),
+ )
+
+ payload = {
+ "merged": merged,
+ "links_moved": moved,
+ "links_dropped": [
+ *({"reason": "loop", "link": link} for link in loops),
+ *({"reason": "twin", "link": link} for link in twins),
+ *({"reason": "cycle", "link": link} for link in refused),
+ ],
+ "images_moved": images_moved,
+ "images_dropped": images_dropped,
+ "pins": pins,
+ "views": views,
+ "survivor_before": {"attrs": survivor["attrs"], "status": survivor["provenance"]["status"]},
+ "survivor_after": {"attrs": survivor_attrs, "status": survivor_status},
+ "compressed": compressed,
+ "sheets": [],
+ }
+ conn.execute(
+ "INSERT INTO entity_merges(id, survivor_id, merged_id, merged_label, at, by, payload_json)"
+ " VALUES(?, ?, ?, ?, ?, ?, ?)",
+ (merge_id, survivor_id, merged_id, merged["label"], at, by, json.dumps(payload, ensure_ascii=False)),
+ )
+ return {
+ "merge": merge_id,
+ "survivor": survivor_after,
+ "merged": merged,
+ "links": {"moved": len(moved), "twins": len(twins), "loops": len(loops), "refused": len(refused)},
+ "refused": [link for link in refused],
+ "images": {"moved": len(images_moved), "twins": len(images_dropped)},
+ "pins": {"moved": sum(1 for pin in pins if pin["moved"]), "kept": sum(1 for pin in pins if not pin["moved"])},
+ "views": [view["name"] for view in views],
+ }
+
+
+def unmerge_rows(
+ conn: sqlite3.Connection,
+ merge_id: str,
+ *,
+ entity_row: EntityRow,
+ sync_temporal: SyncTemporal,
+ search_text: SearchText,
+ folder_of: FolderOf,
+ ensure_primary: Callable[[sqlite3.Connection, str], bool],
+) -> dict[str, Any]:
+ """Take one merge back out, as far as the case still allows, saying what could not."""
+ record = conn.execute("SELECT * FROM entity_merges WHERE id = ?", (merge_id,)).fetchone()
+ if record is None:
+ raise CaseError(f"merge '{merge_id}' not found")
+ payload = json.loads(record["payload_json"])
+ if payload.get("undo_result"):
+ return payload["undo_result"]
+ if conn.execute("SELECT 1 FROM entity_merges WHERE rowid > ? AND (survivor_id IN (?, ?) OR merged_id IN (?, ?))", (conn.execute("SELECT rowid FROM entity_merges WHERE id = ?", (merge_id,)).fetchone()[0], record["survivor_id"], record["merged_id"], record["survivor_id"], record["merged_id"])).fetchone():
+ raise CaseError("undo the later merge involving this subject first")
+ survivor_id = record["survivor_id"]
+ merged = payload["merged"]
+ merged_id = merged["id"]
+ survivor_row = conn.execute("SELECT * FROM entities WHERE id = ?", (survivor_id,)).fetchone()
+ if survivor_row is None:
+ raise CaseError("the surviving entity is unavailable; restore it or undo its later merge first")
+ if conn.execute("SELECT 1 FROM entities WHERE id = ?", (merged_id,)).fetchone() is not None:
+ raise CaseError(f"an entity already holds the id '{merged_id}'")
+ survivor = entity_row(survivor_row)
+ lost: list[str] = []
+
+ attrs = merged.get("attrs") or {}
+ prov = merged.get("provenance") or {}
+ conn.execute(
+ "INSERT INTO entities(id, type, label, attrs_json, folder, search_text,"
+ " prov_by, prov_at, prov_status, prov_source) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
+ (
+ merged_id, merged["type"], merged["label"], json.dumps(attrs, ensure_ascii=False),
+ folder_of(attrs), search_text(merged["type"], merged["label"], attrs),
+ prov.get("by", "user"), prov.get("at", record["at"]), prov.get("status", "confirmed"),
+ prov.get("source"),
+ ),
+ )
+ sync_temporal(conn, merged)
+
+ for move in payload.get("links_moved") or []:
+ start = survivor_id if move["from"] == merged_id else move["from"]
+ end = survivor_id if move["to"] == merged_id else move["to"]
+ row = conn.execute("SELECT * FROM links WHERE id = ?", (move["id"],)).fetchone()
+ if row is None or (row["from_id"], row["to_id"]) != (start, end):
+ lost.append(f"a '{move['type']}' relation moved in the merge was changed or removed since")
+ continue
+ if row["type"] != move["type"] or not valid_restored_link(conn, move["from"], move["to"], row["type"]):
+ lost.append(f"a '{move['type']}' relation no longer fits its original endpoints")
+ continue
+ conn.execute(
+ "UPDATE links SET from_id = ?, to_id = ? WHERE id = ?", (move["from"], move["to"], move["id"])
+ )
+ present = {row["id"] for row in conn.execute("SELECT id FROM entities")}
+ for dropped in payload.get("links_dropped") or []:
+ link = dropped["link"]
+ if link["from"] not in present or link["to"] not in present:
+ lost.append(f"a '{link['type']}' relation whose other end is gone")
+ continue
+ if conn.execute("SELECT 1 FROM links WHERE id = ?", (link["id"],)).fetchone() is not None:
+ continue
+ if not valid_restored_link(conn, link["from"], link["to"], link["type"]):
+ lost.append(f"a '{link['type']}' relation no longer fits the case")
+ continue
+ link_prov = link.get("provenance") or {}
+ conn.execute(
+ "INSERT INTO links(id, from_id, to_id, type, prov_by, prov_at, prov_status,"
+ " prov_source, confidence, nature) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
+ (
+ link["id"], link["from"], link["to"], link["type"], link_prov.get("by", "user"),
+ link_prov.get("at", record["at"]), link_prov.get("status", "confirmed"),
+ link_prov.get("source"), link.get("confidence"), link.get("nature"),
+ ),
+ )
+
+ for image in payload.get("images_moved") or []:
+ row = conn.execute(
+ "SELECT 1 FROM entity_images WHERE entity_id = ? AND image_id = ?",
+ (survivor_id, image["image_id"]),
+ ).fetchone()
+ if row is None:
+ lost.append("a photo moved in the merge was removed since")
+ continue
+ if image["is_primary"]:
+ conn.execute(
+ "UPDATE entity_images SET is_primary = 0 WHERE entity_id = ?", (merged_id,)
+ )
+ conn.execute(
+ "UPDATE entity_images SET entity_id = ?, position = ?, is_primary = ?"
+ " WHERE entity_id = ? AND image_id = ?",
+ (merged_id, image["position"], int(image["is_primary"]), survivor_id, image["image_id"]),
+ )
+ for image in payload.get("images_dropped") or []:
+ if image.get("media_id") not in present:
+ lost.append("a photo whose file is no longer in the case")
+ continue
+ conn.execute(
+ "INSERT OR IGNORE INTO entity_images(entity_id, image_id, media_id, path, thumbnail,"
+ " title, position, is_primary) VALUES(?, ?, ?, ?, ?, ?, ?, ?)",
+ (
+ merged_id, image["image_id"], image["media_id"], image.get("path"),
+ image.get("thumbnail"), image.get("title"), image["position"], image["is_primary"],
+ ),
+ )
+ ensure_primary(conn, survivor_id)
+ ensure_primary(conn, merged_id)
+
+ for pin in payload.get("pins") or []:
+ if pin["moved"]:
+ row = conn.execute(
+ "SELECT x, y FROM graph_pins WHERE entity_id = ? AND lens = ?", (survivor_id, pin["lens"])
+ ).fetchone()
+ if row is not None and (row["x"], row["y"]) == (pin["x"], pin["y"]):
+ conn.execute(
+ "DELETE FROM graph_pins WHERE entity_id = ? AND lens = ?", (survivor_id, pin["lens"])
+ )
+ conn.execute(
+ "INSERT OR IGNORE INTO graph_pins(entity_id, lens, x, y) VALUES(?, ?, ?, ?)",
+ (merged_id, pin["lens"], pin["x"], pin["y"]),
+ )
+
+ for view in payload.get("views") or []:
+ row = conn.execute("SELECT spec_json FROM analysis_views WHERE id = ?", (view["id"],)).fetchone()
+ if row is None:
+ lost.append(f"the view “{view['name']}” was removed since")
+ continue
+ if json.loads(row["spec_json"]) != view["after"]:
+ lost.append(f"the view “{view['name']}” was changed since, and keeps the merged entity")
+ continue
+ conn.execute(
+ "UPDATE analysis_views SET spec_json = ? WHERE id = ?",
+ (json.dumps(view["before"], ensure_ascii=False), view["id"]),
+ )
+
+ before = payload["survivor_before"]
+ after = payload["survivor_after"]
+ current = dict(survivor["attrs"])
+ for key in sorted(set(before["attrs"]) | set(after["attrs"])):
+ was, became = before["attrs"].get(key), after["attrs"].get(key)
+ if was == became:
+ continue
+ if current.get(key) != became:
+ lost.append(f"“{survivor['label']}” has its '{key}' changed since, and keeps it")
+ continue
+ if key in before["attrs"]:
+ current[key] = was
+ else:
+ current.pop(key, None)
+ status = survivor["provenance"]["status"]
+ if before["status"] != after["status"] and status == after["status"]:
+ status = before["status"]
+ conn.execute(
+ "UPDATE entities SET attrs_json = ?, folder = ?, search_text = ?, prov_status = ? WHERE id = ?",
+ (
+ json.dumps(current, ensure_ascii=False), folder_of(current),
+ search_text(survivor["type"], survivor["label"], current), status, survivor_id,
+ ),
+ )
+ sync_temporal(conn, {**survivor, "attrs": current, "provenance": {**survivor["provenance"], "status": status}})
+
+ conn.execute("DELETE FROM entity_redirects WHERE old_id = ?", (merged_id,))
+ for old_id in payload.get("compressed") or []:
+ conn.execute(
+ "UPDATE entity_redirects SET new_id = ? WHERE old_id = ? AND new_id = ?",
+ (merged_id, old_id, survivor_id),
+ )
+ result = {
+ "restored": entity_row(conn.execute("SELECT * FROM entities WHERE id = ?", (merged_id,)).fetchone()),
+ "survivor": survivor_id,
+ "lost": lost,
+ "sheets": payload.get("sheets") or [],
+ }
+ payload["undo_result"] = result
+ payload["pending_sheets"] = True
+ conn.execute("UPDATE entity_merges SET payload_json = ? WHERE id = ?", (json.dumps(payload, ensure_ascii=False), merge_id))
+ return result
+
+
+def valid_restored_link(conn: sqlite3.Connection, start: str, end: str, type_: str) -> bool:
+ source = conn.execute("SELECT type FROM entities WHERE id = ?", (start,)).fetchone()
+ target = conn.execute("SELECT type FROM entities WHERE id = ?", (end,)).fetchone()
+ if source is None or target is None or start == end:
+ return False
+ spec = link_engine.relation_type(type_)
+ if spec and (source["type"] not in spec.from_types or target["type"] not in spec.to_types):
+ return False
+ return type_ not in CYCLE_TYPES or not _reaches(conn, end, start, type_)
diff --git a/src/azimut/store/migrations.py b/src/azimut/store/migrations.py
index 9e98635..b3b2034 100644
--- a/src/azimut/store/migrations.py
+++ b/src/azimut/store/migrations.py
@@ -13,7 +13,7 @@ import json
import sqlite3
from typing import Callable
-from .rows import _entity_search_text, _folder_of, _has_gps
+from .rows import _entity_search_text, _folder_of, _has_gps, _media_search_text
from .temporal import _rebuild_temporal_projection_conn
@@ -249,7 +249,10 @@ def _migrate_14_to_15(conn: sqlite3.Connection) -> None:
" uncertain INTEGER NOT NULL DEFAULT 0 CHECK (uncertain IN (0, 1)),"
" approximate INTEGER NOT NULL DEFAULT 0 CHECK (approximate IN (0, 1)),"
" zone TEXT, sortable INTEGER NOT NULL DEFAULT 0 CHECK (sortable IN (0, 1)),"
- " status TEXT, confidence TEXT, parse_error TEXT"
+ " status TEXT, confidence TEXT, parse_error TEXT,"
+ # The rebuilds of later steps write every column the projection has today,
+ # so the table is born with the zone schema 19 added rather than without it.
+ " tz TEXT"
")"
)
conn.execute(
@@ -304,6 +307,73 @@ def _migrate_17_to_18(conn: sqlite3.Connection) -> None:
_rebuild_temporal_projection_conn(conn)
+#: The two tables schema 19 adds for merges, as `sqlite_backend._SCHEMA` declares them.
+#: `IF NOT EXISTS`, so a database a test rewound by its version number alone replays it.
+_MERGE_TABLES = """
+CREATE TABLE IF NOT EXISTS entity_redirects (
+ old_id TEXT PRIMARY KEY,
+ new_id TEXT NOT NULL,
+ old_label TEXT NOT NULL,
+ old_key TEXT,
+ merge_id TEXT,
+ at TEXT NOT NULL
+);
+CREATE INDEX IF NOT EXISTS idx_entity_redirects_new ON entity_redirects(new_id);
+CREATE INDEX IF NOT EXISTS idx_entity_redirects_key ON entity_redirects(old_key) WHERE old_key IS NOT NULL;
+CREATE TABLE IF NOT EXISTS entity_merges (
+ id TEXT PRIMARY KEY,
+ survivor_id TEXT NOT NULL,
+ merged_id TEXT NOT NULL,
+ merged_label TEXT NOT NULL,
+ at TEXT NOT NULL,
+ by TEXT NOT NULL,
+ payload_json TEXT NOT NULL
+);
+CREATE INDEX IF NOT EXISTS idx_entity_merges_survivor ON entity_merges(survivor_id);
+"""
+
+
+def _add_temporal_zones(conn: sqlite3.Connection) -> None:
+ """Give the Time projection the zone each value was stated in, and re-read it.
+
+ A civil date stated in a zone spans that zone's days, so a dated proof's bounds
+ move with the zone its point is in. Nothing stored before carried one, and those
+ rows rebuild exactly as they were; the rebuild is for the column itself. A table
+ born at 15 already has the column, so it is added only where it is missing.
+ """
+ columns = {row["name"] for row in conn.execute("PRAGMA table_info(temporal_items)")}
+ if "tz" not in columns:
+ conn.execute("ALTER TABLE temporal_items ADD COLUMN tz TEXT")
+ _rebuild_temporal_projection_conn(conn)
+
+
+def _migrate_18_to_19(conn: sqlite3.Connection) -> None:
+ """Rebuild both search indexes, folded the way a search term now is, add the
+ two tables a merge writes, and the zone a temporal value was stated in.
+
+ A term is folded as it is typed (``engine/textfold.py``), so an index written
+ before could only be found by the exact accents it holds: ``Cafe`` would reach a
+ new ``Café`` and miss one filed last week. One pass over each table. The merge
+ tables start empty: nothing was merged before they existed.
+ """
+ # One statement at a time: `executescript` commits first, and the upgrade runs
+ # the whole chain in one transaction it owns.
+ for statement in _MERGE_TABLES.split(";"):
+ if statement.strip():
+ conn.execute(statement)
+ for row in conn.execute("SELECT id, type, label, attrs_json FROM entities").fetchall():
+ conn.execute(
+ "UPDATE entities SET search_text = ? WHERE id = ?",
+ (_entity_search_text(row["type"], row["label"], json.loads(row["attrs_json"])), row["id"]),
+ )
+ for row in conn.execute("SELECT path, item_json FROM media_items").fetchall():
+ conn.execute(
+ "UPDATE media_items SET search_text = ? WHERE path = ?",
+ (_media_search_text(json.loads(row["item_json"])), row["path"]),
+ )
+ _add_temporal_zones(conn)
+
+
# from_version -> function(conn) applying the in-place upgrade to from_version + 1.
# The whole chain runs inside one immediate transaction in `SqliteCase._upgrade`,
# which stamps each new schema_version and records each migration as it goes; a
@@ -327,4 +397,5 @@ _SQLITE_MIGRATIONS: dict[int, Callable[[sqlite3.Connection], None]] = {
15: _migrate_15_to_16,
16: _migrate_16_to_17,
17: _migrate_17_to_18,
+ 18: _migrate_18_to_19,
}
diff --git a/src/azimut/store/rows.py b/src/azimut/store/rows.py
index fa6683b..072d357 100644
--- a/src/azimut/store/rows.py
+++ b/src/azimut/store/rows.py
@@ -15,6 +15,7 @@ from typing import Any
from ..engine import entities as entity_engine
from ..engine import links as link_engine
from ..engine import mapsites
+from ..engine.textfold import fold_text
def _folder_of(attrs: dict[str, Any] | None) -> str | None:
@@ -30,13 +31,33 @@ def _entity_search_text(type_: str, label: str, attrs: dict[str, Any] | None) ->
The label, the type, the folder and the notes, plus the type's own declared text
fields (``entities.search_values``): a vehicle is looked for by its plate and a
claim by the words it quotes, and neither was findable while the index stopped
- at the notes. Recomputed on every write, and rebuilt for existing rows by the
- schema-10 migration.
+ at the notes. Folded the way every search term is (``engine/textfold.py``).
+ Recomputed on every write, and rebuilt for existing rows by a migration whenever
+ what goes in changes: the declared fields at schema 9, the fold at 19.
"""
attrs = attrs or {}
fixed = (label, type_, attrs.get("folder"), attrs.get("notes"))
declared = entity_engine.search_values(type_, attrs)
- return "\n".join(str(value) for value in (*fixed, *declared) if value).casefold()
+ return fold_text("\n".join(str(value) for value in (*fixed, *declared) if value))
+
+
+def _media_search_text(item: dict[str, Any]) -> str:
+ """What a Media Library search matches a file against, folded like a term."""
+ source: dict[str, Any] = item["source"] if isinstance(item.get("source"), dict) else {}
+ filename = str(item.get("filename") or Path(str(item.get("path") or "")).name)
+ return fold_text("\n".join(
+ str(value)
+ for value in (
+ filename,
+ item.get("title"),
+ item.get("notes"),
+ item.get("folder"),
+ source.get("title"),
+ source.get("uploader"),
+ source.get("webpage_url") or source.get("url"),
+ )
+ if value
+ ))
def _replace_exact(value: Any, old: str, new: str) -> Any:
@@ -88,6 +109,21 @@ _PRODUCED_HERE_SQL = (
+ ")"
)
+#: The same question asked of a timeline row ``t``: whether its owner is such a file.
+_PRODUCED_HERE_ROW_SQL = (
+ "EXISTS (SELECT 1 FROM media_items produced"
+ f" WHERE produced.entity_id = t.owner_id AND {_PRODUCED_HERE_SQL})"
+)
+
+#: Whether the entity ``file`` pictures the ground from above (`FROM_ABOVE`): a
+#: capture, or a file one of those routes made. The Timeline's two file lanes split on it.
+_FROM_ABOVE_FILE_SQL = (
+ "(file.type = 'capture' OR EXISTS (SELECT 1 FROM media_items above"
+ " WHERE above.entity_id = file.id AND COALESCE(above.source_type, '') IN ("
+ + ", ".join(f"'{route}'" for route in link_engine.FROM_ABOVE)
+ + ")))"
+)
+
def _has_gps(item: dict[str, Any]) -> bool:
"""Whether an indexed media item carries a usable position.
@@ -140,26 +176,13 @@ def _normalise_media_item(item: dict[str, Any]) -> tuple[dict[str, Any], tuple[A
kind = str(clean.get("kind") or "file")
folder = str(clean.get("folder") or "") or None
title = str(clean.get("title") or "")
- notes = str(clean.get("notes") or "")
name_sort = (title or filename).casefold()
try:
size = max(0, int(clean.get("size") or 0))
except (TypeError, ValueError):
size = 0
added_at = str(clean.get("added_at") or "")
- search_text = "\n".join(
- str(value)
- for value in (
- filename,
- title,
- notes,
- folder,
- source.get("title"),
- source.get("uploader"),
- source.get("webpage_url") or source.get("url"),
- )
- if value
- ).casefold()
+ search_text = _media_search_text(clean)
return clean, (
path,
json.dumps(clean, ensure_ascii=False),
diff --git a/src/azimut/store/temporal.py b/src/azimut/store/temporal.py
index ebb126e..4d40b0f 100644
--- a/src/azimut/store/temporal.py
+++ b/src/azimut/store/temporal.py
@@ -17,7 +17,7 @@ from ..engine import timeline as timeline_engine
_TEMPORAL_COLUMNS = (
"id", "owner_id", "authority", "category", "kind", "raw", "earliest",
"latest", "precision", "shape", "time_role", "uncertain", "approximate",
- "zone", "sortable", "status", "confidence", "parse_error",
+ "zone", "sortable", "status", "confidence", "parse_error", "tz",
)
diff --git a/src/azimut/workspace.py b/src/azimut/workspace.py
index 7af3f1e..ff4c400 100644
--- a/src/azimut/workspace.py
+++ b/src/azimut/workspace.py
@@ -399,6 +399,9 @@ class Case(CaseStore):
from .engine import trash as trash_engine
trash_engine.recover(case)
+ from .engine import merge as merge_engine
+
+ merge_engine.recover(case)
return case
def migrate(self) -> dict[str, Any]:
diff --git a/tests/caseworkspace.py b/tests/caseworkspace.py
new file mode 100644
index 0000000..ffb7de1
--- /dev/null
+++ b/tests/caseworkspace.py
@@ -0,0 +1,427 @@
+"""The Case workspace as a 0.3.1 analyst left it, and how that case reads.
+
+`fullcase.py` plants one artifact per tool so the Trash and bundle gates see
+everything a case can own. This builds on it for the other question a rework of
+the Board, Graph and Timeline has to answer: does a case made before the rework
+still read the same after it? So it adds what those three surfaces keep — saved
+readings of every surface, Live and Snapshot, in both Timeline modes, with tracks
+that hide, pin and add Media; dated, undated and unplaced Claims; a kept Detect
+pin and a proof date, which are Claims of their own; Notebook mentions, a promoted
+Sheet row and entity galleries.
+
+`read_workspace` answers what those surfaces show, with ids replaced by
+`type:label` and the moment of the build scrubbed, so the reading of one build can
+be compared with the recorded one (`fixtures/case-workspace-0.3.1.json`).
+"""
+
+from __future__ import annotations
+
+import json
+import re
+from dataclasses import dataclass, field
+from datetime import datetime, timedelta, timezone
+from pathlib import Path
+from typing import Any
+
+from fullcase import FullCase, build_full_case
+
+GOLDEN = Path(__file__).parent / "fixtures" / "case-workspace-0.3.1.json"
+
+#: The window every saved reading looks at, around the dates planted below.
+WINDOW = {"from": "2026-07-01", "to": "2026-09-01"}
+
+
+@dataclass
+class WorkspaceCase:
+ full: FullCase
+ claims: dict[str, str] = field(default_factory=dict) # statement -> id
+ temporal: dict[str, str] = field(default_factory=dict) # statement -> temporal row id
+ views: dict[str, str] = field(default_factory=dict) # name -> id
+ detect_claim: str = ""
+ dated_proof: str = ""
+ promoted: str = ""
+
+
+def _ok(response, what: str) -> dict[str, Any]:
+ assert response.status_code == 200, f"{what}: {response.text}"
+ return response.json()
+
+
+def build_workspace_case(client) -> WorkspaceCase:
+ from azimut.engine import workqueue
+
+ # This fixture represents 0.3.1, before retyping and merge journals existed.
+ full = build_full_case(client, name="Case workspace", subject_changes=False)
+ ws = WorkspaceCase(full=full)
+ case_id = full.case_id
+ base = f"/api/cases/{case_id}"
+ photo = _ok(
+ client.get(f"{base}/entities/lookup", params={"attr": "path", "value": full.photo}),
+ "photo",
+ )["entity"]["id"]
+
+ # -- a photograph that says when its camera took it -----------------------
+ # A file date, on the Media track: the one a rework must stop confusing with
+ # the analyst's. EXIF keeps the camera's clock without an offset, so it is a
+ # reading the UTC axis cannot place.
+ import io
+
+ from PIL import Image
+
+ shot = Image.new("RGB", (64, 48), (90, 110, 130))
+ exif = Image.Exif()
+ exif.get_ifd(0x8769)[36867] = "2026:08:01 13:58:00"
+ buf = io.BytesIO()
+ shot.save(buf, "JPEG", exif=exif)
+ _ok(client.post(f"{base}/media/upload",
+ files={"file": ("harbour.jpg", io.BytesIO(buf.getvalue()), "image/jpeg")}),
+ "dated photo")
+
+ # -- Claims through the Timeline's own endpoint, one per date shape -------
+ def claim(statement: str, **body: Any) -> str:
+ saved = _ok(client.post(f"{base}/timeline/claims", json={"statement": statement, **body}),
+ statement)
+ ws.claims[statement] = saved["entity"]["id"]
+ ws.temporal[statement] = saved["temporal"]["id"]
+ return saved["entity"]["id"]
+
+ claim("Convoy crossed the east bridge", when="2026-08-01T14:05:00Z",
+ time_role="occurred", confidence="certain",
+ about=[full.vessel_id], at=[full.place_id], cites=[photo])
+ claim("Quay 4 warehouse burned", when="2026-07-30/2026-08-02",
+ time_role="occurred", confidence="probable",
+ about=[full.structure_id], at=[full.place_id], cites=[full.bookmark_id])
+ claim("Recruitment announced", when="2026-07", confidence="possible",
+ about=[full.account_id], cites=[full.bookmark_id])
+ claim("Vessel seen leaving around the first", when="2026-08-01~",
+ time_role="observed", about=[full.vessel_id], at=[full.place_id])
+ claim("Night strike on the quay", when="2026-08-03T22:10:00+03:00",
+ confidence="refuted", about=[full.structure_id], at=[full.place_id])
+ claim("Crew list circulated", when="2026-08-05",
+ about=[full.person_id], cites=[full.note_id])
+ # Undated: it is waiting for a date, which is the Overview's "No date yet".
+ claim("Owner changed the flag", about=[full.vessel_id, full.org_id])
+ # Unplaced: a local wall-clock time is a date the axis cannot place in UTC.
+ claim("Harbour master called in", when="2026-08-02T08:30:00",
+ about=[full.person_id])
+ # A suggestion, filed the way an importer files one.
+ suggested = _ok(client.post(f"{base}/entities", json={
+ "type": "claim", "label": "Second convoy suggested", "status": "suggested",
+ "attrs": {"when": "2026-08-06", "confidence": "possible"},
+ }), "suggested claim")["id"]
+ ws.claims["Second convoy suggested"] = suggested
+
+ # -- a proof that states when its material was taken ----------------------
+ import base64
+ from fullcase import _png
+
+ dated = _ok(client.post(f"{base}/proofs", json={
+ "title": "Bridge proof",
+ "png_base64": base64.b64encode(_png(size=(200, 120), color=(30, 90, 60))).decode(),
+ "spec": {
+ "panels": [{"id": "p0", "src": full.piece, "natural": [60, 60]}],
+ "shapes": [], "pastes": [],
+ "when": "2026-07-31T16:20:00Z",
+ },
+ }), "dated proof")
+ ws.dated_proof = dated["name"]
+
+ # -- a kept Detect pin, which dates itself on a Claim at the pin ----------
+ run_id = Path(full.analyzer_run).stem.split("-", 1)[1]
+ run = _ok(client.get(f"{base}/analysis/runs/{run_id}"), "run")
+ assert run["results"], "the full case's run found a candidate to keep"
+ kept = _ok(client.post(
+ f"{base}/analysis/runs/{run_id}/results/{run['results'][0]['id']}/promote",
+ json={"title": "Levelled yard"},
+ ), "kept pin")
+ ws.detect_claim = (kept["claim"] or {}).get("id", "")
+ assert ws.detect_claim, "keeping a dated candidate states when on a Claim"
+
+ # -- a Sheet row promoted into the case ----------------------------------
+ units = _ok(client.post(f"{base}/sheets", json={"title": "Units"}), "units sheet")
+ promoted = _ok(client.post(f"{base}/sheets/{units['id']}/promote", json={
+ "columns": ["id", "Unit", "Notes"],
+ "rows": [["r1", "3rd Harbour Brigade", "seen at the quay"]],
+ "meta": {},
+ "keys": ["r1"],
+ "subject": {"column": "Unit", "type": "organization", "fields": {}, "attach": {},
+ "skip": [], "group": False, "group_label": None},
+ "point": "",
+ "addresses": "",
+ }), "promote")
+ ws.promoted = promoted["meta"]["links"]["r1"]["Unit"]
+
+ # -- Notebook mentions: the running notes and a filed note ----------------
+ _ok(client.put(f"{base}/notes", json={"text": (
+ "# Case workspace\n\n"
+ f"Owner is [[entity:{full.org_id}|Northwind Shipping]], "
+ f"crew named by [[entity:{full.person_id}|A. Nadeau]].\n\n"
+ f"[[media:{full.photo}]]\n"
+ )}), "notes")
+ _ok(client.put(f"{base}/notes/{full.note_id}", json={
+ "text": f"# Witness\n\nSaw [[entity:{full.vessel_id}|MV Aurora]] leave.\n",
+ }), "filed note")
+
+ # -- saved readings: every surface, Live and Snapshot, both Timeline modes --
+ def view(name: str, surface: str, mode: str, spec: dict[str, Any]) -> None:
+ saved = _ok(client.post(f"{base}/analysis-views", json={
+ "name": name, "surface": surface, "mode": mode, "spec": spec,
+ }), name)
+ ws.views[name] = saved["id"]
+
+ ws.views["People in review"] = full.analysis_view_id
+ ws.views["Chronology in review"] = full.timeline_view_id
+ actors = {
+ "query": {
+ "filter": {"families": ["actor"]},
+ "terms": {"type": "person,organization"},
+ "label": "People and organizations",
+ },
+ "board": {"order": "label", "sortKey": "label", "sortDesc": False},
+ }
+ view("Actors frozen", "board", "snapshot", actors)
+ view("Fleet graph", "graph", "live", {
+ "query": {"filter": {"families": ["asset", "actor"]},
+ "terms": {"type": "vessel,organization,structure"}},
+ "graph": {"lens": "all", "hops": 2, "kept": [full.vessel_id],
+ "arrangement": [{"id": full.vessel_id, "x": 40, "y": -12}],
+ "camera": {"x": 10, "y": 20, "zoom": 1.25}},
+ })
+ view("Fleet graph frozen", "graph", "snapshot", {
+ "query": {"filter": {"families": ["asset"]}, "terms": {"type": "vessel,structure"}},
+ "graph": {"lens": "all", "hops": 1},
+ })
+ media_tracks = [
+ {"id": "events", "label": "Events", "categories": ["statement"],
+ "pinned": [ws.temporal["Recruitment announced"]],
+ "hidden": [ws.temporal["Crew list circulated"]]},
+ {"id": "media", "label": "Media", "categories": ["media"], "color": "blue"},
+ {"id": "preset-vessel", "label": "Vessel", "categories": ["statement"],
+ "query": {"relation": "about", "terms": {"type": "vessel"},
+ "filter": {"types": ["vessel"]}}},
+ {"id": "preset-activity", "label": "Case activity", "categories": ["case_activity"],
+ "collapsed": True},
+ ]
+ view("Chronology with media", "timeline", "live", {"timeline": {
+ **WINDOW, "view_mode": "plot", "zone_choice": "zone:Europe/Kyiv",
+ "timezone": "Europe/Kyiv", "tracks": media_tracks,
+ }})
+ view("Chronology as list", "timeline", "live", {"timeline": {
+ **WINDOW, "view_mode": "list", "group_by": "subject", "tracks": media_tracks[:2],
+ }})
+ view("Chronology frozen", "timeline", "snapshot", {"timeline": {
+ **WINDOW, "view_mode": "plot", "tracks": media_tracks[:3],
+ }})
+ view("Chronology list frozen", "timeline", "snapshot", {"timeline": {
+ **WINDOW, "view_mode": "list", "tracks": media_tracks[:1],
+ }})
+ # A Timeline view saved without tracks: the server gave it its default ones.
+ view("Chronology defaults", "timeline", "live", {"timeline": dict(WINDOW)})
+
+ workqueue.wait_until_idle(timeout=20)
+ return ws
+
+
+# -- reading ----------------------------------------------------------------------
+
+#: Written by the build itself, so different on every run and on nobody's screen as
+#: a fact about the case.
+_VOLATILE_KEYS = {
+ "created_at", "updated_at", "captured_at", "reviewed_at", "mtime", "revision",
+ "stamp", "modified", "size", "bytes", "etag", "fetched", "engine_version",
+}
+_ISO = re.compile(
+ r"\d{4}-\d{2}-\d{2}(?:[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})?)?"
+)
+_COMPACT = re.compile(r"(?<!\d)(\d{8})[-_T]?(\d{6})(?!\d)")
+
+
+def _recent(match: str, now: datetime) -> bool:
+ text = match.replace(" ", "T")
+ try:
+ value = datetime.fromisoformat(text.replace("Z", "+00:00"))
+ except ValueError:
+ return False
+ if value.tzinfo is None:
+ value = value.replace(tzinfo=timezone.utc)
+ return abs(now - value) < timedelta(days=2)
+
+
+def _scrub(text: str, names: dict[str, str], now: datetime | None = None) -> str:
+ now = now or datetime.now(timezone.utc)
+ for ident in sorted(names, key=len, reverse=True):
+ if ident in text:
+ text = text.replace(ident, names[ident])
+ text = _ISO.sub(lambda m: "<now>" if _recent(m.group(0), now) else m.group(0), text)
+
+ def compact(m: re.Match[str]) -> str:
+ day, clock = m.group(1), m.group(2)
+ stamp = f"{day[:4]}-{day[4:6]}-{day[6:]}T{clock[:2]}:{clock[2:4]}:{clock[4:]}"
+ return "<now>" if _recent(stamp, now) else m.group(0)
+
+ return _COMPACT.sub(compact, text)
+
+
+def _normal(value: Any, names: dict[str, str], now: datetime) -> Any:
+ if isinstance(value, dict):
+ return {
+ _scrub(str(key), names, now): _normal(item, names, now)
+ for key, item in sorted(value.items())
+ if key not in _VOLATILE_KEYS
+ }
+ if isinstance(value, list):
+ return [_normal(item, names, now) for item in value]
+ if isinstance(value, str):
+ return _scrub(value, names, now)
+ return value
+
+
+def _row(item: dict[str, Any], names: dict[str, str]) -> dict[str, Any]:
+ """One timeline row as the axis and the list read it, ids named so that rows and
+ their connectors sort the same way on every build."""
+ def named(key: str) -> list[str]:
+ return sorted(_scrub(e.get("id", ""), names) for e in item.get(key) or [])
+
+ return {
+ key: _scrub(item[key], names) if isinstance(item.get(key), str) else item.get(key)
+ for key in (
+ "id", "owner_id", "category", "kind", "label", "raw", "earliest", "latest",
+ "precision", "time_role", "status", "confidence", "parse_error",
+ )
+ if key in item
+ } | {
+ "subjects": named("subject_entities"),
+ "places": named("place_entities"),
+ "sources": named("source_entities"),
+ }
+
+
+def _written_now(row: dict[str, Any]) -> bool:
+ """Rows dated by the build itself: when a file or an entity was filed."""
+ return row.get("kind") in {"added", "filed"}
+
+
+def _timeline_rows(client, base: str, names: dict[str, str], **params: Any) -> dict[str, Any]:
+ rows: list[dict[str, Any]] = []
+ cursor = None
+ while True:
+ page = _ok(client.get(f"{base}/timeline", params={
+ **params, "limit": 200, **({"cursor": cursor} if cursor else {}),
+ }), "timeline")
+ rows.extend(_row(item, names) for item in page["items"])
+ cursor = page["next_cursor"]
+ if cursor is None:
+ break
+ return {
+ "rows": sorted((r for r in rows if not _written_now(r)), key=lambda r: r["id"]),
+ "undated": page["undated"],
+ "unplaced": page["unplaced"],
+ }
+
+
+def _labels(client, base: str, terms: dict[str, Any]) -> list[str]:
+ page = _ok(client.get(f"{base}/catalog/entities", params={**terms, "limit": 500}), "catalog")
+ return sorted(f"{e['type']}:{e['label']}" for e in page["items"])
+
+
+def _snapshot(snapshot: dict[str, Any], names: dict[str, str]) -> dict[str, Any]:
+ return {
+ "entities": sorted(_scrub(e["id"], names) for e in snapshot.get("entities") or []),
+ "links": sorted(
+ _scrub(f"{link['from']} {link['type']} {link['to']}", names)
+ for link in snapshot.get("links") or []
+ ),
+ "timeline_items": sorted(
+ (_row(item, names) for item in snapshot.get("timeline_items") or []
+ if not _written_now(item)),
+ key=lambda r: r["id"],
+ ),
+ "timeline_tracks": {
+ track: sorted(_scrub(one, names) for one in ids)
+ for track, ids in (snapshot.get("timeline_tracks") or {}).items()
+ },
+ }
+
+
+def read_workspace(client, ws: WorkspaceCase) -> dict[str, Any]:
+ """What the Board, Graph and Timeline show of this case, id-free."""
+ from azimut.workspace import Case
+
+ case_id = ws.full.case_id
+ base = f"/api/cases/{case_id}"
+ case = Case.open(case_id)
+ names = {e["id"]: f"{e['type']}:{e['label']}" for e in case.list_entities()}
+ names.update({ident: f"view:{name}" for name, ident in ws.views.items()})
+ names[case_id] = "case"
+ names[Path(ws.full.analyzer_run).stem.split("-", 1)[1]] = "run"
+ names[ws.full.entity_photo_id] = "image:direct"
+ now = datetime.now(timezone.utc)
+
+ views: dict[str, Any] = {}
+ readings: dict[str, Any] = {}
+ for summary in _ok(client.get(f"{base}/analysis-views"), "views")["views"]:
+ stored = _ok(client.get(f"{base}/analysis-views/{summary['id']}"), summary["name"])
+ spec = dict(stored["spec"])
+ if "snapshot" in spec:
+ spec["snapshot"] = _snapshot(spec["snapshot"], names)
+ views[stored["name"]] = {
+ "surface": stored["surface"], "mode": stored["mode"], "spec": spec,
+ }
+ if stored["mode"] != "live":
+ continue
+ if stored["surface"] == "timeline":
+ timeline = spec["timeline"]
+ readings[stored["name"]] = {
+ track["id"]: _timeline_rows(
+ client, base, names,
+ **{"from": timeline["from"], "to": timeline["to"]},
+ category=track["categories"],
+ track=json.dumps({**track["query"], "hidden": track["hidden"]}),
+ )
+ for track in timeline["tracks"]
+ }
+ else:
+ readings[stored["name"]] = _labels(client, base, spec["query"]["terms"])
+
+ claims = {}
+ for entity in case.list_entities():
+ if entity["type"] != "claim":
+ continue
+ connectors: dict[str, list[str]] = {}
+ for link in case.links_of(entity["id"]):
+ if link["from"] == entity["id"]:
+ connectors.setdefault(link["type"], []).append(link["to"])
+ claims[entity["label"]] = {
+ "status": entity.get("status"),
+ "attrs": entity.get("attrs") or {},
+ "connectors": {
+ verb: sorted(names.get(one, one) for one in ids) for verb, ids in connectors.items()
+ },
+ }
+
+ galleries = {
+ names[entity_id]: [
+ {"primary": image.get("primary"), "media": image.get("media_id") or image.get("path")}
+ for image in _ok(client.get(f"{base}/entities/{entity_id}/images"), "images")["images"]
+ ]
+ for entity_id in (ws.full.person_id, ws.full.org_id)
+ }
+
+ reading = {
+ "views": views,
+ "live": readings,
+ "events": _timeline_rows(client, base, names, category=["statement"]),
+ "media": _timeline_rows(client, base, names, category=["media"]),
+ "summary": _ok(client.get(f"{base}/catalog/summary"), "summary"),
+ "search": {
+ q: _labels(client, base, {"q": q})
+ for q in ("Nadeau", "aurora", "handy bulker", "Quay 4", "brigade", "@harbourwatch")
+ },
+ "claims": claims,
+ "galleries": galleries,
+ "notes": _ok(client.get(f"{base}/notes"), "notes").get("text"),
+ "filed_note": _ok(client.get(f"{base}/notes/{ws.full.note_id}"), "note").get("text"),
+ "promoted": names.get(ws.promoted),
+ "detect_claim": names.get(ws.detect_claim),
+ }
+ return _normal(reading, names, now)
diff --git a/tests/fixtures/README.md b/tests/fixtures/README.md
index 4ab365d..c6d5990 100644
--- a/tests/fixtures/README.md
+++ b/tests/fixtures/README.md
@@ -32,3 +32,26 @@ Neither file is written by hand. `npm run calibrate:maps` drives the sites again
rewrites the raw one; `python scripts/build_map_fixture.py` turns that into the other.
The protocol both follow is `frontend/calibration/protocol.mjs`, and it is itself tested
against a map whose layout is known (`frontend/e2e/map-calibration.spec.js`).
+
+## The Case workspace
+
+| File | What it is there to break |
+|---|---|
+| `case-workspace-0.3.1.json` | How the Board, Graph and Timeline read a case left the way a 0.3.1 analyst leaves one: saved readings of each surface, Live and Snapshot, in both Timeline modes, with Media tracks, hides and pins; dated, undated and unplaced Claims; a kept Detect pin and a proof date; Notebook mentions, a promoted Sheet row and galleries. Ids are written `type:label` and the moment of the build is scrubbed. |
+
+Written by `tests/caseworkspace.py`, never by hand, and compared by
+`tests/test_case_workspace_fixture.py`; `frontend/src/lib/caseWorkspaceFixture.test.js`
+reopens its saved views through the parsers the three surfaces use. A change that
+means to alter a reading rewrites it with `AZIMUT_WRITE_GOLDEN=1 uv run pytest
+tests/test_case_workspace_fixture.py`, and the diff is that change's account of what
+reads differently.
+
+## Search folding
+
+| File | What it is there to break |
+|---|---|
+| `fold_cases.json` | What a search folds and what it keeps, one line per case: Latin, Greek and Cyrillic accents, Arabic harakat and the tatweel, Hebrew points go; a Devanagari sign, a dakuten, the Hebrew maqaf and the punctuation of an email, a network or a handle stay. |
+
+Written by hand. Read by `tests/test_textfold.py` against `engine/textfold.py` and by
+`frontend/src/lib/textFold.test.js` against `lib/textFold.js`, so the server's index
+and the browser's in-memory search cannot fold one text two ways.
diff --git a/tests/fixtures/case-workspace-0.3.1.json b/tests/fixtures/case-workspace-0.3.1.json
new file mode 100644
index 0000000..9b6f2b2
--- /dev/null
+++ b/tests/fixtures/case-workspace-0.3.1.json
@@ -0,0 +1,2902 @@
+{
+ "claims": {
+ "Changed: Levelled yard": {
+ "attrs": {
+ "detection": "run/patch-0-1",
+ "time_role": "occurred",
+ "when": "2026-05-04/2026-05-11"
+ },
+ "connectors": {
+ "at": [
+ "place:Levelled yard"
+ ],
+ "cites": [
+ "media:Levelled yard"
+ ]
+ },
+ "status": null
+ },
+ "Convoy crossed the east bridge": {
+ "attrs": {
+ "confidence": "certain",
+ "time_role": "occurred",
+ "when": "2026-08-01T14:05:00Z"
+ },
+ "connectors": {
+ "about": [
+ "vessel:MV Aurora"
+ ],
+ "at": [
+ "place:Tower"
+ ],
+ "cites": [
+ "media:photo"
+ ]
+ },
+ "status": null
+ },
+ "Crew list circulated": {
+ "attrs": {
+ "when": "2026-08-05"
+ },
+ "connectors": {
+ "about": [
+ "person:A. Nadeau"
+ ],
+ "cites": [
+ "note:Witness"
+ ]
+ },
+ "status": null
+ },
+ "Harbour master called in": {
+ "attrs": {
+ "when": "2026-08-02T08:30:00"
+ },
+ "connectors": {
+ "about": [
+ "person:A. Nadeau"
+ ]
+ },
+ "status": null
+ },
+ "Material of Bridge proof was taken": {
+ "attrs": {
+ "proof": "proofs/.meta/Bridge proof.json",
+ "time_role": "observed",
+ "when": "2026-07-31T16:20:00Z"
+ },
+ "connectors": {
+ "about": [
+ "media:piece"
+ ],
+ "cites": [
+ "proof:Bridge proof"
+ ]
+ },
+ "status": null
+ },
+ "Night strike on the quay": {
+ "attrs": {
+ "confidence": "refuted",
+ "when": "2026-08-03T22:10:00+03:00"
+ },
+ "connectors": {
+ "about": [
+ "structure:Quay 4 warehouse"
+ ],
+ "at": [
+ "place:Tower"
+ ]
+ },
+ "status": null
+ },
+ "Owner changed the flag": {
+ "attrs": {},
+ "connectors": {
+ "about": [
+ "organization:Northwind Shipping",
+ "vessel:MV Aurora"
+ ]
+ },
+ "status": null
+ },
+ "Quay 4 warehouse burned": {
+ "attrs": {
+ "confidence": "probable",
+ "time_role": "occurred",
+ "when": "2026-07-30/2026-08-02"
+ },
+ "connectors": {
+ "about": [
+ "structure:Quay 4 warehouse"
+ ],
+ "at": [
+ "place:Tower"
+ ],
+ "cites": [
+ "bookmark:Harbour watch thread"
+ ]
+ },
+ "status": null
+ },
+ "Recruitment announced": {
+ "attrs": {
+ "confidence": "possible",
+ "when": "2026-07"
+ },
+ "connectors": {
+ "about": [
+ "account:@harbourwatch"
+ ],
+ "cites": [
+ "bookmark:Harbour watch thread"
+ ]
+ },
+ "status": null
+ },
+ "Second convoy suggested": {
+ "attrs": {
+ "confidence": "possible",
+ "when": "2026-08-06"
+ },
+ "connectors": {},
+ "status": null
+ },
+ "Two Handysize bulkers berthed at Quay 4": {
+ "attrs": {
+ "condition": "intact",
+ "confidence": "possible",
+ "count": 2
+ },
+ "connectors": {
+ "about": [
+ "equipment-type:Handysize bulker"
+ ],
+ "at": [
+ "place:Tower"
+ ]
+ },
+ "status": null
+ },
+ "Vessel seen leaving around the first": {
+ "attrs": {
+ "time_role": "observed",
+ "when": "2026-08-01~"
+ },
+ "connectors": {
+ "about": [
+ "vessel:MV Aurora"
+ ],
+ "at": [
+ "place:Tower"
+ ]
+ },
+ "status": null
+ },
+ "Where was the photo taken?": {
+ "attrs": {
+ "confidence": "probable",
+ "method": "spans counted against Esri imagery",
+ "time_role": "observed",
+ "when": "2026-08-01T09:12:00Z"
+ },
+ "connectors": {
+ "about": [
+ "media:photo"
+ ],
+ "at": [
+ "place:Tower"
+ ],
+ "cites": [
+ "bookmark:Harbour watch thread",
+ "note:Witness"
+ ]
+ },
+ "status": null
+ }
+ },
+ "detect_claim": "claim:Changed: Levelled yard",
+ "events": {
+ "rows": [
+ {
+ "category": "statement",
+ "confidence": null,
+ "earliest": "2026-05-04T00:00:00.000000Z",
+ "id": "temporal:claim:claim:Changed: Levelled yard",
+ "kind": "claim",
+ "label": "Changed: Levelled yard",
+ "latest": "2026-05-12T00:00:00.000000Z",
+ "owner_id": "claim:Changed: Levelled yard",
+ "parse_error": null,
+ "places": [
+ "place:Levelled yard"
+ ],
+ "precision": "day",
+ "raw": "2026-05-04/2026-05-11",
+ "sources": [
+ "media:Levelled yard"
+ ],
+ "status": "confirmed",
+ "subjects": [],
+ "time_role": "occurred"
+ },
+ {
+ "category": "statement",
+ "confidence": "certain",
+ "earliest": "2026-08-01T14:05:00.000000Z",
+ "id": "temporal:claim:claim:Convoy crossed the east bridge",
+ "kind": "claim",
+ "label": "Convoy crossed the east bridge",
+ "latest": "2026-08-01T14:05:01.000000Z",
+ "owner_id": "claim:Convoy crossed the east bridge",
+ "parse_error": null,
+ "places": [
+ "place:Tower"
+ ],
+ "precision": "second",
+ "raw": "2026-08-01T14:05:00Z",
+ "sources": [
+ "media:photo"
+ ],
+ "status": "confirmed",
+ "subjects": [
+ "vessel:MV Aurora"
+ ],
+ "time_role": "occurred"
+ },
+ {
+ "category": "statement",
+ "confidence": null,
+ "earliest": "2026-08-05T00:00:00.000000Z",
+ "id": "temporal:claim:claim:Crew list circulated",
+ "kind": "claim",
+ "label": "Crew list circulated",
+ "latest": "2026-08-06T00:00:00.000000Z",
+ "owner_id": "claim:Crew list circulated",
+ "parse_error": null,
+ "places": [],
+ "precision": "day",
+ "raw": "2026-08-05",
+ "sources": [
+ "note:Witness"
+ ],
+ "status": "confirmed",
+ "subjects": [
+ "person:A. Nadeau"
+ ],
+ "time_role": null
+ },
+ {
+ "category": "statement",
+ "confidence": null,
+ "earliest": null,
+ "id": "temporal:claim:claim:Harbour master called in",
+ "kind": "claim",
+ "label": "Harbour master called in",
+ "latest": null,
+ "owner_id": "claim:Harbour master called in",
+ "parse_error": null,
+ "places": [],
+ "precision": "second",
+ "raw": "2026-08-02T08:30:00",
+ "sources": [],
+ "status": "confirmed",
+ "subjects": [
+ "person:A. Nadeau"
+ ],
+ "time_role": null
+ },
+ {
+ "category": "statement",
+ "confidence": null,
+ "earliest": "2026-07-31T16:20:00.000000Z",
+ "id": "temporal:claim:claim:Material of Bridge proof was taken",
+ "kind": "claim",
+ "label": "Material of Bridge proof was taken",
+ "latest": "2026-07-31T16:20:01.000000Z",
+ "owner_id": "claim:Material of Bridge proof was taken",
+ "parse_error": null,
+ "places": [],
+ "precision": "second",
+ "raw": "2026-07-31T16:20:00Z",
+ "sources": [
+ "proof:Bridge proof"
+ ],
+ "status": "confirmed",
+ "subjects": [
+ "media:piece"
+ ],
+ "time_role": "observed"
+ },
+ {
+ "category": "statement",
+ "confidence": "refuted",
+ "earliest": "2026-08-03T19:10:00.000000Z",
+ "id": "temporal:claim:claim:Night strike on the quay",
+ "kind": "claim",
+ "label": "Night strike on the quay",
+ "latest": "2026-08-03T19:10:01.000000Z",
+ "owner_id": "claim:Night strike on the quay",
+ "parse_error": null,
+ "places": [
+ "place:Tower"
+ ],
+ "precision": "second",
+ "raw": "2026-08-03T22:10:00+03:00",
+ "sources": [],
+ "status": "confirmed",
+ "subjects": [
+ "structure:Quay 4 warehouse"
+ ],
+ "time_role": null
+ },
+ {
+ "category": "statement",
+ "confidence": null,
+ "earliest": null,
+ "id": "temporal:claim:claim:Owner changed the flag",
+ "kind": "claim",
+ "label": "Owner changed the flag",
+ "latest": null,
+ "owner_id": "claim:Owner changed the flag",
+ "parse_error": null,
+ "places": [],
+ "precision": null,
+ "raw": null,
+ "sources": [],
+ "status": "confirmed",
+ "subjects": [
+ "organization:Northwind Shipping",
+ "vessel:MV Aurora"
+ ],
+ "time_role": null
+ },
+ {
+ "category": "statement",
+ "confidence": "probable",
+ "earliest": "2026-07-30T00:00:00.000000Z",
+ "id": "temporal:claim:claim:Quay 4 warehouse burned",
+ "kind": "claim",
+ "label": "Quay 4 warehouse burned",
+ "latest": "2026-08-03T00:00:00.000000Z",
+ "owner_id": "claim:Quay 4 warehouse burned",
+ "parse_error": null,
+ "places": [
+ "place:Tower"
+ ],
+ "precision": "day",
+ "raw": "2026-07-30/2026-08-02",
+ "sources": [
+ "bookmark:Harbour watch thread"
+ ],
+ "status": "confirmed",
+ "subjects": [
+ "structure:Quay 4 warehouse"
+ ],
+ "time_role": "occurred"
+ },
+ {
+ "category": "statement",
+ "confidence": "possible",
+ "earliest": "2026-07-01T00:00:00.000000Z",
+ "id": "temporal:claim:claim:Recruitment announced",
+ "kind": "claim",
+ "label": "Recruitment announced",
+ "latest": "2026-08-01T00:00:00.000000Z",
+ "owner_id": "claim:Recruitment announced",
+ "parse_error": null,
+ "places": [],
+ "precision": "month",
+ "raw": "2026-07",
+ "sources": [
+ "bookmark:Harbour watch thread"
+ ],
+ "status": "confirmed",
+ "subjects": [
+ "account:@harbourwatch"
+ ],
+ "time_role": null
+ },
+ {
+ "category": "statement",
+ "confidence": "possible",
+ "earliest": "2026-08-06T00:00:00.000000Z",
+ "id": "temporal:claim:claim:Second convoy suggested",
+ "kind": "claim",
+ "label": "Second convoy suggested",
+ "latest": "2026-08-07T00:00:00.000000Z",
+ "owner_id": "claim:Second convoy suggested",
+ "parse_error": null,
+ "places": [],
+ "precision": "day",
+ "raw": "2026-08-06",
+ "sources": [],
+ "status": "suggested",
+ "subjects": [],
+ "time_role": null
+ },
+ {
+ "category": "statement",
+ "confidence": "possible",
+ "earliest": null,
+ "id": "temporal:claim:claim:Two Handysize bulkers berthed at Quay 4",
+ "kind": "claim",
+ "label": "Two Handysize bulkers berthed at Quay 4",
+ "latest": null,
+ "owner_id": "claim:Two Handysize bulkers berthed at Quay 4",
+ "parse_error": null,
+ "places": [
+ "place:Tower"
+ ],
+ "precision": null,
+ "raw": null,
+ "sources": [],
+ "status": "confirmed",
+ "subjects": [
+ "equipment-type:Handysize bulker"
+ ],
+ "time_role": null
+ },
+ {
+ "category": "statement",
+ "confidence": null,
+ "earliest": "2026-08-01T00:00:00.000000Z",
+ "id": "temporal:claim:claim:Vessel seen leaving around the first",
+ "kind": "claim",
+ "label": "Vessel seen leaving around the first",
+ "latest": "2026-08-02T00:00:00.000000Z",
+ "owner_id": "claim:Vessel seen leaving around the first",
+ "parse_error": null,
+ "places": [
+ "place:Tower"
+ ],
+ "precision": "day",
+ "raw": "2026-08-01~",
+ "sources": [],
+ "status": "confirmed",
+ "subjects": [
+ "vessel:MV Aurora"
+ ],
+ "time_role": "observed"
+ },
+ {
+ "category": "statement",
+ "confidence": "probable",
+ "earliest": "2026-08-01T09:12:00.000000Z",
+ "id": "temporal:claim:claim:Where was the photo taken?",
+ "kind": "claim",
+ "label": "Where was the photo taken?",
+ "latest": "2026-08-01T09:12:01.000000Z",
+ "owner_id": "claim:Where was the photo taken?",
+ "parse_error": null,
+ "places": [
+ "place:Tower"
+ ],
+ "precision": "second",
+ "raw": "2026-08-01T09:12:00Z",
+ "sources": [
+ "bookmark:Harbour watch thread",
+ "note:Witness"
+ ],
+ "status": "confirmed",
+ "subjects": [
+ "media:photo"
+ ],
+ "time_role": "observed"
+ }
+ ],
+ "undated": 2,
+ "unplaced": 1
+ },
+ "filed_note": "# Witness\n\nSaw [[entity:vessel:MV Aurora|MV Aurora]] leave.\n",
+ "galleries": {
+ "organization:Northwind Shipping": [
+ {
+ "media": ".data/entity-images/image:direct.jpg",
+ "primary": true
+ }
+ ],
+ "person:A. Nadeau": [
+ {
+ "media": "media:photo",
+ "primary": true
+ }
+ ]
+ },
+ "live": {
+ "Chronology as list": {
+ "events": {
+ "rows": [
+ {
+ "category": "statement",
+ "confidence": "certain",
+ "earliest": "2026-08-01T14:05:00.000000Z",
+ "id": "temporal:claim:claim:Convoy crossed the east bridge",
+ "kind": "claim",
+ "label": "Convoy crossed the east bridge",
+ "latest": "2026-08-01T14:05:01.000000Z",
+ "owner_id": "claim:Convoy crossed the east bridge",
+ "parse_error": null,
+ "places": [
+ "place:Tower"
+ ],
+ "precision": "second",
+ "raw": "2026-08-01T14:05:00Z",
+ "sources": [
+ "media:photo"
+ ],
+ "status": "confirmed",
+ "subjects": [
+ "vessel:MV Aurora"
+ ],
+ "time_role": "occurred"
+ },
+ {
+ "category": "statement",
+ "confidence": null,
+ "earliest": null,
+ "id": "temporal:claim:claim:Harbour master called in",
+ "kind": "claim",
+ "label": "Harbour master called in",
+ "latest": null,
+ "owner_id": "claim:Harbour master called in",
+ "parse_error": null,
+ "places": [],
+ "precision": "second",
+ "raw": "2026-08-02T08:30:00",
+ "sources": [],
+ "status": "confirmed",
+ "subjects": [
+ "person:A. Nadeau"
+ ],
+ "time_role": null
+ },
+ {
+ "category": "statement",
+ "confidence": null,
+ "earliest": "2026-07-31T16:20:00.000000Z",
+ "id": "temporal:claim:claim:Material of Bridge proof was taken",
+ "kind": "claim",
+ "label": "Material of Bridge proof was taken",
+ "latest": "2026-07-31T16:20:01.000000Z",
+ "owner_id": "claim:Material of Bridge proof was taken",
+ "parse_error": null,
+ "places": [],
+ "precision": "second",
+ "raw": "2026-07-31T16:20:00Z",
+ "sources": [
+ "proof:Bridge proof"
+ ],
+ "status": "confirmed",
+ "subjects": [
+ "media:piece"
+ ],
+ "time_role": "observed"
+ },
+ {
+ "category": "statement",
+ "confidence": "refuted",
+ "earliest": "2026-08-03T19:10:00.000000Z",
+ "id": "temporal:claim:claim:Night strike on the quay",
+ "kind": "claim",
+ "label": "Night strike on the quay",
+ "latest": "2026-08-03T19:10:01.000000Z",
+ "owner_id": "claim:Night strike on the quay",
+ "parse_error": null,
+ "places": [
+ "place:Tower"
+ ],
+ "precision": "second",
+ "raw": "2026-08-03T22:10:00+03:00",
+ "sources": [],
+ "status": "confirmed",
+ "subjects": [
+ "structure:Quay 4 warehouse"
+ ],
+ "time_role": null
+ },
+ {
+ "category": "statement",
+ "confidence": null,
+ "earliest": null,
+ "id": "temporal:claim:claim:Owner changed the flag",
+ "kind": "claim",
+ "label": "Owner changed the flag",
+ "latest": null,
+ "owner_id": "claim:Owner changed the flag",
+ "parse_error": null,
+ "places": [],
+ "precision": null,
+ "raw": null,
+ "sources": [],
+ "status": "confirmed",
+ "subjects": [
+ "organization:Northwind Shipping",
+ "vessel:MV Aurora"
+ ],
+ "time_role": null
+ },
+ {
+ "category": "statement",
+ "confidence": "probable",
+ "earliest": "2026-07-30T00:00:00.000000Z",
+ "id": "temporal:claim:claim:Quay 4 warehouse burned",
+ "kind": "claim",
+ "label": "Quay 4 warehouse burned",
+ "latest": "2026-08-03T00:00:00.000000Z",
+ "owner_id": "claim:Quay 4 warehouse burned",
+ "parse_error": null,
+ "places": [
+ "place:Tower"
+ ],
+ "precision": "day",
+ "raw": "2026-07-30/2026-08-02",
+ "sources": [
+ "bookmark:Harbour watch thread"
+ ],
+ "status": "confirmed",
+ "subjects": [
+ "structure:Quay 4 warehouse"
+ ],
+ "time_role": "occurred"
+ },
+ {
+ "category": "statement",
+ "confidence": "possible",
+ "earliest": "2026-07-01T00:00:00.000000Z",
+ "id": "temporal:claim:claim:Recruitment announced",
+ "kind": "claim",
+ "label": "Recruitment announced",
+ "latest": "2026-08-01T00:00:00.000000Z",
+ "owner_id": "claim:Recruitment announced",
+ "parse_error": null,
+ "places": [],
+ "precision": "month",
+ "raw": "2026-07",
+ "sources": [
+ "bookmark:Harbour watch thread"
+ ],
+ "status": "confirmed",
+ "subjects": [
+ "account:@harbourwatch"
+ ],
+ "time_role": null
+ },
+ {
+ "category": "statement",
+ "confidence": "possible",
+ "earliest": "2026-08-06T00:00:00.000000Z",
+ "id": "temporal:claim:claim:Second convoy suggested",
+ "kind": "claim",
+ "label": "Second convoy suggested",
+ "latest": "2026-08-07T00:00:00.000000Z",
+ "owner_id": "claim:Second convoy suggested",
+ "parse_error": null,
+ "places": [],
+ "precision": "day",
+ "raw": "2026-08-06",
+ "sources": [],
+ "status": "suggested",
+ "subjects": [],
+ "time_role": null
+ },
+ {
+ "category": "statement",
+ "confidence": "possible",
+ "earliest": null,
+ "id": "temporal:claim:claim:Two Handysize bulkers berthed at Quay 4",
+ "kind": "claim",
+ "label": "Two Handysize bulkers berthed at Quay 4",
+ "latest": null,
+ "owner_id": "claim:Two Handysize bulkers berthed at Quay 4",
+ "parse_error": null,
+ "places": [
+ "place:Tower"
+ ],
+ "precision": null,
+ "raw": null,
+ "sources": [],
+ "status": "confirmed",
+ "subjects": [
+ "equipment-type:Handysize bulker"
+ ],
+ "time_role": null
+ },
+ {
+ "category": "statement",
+ "confidence": null,
+ "earliest": "2026-08-01T00:00:00.000000Z",
+ "id": "temporal:claim:claim:Vessel seen leaving around the first",
+ "kind": "claim",
+ "label": "Vessel seen leaving around the first",
+ "latest": "2026-08-02T00:00:00.000000Z",
+ "owner_id": "claim:Vessel seen leaving around the first",
+ "parse_error": null,
+ "places": [
+ "place:Tower"
+ ],
+ "precision": "day",
+ "raw": "2026-08-01~",
+ "sources": [],
+ "status": "confirmed",
+ "subjects": [
+ "vessel:MV Aurora"
+ ],
+ "time_role": "observed"
+ },
+ {
+ "category": "statement",
+ "confidence": "probable",
+ "earliest": "2026-08-01T09:12:00.000000Z",
+ "id": "temporal:claim:claim:Where was the photo taken?",
+ "kind": "claim",
+ "label": "Where was the photo taken?",
+ "latest": "2026-08-01T09:12:01.000000Z",
+ "owner_id": "claim:Where was the photo taken?",
+ "parse_error": null,
+ "places": [
+ "place:Tower"
+ ],
+ "precision": "second",
+ "raw": "2026-08-01T09:12:00Z",
+ "sources": [
+ "bookmark:Harbour watch thread",
+ "note:Witness"
+ ],
+ "status": "confirmed",
+ "subjects": [
+ "media:photo"
+ ],
+ "time_role": "observed"
+ }
+ ],
+ "undated": 2,
+ "unplaced": 1
+ },
+ "media": {
+ "rows": [
+ {
+ "category": "media",
+ "confidence": null,
+ "earliest": null,
+ "id": "temporal:media:media:harbour:captured",
+ "kind": "captured",
+ "label": "harbour",
+ "latest": null,
+ "owner_id": "media:harbour",
+ "parse_error": null,
+ "places": [],
+ "precision": "second",
+ "raw": "2026-08-01T13:58:00",
+ "sources": [],
+ "status": null,
+ "subjects": [],
+ "time_role": null
+ }
+ ],
+ "undated": 0,
+ "unplaced": 1
+ }
+ },
+ "Chronology defaults": {
+ "events": {
+ "rows": [
+ {
+ "category": "statement",
+ "confidence": "certain",
+ "earliest": "2026-08-01T14:05:00.000000Z",
+ "id": "temporal:claim:claim:Convoy crossed the east bridge",
+ "kind": "claim",
+ "label": "Convoy crossed the east bridge",
+ "latest": "2026-08-01T14:05:01.000000Z",
+ "owner_id": "claim:Convoy crossed the east bridge",
+ "parse_error": null,
+ "places": [
+ "place:Tower"
+ ],
+ "precision": "second",
+ "raw": "2026-08-01T14:05:00Z",
+ "sources": [
+ "media:photo"
+ ],
+ "status": "confirmed",
+ "subjects": [
+ "vessel:MV Aurora"
+ ],
+ "time_role": "occurred"
+ },
+ {
+ "category": "statement",
+ "confidence": null,
+ "earliest": "2026-08-05T00:00:00.000000Z",
+ "id": "temporal:claim:claim:Crew list circulated",
+ "kind": "claim",
+ "label": "Crew list circulated",
+ "latest": "2026-08-06T00:00:00.000000Z",
+ "owner_id": "claim:Crew list circulated",
+ "parse_error": null,
+ "places": [],
+ "precision": "day",
+ "raw": "2026-08-05",
+ "sources": [
+ "note:Witness"
+ ],
+ "status": "confirmed",
+ "subjects": [
+ "person:A. Nadeau"
+ ],
+ "time_role": null
+ },
+ {
+ "category": "statement",
+ "confidence": null,
+ "earliest": null,
+ "id": "temporal:claim:claim:Harbour master called in",
+ "kind": "claim",
+ "label": "Harbour master called in",
+ "latest": null,
+ "owner_id": "claim:Harbour master called in",
+ "parse_error": null,
+ "places": [],
+ "precision": "second",
+ "raw": "2026-08-02T08:30:00",
+ "sources": [],
+ "status": "confirmed",
+ "subjects": [
+ "person:A. Nadeau"
+ ],
+ "time_role": null
+ },
+ {
+ "category": "statement",
+ "confidence": null,
+ "earliest": "2026-07-31T16:20:00.000000Z",
+ "id": "temporal:claim:claim:Material of Bridge proof was taken",
+ "kind": "claim",
+ "label": "Material of Bridge proof was taken",
+ "latest": "2026-07-31T16:20:01.000000Z",
+ "owner_id": "claim:Material of Bridge proof was taken",
+ "parse_error": null,
+ "places": [],
+ "precision": "second",
+ "raw": "2026-07-31T16:20:00Z",
+ "sources": [
+ "proof:Bridge proof"
+ ],
+ "status": "confirmed",
+ "subjects": [
+ "media:piece"
+ ],
+ "time_role": "observed"
+ },
+ {
+ "category": "statement",
+ "confidence": "refuted",
+ "earliest": "2026-08-03T19:10:00.000000Z",
+ "id": "temporal:claim:claim:Night strike on the quay",
+ "kind": "claim",
+ "label": "Night strike on the quay",
+ "latest": "2026-08-03T19:10:01.000000Z",
+ "owner_id": "claim:Night strike on the quay",
+ "parse_error": null,
+ "places": [
+ "place:Tower"
+ ],
+ "precision": "second",
+ "raw": "2026-08-03T22:10:00+03:00",
+ "sources": [],
+ "status": "confirmed",
+ "subjects": [
+ "structure:Quay 4 warehouse"
+ ],
+ "time_role": null
+ },
+ {
+ "category": "statement",
+ "confidence": null,
+ "earliest": null,
+ "id": "temporal:claim:claim:Owner changed the flag",
+ "kind": "claim",
+ "label": "Owner changed the flag",
+ "latest": null,
+ "owner_id": "claim:Owner changed the flag",
+ "parse_error": null,
+ "places": [],
+ "precision": null,
+ "raw": null,
+ "sources": [],
+ "status": "confirmed",
+ "subjects": [
+ "organization:Northwind Shipping",
+ "vessel:MV Aurora"
+ ],
+ "time_role": null
+ },
+ {
+ "category": "statement",
+ "confidence": "probable",
+ "earliest": "2026-07-30T00:00:00.000000Z",
+ "id": "temporal:claim:claim:Quay 4 warehouse burned",
+ "kind": "claim",
+ "label": "Quay 4 warehouse burned",
+ "latest": "2026-08-03T00:00:00.000000Z",
+ "owner_id": "claim:Quay 4 warehouse burned",
+ "parse_error": null,
+ "places": [
+ "place:Tower"
+ ],
+ "precision": "day",
+ "raw": "2026-07-30/2026-08-02",
+ "sources": [
+ "bookmark:Harbour watch thread"
+ ],
+ "status": "confirmed",
+ "subjects": [
+ "structure:Quay 4 warehouse"
+ ],
+ "time_role": "occurred"
+ },
+ {
+ "category": "statement",
+ "confidence": "possible",
+ "earliest": "2026-07-01T00:00:00.000000Z",
+ "id": "temporal:claim:claim:Recruitment announced",
+ "kind": "claim",
+ "label": "Recruitment announced",
+ "latest": "2026-08-01T00:00:00.000000Z",
+ "owner_id": "claim:Recruitment announced",
+ "parse_error": null,
+ "places": [],
+ "precision": "month",
+ "raw": "2026-07",
+ "sources": [
+ "bookmark:Harbour watch thread"
+ ],
+ "status": "confirmed",
+ "subjects": [
+ "account:@harbourwatch"
+ ],
+ "time_role": null
+ },
+ {
+ "category": "statement",
+ "confidence": "possible",
+ "earliest": "2026-08-06T00:00:00.000000Z",
+ "id": "temporal:claim:claim:Second convoy suggested",
+ "kind": "claim",
+ "label": "Second convoy suggested",
+ "latest": "2026-08-07T00:00:00.000000Z",
+ "owner_id": "claim:Second convoy suggested",
+ "parse_error": null,
+ "places": [],
+ "precision": "day",
+ "raw": "2026-08-06",
+ "sources": [],
+ "status": "suggested",
+ "subjects": [],
+ "time_role": null
+ },
+ {
+ "category": "statement",
+ "confidence": "possible",
+ "earliest": null,
+ "id": "temporal:claim:claim:Two Handysize bulkers berthed at Quay 4",
+ "kind": "claim",
+ "label": "Two Handysize bulkers berthed at Quay 4",
+ "latest": null,
+ "owner_id": "claim:Two Handysize bulkers berthed at Quay 4",
+ "parse_error": null,
+ "places": [
+ "place:Tower"
+ ],
+ "precision": null,
+ "raw": null,
+ "sources": [],
+ "status": "confirmed",
+ "subjects": [
+ "equipment-type:Handysize bulker"
+ ],
+ "time_role": null
+ },
+ {
+ "category": "statement",
+ "confidence": null,
+ "earliest": "2026-08-01T00:00:00.000000Z",
+ "id": "temporal:claim:claim:Vessel seen leaving around the first",
+ "kind": "claim",
+ "label": "Vessel seen leaving around the first",
+ "latest": "2026-08-02T00:00:00.000000Z",
+ "owner_id": "claim:Vessel seen leaving around the first",
+ "parse_error": null,
+ "places": [
+ "place:Tower"
+ ],
+ "precision": "day",
+ "raw": "2026-08-01~",
+ "sources": [],
+ "status": "confirmed",
+ "subjects": [
+ "vessel:MV Aurora"
+ ],
+ "time_role": "observed"
+ },
+ {
+ "category": "statement",
+ "confidence": "probable",
+ "earliest": "2026-08-01T09:12:00.000000Z",
+ "id": "temporal:claim:claim:Where was the photo taken?",
+ "kind": "claim",
+ "label": "Where was the photo taken?",
+ "latest": "2026-08-01T09:12:01.000000Z",
+ "owner_id": "claim:Where was the photo taken?",
+ "parse_error": null,
+ "places": [
+ "place:Tower"
+ ],
+ "precision": "second",
+ "raw": "2026-08-01T09:12:00Z",
+ "sources": [
+ "bookmark:Harbour watch thread",
+ "note:Witness"
+ ],
+ "status": "confirmed",
+ "subjects": [
+ "media:photo"
+ ],
+ "time_role": "observed"
+ }
+ ],
+ "undated": 2,
+ "unplaced": 1
+ },
+ "media": {
+ "rows": [
+ {
+ "category": "media",
+ "confidence": null,
+ "earliest": null,
+ "id": "temporal:media:media:harbour:captured",
+ "kind": "captured",
+ "label": "harbour",
+ "latest": null,
+ "owner_id": "media:harbour",
+ "parse_error": null,
+ "places": [],
+ "precision": "second",
+ "raw": "2026-08-01T13:58:00",
+ "sources": [],
+ "status": null,
+ "subjects": [],
+ "time_role": null
+ }
+ ],
+ "undated": 0,
+ "unplaced": 1
+ }
+ },
+ "Chronology in review": {
+ "events": {
+ "rows": [
+ {
+ "category": "statement",
+ "confidence": "certain",
+ "earliest": "2026-08-01T14:05:00.000000Z",
+ "id": "temporal:claim:claim:Convoy crossed the east bridge",
+ "kind": "claim",
+ "label": "Convoy crossed the east bridge",
+ "latest": "2026-08-01T14:05:01.000000Z",
+ "owner_id": "claim:Convoy crossed the east bridge",
+ "parse_error": null,
+ "places": [
+ "place:Tower"
+ ],
+ "precision": "second",
+ "raw": "2026-08-01T14:05:00Z",
+ "sources": [
+ "media:photo"
+ ],
+ "status": "confirmed",
+ "subjects": [
+ "vessel:MV Aurora"
+ ],
+ "time_role": "occurred"
+ },
+ {
+ "category": "statement",
+ "confidence": null,
+ "earliest": null,
+ "id": "temporal:claim:claim:Harbour master called in",
+ "kind": "claim",
+ "label": "Harbour master called in",
+ "latest": null,
+ "owner_id": "claim:Harbour master called in",
+ "parse_error": null,
+ "places": [],
+ "precision": "second",
+ "raw": "2026-08-02T08:30:00",
+ "sources": [],
+ "status": "confirmed",
+ "subjects": [
+ "person:A. Nadeau"
+ ],
+ "time_role": null
+ },
+ {
+ "category": "statement",
+ "confidence": null,
+ "earliest": null,
+ "id": "temporal:claim:claim:Owner changed the flag",
+ "kind": "claim",
+ "label": "Owner changed the flag",
+ "latest": null,
+ "owner_id": "claim:Owner changed the flag",
+ "parse_error": null,
+ "places": [],
+ "precision": null,
+ "raw": null,
+ "sources": [],
+ "status": "confirmed",
+ "subjects": [
+ "organization:Northwind Shipping",
+ "vessel:MV Aurora"
+ ],
+ "time_role": null
+ },
+ {
+ "category": "statement",
+ "confidence": "probable",
+ "earliest": "2026-07-30T00:00:00.000000Z",
+ "id": "temporal:claim:claim:Quay 4 warehouse burned",
+ "kind": "claim",
+ "label": "Quay 4 warehouse burned",
+ "latest": "2026-08-03T00:00:00.000000Z",
+ "owner_id": "claim:Quay 4 warehouse burned",
+ "parse_error": null,
+ "places": [
+ "place:Tower"
+ ],
+ "precision": "day",
+ "raw": "2026-07-30/2026-08-02",
+ "sources": [
+ "bookmark:Harbour watch thread"
+ ],
+ "status": "confirmed",
+ "subjects": [
+ "structure:Quay 4 warehouse"
+ ],
+ "time_role": "occurred"
+ },
+ {
+ "category": "statement",
+ "confidence": "possible",
+ "earliest": null,
+ "id": "temporal:claim:claim:Two Handysize bulkers berthed at Quay 4",
+ "kind": "claim",
+ "label": "Two Handysize bulkers berthed at Quay 4",
+ "latest": null,
+ "owner_id": "claim:Two Handysize bulkers berthed at Quay 4",
+ "parse_error": null,
+ "places": [
+ "place:Tower"
+ ],
+ "precision": null,
+ "raw": null,
+ "sources": [],
+ "status": "confirmed",
+ "subjects": [
+ "equipment-type:Handysize bulker"
+ ],
+ "time_role": null
+ },
+ {
+ "category": "statement",
+ "confidence": null,
+ "earliest": "2026-08-01T00:00:00.000000Z",
+ "id": "temporal:claim:claim:Vessel seen leaving around the first",
+ "kind": "claim",
+ "label": "Vessel seen leaving around the first",
+ "latest": "2026-08-02T00:00:00.000000Z",
+ "owner_id": "claim:Vessel seen leaving around the first",
+ "parse_error": null,
+ "places": [
+ "place:Tower"
+ ],
+ "precision": "day",
+ "raw": "2026-08-01~",
+ "sources": [],
+ "status": "confirmed",
+ "subjects": [
+ "vessel:MV Aurora"
+ ],
+ "time_role": "observed"
+ },
+ {
+ "category": "statement",
+ "confidence": "probable",
+ "earliest": "2026-08-01T09:12:00.000000Z",
+ "id": "temporal:claim:claim:Where was the photo taken?",
+ "kind": "claim",
+ "label": "Where was the photo taken?",
+ "latest": "2026-08-01T09:12:01.000000Z",
+ "owner_id": "claim:Where was the photo taken?",
+ "parse_error": null,
+ "places": [
+ "place:Tower"
+ ],
+ "precision": "second",
+ "raw": "2026-08-01T09:12:00Z",
+ "sources": [
+ "bookmark:Harbour watch thread",
+ "note:Witness"
+ ],
+ "status": "confirmed",
+ "subjects": [
+ "media:photo"
+ ],
+ "time_role": "observed"
+ }
+ ],
+ "undated": 2,
+ "unplaced": 1
+ }
+ },
+ "Chronology with media": {
+ "events": {
+ "rows": [
+ {
+ "category": "statement",
+ "confidence": "certain",
+ "earliest": "2026-08-01T14:05:00.000000Z",
+ "id": "temporal:claim:claim:Convoy crossed the east bridge",
+ "kind": "claim",
+ "label": "Convoy crossed the east bridge",
+ "latest": "2026-08-01T14:05:01.000000Z",
+ "owner_id": "claim:Convoy crossed the east bridge",
+ "parse_error": null,
+ "places": [
+ "place:Tower"
+ ],
+ "precision": "second",
+ "raw": "2026-08-01T14:05:00Z",
+ "sources": [
+ "media:photo"
+ ],
+ "status": "confirmed",
+ "subjects": [
+ "vessel:MV Aurora"
+ ],
+ "time_role": "occurred"
+ },
+ {
+ "category": "statement",
+ "confidence": null,
+ "earliest": null,
+ "id": "temporal:claim:claim:Harbour master called in",
+ "kind": "claim",
+ "label": "Harbour master called in",
+ "latest": null,
+ "owner_id": "claim:Harbour master called in",
+ "parse_error": null,
+ "places": [],
+ "precision": "second",
+ "raw": "2026-08-02T08:30:00",
+ "sources": [],
+ "status": "confirmed",
+ "subjects": [
+ "person:A. Nadeau"
+ ],
+ "time_role": null
+ },
+ {
+ "category": "statement",
+ "confidence": null,
+ "earliest": "2026-07-31T16:20:00.000000Z",
+ "id": "temporal:claim:claim:Material of Bridge proof was taken",
+ "kind": "claim",
+ "label": "Material of Bridge proof was taken",
+ "latest": "2026-07-31T16:20:01.000000Z",
+ "owner_id": "claim:Material of Bridge proof was taken",
+ "parse_error": null,
+ "places": [],
+ "precision": "second",
+ "raw": "2026-07-31T16:20:00Z",
+ "sources": [
+ "proof:Bridge proof"
+ ],
+ "status": "confirmed",
+ "subjects": [
+ "media:piece"
+ ],
+ "time_role": "observed"
+ },
+ {
+ "category": "statement",
+ "confidence": "refuted",
+ "earliest": "2026-08-03T19:10:00.000000Z",
+ "id": "temporal:claim:claim:Night strike on the quay",
+ "kind": "claim",
+ "label": "Night strike on the quay",
+ "latest": "2026-08-03T19:10:01.000000Z",
+ "owner_id": "claim:Night strike on the quay",
+ "parse_error": null,
+ "places": [
+ "place:Tower"
+ ],
+ "precision": "second",
+ "raw": "2026-08-03T22:10:00+03:00",
+ "sources": [],
+ "status": "confirmed",
+ "subjects": [
+ "structure:Quay 4 warehouse"
+ ],
+ "time_role": null
+ },
+ {
+ "category": "statement",
+ "confidence": null,
+ "earliest": null,
+ "id": "temporal:claim:claim:Owner changed the flag",
+ "kind": "claim",
+ "label": "Owner changed the flag",
+ "latest": null,
+ "owner_id": "claim:Owner changed the flag",
+ "parse_error": null,
+ "places": [],
+ "precision": null,
+ "raw": null,
+ "sources": [],
+ "status": "confirmed",
+ "subjects": [
+ "organization:Northwind Shipping",
+ "vessel:MV Aurora"
+ ],
+ "time_role": null
+ },
+ {
+ "category": "statement",
+ "confidence": "probable",
+ "earliest": "2026-07-30T00:00:00.000000Z",
+ "id": "temporal:claim:claim:Quay 4 warehouse burned",
+ "kind": "claim",
+ "label": "Quay 4 warehouse burned",
+ "latest": "2026-08-03T00:00:00.000000Z",
+ "owner_id": "claim:Quay 4 warehouse burned",
+ "parse_error": null,
+ "places": [
+ "place:Tower"
+ ],
+ "precision": "day",
+ "raw": "2026-07-30/2026-08-02",
+ "sources": [
+ "bookmark:Harbour watch thread"
+ ],
+ "status": "confirmed",
+ "subjects": [
+ "structure:Quay 4 warehouse"
+ ],
+ "time_role": "occurred"
+ },
+ {
+ "category": "statement",
+ "confidence": "possible",
+ "earliest": "2026-07-01T00:00:00.000000Z",
+ "id": "temporal:claim:claim:Recruitment announced",
+ "kind": "claim",
+ "label": "Recruitment announced",
+ "latest": "2026-08-01T00:00:00.000000Z",
+ "owner_id": "claim:Recruitment announced",
+ "parse_error": null,
+ "places": [],
+ "precision": "month",
+ "raw": "2026-07",
+ "sources": [
+ "bookmark:Harbour watch thread"
+ ],
+ "status": "confirmed",
+ "subjects": [
+ "account:@harbourwatch"
+ ],
+ "time_role": null
+ },
+ {
+ "category": "statement",
+ "confidence": "possible",
+ "earliest": "2026-08-06T00:00:00.000000Z",
+ "id": "temporal:claim:claim:Second convoy suggested",
+ "kind": "claim",
+ "label": "Second convoy suggested",
+ "latest": "2026-08-07T00:00:00.000000Z",
+ "owner_id": "claim:Second convoy suggested",
+ "parse_error": null,
+ "places": [],
+ "precision": "day",
+ "raw": "2026-08-06",
+ "sources": [],
+ "status": "suggested",
+ "subjects": [],
+ "time_role": null
+ },
+ {
+ "category": "statement",
+ "confidence": "possible",
+ "earliest": null,
+ "id": "temporal:claim:claim:Two Handysize bulkers berthed at Quay 4",
+ "kind": "claim",
+ "label": "Two Handysize bulkers berthed at Quay 4",
+ "latest": null,
+ "owner_id": "claim:Two Handysize bulkers berthed at Quay 4",
+ "parse_error": null,
+ "places": [
+ "place:Tower"
+ ],
+ "precision": null,
+ "raw": null,
+ "sources": [],
+ "status": "confirmed",
+ "subjects": [
+ "equipment-type:Handysize bulker"
+ ],
+ "time_role": null
+ },
+ {
+ "category": "statement",
+ "confidence": null,
+ "earliest": "2026-08-01T00:00:00.000000Z",
+ "id": "temporal:claim:claim:Vessel seen leaving around the first",
+ "kind": "claim",
+ "label": "Vessel seen leaving around the first",
+ "latest": "2026-08-02T00:00:00.000000Z",
+ "owner_id": "claim:Vessel seen leaving around the first",
+ "parse_error": null,
+ "places": [
+ "place:Tower"
+ ],
+ "precision": "day",
+ "raw": "2026-08-01~",
+ "sources": [],
+ "status": "confirmed",
+ "subjects": [
+ "vessel:MV Aurora"
+ ],
+ "time_role": "observed"
+ },
+ {
+ "category": "statement",
+ "confidence": "probable",
+ "earliest": "2026-08-01T09:12:00.000000Z",
+ "id": "temporal:claim:claim:Where was the photo taken?",
+ "kind": "claim",
+ "label": "Where was the photo taken?",
+ "latest": "2026-08-01T09:12:01.000000Z",
+ "owner_id": "claim:Where was the photo taken?",
+ "parse_error": null,
+ "places": [
+ "place:Tower"
+ ],
+ "precision": "second",
+ "raw": "2026-08-01T09:12:00Z",
+ "sources": [
+ "bookmark:Harbour watch thread",
+ "note:Witness"
+ ],
+ "status": "confirmed",
+ "subjects": [
+ "media:photo"
+ ],
+ "time_role": "observed"
+ }
+ ],
+ "undated": 2,
+ "unplaced": 1
+ },
+ "media": {
+ "rows": [
+ {
+ "category": "media",
+ "confidence": null,
+ "earliest": null,
+ "id": "temporal:media:media:harbour:captured",
+ "kind": "captured",
+ "label": "harbour",
+ "latest": null,
+ "owner_id": "media:harbour",
+ "parse_error": null,
+ "places": [],
+ "precision": "second",
+ "raw": "2026-08-01T13:58:00",
+ "sources": [],
+ "status": null,
+ "subjects": [],
+ "time_role": null
+ }
+ ],
+ "undated": 0,
+ "unplaced": 1
+ },
+ "preset-activity": {
+ "rows": [],
+ "undated": 0,
+ "unplaced": 0
+ },
+ "preset-vessel": {
+ "rows": [
+ {
+ "category": "statement",
+ "confidence": "certain",
+ "earliest": "2026-08-01T14:05:00.000000Z",
+ "id": "temporal:claim:claim:Convoy crossed the east bridge",
+ "kind": "claim",
+ "label": "Convoy crossed the east bridge",
+ "latest": "2026-08-01T14:05:01.000000Z",
+ "owner_id": "claim:Convoy crossed the east bridge",
+ "parse_error": null,
+ "places": [
+ "place:Tower"
+ ],
+ "precision": "second",
+ "raw": "2026-08-01T14:05:00Z",
+ "sources": [
+ "media:photo"
+ ],
+ "status": "confirmed",
+ "subjects": [
+ "vessel:MV Aurora"
+ ],
+ "time_role": "occurred"
+ },
+ {
+ "category": "statement",
+ "confidence": null,
+ "earliest": null,
+ "id": "temporal:claim:claim:Owner changed the flag",
+ "kind": "claim",
+ "label": "Owner changed the flag",
+ "latest": null,
+ "owner_id": "claim:Owner changed the flag",
+ "parse_error": null,
+ "places": [],
+ "precision": null,
+ "raw": null,
+ "sources": [],
+ "status": "confirmed",
+ "subjects": [
+ "organization:Northwind Shipping",
+ "vessel:MV Aurora"
+ ],
+ "time_role": null
+ },
+ {
+ "category": "statement",
+ "confidence": null,
+ "earliest": "2026-08-01T00:00:00.000000Z",
+ "id": "temporal:claim:claim:Vessel seen leaving around the first",
+ "kind": "claim",
+ "label": "Vessel seen leaving around the first",
+ "latest": "2026-08-02T00:00:00.000000Z",
+ "owner_id": "claim:Vessel seen leaving around the first",
+ "parse_error": null,
+ "places": [
+ "place:Tower"
+ ],
+ "precision": "day",
+ "raw": "2026-08-01~",
+ "sources": [],
+ "status": "confirmed",
+ "subjects": [
+ "vessel:MV Aurora"
+ ],
+ "time_role": "observed"
+ }
+ ],
+ "undated": 1,
+ "unplaced": 0
+ }
+ },
+ "Fleet graph": [
+ "organization:3rd Harbour Brigade",
+ "organization:Northwind Shipping",
+ "structure:Quay 4 warehouse",
+ "vessel:MV Aurora"
+ ],
+ "People in review": []
+ },
+ "media": {
+ "rows": [
+ {
+ "category": "media",
+ "confidence": null,
+ "earliest": "2026-05-04T00:00:00.000000Z",
+ "id": "temporal:media:media:Levelled yard:imagery-a",
+ "kind": "imagery-a",
+ "label": "Levelled yard",
+ "latest": "2026-05-05T00:00:00.000000Z",
+ "owner_id": "media:Levelled yard",
+ "parse_error": null,
+ "places": [],
+ "precision": "day",
+ "raw": "2026-05-04",
+ "sources": [],
+ "status": null,
+ "subjects": [],
+ "time_role": null
+ },
+ {
+ "category": "media",
+ "confidence": null,
+ "earliest": "2026-05-11T00:00:00.000000Z",
+ "id": "temporal:media:media:Levelled yard:imagery-b",
+ "kind": "imagery-b",
+ "label": "Levelled yard",
+ "latest": "2026-05-12T00:00:00.000000Z",
+ "owner_id": "media:Levelled yard",
+ "parse_error": null,
+ "places": [],
+ "precision": "day",
+ "raw": "2026-05-11",
+ "sources": [],
+ "status": null,
+ "subjects": [],
+ "time_role": null
+ },
+ {
+ "category": "media",
+ "confidence": null,
+ "earliest": null,
+ "id": "temporal:media:media:harbour:captured",
+ "kind": "captured",
+ "label": "harbour",
+ "latest": null,
+ "owner_id": "media:harbour",
+ "parse_error": null,
+ "places": [],
+ "precision": "second",
+ "raw": "2026-08-01T13:58:00",
+ "sources": [],
+ "status": null,
+ "subjects": [],
+ "time_role": null
+ }
+ ],
+ "undated": 0,
+ "unplaced": 1
+ },
+ "notes": "# case\n\nOwner is [[entity:organization:Northwind Shipping|Northwind Shipping]], crew named by [[entity:person:A. Nadeau|A. Nadeau]].\n\n[[media:media/photo.png]]\n",
+ "promoted": "organization:3rd Harbour Brigade",
+ "search": {
+ "@harbourwatch": [
+ "account:@harbourwatch"
+ ],
+ "Nadeau": [
+ "person:A. Nadeau"
+ ],
+ "Quay 4": [
+ "claim:Quay 4 warehouse burned",
+ "claim:Two Handysize bulkers berthed at Quay 4",
+ "structure:Quay 4 warehouse"
+ ],
+ "aurora": [
+ "vessel:MV Aurora"
+ ],
+ "brigade": [
+ "organization:3rd Harbour Brigade"
+ ],
+ "handy bulker": [
+ "claim:Two Handysize bulkers berthed at Quay 4",
+ "equipment-type:Handysize bulker"
+ ]
+ },
+ "summary": {
+ "by_folder": {
+ "Sources/Telegram": 1
+ },
+ "by_source": {
+ "compare": 10,
+ "inspect": 3,
+ "map-layers": 1,
+ "media-library": 3,
+ "post-composer": 1,
+ "proof-composer": 3,
+ "satellite": 2,
+ "sheet": 3,
+ "user": 20
+ },
+ "by_status": {
+ "confirmed": 45,
+ "suggested": 1
+ },
+ "by_type": {
+ "account": 1,
+ "analysis-area": 2,
+ "analysis-follow-up": 1,
+ "analysis-run": 1,
+ "analysis-zones": 1,
+ "bookmark": 1,
+ "capture": 1,
+ "claim": 13,
+ "collage": 1,
+ "compare-session": 1,
+ "equipment-type": 1,
+ "inspect-session": 1,
+ "map-layer": 1,
+ "media": 6,
+ "network": 1,
+ "note": 1,
+ "organization": 2,
+ "person": 1,
+ "place": 2,
+ "post": 1,
+ "proof": 2,
+ "sheet": 2,
+ "structure": 1,
+ "vessel": 1
+ },
+ "countable": 1,
+ "lacks": {
+ "assessment": 6,
+ "source": 6
+ },
+ "linked_to": {
+ "account": 3,
+ "bookmark": 3,
+ "capture": 4,
+ "claim": 14,
+ "equipment-type": 2,
+ "inspect-session": 1,
+ "media": 20,
+ "network": 1,
+ "note": 2,
+ "organization": 3,
+ "person": 4,
+ "place": 10,
+ "post": 2,
+ "proof": 4,
+ "sheet": 3,
+ "structure": 4,
+ "vessel": 6
+ },
+ "total": 46,
+ "unlinked": 9
+ },
+ "views": {
+ "Actors frozen": {
+ "mode": "snapshot",
+ "spec": {
+ "board": {
+ "order": "label",
+ "sortDesc": false,
+ "sortKey": "label"
+ },
+ "query": {
+ "filter": {
+ "families": [
+ "actor"
+ ]
+ },
+ "label": "People and organizations",
+ "terms": {
+ "type": "person,organization"
+ }
+ },
+ "snapshot": {
+ "entities": [
+ "organization:3rd Harbour Brigade",
+ "organization:Northwind Shipping",
+ "person:A. Nadeau"
+ ],
+ "links": [],
+ "timeline_items": [],
+ "timeline_tracks": {}
+ },
+ "surface": "board",
+ "timeline": {
+ "categories": [
+ "statement",
+ "media"
+ ],
+ "field": null,
+ "from": null,
+ "to": null
+ },
+ "version": 1
+ },
+ "surface": "board"
+ },
+ "Chronology as list": {
+ "mode": "live",
+ "spec": {
+ "query": {
+ "terms": {}
+ },
+ "surface": "timeline",
+ "timeline": {
+ "entity": null,
+ "field": null,
+ "from": "2026-07-01",
+ "group_by": "subject",
+ "timezone": "UTC",
+ "to": "2026-09-01",
+ "tracks": [
+ {
+ "categories": [
+ "statement"
+ ],
+ "collapsed": false,
+ "color": "",
+ "hidden": [
+ "temporal:claim:claim:Crew list circulated"
+ ],
+ "id": "events",
+ "label": "Events",
+ "pinned": [
+ "temporal:claim:claim:Recruitment announced"
+ ],
+ "query": {
+ "filter": {},
+ "label": "",
+ "relation": "any",
+ "roles": [],
+ "terms": {}
+ }
+ },
+ {
+ "categories": [
+ "media"
+ ],
+ "collapsed": false,
+ "color": "blue",
+ "hidden": [],
+ "id": "media",
+ "label": "Media",
+ "pinned": [],
+ "query": {
+ "filter": {},
+ "label": "",
+ "relation": "any",
+ "roles": [],
+ "terms": {}
+ }
+ }
+ ],
+ "view_mode": "list",
+ "visible_categories": [
+ "statement",
+ "media"
+ ],
+ "zone_choice": "utc"
+ },
+ "version": 1
+ },
+ "surface": "timeline"
+ },
+ "Chronology defaults": {
+ "mode": "live",
+ "spec": {
+ "query": {
+ "terms": {}
+ },
+ "surface": "timeline",
+ "timeline": {
+ "entity": null,
+ "field": null,
+ "from": "2026-07-01",
+ "group_by": "none",
+ "timezone": "UTC",
+ "to": "2026-09-01",
+ "tracks": [
+ {
+ "categories": [
+ "statement"
+ ],
+ "collapsed": false,
+ "color": "",
+ "hidden": [],
+ "id": "events",
+ "label": "Events",
+ "pinned": [],
+ "query": {
+ "filter": {},
+ "label": "",
+ "relation": "any",
+ "roles": [],
+ "terms": {}
+ }
+ },
+ {
+ "categories": [
+ "media"
+ ],
+ "collapsed": false,
+ "color": "",
+ "hidden": [],
+ "id": "media",
+ "label": "Media",
+ "pinned": [],
+ "query": {
+ "filter": {},
+ "label": "",
+ "relation": "any",
+ "roles": [],
+ "terms": {}
+ }
+ }
+ ],
+ "view_mode": "plot",
+ "visible_categories": [
+ "statement",
+ "media"
+ ],
+ "zone_choice": "utc"
+ },
+ "version": 1
+ },
+ "surface": "timeline"
+ },
+ "Chronology frozen": {
+ "mode": "snapshot",
+ "spec": {
+ "query": {
+ "terms": {}
+ },
+ "snapshot": {
+ "entities": [],
+ "links": [],
+ "timeline_items": [
+ {
+ "category": "statement",
+ "confidence": "certain",
+ "earliest": "2026-08-01T14:05:00.000000Z",
+ "id": "temporal:claim:claim:Convoy crossed the east bridge",
+ "kind": "claim",
+ "label": "Convoy crossed the east bridge",
+ "latest": "2026-08-01T14:05:01.000000Z",
+ "owner_id": "claim:Convoy crossed the east bridge",
+ "parse_error": null,
+ "places": [
+ "place:Tower"
+ ],
+ "precision": "second",
+ "raw": "2026-08-01T14:05:00Z",
+ "sources": [
+ "media:photo"
+ ],
+ "status": "confirmed",
+ "subjects": [
+ "vessel:MV Aurora"
+ ],
+ "time_role": "occurred"
+ },
+ {
+ "category": "statement",
+ "confidence": null,
+ "earliest": null,
+ "id": "temporal:claim:claim:Harbour master called in",
+ "kind": "claim",
+ "label": "Harbour master called in",
+ "latest": null,
+ "owner_id": "claim:Harbour master called in",
+ "parse_error": null,
+ "places": [],
+ "precision": "second",
+ "raw": "2026-08-02T08:30:00",
+ "sources": [],
+ "status": "confirmed",
+ "subjects": [
+ "person:A. Nadeau"
+ ],
+ "time_role": null
+ },
+ {
+ "category": "statement",
+ "confidence": null,
+ "earliest": "2026-07-31T16:20:00.000000Z",
+ "id": "temporal:claim:claim:Material of Bridge proof was taken",
+ "kind": "claim",
+ "label": "Material of Bridge proof was taken",
+ "latest": "2026-07-31T16:20:01.000000Z",
+ "owner_id": "claim:Material of Bridge proof was taken",
+ "parse_error": null,
+ "places": [],
+ "precision": "second",
+ "raw": "2026-07-31T16:20:00Z",
+ "sources": [
+ "proof:Bridge proof"
+ ],
+ "status": "confirmed",
+ "subjects": [
+ "media:piece"
+ ],
+ "time_role": "observed"
+ },
+ {
+ "category": "statement",
+ "confidence": "refuted",
+ "earliest": "2026-08-03T19:10:00.000000Z",
+ "id": "temporal:claim:claim:Night strike on the quay",
+ "kind": "claim",
+ "label": "Night strike on the quay",
+ "latest": "2026-08-03T19:10:01.000000Z",
+ "owner_id": "claim:Night strike on the quay",
+ "parse_error": null,
+ "places": [
+ "place:Tower"
+ ],
+ "precision": "second",
+ "raw": "2026-08-03T22:10:00+03:00",
+ "sources": [],
+ "status": "confirmed",
+ "subjects": [
+ "structure:Quay 4 warehouse"
+ ],
+ "time_role": null
+ },
+ {
+ "category": "statement",
+ "confidence": null,
+ "earliest": null,
+ "id": "temporal:claim:claim:Owner changed the flag",
+ "kind": "claim",
+ "label": "Owner changed the flag",
+ "latest": null,
+ "owner_id": "claim:Owner changed the flag",
+ "parse_error": null,
+ "places": [],
+ "precision": null,
+ "raw": null,
+ "sources": [],
+ "status": "confirmed",
+ "subjects": [
+ "organization:Northwind Shipping",
+ "vessel:MV Aurora"
+ ],
+ "time_role": null
+ },
+ {
+ "category": "statement",
+ "confidence": "probable",
+ "earliest": "2026-07-30T00:00:00.000000Z",
+ "id": "temporal:claim:claim:Quay 4 warehouse burned",
+ "kind": "claim",
+ "label": "Quay 4 warehouse burned",
+ "latest": "2026-08-03T00:00:00.000000Z",
+ "owner_id": "claim:Quay 4 warehouse burned",
+ "parse_error": null,
+ "places": [
+ "place:Tower"
+ ],
+ "precision": "day",
+ "raw": "2026-07-30/2026-08-02",
+ "sources": [
+ "bookmark:Harbour watch thread"
+ ],
+ "status": "confirmed",
+ "subjects": [
+ "structure:Quay 4 warehouse"
+ ],
+ "time_role": "occurred"
+ },
+ {
+ "category": "statement",
+ "confidence": "possible",
+ "earliest": "2026-07-01T00:00:00.000000Z",
+ "id": "temporal:claim:claim:Recruitment announced",
+ "kind": "claim",
+ "label": "Recruitment announced",
+ "latest": "2026-08-01T00:00:00.000000Z",
+ "owner_id": "claim:Recruitment announced",
+ "parse_error": null,
+ "places": [],
+ "precision": "month",
+ "raw": "2026-07",
+ "sources": [
+ "bookmark:Harbour watch thread"
+ ],
+ "status": "confirmed",
+ "subjects": [
+ "account:@harbourwatch"
+ ],
+ "time_role": null
+ },
+ {
+ "category": "statement",
+ "confidence": "possible",
+ "earliest": "2026-08-06T00:00:00.000000Z",
+ "id": "temporal:claim:claim:Second convoy suggested",
+ "kind": "claim",
+ "label": "Second convoy suggested",
+ "latest": "2026-08-07T00:00:00.000000Z",
+ "owner_id": "claim:Second convoy suggested",
+ "parse_error": null,
+ "places": [],
+ "precision": "day",
+ "raw": "2026-08-06",
+ "sources": [],
+ "status": "suggested",
+ "subjects": [],
+ "time_role": null
+ },
+ {
+ "category": "statement",
+ "confidence": "possible",
+ "earliest": null,
+ "id": "temporal:claim:claim:Two Handysize bulkers berthed at Quay 4",
+ "kind": "claim",
+ "label": "Two Handysize bulkers berthed at Quay 4",
+ "latest": null,
+ "owner_id": "claim:Two Handysize bulkers berthed at Quay 4",
+ "parse_error": null,
+ "places": [
+ "place:Tower"
+ ],
+ "precision": null,
+ "raw": null,
+ "sources": [],
+ "status": "confirmed",
+ "subjects": [
+ "equipment-type:Handysize bulker"
+ ],
+ "time_role": null
+ },
+ {
+ "category": "statement",
+ "confidence": null,
+ "earliest": "2026-08-01T00:00:00.000000Z",
+ "id": "temporal:claim:claim:Vessel seen leaving around the first",
+ "kind": "claim",
+ "label": "Vessel seen leaving around the first",
+ "latest": "2026-08-02T00:00:00.000000Z",
+ "owner_id": "claim:Vessel seen leaving around the first",
+ "parse_error": null,
+ "places": [
+ "place:Tower"
+ ],
+ "precision": "day",
+ "raw": "2026-08-01~",
+ "sources": [],
+ "status": "confirmed",
+ "subjects": [
+ "vessel:MV Aurora"
+ ],
+ "time_role": "observed"
+ },
+ {
+ "category": "statement",
+ "confidence": "probable",
+ "earliest": "2026-08-01T09:12:00.000000Z",
+ "id": "temporal:claim:claim:Where was the photo taken?",
+ "kind": "claim",
+ "label": "Where was the photo taken?",
+ "latest": "2026-08-01T09:12:01.000000Z",
+ "owner_id": "claim:Where was the photo taken?",
+ "parse_error": null,
+ "places": [
+ "place:Tower"
+ ],
+ "precision": "second",
+ "raw": "2026-08-01T09:12:00Z",
+ "sources": [
+ "bookmark:Harbour watch thread",
+ "note:Witness"
+ ],
+ "status": "confirmed",
+ "subjects": [
+ "media:photo"
+ ],
+ "time_role": "observed"
+ },
+ {
+ "category": "media",
+ "confidence": null,
+ "earliest": null,
+ "id": "temporal:media:media:harbour:captured",
+ "kind": "captured",
+ "label": "harbour",
+ "latest": null,
+ "owner_id": "media:harbour",
+ "parse_error": null,
+ "places": [],
+ "precision": "second",
+ "raw": "2026-08-01T13:58:00",
+ "sources": [],
+ "status": null,
+ "subjects": [],
+ "time_role": null
+ }
+ ],
+ "timeline_tracks": {
+ "events": [
+ "temporal:claim:claim:Convoy crossed the east bridge",
+ "temporal:claim:claim:Harbour master called in",
+ "temporal:claim:claim:Material of Bridge proof was taken",
+ "temporal:claim:claim:Night strike on the quay",
+ "temporal:claim:claim:Owner changed the flag",
+ "temporal:claim:claim:Quay 4 warehouse burned",
+ "temporal:claim:claim:Recruitment announced",
+ "temporal:claim:claim:Second convoy suggested",
+ "temporal:claim:claim:Two Handysize bulkers berthed at Quay 4",
+ "temporal:claim:claim:Vessel seen leaving around the first",
+ "temporal:claim:claim:Where was the photo taken?"
+ ],
+ "media": [
+ "temporal:media:media:harbour:captured"
+ ],
+ "preset-vessel": [
+ "temporal:claim:claim:Convoy crossed the east bridge",
+ "temporal:claim:claim:Owner changed the flag",
+ "temporal:claim:claim:Vessel seen leaving around the first"
+ ]
+ }
+ },
+ "surface": "timeline",
+ "timeline": {
+ "entity": null,
+ "field": null,
+ "from": "2026-07-01",
+ "group_by": "none",
+ "timezone": "UTC",
+ "to": "2026-09-01",
+ "tracks": [
+ {
+ "categories": [
+ "statement"
+ ],
+ "collapsed": false,
+ "color": "",
+ "hidden": [
+ "temporal:claim:claim:Crew list circulated"
+ ],
+ "id": "events",
+ "label": "Events",
+ "pinned": [
+ "temporal:claim:claim:Recruitment announced"
+ ],
+ "query": {
+ "filter": {},
+ "label": "",
+ "relation": "any",
+ "roles": [],
+ "terms": {}
+ }
+ },
+ {
+ "categories": [
+ "media"
+ ],
+ "collapsed": false,
+ "color": "blue",
+ "hidden": [],
+ "id": "media",
+ "label": "Media",
+ "pinned": [],
+ "query": {
+ "filter": {},
+ "label": "",
+ "relation": "any",
+ "roles": [],
+ "terms": {}
+ }
+ },
+ {
+ "categories": [
+ "statement"
+ ],
+ "collapsed": false,
+ "color": "",
+ "hidden": [],
+ "id": "preset-vessel",
+ "label": "Vessel",
+ "pinned": [],
+ "query": {
+ "filter": {
+ "types": [
+ "vessel"
+ ]
+ },
+ "label": "",
+ "relation": "about",
+ "roles": [],
+ "terms": {
+ "type": "vessel"
+ }
+ }
+ }
+ ],
+ "view_mode": "plot",
+ "visible_categories": [
+ "statement",
+ "media"
+ ],
+ "zone_choice": "utc"
+ },
+ "version": 1
+ },
+ "surface": "timeline"
+ },
+ "Chronology in review": {
+ "mode": "live",
+ "spec": {
+ "query": {
+ "terms": {}
+ },
+ "surface": "timeline",
+ "timeline": {
+ "entity": null,
+ "field": null,
+ "from": "2026-08-01",
+ "group_by": "none",
+ "timezone": "UTC",
+ "to": "2026-08-02",
+ "tracks": [
+ {
+ "categories": [
+ "statement"
+ ],
+ "collapsed": false,
+ "color": "",
+ "hidden": [],
+ "id": "events",
+ "label": "Events",
+ "pinned": [],
+ "query": {
+ "filter": {},
+ "label": "",
+ "relation": "any",
+ "roles": [],
+ "terms": {}
+ }
+ }
+ ],
+ "view_mode": "plot",
+ "visible_categories": [
+ "statement"
+ ],
+ "zone_choice": "utc"
+ },
+ "version": 1
+ },
+ "surface": "timeline"
+ },
+ "Chronology list frozen": {
+ "mode": "snapshot",
+ "spec": {
+ "query": {
+ "terms": {}
+ },
+ "snapshot": {
+ "entities": [],
+ "links": [],
+ "timeline_items": [
+ {
+ "category": "statement",
+ "confidence": "certain",
+ "earliest": "2026-08-01T14:05:00.000000Z",
+ "id": "temporal:claim:claim:Convoy crossed the east bridge",
+ "kind": "claim",
+ "label": "Convoy crossed the east bridge",
+ "latest": "2026-08-01T14:05:01.000000Z",
+ "owner_id": "claim:Convoy crossed the east bridge",
+ "parse_error": null,
+ "places": [
+ "place:Tower"
+ ],
+ "precision": "second",
+ "raw": "2026-08-01T14:05:00Z",
+ "sources": [
+ "media:photo"
+ ],
+ "status": "confirmed",
+ "subjects": [
+ "vessel:MV Aurora"
+ ],
+ "time_role": "occurred"
+ },
+ {
+ "category": "statement",
+ "confidence": null,
+ "earliest": null,
+ "id": "temporal:claim:claim:Harbour master called in",
+ "kind": "claim",
+ "label": "Harbour master called in",
+ "latest": null,
+ "owner_id": "claim:Harbour master called in",
+ "parse_error": null,
+ "places": [],
+ "precision": "second",
+ "raw": "2026-08-02T08:30:00",
+ "sources": [],
+ "status": "confirmed",
+ "subjects": [
+ "person:A. Nadeau"
+ ],
+ "time_role": null
+ },
+ {
+ "category": "statement",
+ "confidence": null,
+ "earliest": "2026-07-31T16:20:00.000000Z",
+ "id": "temporal:claim:claim:Material of Bridge proof was taken",
+ "kind": "claim",
+ "label": "Material of Bridge proof was taken",
+ "latest": "2026-07-31T16:20:01.000000Z",
+ "owner_id": "claim:Material of Bridge proof was taken",
+ "parse_error": null,
+ "places": [],
+ "precision": "second",
+ "raw": "2026-07-31T16:20:00Z",
+ "sources": [
+ "proof:Bridge proof"
+ ],
+ "status": "confirmed",
+ "subjects": [
+ "media:piece"
+ ],
+ "time_role": "observed"
+ },
+ {
+ "category": "statement",
+ "confidence": "refuted",
+ "earliest": "2026-08-03T19:10:00.000000Z",
+ "id": "temporal:claim:claim:Night strike on the quay",
+ "kind": "claim",
+ "label": "Night strike on the quay",
+ "latest": "2026-08-03T19:10:01.000000Z",
+ "owner_id": "claim:Night strike on the quay",
+ "parse_error": null,
+ "places": [
+ "place:Tower"
+ ],
+ "precision": "second",
+ "raw": "2026-08-03T22:10:00+03:00",
+ "sources": [],
+ "status": "confirmed",
+ "subjects": [
+ "structure:Quay 4 warehouse"
+ ],
+ "time_role": null
+ },
+ {
+ "category": "statement",
+ "confidence": null,
+ "earliest": null,
+ "id": "temporal:claim:claim:Owner changed the flag",
+ "kind": "claim",
+ "label": "Owner changed the flag",
+ "latest": null,
+ "owner_id": "claim:Owner changed the flag",
+ "parse_error": null,
+ "places": [],
+ "precision": null,
+ "raw": null,
+ "sources": [],
+ "status": "confirmed",
+ "subjects": [
+ "organization:Northwind Shipping",
+ "vessel:MV Aurora"
+ ],
+ "time_role": null
+ },
+ {
+ "category": "statement",
+ "confidence": "probable",
+ "earliest": "2026-07-30T00:00:00.000000Z",
+ "id": "temporal:claim:claim:Quay 4 warehouse burned",
+ "kind": "claim",
+ "label": "Quay 4 warehouse burned",
+ "latest": "2026-08-03T00:00:00.000000Z",
+ "owner_id": "claim:Quay 4 warehouse burned",
+ "parse_error": null,
+ "places": [
+ "place:Tower"
+ ],
+ "precision": "day",
+ "raw": "2026-07-30/2026-08-02",
+ "sources": [
+ "bookmark:Harbour watch thread"
+ ],
+ "status": "confirmed",
+ "subjects": [
+ "structure:Quay 4 warehouse"
+ ],
+ "time_role": "occurred"
+ },
+ {
+ "category": "statement",
+ "confidence": "possible",
+ "earliest": "2026-07-01T00:00:00.000000Z",
+ "id": "temporal:claim:claim:Recruitment announced",
+ "kind": "claim",
+ "label": "Recruitment announced",
+ "latest": "2026-08-01T00:00:00.000000Z",
+ "owner_id": "claim:Recruitment announced",
+ "parse_error": null,
+ "places": [],
+ "precision": "month",
+ "raw": "2026-07",
+ "sources": [
+ "bookmark:Harbour watch thread"
+ ],
+ "status": "confirmed",
+ "subjects": [
+ "account:@harbourwatch"
+ ],
+ "time_role": null
+ },
+ {
+ "category": "statement",
+ "confidence": "possible",
+ "earliest": "2026-08-06T00:00:00.000000Z",
+ "id": "temporal:claim:claim:Second convoy suggested",
+ "kind": "claim",
+ "label": "Second convoy suggested",
+ "latest": "2026-08-07T00:00:00.000000Z",
+ "owner_id": "claim:Second convoy suggested",
+ "parse_error": null,
+ "places": [],
+ "precision": "day",
+ "raw": "2026-08-06",
+ "sources": [],
+ "status": "suggested",
+ "subjects": [],
+ "time_role": null
+ },
+ {
+ "category": "statement",
+ "confidence": "possible",
+ "earliest": null,
+ "id": "temporal:claim:claim:Two Handysize bulkers berthed at Quay 4",
+ "kind": "claim",
+ "label": "Two Handysize bulkers berthed at Quay 4",
+ "latest": null,
+ "owner_id": "claim:Two Handysize bulkers berthed at Quay 4",
+ "parse_error": null,
+ "places": [
+ "place:Tower"
+ ],
+ "precision": null,
+ "raw": null,
+ "sources": [],
+ "status": "confirmed",
+ "subjects": [
+ "equipment-type:Handysize bulker"
+ ],
+ "time_role": null
+ },
+ {
+ "category": "statement",
+ "confidence": null,
+ "earliest": "2026-08-01T00:00:00.000000Z",
+ "id": "temporal:claim:claim:Vessel seen leaving around the first",
+ "kind": "claim",
+ "label": "Vessel seen leaving around the first",
+ "latest": "2026-08-02T00:00:00.000000Z",
+ "owner_id": "claim:Vessel seen leaving around the first",
+ "parse_error": null,
+ "places": [
+ "place:Tower"
+ ],
+ "precision": "day",
+ "raw": "2026-08-01~",
+ "sources": [],
+ "status": "confirmed",
+ "subjects": [
+ "vessel:MV Aurora"
+ ],
+ "time_role": "observed"
+ },
+ {
+ "category": "statement",
+ "confidence": "probable",
+ "earliest": "2026-08-01T09:12:00.000000Z",
+ "id": "temporal:claim:claim:Where was the photo taken?",
+ "kind": "claim",
+ "label": "Where was the photo taken?",
+ "latest": "2026-08-01T09:12:01.000000Z",
+ "owner_id": "claim:Where was the photo taken?",
+ "parse_error": null,
+ "places": [
+ "place:Tower"
+ ],
+ "precision": "second",
+ "raw": "2026-08-01T09:12:00Z",
+ "sources": [
+ "bookmark:Harbour watch thread",
+ "note:Witness"
+ ],
+ "status": "confirmed",
+ "subjects": [
+ "media:photo"
+ ],
+ "time_role": "observed"
+ }
+ ],
+ "timeline_tracks": {
+ "events": [
+ "temporal:claim:claim:Convoy crossed the east bridge",
+ "temporal:claim:claim:Harbour master called in",
+ "temporal:claim:claim:Material of Bridge proof was taken",
+ "temporal:claim:claim:Night strike on the quay",
+ "temporal:claim:claim:Owner changed the flag",
+ "temporal:claim:claim:Quay 4 warehouse burned",
+ "temporal:claim:claim:Recruitment announced",
+ "temporal:claim:claim:Second convoy suggested",
+ "temporal:claim:claim:Two Handysize bulkers berthed at Quay 4",
+ "temporal:claim:claim:Vessel seen leaving around the first",
+ "temporal:claim:claim:Where was the photo taken?"
+ ]
+ }
+ },
+ "surface": "timeline",
+ "timeline": {
+ "entity": null,
+ "field": null,
+ "from": "2026-07-01",
+ "group_by": "none",
+ "timezone": "UTC",
+ "to": "2026-09-01",
+ "tracks": [
+ {
+ "categories": [
+ "statement"
+ ],
+ "collapsed": false,
+ "color": "",
+ "hidden": [
+ "temporal:claim:claim:Crew list circulated"
+ ],
+ "id": "events",
+ "label": "Events",
+ "pinned": [
+ "temporal:claim:claim:Recruitment announced"
+ ],
+ "query": {
+ "filter": {},
+ "label": "",
+ "relation": "any",
+ "roles": [],
+ "terms": {}
+ }
+ }
+ ],
+ "view_mode": "list",
+ "visible_categories": [
+ "statement"
+ ],
+ "zone_choice": "utc"
+ },
+ "version": 1
+ },
+ "surface": "timeline"
+ },
+ "Chronology with media": {
+ "mode": "live",
+ "spec": {
+ "query": {
+ "terms": {}
+ },
+ "surface": "timeline",
+ "timeline": {
+ "entity": null,
+ "field": null,
+ "from": "2026-07-01",
+ "group_by": "none",
+ "timezone": "Europe/Kyiv",
+ "to": "2026-09-01",
+ "tracks": [
+ {
+ "categories": [
+ "statement"
+ ],
+ "collapsed": false,
+ "color": "",
+ "hidden": [
+ "temporal:claim:claim:Crew list circulated"
+ ],
+ "id": "events",
+ "label": "Events",
+ "pinned": [
+ "temporal:claim:claim:Recruitment announced"
+ ],
+ "query": {
+ "filter": {},
+ "label": "",
+ "relation": "any",
+ "roles": [],
+ "terms": {}
+ }
+ },
+ {
+ "categories": [
+ "media"
+ ],
+ "collapsed": false,
+ "color": "blue",
+ "hidden": [],
+ "id": "media",
+ "label": "Media",
+ "pinned": [],
+ "query": {
+ "filter": {},
+ "label": "",
+ "relation": "any",
+ "roles": [],
+ "terms": {}
+ }
+ },
+ {
+ "categories": [
+ "statement"
+ ],
+ "collapsed": false,
+ "color": "",
+ "hidden": [],
+ "id": "preset-vessel",
+ "label": "Vessel",
+ "pinned": [],
+ "query": {
+ "filter": {
+ "types": [
+ "vessel"
+ ]
+ },
+ "label": "",
+ "relation": "about",
+ "roles": [],
+ "terms": {
+ "type": "vessel"
+ }
+ }
+ },
+ {
+ "categories": [
+ "case_activity"
+ ],
+ "collapsed": true,
+ "color": "",
+ "hidden": [],
+ "id": "preset-activity",
+ "label": "Case activity",
+ "pinned": [],
+ "query": {
+ "filter": {},
+ "label": "",
+ "relation": "any",
+ "roles": [],
+ "terms": {}
+ }
+ }
+ ],
+ "view_mode": "plot",
+ "visible_categories": [
+ "statement",
+ "media",
+ "case_activity"
+ ],
+ "zone_choice": "zone:Europe/Kyiv"
+ },
+ "version": 1
+ },
+ "surface": "timeline"
+ },
+ "Fleet graph": {
+ "mode": "live",
+ "spec": {
+ "graph": {
+ "arrangement": [
+ {
+ "id": "vessel:MV Aurora",
+ "x": 40,
+ "y": -12
+ }
+ ],
+ "camera": {
+ "x": 10,
+ "y": 20,
+ "zoom": 1.25
+ },
+ "hops": 2,
+ "kept": [
+ "vessel:MV Aurora"
+ ],
+ "lens": "all"
+ },
+ "query": {
+ "filter": {
+ "families": [
+ "asset",
+ "actor"
+ ]
+ },
+ "terms": {
+ "type": "vessel,organization,structure"
+ }
+ },
+ "surface": "graph",
+ "timeline": {
+ "categories": [
+ "statement",
+ "media"
+ ],
+ "field": null,
+ "from": null,
+ "to": null
+ },
+ "version": 1
+ },
+ "surface": "graph"
+ },
+ "Fleet graph frozen": {
+ "mode": "snapshot",
+ "spec": {
+ "graph": {
+ "hops": 1,
+ "lens": "all"
+ },
+ "query": {
+ "filter": {
+ "families": [
+ "asset"
+ ]
+ },
+ "terms": {
+ "type": "vessel,structure"
+ }
+ },
+ "snapshot": {
+ "entities": [
+ "structure:Quay 4 warehouse",
+ "vessel:MV Aurora"
+ ],
+ "links": [],
+ "timeline_items": [],
+ "timeline_tracks": {}
+ },
+ "surface": "graph",
+ "timeline": {
+ "categories": [
+ "statement",
+ "media"
+ ],
+ "field": null,
+ "from": null,
+ "to": null
+ },
+ "version": 1
+ },
+ "surface": "graph"
+ },
+ "People in review": {
+ "mode": "live",
+ "spec": {
+ "board": {
+ "order": "-created",
+ "sortDesc": true,
+ "sortKey": "created"
+ },
+ "query": {
+ "filter": {
+ "families": [
+ "actor"
+ ],
+ "status": "suggested"
+ },
+ "terms": {
+ "status": "suggested",
+ "type": "person,organization"
+ }
+ },
+ "surface": "board",
+ "timeline": {
+ "categories": [
+ "statement",
+ "media"
+ ],
+ "field": null,
+ "from": null,
+ "to": null
+ },
+ "version": 1
+ },
+ "surface": "board"
+ }
+ }
+}
diff --git a/tests/fixtures/fold_cases.json b/tests/fixtures/fold_cases.json
new file mode 100644
index 0000000..2437811
--- /dev/null
+++ b/tests/fixtures/fold_cases.json
@@ -0,0 +1,31 @@
+{
+ "about": "What search folds, read by tests/test_textfold.py and frontend/src/lib/textFold.test.js so the server index and the browser mirror fold alike.",
+ "cases": [
+ ["Café", "cafe", "a Latin accent"],
+ ["Hà Nội", "ha noi", "Vietnamese stacks two marks on one letter"],
+ ["Ålesund", "alesund", "a ring above"],
+ ["İstanbul", "istanbul", "a capital dotted I lowers with a dot, which goes"],
+ ["Straße", "strasse", "sharp s reads as ss"],
+ ["STRASSE", "strasse", "and the plain spelling meets it"],
+ ["Ørsted", "ørsted", "a letter of its own, not a letter with a mark"],
+ ["Łódź", "łodz", "the stroke is a letter, the acute is a mark"],
+ ["ΟΔΟΣ", "οδοσ", "a final sigma reads as a sigma"],
+ ["Ἀθῆναι", "αθηναι", "polytonic Greek loses its breathings and accents"],
+ ["Москва", "москва", "Cyrillic lowers"],
+ ["Ёлка", "елка", "ё meets е, as Russian readers expect"],
+ ["Йошкар-Ола", "иошкар-ола", "й meets и, an overmatch search accepts"],
+ ["Київ", "киів", "ї meets і"],
+ ["مُحَمَّد", "محمد", "Arabic harakat go"],
+ ["كـتـاب", "كتاب", "so does the tatweel that stretches a word"],
+ ["شَارِعٌ", "شارع", "and tanwin"],
+ ["שָׁלוֹם", "שלום", "Hebrew points go"],
+ ["בית־לחם", "בית־לחם", "the maqaf is punctuation and stays"],
+ ["हिंदी", "हिंदी", "a Devanagari sign changes the syllable and stays"],
+ ["が", "が", "a dakuten changes the sound and stays"],
+ ["ガイド", "ガイド", "on katakana too"],
+ ["[email protected]", "[email protected]", "an email keeps its punctuation"],
+ ["192.168.0.1/24", "192.168.0.1/24", "a network keeps its dots and slash"],
+ ["@Handle_01", "@handle_01", "a handle keeps its at sign and underscore"],
+ ["Café Москва\nnote", "cafe москва\nnote", "spacing and lines are left alone"]
+ ]
+}
diff --git a/tests/fullcase.py b/tests/fullcase.py
index a35adf3..60c1e22 100644
--- a/tests/fullcase.py
+++ b/tests/fullcase.py
@@ -74,6 +74,7 @@ class FullCase:
piece: str = ""
collage: str = "" # the exported picture, which is media
collage_doc: str = "" # the layout it was exported from
+ collage_thumb: str = "" # the layout's preview, which travels with it
capture: str = ""
session: str = "" # the photo's Inspect work
compare_session: str = ""
@@ -116,7 +117,7 @@ class FullCase:
entity_types: set[str] = field(default_factory=set)
-def build_full_case(client, name: str = "Full case") -> FullCase:
+def build_full_case(client, name: str = "Full case", *, subject_changes: bool = True) -> FullCase:
"""Fill one case through every tool that files an artifact.
Returns once the background queue is idle, so a caller can move or delete the
@@ -205,6 +206,12 @@ def build_full_case(client, name: str = "Full case") -> FullCase:
)
assert layout_doc.status_code == 200, layout_doc.text
full.collage_doc = f".collages/{layout_doc.json()['name']}.json"
+ preview = client.put(
+ f"/api/cases/{case_id}/collages/{layout_doc.json()['name']}/thumb",
+ files={"file": ("preview.png", io.BytesIO(_png((160, 80))), "image/png")},
+ )
+ assert preview.status_code == 200, preview.text
+ full.collage_thumb = preview.json()["thumb"]
comparison = client.post(
f"/api/cases/{case_id}/compare/sessions",
@@ -558,10 +565,14 @@ def build_full_case(client, name: str = "Full case") -> FullCase:
seed_images(analysis)
from azimut.engine.analysis_models import Zone
ring = Zone.model_validate(analysis["zones"][0]).ring()
+ area = client.post(f"/api/cases/{case_id}/analysis/areas", json={
+ "name": "Port", "colour": "#38bdf8", "geometry": {
+ "type": "Polygon", "coordinates": [ring + [ring[0]]]},
+ })
+ assert area.status_code == 200, area.text
+ full.analyzer_area = f"{layout.ANALYSIS_DIR}/areas-{area.json()['id']}.json"
for kind, body, attr in (
- ("areas", {"name": "Port", "colour": "#38bdf8", "geometry": {
- "type": "Polygon", "coordinates": [ring + [ring[0]]]}}, "analyzer_area"),
- ("zones", {"title": "Port areas", "zones": analysis["zones"]}, "analyzer_zones"),
+ ("zones", {"title": "Port areas", "area_ids": [area.json()["id"]]}, "analyzer_zones"),
("followups", analysis, "analyzer_followup"),
("runs", analysis, "analyzer_run"),
):
@@ -576,6 +587,16 @@ def build_full_case(client, name: str = "Full case") -> FullCase:
result = client.get(f"/api/cases/{case_id}/analysis/runs/{run_id}").json()
assert result["status"] == "ready", result
+ # Exercise the local merge journal, portable redirects, and retained fields in
+ # the same birth-state and bundle gates as every other case artifact.
+ if subject_changes:
+ first = entity("vehicle", "Unclassified subject")
+ changed = client.patch(f"/api/cases/{case_id}/entities/{first}", json={"type": "vessel"})
+ assert changed.status_code == 200, changed.text
+ duplicate = entity("vessel", "Duplicate subject")
+ merged = client.post(f"/api/cases/{case_id}/entities/{first}/merge", json={"other": duplicate})
+ assert merged.status_code == 200, merged.text
+
entities = client.get(
f"/api/cases/{case_id}/catalog/entities", params={"limit": 500}
).json()["items"]
diff --git a/tests/schema_rewind.py b/tests/schema_rewind.py
index 8f85f7f..b43b19e 100644
--- a/tests/schema_rewind.py
+++ b/tests/schema_rewind.py
@@ -15,10 +15,13 @@ newer SQLite than the code does is a false alarm waiting to fire on one OS.
from __future__ import annotations
+import json
import sqlite3
from contextlib import closing
from pathlib import Path
+from azimut.engine import entities as entity_engine
+
#: Objects created after schema 7, dropped newest first. A migration that adds a
#: table or an index adds its line here in the same change.
_AFTER_7 = (
@@ -30,6 +33,12 @@ _AFTER_7 = (
"DROP TABLE IF EXISTS graph_pins",
)
+#: Objects created after schema 18, the release 0.3.1 shipped.
+_AFTER_18 = (
+ "DROP TABLE IF EXISTS entity_merges",
+ "DROP TABLE IF EXISTS entity_redirects",
+)
+
#: The `links` table exactly as schema 7 shipped it: before `confidence` (8) and
#: before `nature` (11).
_LINKS_V7 = """
@@ -52,6 +61,25 @@ CREATE INDEX idx_links_to ON links(to_id);
CREATE INDEX idx_links_type ON links(type);
"""
+#: The Time projection as 0.3.1 shipped it, before schema 19 added the zone a value
+#: was stated in. Rebuilt rather than altered, for the SQLite floor noted above.
+_TEMPORAL_V18 = """
+CREATE TABLE temporal_rewound AS SELECT id, owner_id, authority, category, kind, raw,
+ earliest, latest, precision, shape, time_role, uncertain, approximate, zone,
+ sortable, status, confidence, parse_error FROM temporal_items;
+DROP TABLE temporal_items;
+ALTER TABLE temporal_rewound RENAME TO temporal_items;
+CREATE INDEX idx_temporal_window ON temporal_items(category, earliest, latest);
+CREATE INDEX idx_temporal_owner ON temporal_items(owner_id, category);
+CREATE INDEX idx_temporal_kind ON temporal_items(kind);
+"""
+
+
+def drop_temporal_zones(conn: sqlite3.Connection) -> None:
+ """Take the zone column off the Time projection, as a case before 19 had it."""
+ conn.executescript(_TEMPORAL_V18)
+
+
#: The `links` table as schema 8 shipped it: `confidence` is in, `nature` is not.
_LINKS_V8 = """
CREATE TABLE links_rewound AS SELECT id, from_id, to_id, type, prov_by,
@@ -64,14 +92,49 @@ CREATE INDEX idx_links_type ON links(type);
"""
+def _unfold_search_text(conn: sqlite3.Connection) -> None:
+ """Write both search indexes the way 0.3.1 did, before schema 19 folded them:
+ case only, every accent kept. Column for column what `_entity_search_text` and
+ `_media_search_text` put in, less the fold."""
+ conn.row_factory = sqlite3.Row
+ for row in conn.execute("SELECT id, type, label, attrs_json FROM entities").fetchall():
+ attrs = json.loads(row["attrs_json"])
+ fixed = (row["label"], row["type"], attrs.get("folder"), attrs.get("notes"))
+ declared = entity_engine.search_values(row["type"], attrs)
+ text = "\n".join(str(value) for value in (*fixed, *declared) if value)
+ conn.execute("UPDATE entities SET search_text = ? WHERE id = ?", (text.casefold(), row["id"]))
+ for row in conn.execute("SELECT path, item_json FROM media_items").fetchall():
+ item = json.loads(row["item_json"])
+ source = item.get("source") or {}
+ text = "\n".join(str(value) for value in (
+ item.get("filename") or Path(str(item.get("path") or "")).name,
+ item.get("title"), item.get("notes"), item.get("folder"),
+ source.get("title"), source.get("uploader"),
+ source.get("webpage_url") or source.get("url"),
+ ) if value)
+ conn.execute(
+ "UPDATE media_items SET search_text = ? WHERE path = ?", (text.casefold(), row["path"])
+ )
+
+
def rewind(db: Path | str, version: int) -> None:
- """Put `case.db` back at `version`, shape included, ready to be migrated up."""
- if version not in (7, 8):
+ """Put `case.db` back at `version`, shape included, ready to be migrated up.
+
+ 18 is what 0.3.1 shipped. After it, 19 folds what the search indexes hold, adds
+ the two merge tables and the zone column, so that is what a rewind to it undoes.
+ """
+ if version not in (7, 8, 18):
raise ValueError(f"no rewind to schema {version}")
with closing(sqlite3.connect(db)) as conn, conn:
- conn.executescript(_LINKS_V7 if version == 7 else _LINKS_V8)
- for statement in _AFTER_7:
- conn.execute(statement)
+ if version == 18:
+ _unfold_search_text(conn)
+ for statement in _AFTER_18:
+ conn.execute(statement)
+ drop_temporal_zones(conn)
+ else:
+ conn.executescript(_LINKS_V7 if version == 7 else _LINKS_V8)
+ for statement in (*_AFTER_18, *_AFTER_7):
+ conn.execute(statement)
conn.execute(
"UPDATE meta SET value = ? WHERE key = 'schema_version'", (str(version),)
)
diff --git a/tests/test_analysis_views.py b/tests/test_analysis_views.py
index 7eb8461..5d6fe67 100644
--- a/tests/test_analysis_views.py
+++ b/tests/test_analysis_views.py
@@ -6,6 +6,8 @@ import io
from PIL import Image
+from azimut.workspace import Case
+
def _case(client, name: str = "View case") -> str:
return client.post("/api/cases", json={"name": name}).json()["id"]
@@ -438,6 +440,49 @@ def test_a_track_captures_the_case_activity_it_asks_for(client):
assert created.json()["snapshot_count"] == 2
+def test_a_frozen_media_track_holds_back_working_files_as_it_did_live(client):
+ """`collected_only` travels with the saved track and the snapshot honours it; a
+ track saved without it reads back without the key, as it was stored."""
+ case_id = _case(client, "Collected track")
+ case = Case.open(case_id)
+ kept = {}
+ for name, source in (("clip", "upload"), ("frame", "inspect")):
+ entity = case.add_entity("media", name, {"path": f"media/{name}.jpg", "kind": "image"}, by="user")
+ case.upsert_media_item(
+ {
+ "path": f"media/{name}.jpg", "filename": f"{name}.jpg", "kind": "image",
+ "taken_at": "2024-02-03T10:11:12Z", "added_at": "2026-08-11T10:00:00Z",
+ "source": {"type": source},
+ },
+ entity_id=entity["id"],
+ )
+ kept[name] = entity["id"]
+
+ created = client.post(
+ f"/api/cases/{case_id}/analysis-views",
+ json={
+ "name": "Collected",
+ "mode": "snapshot",
+ "surface": "timeline",
+ "spec": {"timeline": {"tracks": [
+ {"id": "media", "label": "Media", "categories": ["media"],
+ "query": {"collected_only": True}},
+ {"id": "all", "label": "All files", "categories": ["media"]},
+ ]}},
+ },
+ )
+ assert created.status_code == 200, created.text
+ spec = created.json()["spec"]
+ tracks = {track["id"]: track["query"] for track in spec["timeline"]["tracks"]}
+ assert tracks["media"]["collected_only"] is True
+ assert "collected_only" not in tracks["all"]
+ frozen = spec["snapshot"]["timeline_tracks"]
+ assert frozen["media"] == [f"temporal:media:{kept['clip']}:captured"]
+ assert sorted(frozen["all"]) == sorted(
+ f"temporal:media:{kept[name]}:captured" for name in ("clip", "frame")
+ )
+
+
def test_empty_timeline_snapshot_duplicates_without_changing_its_tracks(client):
case_id = _case(client, "Empty Timeline snapshot")
created = client.post(
@@ -610,6 +655,13 @@ def test_a_timeline_view_keeps_the_clock_and_the_colours_it_was_read_with(client
"label": "Media",
"categories": ["media"],
"color": "chartreuse",
+ "query": {"as_files": "imagery"},
+ },
+ {
+ "id": "files",
+ "label": "Files",
+ "categories": ["statement"],
+ "query": {"as_files": True},
},
],
},
@@ -621,7 +673,17 @@ def test_a_timeline_view_keeps_the_clock_and_the_colours_it_was_read_with(client
# a zone named outright travels: the view was read on it and must reopen on it
assert timeline["zone_choice"] == "zone:Asia/Tokyo"
- assert [track["color"] for track in timeline["tracks"]] == ["blue", ""]
+ assert [track["color"] for track in timeline["tracks"]] == ["blue", "", ""]
+ # a lane drawn as the files its events date keeps the files it draws, and only it
+ assert [track["query"].get("as_files") for track in timeline["tracks"]] == [
+ None, "imagery", None,
+ ]
+
+ # the zone of the case's places is a reading too, and the one a Timeline opens on
+ body["spec"]["timeline"]["zone_choice"] = "case"
+ kept = client.put(f"/api/cases/{case_id}/analysis-views/{created.json()['id']}", json=body)
+ assert kept.status_code == 200, kept.text
+ assert kept.json()["spec"]["timeline"]["zone_choice"] == "case"
for refused in ("zone:../../etc/passwd", "zone:", "somewhere else"):
body["spec"]["timeline"]["zone_choice"] = refused
@@ -630,3 +692,26 @@ def test_a_timeline_view_keeps_the_clock_and_the_colours_it_was_read_with(client
)
assert answer.status_code == 200, answer.text
assert answer.json()["spec"]["timeline"]["zone_choice"] == "utc"
+
+
+def test_a_snapshot_freezes_the_claims_that_lack_a_source(client):
+ case_id = _case(client)
+ clip = _entity(client, case_id, "media", "clip.mp4", {"kind": "video"})
+ for statement, cites in (("Heard of it", []), ("Seen in the clip", [clip["id"]])):
+ filed = client.post(
+ f"/api/cases/{case_id}/timeline/claims",
+ json={"statement": statement, "cites": cites},
+ )
+ assert filed.status_code == 200, filed.text
+ body = _body("No source yet", mode="snapshot")
+ body["spec"]["query"] = {
+ "filter": {"lacks": ["source"]},
+ "terms": {"lacks": "source"},
+ "label": "No source",
+ }
+
+ saved = client.post(f"/api/cases/{case_id}/analysis-views", json=body)
+
+ assert saved.status_code == 200, saved.text
+ frozen = saved.json()["spec"]["snapshot"]["entities"]
+ assert [entity["label"] for entity in frozen] == ["Heard of it"]
diff --git a/tests/test_analyzers.py b/tests/test_analyzers.py
index 873818f..7548f0f 100644
--- a/tests/test_analyzers.py
+++ b/tests/test_analyzers.py
@@ -335,7 +335,13 @@ def test_reading_saved_items_never_starts_jobs(client, scenario):
for kind in ("zones", "followups", "runs"):
assert client.get(f"/api/cases/{case.id}/analysis/{kind}").json() == []
assert case.list_jobs() == before
- area = client.post(f"/api/cases/{case.id}/analysis/zones", json={"title": "Port", "zones": body["zones"]}).json()
+ ring = Zone.model_validate(body["zones"][0]).ring()
+ shared = client.post(f"/api/cases/{case.id}/analysis/areas", json={
+ "name": "Port", "geometry": {"type": "Polygon", "coordinates": [ring + [ring[0]]]},
+ }).json()
+ area = client.post(f"/api/cases/{case.id}/analysis/zones", json={
+ "title": "Port", "area_ids": [shared["id"]],
+ }).json()
follow = client.post(f"/api/cases/{case.id}/analysis/followups", json=body).json()
for kind, saved in (("zones", area), ("followups", follow)):
assert client.get(f"/api/cases/{case.id}/analysis/{kind}/{saved['id']}").status_code == 200
@@ -461,7 +467,7 @@ def test_a_candidate_can_be_kept_in_the_detections_view_without_touching_the_cas
assert client.get(f"{base}/followups/{watch['id']}/findings").json() == []
assert client.post(endpoint + "/promote", json={"title": "Gone"}).status_code == 404
# A later sweep can find the dismissed candidate again.
- saved = run(client, case, {**body, "followup_id": watch["id"]})
+ saved = run(client, case, {**body, "followup_id": watch["id"], "run_anyway": True})
endpoint = f"{base}/runs/{saved['id']}/results/{saved['results'][0]['id']}"
client.post(endpoint + "/promote", json={"title": "Kept change"})
[pinned] = client.get(f"{base}/followups/{watch['id']}/findings").json()
@@ -500,6 +506,68 @@ def test_a_second_pass_of_a_routine_compares_against_the_pass_before_it(client,
assert [saved["input"]["a"]["date"], saved["input"]["b"]["date"]] == [body["b"]["date"], later]
+def test_a_routine_skips_current_areas_and_only_sweeps_the_area_with_a_new_pass(client, scenario):
+ case, body = scenario
+ base = f"/api/cases/{case.id}/analysis"
+ zones = [body["zones"][0], {**body["zones"][0], "id": "other", "name": "Other"}]
+ routine = {**deepcopy(body), "title": "Two areas", "zones": zones, "date_rule": "latest_previous",
+ "area_dates": [{"area_id": zone["id"], "a": body["a"],
+ "b": {**body["b"], "date": ""}, "date_rule": "latest_previous"}
+ for zone in zones]}
+ watch = client.post(f"{base}/followups", json=routine).json()
+ chosen = [{**pair, "b": {**pair["b"], "date": body["b"]["date"]}}
+ for pair in watch["area_dates"]]
+ first = client.post(f"{base}/followups/{watch['id']}/run", json={"area_dates": chosen}).json()
+ workqueue.drain(case)
+ assert client.get(f"{base}/runs/{first['id']}").json()["status"] == "ready"
+ last = client.get(f"{base}/followups/{watch['id']}/last-passes").json()
+ assert {source["date"] for source in last.values()} == {body["b"]["date"]}
+
+ before = len(client.get(f"{base}/runs").json())
+ unchanged = client.post(f"{base}/followups/{watch['id']}/run", json={"area_dates": chosen}).json()
+ assert unchanged["status"] == "no_new_imagery" and "id" not in unchanged
+ assert len(client.get(f"{base}/runs").json()) == before
+
+ later = "2026-05-18"
+ seed_images({**body, "a": body["b"], "b": {**body["b"], "date": later}})
+ changed = [chosen[0], {**chosen[1], "b": {**chosen[1]["b"], "date": later}}]
+ second = client.post(f"{base}/followups/{watch['id']}/run", json={"area_dates": changed}).json()
+ assert [row["status"] for row in second["area_runs"]] == ["no_new_imagery", "pending"]
+ workqueue.drain(case)
+ saved = client.get(f"{base}/runs/{second['id']}").json()
+ assert [row["status"] for row in saved["area_runs"]] == ["no_new_imagery", "ready"]
+ assert saved["area_runs"][1]["a"]["date"] == body["b"]["date"]
+ assert saved["area_runs"][0]["status"] == "no_new_imagery"
+ assert saved["area_runs"][1]["status"] == "ready"
+
+
+def test_a_comparison_rejects_a_date_that_is_not_before_b(client, scenario):
+ case, body = scenario
+ base = f"/api/cases/{case.id}/analysis/runs"
+ later_a = {**deepcopy(body), "a": {**body["a"], "date": "2026-05-20"}}
+ assert client.post(base, json=later_a).status_code == 422
+ same_day = {**deepcopy(body), "a": {**body["a"], "date": body["b"]["date"]}}
+ assert client.post(base, json=same_day).status_code == 422
+ per_area = {**deepcopy(body), "area_dates": [{"area_id": body["zones"][0]["id"],
+ "a": later_a["a"], "b": body["b"], "date_rule": "manual"}]}
+ assert client.post(base, json=per_area).status_code == 422
+
+
+def test_previous_pass_follows_image_order_after_a_later_backfill(client, scenario, monkeypatch):
+ case, body = scenario
+ ident = "abcdef123456"
+ dates = ["2026-05-11", "2026-05-18", "2026-05-14"]
+ monkeypatch.setattr(analyzers, "ready_runs", lambda *_: [
+ ({"created_at": f"2026-06-0{index}T00:00:00Z"},
+ {"area_runs": [{"area_id": body["zones"][0]["id"], "status": "ready",
+ "b": {**body["b"], "date": day}}]})
+ for index, day in enumerate(dates, 1)
+ ])
+ query = RunInput.model_validate({**body, "followup_id": ident,
+ "b": {**body["b"], "date": "2026-05-25"}})
+ assert analyzers.previous_pass(case, query).date == "2026-05-18"
+
+
def test_a_detection_carries_what_it_is_for(client, scenario):
case, body = scenario
base = f"/api/cases/{case.id}/analysis"
@@ -510,6 +578,34 @@ def test_a_detection_carries_what_it_is_for(client, scenario):
assert client.get(f"{base}/runs").json()[0]["note"] == "Vessels weekly"
+def test_a_saved_routine_colour_can_change_without_losing_its_areas(client, scenario):
+ case, body = scenario
+ base = f"/api/cases/{case.id}/analysis/followups"
+ watch = client.post(base, json=body).json()
+ before = client.get(f"{base}/{watch['id']}").json()
+ response = client.patch(f"{base}/{watch['id']}/colour", json={"colour": "#22d3ee"})
+ assert response.status_code == 200, response.text
+ changed = client.get(f"{base}/{watch['id']}").json()
+ assert changed["recipe"]["colour"] == "#22d3ee"
+ assert changed["area_dates"] == before["area_dates"]
+ assert client.get(base).json()[0]["colour"] == "#22d3ee"
+ assert client.patch(f"{base}/{watch['id']}/colour", json={"colour": "red"}).status_code == 422
+ assert client.get(f"{base}/{watch['id']}").json()["recipe"]["colour"] == "#22d3ee"
+
+
+def test_a_finished_one_pass_has_a_saved_display_colour(client, scenario):
+ case, body = scenario
+ finished = run(client, case, body)
+ base = f"/api/cases/{case.id}/analysis/runs"
+ original = finished["input"]["recipe"]["colour"]
+ response = client.patch(f"{base}/{finished['id']}/colour", json={"colour": "#eab308"})
+ assert response.status_code == 200, response.text
+ changed = client.get(f"{base}/{finished['id']}").json()
+ assert changed["display_colour"] == "#eab308"
+ assert changed["input"]["recipe"]["colour"] == original
+ assert client.get(base).json()[0]["colour"] == "#eab308"
+
+
def test_reexecution_uses_preserved_frames_after_tile_cache_loss(client, scenario, monkeypatch):
case, body = scenario
first = run(client, case, body)
@@ -1266,8 +1362,40 @@ def test_an_automatic_date_rule_still_honours_the_cloud_ceiling(client, scenario
{"date": "2026-05-20", "cloud": 80.0, "granules": 1, "coverage": 1.0},
{"date": "2026-05-11", "cloud": 5.0, "granules": 1, "coverage": 1.0},
], "truncated": False})
- resolved = analyzers.resolve_dates(case, RunInput.model_validate(_rule(body)))
+ notes = []
+ resolved = analyzers.resolve_dates(case, RunInput.model_validate(_rule(body)), notes=notes)
assert resolved.b.date == "2026-05-11"
+ assert notes == ["Skipped 2026-05-20 (80% cloud, limit 30%); using 2026-05-11."]
+
+
+def test_cloudy_latest_pass_is_explained_when_clear_imagery_has_only_partial_cover(
+ client, scenario, monkeypatch
+):
+ case, body = scenario
+ client.put("/api/settings/keys", json={"sentinelhub": "inst-uuid"})
+ monkeypatch.setattr(analyzers.sentinel, "acquisitions", lambda *a, **k: {"dates": [
+ {"date": "2026-05-20", "cloud": 80.0, "granules": 1, "coverage": 1.0},
+ {"date": "2026-05-11", "cloud": 5.0, "granules": 1, "coverage": 0.61},
+ ], "truncated": False})
+ with pytest.raises(ValueError, match="latest pass 2026-05-20 has 80% cloud"):
+ analyzers.resolve_dates(case, RunInput.model_validate(_rule(body)))
+
+
+def test_an_automatic_comparison_rejects_a_pass_before_its_fixed_reference(client, scenario, monkeypatch):
+ case, body = scenario
+ client.put("/api/settings/keys", json={"sentinelhub": "inst-uuid"})
+ monkeypatch.setattr(analyzers.sentinel, "acquisitions", lambda *a, **k: {"dates": [
+ {"date": "2026-05-11", "cloud": 5.0, "granules": 1, "coverage": 1.0},
+ ], "truncated": False})
+ asked = RunInput.model_validate({**_rule(body), "a": {**body["a"], "date": "2026-05-20"},
+ "b": {**body["b"], "date": ""}})
+ _, outcomes = analyzers.prepare_areas(case, asked)
+ assert outcomes[0]["status"] == "failed"
+ assert "date A must be before date B" in outcomes[0]["message"]
+ response = client.post(f"/api/cases/{case.id}/analysis/runs", json=asked.model_dump())
+ assert response.status_code == 422
+ assert "date A must be before date B" in response.json()["detail"]
+ assert client.get(f"/api/cases/{case.id}/analysis/runs").json() == []
def test_band_products_are_padded_and_keyed_apart_from_older_layouts():
diff --git a/tests/test_area_groups.py b/tests/test_area_groups.py
new file mode 100644
index 0000000..ffdfc28
--- /dev/null
+++ b/tests/test_area_groups.py
@@ -0,0 +1,72 @@
+"""Area groups share case areas and preserve saved sets during migration."""
+
+import pytest
+
+from azimut.api import analyzers as api
+from azimut.engine import analyzers
+from azimut.engine.analysis_models import AreaGroup
+from azimut.workspace import Case
+
+
+def shape(points):
+ return {"type": "Polygon", "coordinates": [points + [points[0]]]}
+
+
+def test_old_sets_become_ordered_groups_without_losing_shapes(tmp_workspace):
+ case = Case.create("Area group test")
+ original = [[2.0, 48.0], [2.01, 48.0], [2.01, 48.01], [2.0, 48.01]]
+ changed = [[2.0, 48.0], [2.02, 48.0], [2.02, 48.02], [2.0, 48.02]]
+ shared = analyzers.save(case, "areas", {"name": "Harbor", "colour": "#38bdf8",
+ "geometry": shape(changed)}, new_id="111111111111")
+ legacy = analyzers.save(case, "zones", {"title": "Ports", "zones": [
+ {"id": shared["id"], "name": "Harbor", "kind": "polygon", "points": original},
+ {"id": "draft", "name": "River", "kind": "polygon", "points": changed},
+ ]}, new_id="aaaaaaaaaaaa")
+ second = analyzers.save(case, "zones", {"title": "Priority", "zones": [
+ {"id": "draft", "name": "River", "kind": "polygon", "points": changed},
+ ]}, new_id="bbbbbbbbbbbb")
+ current = analyzers.save(case, "zones", {"title": "Current", "zones": [
+ {"id": shared["id"], "name": "Harbor", "kind": "polygon", "points": changed},
+ ]}, new_id="cccccccccccc")
+
+ groups = analyzers.listing(case, "zones")
+ migrated = analyzers.read(case, "zones", legacy["id"])
+ again = analyzers.read(case, "zones", second["id"])
+ assert {row["title"] for row in groups} == {"Priority", "Ports", "Current"}
+ assert [row["position"] for row in groups] == [0, 1, 2]
+ assert "zones" not in migrated
+ assert migrated["area_ids"][0] != shared["id"]
+ assert migrated["pending_review"] == [{
+ "saved_area_id": migrated["area_ids"][0], "current_area_id": shared["id"], "name": "Harbor",
+ }]
+ assert analyzers.read(case, "areas", migrated["area_ids"][0])["geometry"] == shape(original)
+ assert migrated["area_ids"][1] == again["area_ids"][0]
+ assert analyzers.read(case, "zones", current["id"])["area_ids"] == [shared["id"]]
+ assert len(analyzers.listing(case, "areas")) == 3
+ assert analyzers.listing(case, "zones") == groups
+ assert len(analyzers.listing(case, "areas")) == 3
+ api.update_zones(case.id, legacy["id"], AreaGroup(title="Ports", position=migrated["position"],
+ area_ids=[shared["id"], migrated["area_ids"][1]]))
+ assert analyzers.read(case, "zones", legacy["id"])["pending_review"] == []
+ assert len(analyzers.listing(case, "areas")) == 3
+
+
+def test_groups_reference_the_same_area_and_keep_their_own_order(tmp_workspace):
+ case = Case.create("Area group test")
+ outline = [[2.0, 48.0], [2.01, 48.0], [2.01, 48.01], [2.0, 48.01]]
+ first = analyzers.save(case, "areas", {"name": "Harbor", "geometry": shape(outline)})
+ other = analyzers.save(case, "areas", {"name": "River", "geometry": shape(outline)})
+ ports = api.save_zones(case.id, AreaGroup(title="Ports", area_ids=[first["id"], other["id"]]))
+ priority = api.save_zones(case.id, AreaGroup(title="Priority", area_ids=[first["id"]]))
+ api.update_zones(case.id, ports["id"], AreaGroup(title="Ports", area_ids=[other["id"], first["id"]]))
+
+ assert analyzers.read(case, "zones", ports["id"])["area_ids"] == [other["id"], first["id"]]
+ assert analyzers.read(case, "zones", priority["id"])["area_ids"] == [first["id"]]
+ assert len(analyzers.listing(case, "areas")) == 2
+ api.delete_item(case.id, "zones", ports["id"])
+ later = api.save_zones(case.id, AreaGroup(title="Later", area_ids=[other["id"]]))
+ assert [row["title"] for row in analyzers.listing(case, "zones")] == ["Priority", "Later"]
+ assert later["position"] == 2
+ assert len(analyzers.listing(case, "areas")) == 2
+ with pytest.raises(ValueError):
+ AreaGroup(title="Duplicate", area_ids=[first["id"], first["id"]])
diff --git a/tests/test_artifacts.py b/tests/test_artifacts.py
index 6e100f8..f8d5d46 100644
--- a/tests/test_artifacts.py
+++ b/tests/test_artifacts.py
@@ -103,6 +103,9 @@ def test_deleting_everything_returns_the_case_to_its_birth_state(client):
# The tool root, not the case folder: what the analyst keeps beside it is
# theirs, and a gate on files Azimut never wrote would be meaningless.
assert tree(emptied.tool_root) == tree(born.tool_root)
+ assert emptied.entity_redirects() == {}
+ with emptied._graph()._connect() as conn:
+ assert conn.execute('SELECT COUNT(*) FROM entity_merges').fetchone()[0] == 0
def test_deleting_a_proof_takes_its_pasted_images(client):
@@ -123,6 +126,15 @@ def test_deleting_a_proof_takes_its_pasted_images(client):
assert not case.resolve_inside(full.proof).exists()
+def test_a_collage_owns_its_preview_but_not_its_exported_picture(client):
+ full = fullcase.build_full_case(client)
+ case = Case.open(full.case_id)
+ entity = case.find_entity(attr="spec", value=full.collage_doc)
+
+ assert set(artifacts.owned(case, entity)) == {full.collage_doc, full.collage_thumb}
+ assert artifacts.caches(case, entity) == []
+
+
def test_every_type_in_a_full_case_declares_what_it_owns(client):
"""A type in neither table is not a decision, it is an oversight — the next
tool declares its files in ``KINDS`` or declares it has none in ``NO_FILES``,
diff --git a/tests/test_board_groups.py b/tests/test_board_groups.py
new file mode 100644
index 0000000..fcd1ac6
--- /dev/null
+++ b/tests/test_board_groups.py
@@ -0,0 +1,225 @@
+"""The reads behind the Board's groups: counts per type under the question, the
+"Most noted" ordering, and the per-page event summary its rows are drawn from."""
+
+from __future__ import annotations
+
+
+def _case(client, name: str = "Groups") -> str:
+ return client.post("/api/cases", json={"name": name}).json()["id"]
+
+
+def _entity(client, case_id: str, type_: str, label: str, attrs: dict | None = None) -> dict:
+ response = client.post(
+ f"/api/cases/{case_id}/entities",
+ json={"type": type_, "label": label, "attrs": attrs or {}},
+ )
+ assert response.status_code == 200, response.text
+ return response.json()
+
+
+def _claim(client, case_id: str, statement: str, **connectors) -> dict:
+ response = client.post(
+ f"/api/cases/{case_id}/timeline/claims",
+ json={"statement": statement, **connectors},
+ )
+ assert response.status_code == 200, response.text
+ return response.json()["entity"]
+
+
+def test_a_page_counts_its_answer_per_type_under_the_same_question(client):
+ cid = _case(client)
+ _entity(client, cid, "person", "Anna North")
+ _entity(client, cid, "person", "Boris Nord")
+ _entity(client, cid, "organization", "North Unit")
+ _entity(client, cid, "bookmark", "North log", {"url": "https://x.test"})
+ _entity(client, cid, "person", "Carla South")
+
+ page = client.get(
+ f"/api/cases/{cid}/catalog/entities",
+ params={"q": "north", "limit": 1, "counts": "type"},
+ ).json()
+
+ assert page["total"] == 3
+ assert page["by_type"] == {"person": 1, "organization": 1, "bookmark": 1}
+ # Without the ask, the page stays the shape every other caller reads.
+ plain = client.get(f"/api/cases/{cid}/catalog/entities").json()
+ assert "by_type" not in plain
+
+
+def test_a_count_it_does_not_know_is_refused(client):
+ cid = _case(client)
+ res = client.get(f"/api/cases/{cid}/catalog/entities", params={"counts": "folder"})
+ assert res.status_code == 400
+
+
+def test_most_noted_orders_the_case_by_the_claims_naming_each_row(client):
+ cid = _case(client)
+ quiet = _entity(client, cid, "person", "Quiet")
+ busy = _entity(client, cid, "person", "Busy")
+ some = _entity(client, cid, "person", "Some")
+ place = _entity(client, cid, "place", "Crossroads", {"lat": 49.9, "lon": 36.2})
+ for n in range(3):
+ _claim(client, cid, f"Busy seen {n}", about=[busy["id"]])
+ _claim(client, cid, "Some seen", about=[some["id"]], at=[place["id"]])
+ # One Claim placing and naming the same row is one event about it, not two.
+ _claim(client, cid, "Busy there", about=[busy["id"]], at=[place["id"]])
+
+ page = client.get(
+ f"/api/cases/{cid}/catalog/entities",
+ params={"type": "person", "order": "-events", "limit": 2},
+ ).json()
+ assert [row["label"] for row in page["items"]] == ["Busy", "Some"]
+ rest = client.get(
+ f"/api/cases/{cid}/catalog/entities",
+ params={
+ "type": "person", "order": "-events", "limit": 2,
+ "cursor": page["next_cursor"],
+ },
+ ).json()
+ # The cursor resumes on a count, so the last row is neither skipped nor repeated.
+ assert [row["label"] for row in rest["items"]] == ["Quiet"]
+ assert rest["next_cursor"] is None
+ assert quiet["id"] == rest["items"][0]["id"]
+
+
+def test_most_noted_breaks_ties_on_the_newest_row(client):
+ cid = _case(client)
+ for label in ("older", "newer"):
+ _entity(client, cid, "person", label)
+ page = client.get(
+ f"/api/cases/{cid}/catalog/entities", params={"type": "person", "order": "-events"}
+ ).json()
+ assert [row["label"] for row in page["items"]] == ["newer", "older"]
+
+
+def test_most_noted_is_asked_of_a_group_never_of_the_whole_case(client):
+ cid = _case(client)
+ res = client.get(f"/api/cases/{cid}/catalog/entities", params={"order": "-events"})
+ assert res.status_code == 400
+
+
+def test_a_count_cursor_that_is_not_a_number_is_refused(client):
+ cid = _case(client)
+ res = client.get(
+ f"/api/cases/{cid}/catalog/entities",
+ params={"type": "person", "order": "-events", "cursor": "3:many"},
+ )
+ assert res.status_code == 400
+
+
+def test_event_rows_say_how_often_when_and_through_what_each_row_is_named(client):
+ cid = _case(client)
+ brigade = _entity(client, cid, "organization", "4th brigade")
+ idle = _entity(client, cid, "person", "Nobody")
+ place = _entity(client, cid, "place", "Crossroads", {"lat": 49.9, "lon": 36.2})
+ video = _entity(client, cid, "bookmark", "VID_0312", {"url": "https://x.test/v"})
+ photo = _entity(client, cid, "bookmark", "S2 11/03", {"url": "https://x.test/p"})
+ _claim(
+ client, cid, "Column seen", when="2026-03-11",
+ about=[brigade["id"]], at=[place["id"]], cites=[video["id"]],
+ )
+ _claim(
+ client, cid, "Column again", when="2026-03-19T10:00:00Z",
+ about=[brigade["id"]], cites=[video["id"], photo["id"]],
+ )
+ _claim(client, cid, "Undated rumour", about=[brigade["id"]])
+
+ body = client.post(
+ f"/api/cases/{cid}/catalog/events",
+ json={"ids": [brigade["id"], idle["id"], place["id"]]},
+ ).json()
+
+ row = body["rows"][brigade["id"]]
+ assert row["events"] == 3
+ assert row["first"] == "2026-03-11T00:00:00.000000Z"
+ assert row["last"] == "2026-03-19T10:00:01.000000Z"
+ assert row["sources"] == 2
+ assert row["places"] == 1
+ # Two dated Claims across the case's own span: the first and the last bucket.
+ assert len(row["buckets"]) == 12
+ assert sum(row["buckets"]) == 2
+ assert row["buckets"][0] == 1 and row["buckets"][-1] == 1
+ assert body["range"] == {
+ "from": "2026-03-11T00:00:00.000000Z",
+ "to": "2026-03-19T10:00:01.000000Z",
+ }
+ assert body["rows"][idle["id"]] == {
+ "events": 0, "first": None, "last": None,
+ "sources": 0, "places": 0, "buckets": [0] * 12,
+ }
+ # The place is named by one Claim through `at`, and is not its own place.
+ assert body["rows"][place["id"]]["events"] == 1
+ assert body["rows"][place["id"]]["places"] == 0
+
+
+def test_event_rows_count_a_place_the_entity_states_itself(client):
+ cid = _case(client)
+ truck = _entity(client, cid, "structure", "Depot hall")
+ depot = _entity(client, cid, "place", "Depot", {"lat": 49.0, "lon": 36.0})
+ linked = client.post(
+ f"/api/cases/{cid}/links",
+ json={"from_id": truck["id"], "to_id": depot["id"], "type": "sited-at"},
+ )
+ assert linked.status_code == 200, linked.text
+ body = client.post(f"/api/cases/{cid}/catalog/events", json={"ids": [truck["id"]]}).json()
+ assert body["rows"][truck["id"]]["places"] == 1
+ assert body["range"] is None
+
+
+def test_event_rows_are_bounded_to_a_page(client):
+ cid = _case(client)
+ res = client.post(
+ f"/api/cases/{cid}/catalog/events", json={"ids": [f"e{n}" for n in range(201)]}
+ )
+ assert res.status_code == 422
+ empty = client.post(f"/api/cases/{cid}/catalog/events", json={"ids": []}).json()
+ assert empty == {"range": None, "rows": {}}
+
+
+def test_a_snapshot_page_narrows_counts_and_orders_its_frozen_rows(client):
+ cid = _case(client)
+ busy = _entity(client, cid, "person", "Busy")
+ _entity(client, cid, "person", "Quiet")
+ _entity(client, cid, "bookmark", "Log", {"url": "https://x.test"})
+ _claim(client, cid, "Busy seen", about=[busy["id"]])
+ view = client.post(
+ f"/api/cases/{cid}/analysis-views",
+ json={"name": "Frozen", "surface": "board", "mode": "snapshot", "spec": {}},
+ )
+ assert view.status_code == 200, view.text
+ vid = view.json()["id"]
+ # A row the live case gains afterwards is not in the frozen reading.
+ _claim(client, cid, "Quiet seen", about=[busy["id"]])
+
+ page = client.get(
+ f"/api/cases/{cid}/catalog/entities",
+ params={"view": vid, "type": "person", "order": "-events", "counts": "type"},
+ ).json()
+ assert [row["label"] for row in page["items"]] == ["Busy", "Quiet"]
+ assert page["total"] == 2
+ assert page["by_type"] == {"person": 2}
+
+
+def test_the_summary_prices_what_the_claims_lack(client):
+ cid = _case(client)
+ log = _entity(client, cid, "bookmark", "Log", {"url": "https://x.test"})
+ _claim(client, cid, "Cited and graded", cites=[log["id"]], confidence="probable")
+ _claim(client, cid, "Cited only", cites=[log["id"]])
+ _claim(client, cid, "Bare")
+ summary = client.get(f"/api/cases/{cid}/catalog/summary").json()
+ assert summary["lacks"] == {"source": 1, "assessment": 2}
+
+
+def test_a_claim_says_where_it_sits_on_the_timeline(client):
+ cid = _case(client)
+ dated = _claim(client, cid, "Seen", when="2026-03-12")["id"]
+ undated = _claim(client, cid, "Rumoured")["id"]
+ person = _entity(client, cid, "person", "Witness")
+
+ item = client.get(f"/api/cases/{cid}/timeline/claims/{dated}").json()["item"]
+ assert item["id"] == f"temporal:claim:{dated}"
+ assert item["earliest"] == "2026-03-12T00:00:00.000000Z"
+ assert client.get(f"/api/cases/{cid}/timeline/claims/{undated}").json()["item"]["earliest"] is None
+ # only a Claim has a row of its own to land on
+ assert client.get(f"/api/cases/{cid}/timeline/claims/{person['id']}").status_code == 404
+ assert client.get(f"/api/cases/{cid}/timeline/claims/e_missing").status_code == 404
diff --git a/tests/test_case_workspace_fixture.py b/tests/test_case_workspace_fixture.py
new file mode 100644
index 0000000..f09172c
--- /dev/null
+++ b/tests/test_case_workspace_fixture.py
@@ -0,0 +1,95 @@
+"""A case the Board, Graph and Timeline kept in 0.3.1 still reads the same.
+
+The rework of those three surfaces changes how they draw and what they open on,
+never what a case already holds or what a saved reading answers. This builds the
+case such an analyst leaves behind (`caseworkspace.py`), reopens it, and compares
+its reading with the one recorded when the rework began.
+
+A change that means to alter a reading records it on purpose:
+
+ AZIMUT_WRITE_GOLDEN=1 uv run pytest tests/test_case_workspace_fixture.py
+
+and the diff of `fixtures/case-workspace-0.3.1.json` is then the change's own
+account of what reads differently.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import sqlite3
+from contextlib import closing
+
+import schema_rewind
+from azimut.sqlite_backend import SQLITE_SCHEMA
+from azimut.workspace import Case
+from caseworkspace import GOLDEN, build_workspace_case, read_workspace
+
+#: The storage schema 0.3.1 shipped. A newer one must still open this case.
+SHIPPED_SCHEMA = 18
+
+
+def test_a_case_workspace_from_0_3_1_reads_as_it_did(client):
+ ws = build_workspace_case(client)
+ assert SQLITE_SCHEMA >= SHIPPED_SCHEMA
+ # Taken back to the shape 0.3.1 wrote, then opened, so what is read is what the
+ # migrations make of a real 0.3.1 case and not a case born at today's schema.
+ schema_rewind.rewind(Case.open(ws.full.case_id).db_path, SHIPPED_SCHEMA)
+ case = Case.open(ws.full.case_id)
+ with closing(sqlite3.connect(case.db_path)) as conn:
+ assert conn.execute(
+ "SELECT value FROM meta WHERE key = 'schema_version'"
+ ).fetchone()[0] == str(SQLITE_SCHEMA)
+
+ reading = read_workspace(client, ws)
+ if os.environ.get("AZIMUT_WRITE_GOLDEN") == "1":
+ GOLDEN.write_text(
+ json.dumps(reading, indent=1, ensure_ascii=False, sort_keys=True) + "\n",
+ encoding="utf-8",
+ )
+ recorded = json.loads(GOLDEN.read_text(encoding="utf-8"))
+ assert case.list_entities(), "the fixture planted nothing"
+ for part in recorded:
+ assert reading[part] == recorded[part], f"'{part}' reads differently"
+ assert set(reading) == set(recorded)
+
+
+def test_the_fixture_holds_what_the_rework_has_to_keep(client):
+ """Guard the fixture itself: a reading of nothing would match forever."""
+ ws = build_workspace_case(client)
+ reading = read_workspace(client, ws)
+ views = reading["views"]
+ assert {(v["surface"], v["mode"]) for v in views.values()} == {
+ (surface, mode)
+ for surface in ("board", "graph", "timeline")
+ for mode in ("live", "snapshot")
+ }
+ modes = {v["spec"]["timeline"]["view_mode"] for v in views.values() if v["surface"] == "timeline"}
+ assert modes == {"plot", "list"}
+ tracks = views["Chronology with media"]["spec"]["timeline"]["tracks"]
+ assert any("media" in t["categories"] for t in tracks)
+ assert any(t["hidden"] for t in tracks) and any(t["pinned"] for t in tracks)
+
+ rows = reading["events"]["rows"]
+ assert any(row["kind"] == "claim" for row in rows), "Claims are on the Events track"
+ # A proof's date is on it once, as the Claim about the footage that cites the proof:
+ # the proof's own row said the same date a second time and is no longer drawn.
+ proof_dates = [row for row in rows if any(s.startswith("proof:") for s in row["sources"])]
+ assert proof_dates, "a proof date is on the Events track"
+ assert not any(
+ row["kind"] == "taken" and row["raw"] == stated["raw"]
+ for row in rows
+ for stated in proof_dates
+ ), "and it is there once"
+ assert reading["events"]["undated"] >= 1 and reading["events"]["unplaced"] >= 1
+ assert reading["detect_claim"].startswith("claim:")
+ assert reading["claims"][reading["detect_claim"].removeprefix("claim:")]["attrs"].get(
+ "detection"
+ ), "a kept Detect pin is a Claim that says it came from a detection"
+ assert reading["promoted"] == "organization:3rd Harbour Brigade"
+ assert "[[entity:organization:Northwind Shipping|" in reading["notes"]
+ assert any(image["primary"] for image in reading["galleries"]["person:A. Nadeau"])
+ for view in views.values():
+ if view["mode"] == "snapshot":
+ snap = view["spec"]["snapshot"]
+ assert snap["entities"] or snap["timeline_items"], "a snapshot froze something"
diff --git a/tests/test_cases_api.py b/tests/test_cases_api.py
index 16cdee2..647d696 100644
--- a/tests/test_cases_api.py
+++ b/tests/test_cases_api.py
@@ -528,6 +528,42 @@ def test_catalog_lists_what_the_case_connects_to_nothing(client):
assert client.get(f"/api/cases/{cid}/catalog/summary").json()["unlinked"] == 1
+def test_catalog_lists_the_claims_with_no_source_or_no_assessment(client):
+ cid = client.post("/api/cases", json={"name": "Waiting"}).json()["id"]
+ clip = client.post(
+ f"/api/cases/{cid}/entities",
+ json={"type": "media", "label": "clip.mp4", "attrs": {"kind": "video"}},
+ ).json()["id"]
+
+ def claim(statement, **extra):
+ body = {"statement": statement, **extra}
+ response = client.post(f"/api/cases/{cid}/timeline/claims", json=body)
+ assert response.status_code == 200, response.text
+ return response.json()["entity"]["id"]
+
+ bare = claim("Heard of it")
+ graded = claim("Graded, no source", confidence="probable")
+ sourced = claim("Sourced, not graded", cites=[clip])
+ whole = claim("Sourced and graded", cites=[clip], confidence="certain")
+
+ def ids(**params):
+ page = client.get(f"/api/cases/{cid}/catalog/entities", params=params)
+ assert page.status_code == 200, page.text
+ return {row["id"] for row in page.json()["items"]}
+
+ # The media is neither: a file is its own source and nothing grades it.
+ assert ids(lacks="source") == {bare, graded}
+ assert ids(lacks="assessment") == {bare, sourced}
+ assert ids(lacks="source,assessment") == {bare}
+ assert whole not in ids(lacks="source") | ids(lacks="assessment")
+ # The graph route asks the same predicate.
+ drawn = client.get(f"/api/cases/{cid}/graph", params={"lacks": "source"}).json()
+ assert {node["id"] for node in drawn["nodes"]} >= {bare, graded}
+ assert sourced not in {node["id"] for node in drawn["nodes"]}
+ refused = client.get(f"/api/cases/{cid}/catalog/entities", params={"lacks": "photo"})
+ assert refused.status_code == 400
+
+
def test_the_summary_prices_linked_to_by_what_it_would_answer_with(client):
"""Four media pointing at one place is **four** under "linked to a place" and one
under "type: place". The filter asks the first, so the menu has to price the
@@ -1079,3 +1115,27 @@ def test_details_title_edit_moves_every_named_tool_file(client):
proof = next(entity for entity in case.list_entities() if entity["type"] == "proof")
assert proof["attrs"]["path"] == layout.proof_export_rel("New proof")
assert case.resolve_inside(proof["attrs"]["path"]).is_file()
+
+
+def test_a_picker_page_brings_the_preview_each_source_already_has(client):
+ cid = client.post("/api/cases", json={"name": "Previews"}).json()["id"]
+ case = Case.open(cid)
+ frame = case.add_entity("media", "frame.jpg", {"path": "media/frame.jpg", "kind": "image"}, by="user")
+ case.upsert_media_item(
+ {"path": "media/frame.jpg", "filename": "frame.jpg", "kind": "image",
+ "added_at": "2026-08-11T10:00:00Z", "thumbnail": ".thumbs/frame.jpg"},
+ entity_id=frame["id"],
+ )
+ capture = case.add_entity("capture", "S2 11 Mar", {"thumb": ".thumbs/s2.jpg"}, by="user")
+ note = case.add_entity("note", "Interview", {}, by="user")
+
+ def thumbs(**params):
+ page = client.get(f"/api/cases/{cid}/catalog/entities", params=params).json()
+ return {row["id"]: row.get("thumb") for row in page["items"]}
+
+ # The table draws its own pictures and does not ask.
+ assert thumbs()[frame["id"]] is None
+ picked = thumbs(previews="true")
+ assert picked[frame["id"]] == ".thumbs/frame.jpg"
+ assert picked[capture["id"]] == ".thumbs/s2.jpg"
+ assert picked[note["id"]] is None
diff --git a/tests/test_compare_api.py b/tests/test_compare_api.py
index 1af12eb..a544551 100644
--- a/tests/test_compare_api.py
+++ b/tests/test_compare_api.py
@@ -711,7 +711,7 @@ MARKS = {"red": (0xEF, 0x44, 0x44), "blue": (0x38, 0xBD, 0xF8), "green": (0x22,
def _marked_imagery() -> bytes:
- """Grey-green fields with three thin outlines, the case median cut got wrong."""
+ """Grey-green fields with three thin outlines, useful for palette checks."""
import random
from PIL import ImageDraw
@@ -753,8 +753,41 @@ def test_a_gif_keeps_the_colours_it_is_asked_to_keep(client):
assert response.status_code == 200, response.text
written[asked] = _first_frame_marks(Path(response.json()["path"]) / response.json()["file"])
assert written[keep] == list(MARKS.values())
- # Without the list, median cut spends the palette on the fields.
- assert written[""] != list(MARKS.values())
+
+
+def test_a_gif_uses_the_full_palette_for_satellite_imagery():
+ image = Image.new("RGB", (256, 256))
+ image.putdata([
+ ((index * 37) % 256, (index * 67) % 256, (index * 97) % 256)
+ for index in range(256 * 256)
+ ])
+
+ data = compare_api._gif_bytes(image, image, "blink")
+
+ with Image.open(io.BytesIO(data)) as gif:
+ rgb = gif.convert("RGB")
+ colours = {rgb.getpixel((x, y)) for y in range(rgb.height) for x in range(rgb.width)}
+ assert len(colours) > 192
+
+
+def test_a_gif_preserves_rare_dark_satellite_pixels():
+ image = Image.new("RGB", (256, 256))
+ pixels = [
+ (150 + (index * 37) % 106, 80 + (index * 67) % 110, 40 + (index * 97) % 100)
+ for index in range(256 * 256)
+ ]
+ dark_pixel = 12_345
+ overlay_pixel = 23_456
+ pixels[dark_pixel] = (15, 15, 15)
+ pixels[overlay_pixel] = (0, 114, 178)
+ image.putdata(pixels)
+
+ for kept in ([], [(0, 114, 178), (230, 159, 0), (204, 121, 167)]):
+ data = compare_api._gif_bytes(image, image, "blink", kept=kept)
+ with Image.open(io.BytesIO(data)) as gif:
+ frame = gif.convert("RGB")
+ assert frame.getpixel((dark_pixel % 256, dark_pixel // 256)) == (15, 15, 15)
+ assert frame.getpixel((overlay_pixel % 256, overlay_pixel // 256)) == (0, 114, 178)
def test_an_evolution_keeps_its_mark_colours_too(client):
diff --git a/tests/test_confidence.py b/tests/test_confidence.py
index 2f415ef..68288eb 100644
--- a/tests/test_confidence.py
+++ b/tests/test_confidence.py
@@ -53,7 +53,8 @@ def test_claim_confidence_is_a_closed_entity_field(client):
fields = {field["key"]: field for field in rows["claim"]["attrs"]}
assert set(fields) == {
- "count", "condition", "when", "time_role", "confidence", "method", "verbatim",
+ "count", "condition", "when", "when_zone", "time_role", "confidence", "method",
+ "verbatim",
}
assert fields["confidence"]["kind"] == "choice"
assert [option["value"] for option in fields["confidence"]["options"]] == [
diff --git a/tests/test_detect_rework.py b/tests/test_detect_rework.py
index 89fb709..aef1481 100644
--- a/tests/test_detect_rework.py
+++ b/tests/test_detect_rework.py
@@ -258,7 +258,8 @@ def test_export_snapshots_kept_candidates_with_pass_categories_and_replaces_a_pa
def test_detect_preferences_round_trip_through_settings_backup(client):
- choice = {"collapsed": True, "basemap": "osm", "overlays": ["roads"], "saved": False}
+ choice = {"collapsed": True, "basemap": "osm", "overlays": ["roads"], "saved": False,
+ "width": 480}
assert client.put("/api/settings/prefs", json={"detect_view": choice}).status_code == 200
backup = client.get("/api/settings/export").json()
client.put("/api/settings/prefs", json={"detect_view": {}})
diff --git a/tests/test_detect_rules.py b/tests/test_detect_rules.py
index ca495a9..82ee2db 100644
--- a/tests/test_detect_rules.py
+++ b/tests/test_detect_rules.py
@@ -31,6 +31,7 @@ from azimut.engine.analysis_models import (
is_radar,
is_single,
recipe_products,
+ stored,
)
from azimut.workspace import Case
from analyzerfixture import BARE, CLOUD, DARK, EDGE, SENTINEL_TILE, UNSURE, VEGETATION, WATER, at, put_picture, zone
@@ -147,6 +148,60 @@ def test_only_an_analyzer_of_your_own_carries_rules_and_it_needs_one():
assert all(not r.rules and r.match == "all" and r.parameters.shape == "any" for r in BUILTINS)
+def test_an_analyzer_declares_what_it_reads_and_its_rules_have_to_agree():
+ change = recipe(LOSS, GREEN_BEFORE)
+ assert (change.sensor, change.dates) == ("sentinel2", "two")
+ spot = recipe({"measure": "band", "band": "B12", "on": "b", "op": "ge", "value": 0.3})
+ assert (spot.sensor, spot.dates) == ("sentinel2", "one")
+ radar = recipe({"measure": "radar", "on": "change", "op": "moved", "value": 3})
+ assert (radar.sensor, radar.dates) == ("sentinel1", "two")
+ # said out loud, it is kept as said: a rule may not contradict it
+ assert recipe(LOSS, sensor="sentinel2", dates="two").dates == "two"
+ with pytest.raises(ValidationError, match="Sentinel-2 one optical rules"):
+ recipe(LOSS, sensor="sentinel1")
+ with pytest.raises(ValidationError, match="radar analyzer reads radar rules"):
+ recipe({"measure": "radar", "on": "change", "op": "moved", "value": 3}, sensor="sentinel2")
+ with pytest.raises(ValidationError, match="one date reads the pass itself"):
+ recipe(LOSS, dates="one")
+ with pytest.raises(ValidationError, match="two dates needs a rule"):
+ recipe({"measure": "band", "band": "B12", "on": "b", "op": "ge", "value": 0.3}, dates="two")
+ # only the rules declare it: a calibrated method says what it reads in `METHODS`
+ assert "sensor" not in BUILTINS[0].model_dump() and "dates" not in BUILTINS[0].model_dump()
+ with pytest.raises(ValidationError, match="only an analyzer of your own"):
+ Recipe(name="x", method="surface", sensor="sentinel2")
+ assert change.model_dump()["sensor"] == "sentinel2" and change.model_dump()["dates"] == "two"
+
+
+def test_an_analyzer_saved_before_it_declared_what_it_reads_gets_it_from_its_rules_once():
+ raw = recipe(LOSS, GREEN_BEFORE).model_dump()
+ del raw["sensor"], raw["dates"]
+ raw["checks"] = [{"id": "old", "name": "Old", "b": {"date": DAY_B}, "marks": [],
+ "bounds": {"west": 0, "south": 0, "east": 1, "north": 1}}]
+ loaded = stored(Recipe, raw)
+ assert (loaded.sensor, loaded.dates) == ("sentinel2", "two")
+ assert [check.id for check in loaded.checks] == ["old"] # its frame is gone, the check is not
+ # and it is asked the same thing whether it comes from a file or from a request
+ assert loaded.model_dump() == Recipe.model_validate({**raw, "checks": []}).model_copy(
+ update={"checks": loaded.checks}).model_dump()
+
+
+def test_a_run_saved_with_an_older_analyzer_still_reads():
+ """Runs and routines keep the analyzer they ran with: one saved before an analyzer declared what
+ it reads, or before a check lost its frame, is history and must still open."""
+ older = recipe(LOSS, GREEN_BEFORE).model_dump()
+ del older["sensor"], older["dates"]
+ older["checks"] = [{"id": "old", "name": "Old", "b": {"date": DAY_B}, "marks": [],
+ "bounds": {"west": 0, "south": 0, "east": 1, "north": 1}}]
+ body = {**sweep_body(recipe(LOSS, GREEN_BEFORE)), "recipe": older}
+ run = stored(RunInput, body)
+ assert (run.recipe.sensor, run.recipe.dates) == ("sentinel2", "two")
+ assert [check.id for check in run.recipe.checks] == ["old"]
+ assert is_single(older) is False and is_radar(older) is False # the dictionaries it is saved as
+ # a request that still names the dropped field is a caller's mistake, and is refused
+ with pytest.raises(ValidationError):
+ RunInput.model_validate(body)
+
+
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)
@@ -431,125 +486,6 @@ def test_the_shape_filter_applies_to_a_sweep(client, offline):
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 ----------------------------------------------------------------------
@@ -570,6 +506,7 @@ def test_the_catalogue_offers_the_rules_vocabulary_and_the_convertible_built_ins
catalogue = client.get("/api/compare/analyzers").json()
assert catalogue["rules"]["bands"] == list(sentinel.L2A_BANDS)
assert "water" in catalogue["rules"]["classes"]
+ assert catalogue["rules"]["max_check_tiles"] == detect_rules.MAX_CHECK_TILES
assert set(catalogue["as_rules"]) == {"burn-scars", "vegetation-loss", "new-water"}
assert any(method["id"] == "rules" and method["rules"] for method in catalogue["methods"])
@@ -584,24 +521,6 @@ def test_an_analyzer_of_your_own_is_saved_for_every_case_and_carried_by_the_back
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 --------------------------------------------------------------------------------
@@ -616,25 +535,28 @@ 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}
+ "marks": marks, **extra}
-def test_a_check_is_a_place_its_passes_and_its_marks():
+def test_a_check_is_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)))
+ # a check has no frame of its own: a request naming one is refused, a saved one is read without it
+ framed = check_body([found], bounds={"west": 0, "south": 0, "east": 1, "north": 1})
+ with pytest.raises(ValidationError):
+ Check.model_validate(framed)
+ assert not hasattr(stored(Check, framed), "bounds")
# checks belong to rules of your own, one id each
- with pytest.raises(ValidationError, match="rules and checks"):
+ with pytest.raises(ValidationError, match="rules, checks"):
Recipe(name="x", method="surface", checks=[check])
with pytest.raises(ValidationError, match="unique"):
recipe(LOSS, checks=[check, check])
@@ -642,6 +564,55 @@ def test_a_check_is_a_place_its_passes_and_its_marks():
recipe(LOSS, checks=[check.model_copy(update={"id": f"c{i}"}) for i in range(MAX_CHECKS + 1)])
+def test_a_check_reads_the_tiles_under_its_marks_and_beside_a_mark_near_an_edge():
+ 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)]
+
+ def reads(px, py):
+ return detect_rules.check_tiles(Check.model_validate(check_body([{"point": pixel_point(px, py), "expect": "found"}])))
+
+ # the examples keep their marks 64 pixels inside a tile, which reads that tile alone
+ assert reads(64, 64) == reads(448, 448) == [(x, y)]
+ # nearer an edge the tile across it is read as well, and in a corner the three around it
+ assert reads(20, 256) == [(x, y), (x - 1, y)]
+ assert reads(256, 500) == [(x, y), (x, y + 1)]
+ assert reads(10, 10) == [(x, y), (x - 1, y), (x, y - 1), (x - 1, y - 1)]
+ with pytest.raises(ValueError, match="drop a pin"):
+ detect_rules.check_tiles(Check.model_validate(check_body([])))
+
+
+def test_a_check_may_not_reach_more_tiles_than_a_handful():
+ z, x, y = SENTINEL_TILE
+ wide = [{"point": pixel_point(256, 256, (z, x + 2 * i, y)), "expect": "found"} for i in range(detect_rules.MAX_CHECK_TILES + 1)]
+ with pytest.raises(ValueError, match="at most 12"):
+ detect_rules.check_tiles(Check.model_validate(check_body(wide)))
+
+
+def test_a_check_asks_what_testing_it_costs_before_anything_is_fetched(client, offline):
+ built = recipe(LOSS, GREEN_BEFORE)
+ marks = [{"point": PLOT, "expect": "found"}, {"point": STANDING, "expect": "empty"}]
+ body = {"recipe": built.model_dump(), "check": check_body(marks)}
+ # one tile, and one product on each date
+ assert client.post("/api/compare/analyzers/check/plan", json=body).json() == {"tiles": 1, "missing": 2}
+ seed_frames(sweep_body(built, maxcc=100), *cleared(), pictures=False)
+ assert client.post("/api/compare/analyzers/check/plan", json=body).json() == {"tiles": 1, "missing": 0}
+ # a pin near an edge reads the tile across it too, so it costs twice
+ near = check_body([{"point": pixel_point(500, 256), "expect": "found"}])
+ assert client.post("/api/compare/analyzers/check/plan", json={**body, "check": near}).json() == {"tiles": 2, "missing": 2}
+ # no pin, nothing to read; too many tiles, too much to read
+ empty = client.post("/api/compare/analyzers/check/plan", json={**body, "check": check_body([])})
+ assert empty.status_code == 422 and "drop a pin" in empty.text
+ z, x, y = SENTINEL_TILE
+ wide = [{"point": pixel_point(256, 256, (z, x + 2 * i, y)), "expect": "found"} for i in range(13)]
+ refused = client.post("/api/compare/analyzers/check/plan", json={**body, "check": check_body(wide)})
+ assert refused.status_code == 422 and "at most 12" in refused.text
+ builtin = next(r for r in BUILTINS if r.id == "large-change").model_dump()
+ assert client.post("/api/compare/analyzers/check/plan", json={**body, "recipe": builtin}).status_code == 422
+
+
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"}]
@@ -671,26 +642,176 @@ def test_a_check_reads_the_cache_then_what_it_lacks_and_says_what_came_out_on_ea
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
+ # a built-in has no checks to try
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():
+def test_a_test_hands_back_what_the_map_draws(client, offline):
+ built = recipe(LOSS, GREEN_BEFORE, parameters={"merge_metres": 30})
+ marks = [{"point": PLOT, "expect": "found"}, {"point": STANDING, "expect": "empty"}]
+ seed_frames(sweep_body(built, maxcc=100), *cleared(), pictures=False)
+ body = {"recipe": built.model_dump(), "check": check_body(marks)}
+ plain = client.post("/api/compare/analyzers/check", json=body).json()
+ assert set(plain) == {"ready", "missing", "count", "covered"} # the list of checks asks for no more
+ answer = client.post("/api/compare/analyzers/check", json={**body, "detail": True}).json()
+ assert answer["ready"] and answer["count"] == 1 and answer["covered"] == [True, False]
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)]
+ [tile] = answer["tiles"]
+ assert (tile["x"], tile["y"]) == (x, y) and answer["size"] == 512
+ assert tile["box"] == detect_rules.tile_box(x, y)
+ mask = np.array(Image.open(io.BytesIO(base64.b64decode(tile["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
+ # 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) and second["kept"] == pytest.approx(first["share"], rel=0.01)
+ candidate = answer["candidates"][0]
+ assert candidate["strength"] == "strong" and "parts" not in candidate
+ # what every rule read under each pin, for the line to be set against
+ plot, standing = answer["readings"]
+ assert plot["kept"] and plot["rules"][0]["passes"] and plot["rules"][0]["before"] == pytest.approx(0.81, abs=0.01)
+ assert plot["rules"][0]["value"] == pytest.approx(-0.69, abs=0.01)
+ assert not standing["kept"] and not standing["rules"][0]["passes"] and standing["rules"][1]["passes"]
+ assert standing["rules"][0]["value"] == pytest.approx(0, abs=0.01)
-def test_a_check_without_marks_counts_what_its_view_gave(client, offline):
+def test_a_test_says_what_the_pins_would_come_to_without_each_rule(client, offline):
built = recipe(LOSS, GREEN_BEFORE)
+ marks = [{"point": PLOT, "expect": "found"}, {"point": STANDING, "expect": "empty"}]
seed_frames(sweep_body(built, maxcc=100), *cleared(), pictures=False)
+ body = {"recipe": built.model_dump(), "check": check_body(marks)}
+ answer = client.post("/api/compare/analyzers/check", json={**body, "detail": True}).json()
+ assert answer["covered"] == [True, False]
+ # without the loss every green field is flagged, the trap with it; without the green ground nothing changes
+ assert answer["without"] == [{"covered": [True, True]}, {"covered": [True, False]}]
+ # the list of checks asks for no more than it needs, and one rule has nothing to be left out of
+ assert "without" not in client.post("/api/compare/analyzers/check", json=body).json()
+ alone = {"recipe": recipe(LOSS).model_dump(), "check": check_body(marks), "detail": True}
+ assert "without" not in client.post("/api/compare/analyzers/check", json=alone).json()
+
+
+def test_a_rule_that_loses_a_pin_shows_in_what_the_pins_would_come_to_without_it(client, offline):
+ strict = recipe({**LOSS, "value": -0.9}, GREEN_BEFORE)
+ marks = [{"point": PLOT, "expect": "found"}, {"point": STANDING, "expect": "empty"}]
+ seed_frames(sweep_body(strict, maxcc=100), *cleared(), pictures=False)
+ body = {"recipe": strict.model_dump(), "check": check_body(marks), "detail": True}
+ answer = client.post("/api/compare/analyzers/check", json=body).json()
+ # the line is past the plot's loss, so the found pin is lost; it is the strict line that loses it
+ assert answer["covered"] == [False, False]
+ assert answer["without"][0]["covered"] == [True, True]
+ assert answer["without"][1]["covered"] == [False, False]
+
+
+def test_a_rule_left_out_that_would_flag_more_fragments_than_a_run_keeps_flags_everything(client, offline, monkeypatch):
+ before, after = scene(), scene()
+ paint(after, 150, 150, 40, 30, sky=BARE, **SOIL) # the plot, as bare as soil
+ for i in range(100): # a hundred patches that lost less
+ paint(after, 20 + (i % 10) * 45, 300 + (i // 10) * 12, 3, 3, sky=BARE, B04=0.12, B08=0.30)
+ built = recipe(LOSS, {"measure": "index", "index": "ndvi", "on": "b", "op": "le", "value": 0.12})
+ seed_frames(sweep_body(built, maxcc=100), before, after, pictures=False)
+ monkeypatch.setattr(analyzers, "MAX_RESULTS", 20)
+ marks = [{"point": PLOT, "expect": "found"}, {"point": STANDING, "expect": "empty"}]
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": []}
+ json={"recipe": built.model_dump(), "check": check_body(marks), "detail": True}).json()
+ assert answer["covered"] == [True, False]
+ assert answer["without"][1]["covered"] == [True, True] # a run would refuse that many pieces
+ assert answer["without"][0]["covered"] == [True, False]
+
+
+def test_what_a_measured_tile_makes_of_some_rules_is_what_a_recipe_of_those_rules_makes_of_it():
+ before, after = cleared()
+ both = recipe(LOSS, GREEN_BEFORE)
+ products = {name: (product(before, name), product(after, name)) for name in recipe_products(both)}
+ mask = np.ones((512, 512), np.uint8)
+ tile = detect_rules.measure(products, mask, both, (DAY_A, DAY_B), LAT)
+ loss_only = evaluate(recipe(LOSS), before, after).reading
+ assert (detect_rules.judge(tile, [0]).binary == loss_only.binary).all()
+ assert (detect_rules.judge(tile).binary == evaluate(both, before, after).reading.binary).all()
+ # under "any" taking one away can only take pixels away
+ either = recipe(LOSS, GREEN_BEFORE, match="any")
+ tile = detect_rules.measure({name: (product(before, name), product(after, name)) for name in recipe_products(either)},
+ mask, either, (DAY_A, DAY_B), LAT)
+ assert detect_rules.judge(tile, [0]).binary.sum() < detect_rules.judge(tile).binary.sum()
+
+
+def test_a_test_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()
+ marks = [{"point": PLOT, "expect": "found"}]
+ shown = client.post("/api/compare/analyzers/check",
+ json={"recipe": built.model_dump(), "check": check_body(marks), "detail": True}).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_candidate_cut_by_a_tile_seam_is_judged_whole_when_the_mark_reads_both_sides(client, offline, monkeypatch):
+ z, x, y = SENTINEL_TILE
+ east = (z, x + 1, y)
+ # a plot that runs across the seam, each half too small to keep and the whole not
+ built = recipe(LOSS, GREEN_BEFORE, parameters={"min_area": 120_000})
+ left_before, left_after = scene(), paint(scene(), 470, 226, 42, 60, sky=BARE, **SOIL)
+ right_before, right_after = scene(), paint(scene(), 0, 226, 30, 60, sky=BARE, **SOIL)
+ body = sweep_body(recipe(LOSS, GREEN_BEFORE), maxcc=100)
+ seed_frames(body, left_before, left_after, pictures=False)
+ seed_frames(body, right_before, right_after, tile=east, pictures=False)
+ near = check_body([{"point": pixel_point(490, 256), "expect": "found"}])
+ request = {"recipe": built.model_dump(), "check": near, "detail": True}
+ whole = client.post("/api/compare/analyzers/check", json=request).json()
+ assert [(tile["x"], tile["y"]) for tile in whole["tiles"]] == [(x, y), (x + 1, y)]
+ assert whole["count"] == 1 and whole["covered"] == [True]
+ assert whole["candidates"][0]["area"] > 120_000
+ # read on its own tile, as a mark nearer the middle is, only its half is left, and too small
+ monkeypatch.setattr(detect_rules, "EDGE_PX", 0)
+ half = client.post("/api/compare/analyzers/check", json=request).json()
+ assert [(tile["x"], tile["y"]) for tile in half["tiles"]] == [(x, y)]
+ assert half["count"] == 0 and half["covered"] == [False]
+
+
+def test_a_point_of_a_tested_check_says_what_every_rule_read_there(client, offline):
+ built = recipe(LOSS, GREEN_BEFORE)
+ body = {"recipe": built.model_dump(), "check": check_body([{"point": PLOT, "expect": "found"}]), "point": PLOT}
+ assert client.post("/api/compare/analyzers/probe", json=body).json() == {"ready": False}
+ seed_frames(sweep_body(built, maxcc=100), *cleared(), pictures=False)
+ probed = client.post("/api/compare/analyzers/probe", json=body).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)
+ # anywhere outside the tiles the check was read on, nothing is held
+ elsewhere = pixel_point(256, 256, (SENTINEL_TILE[0], SENTINEL_TILE[1] + 3, SENTINEL_TILE[2]))
+ assert client.post("/api/compare/analyzers/probe", json={**body, "point": elsewhere}).json() == {"ready": False}
+
+
+def test_a_check_needs_its_passes_and_the_track_they_share(client, offline):
+ built = recipe(LOSS)
+ body = {"recipe": built.model_dump(), "check": check_body([{"point": PLOT, "expect": "found"}], a={"date": ""})}
+ unpaired = client.post("/api/compare/analyzers/check", json=body)
+ assert unpaired.status_code == 422 and "before date" in unpaired.text
+ client.put("/api/settings/prefs", json={"sentinel1_layer": LAYER})
+ radar = recipe({"measure": "radar", "on": "change", "op": "moved", "value": 3})
+ source = lambda day, time: {"provider": "sentinel1", "date": day, "time": time} # noqa: E731
+ marks = [{"point": PLOT, "expect": "found"}]
+ crossed = check_body(marks, a=source(DAY_A, TIME), b=source(DAY_B, "17:40:00"))
+ refused = client.post("/api/compare/analyzers/check/plan", json={"recipe": radar.model_dump(), "check": crossed})
+ assert refused.status_code == 422 and "track" in refused.text
+ same = check_body(marks, a=source(DAY_A, TIME), b=source(DAY_B, TIME))
+ assert client.post("/api/compare/analyzers/check/plan",
+ json={"recipe": radar.model_dump(), "check": same}).json() == {"tiles": 1, "missing": 2}
def test_a_check_saved_on_other_passes_asks_to_be_saved_again(client, offline):
@@ -731,13 +852,14 @@ def test_the_examples_are_whole_analyzers_whose_marks_sit_well_inside_their_tile
assert bool(check.a.date) is not single, (example["id"], check.id)
if not single:
assert check.a.date < check.b.date
+ assert check.marks, (example["id"], check.id)
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))
+ # well inside, so no mark reads the tile across an edge as well
+ assert set(detect_rules.check_tiles(check)) == {detect_rules.pixel_of(mark.point)[:2] for mark in check.marks}
# 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"]
diff --git a/tests/test_entities.py b/tests/test_entities.py
index 9dda009..9e1c4ef 100644
--- a/tests/test_entities.py
+++ b/tests/test_entities.py
@@ -102,9 +102,10 @@ def test_the_legacy_ip_network_field_is_read_only(client):
def test_a_field_that_opens_a_subject_says_what_heads_it(client):
- """A place's four fields are all about how tightly the point is pinned, which is
- worth saying once above them. A vessel's registration numbers are just its own
- fields, so they head nothing — and the panel renders them bare.
+ """A place's four precision fields are all about how tightly the point is pinned,
+ which is worth saying once above them; its other names come first, bare, because
+ they are not. A vessel's registration numbers are just its own fields, so they
+ head nothing — and the panel renders them bare.
The heading is on the field rather than on the type because one type can hold two
subjects: a Claim says *what* it states, *when* it applies and *why* that is
@@ -112,10 +113,13 @@ def test_a_field_that_opens_a_subject_says_what_heads_it(client):
rows = {row["type"]: row for row in client.get("/api/cases/entity-types").json()}
heads = {attr["key"]: attr["group"] for attr in rows["place"]["attrs"]}
- assert heads == {"radius_m": "How precise", "footprint": "", "verbatim": "", "method": ""}
+ assert heads == {
+ "aliases": "", "radius_m": "How precise", "footprint": "", "verbatim": "", "method": "",
+ }
+ assert [attr["key"] for attr in rows["place"]["attrs"]][:2] == ["aliases", "radius_m"]
assert {attr["group"] for attr in rows["vessel"]["attrs"]} == {""}
assert [attr["group"] for attr in rows["claim"]["attrs"]] == [
- "What it states", "", "When", "", "Reasoning", "", "",
+ "What it states", "", "When", "", "", "Reasoning", "", "",
]
@@ -226,7 +230,7 @@ def test_a_type_is_shown_by_the_name_its_tool_gives_it(client):
assert rows["inspect-session"]["label"] == "Inspect work"
assert rows["analysis-follow-up"]["label"] == "Detect routine"
- assert "Detect analyzer" in rows["analysis-zones"]["hint"]
+ assert "Detect" in rows["analysis-zones"]["hint"]
for row in rows.values():
assert "session" not in row["label"].lower() or row["type"] == "compare-session"
assert "watch" not in row["label"].lower(), row["type"]
@@ -610,6 +614,35 @@ def test_a_claim_may_keep_a_local_time_or_no_time_at_all(client):
assert cleared.status_code == 200, cleared.text
+def test_a_claim_states_the_zone_its_date_was_read_in(client):
+ """A day stated in Kyiv is Kyiv's day: the Timeline bounds it from that zone's
+ midnights, and a zone this install cannot load is refused rather than stored."""
+ cid = _new_case(client, "Zoned statement")
+
+ created = client.post(
+ f"/api/cases/{cid}/entities",
+ json={
+ "type": "claim",
+ "label": "The strike was filmed",
+ "attrs": {"when": "2024-03-12", "when_zone": "Europe/Kyiv"},
+ },
+ )
+ bad_zone = client.patch(
+ f"/api/cases/{cid}/entities/{created.json()['id']}",
+ json={"attrs": {"when_zone": "Mars/Olympus"}},
+ )
+ rows = client.get(
+ f"/api/cases/{cid}/timeline",
+ params={"entity": created.json()["id"], "category": "statement", "include_undated": "true"},
+ ).json()["items"]
+
+ assert created.status_code == 200, created.text
+ assert bad_zone.status_code == 400
+ assert [(row["earliest"], row["latest"], row["tz"]) for row in rows] == [
+ ("2024-03-11T22:00:00.000000Z", "2024-03-12T22:00:00.000000Z", "Europe/Kyiv"),
+ ]
+
+
# -- the class family ----------------------------------------------------------
@@ -985,3 +1018,23 @@ def test_the_case_says_which_row_already_holds_an_identifier(client):
json={"type": "account", "label": "osint_handle", "attrs": {}},
)
assert again.status_code == 200
+
+
[email protected]("type_", ["person", "organization", "vessel", "structure", "place", "equipment-type"])
+def test_a_subject_can_be_found_by_its_other_names(client, type_):
+ """A ship renamed twice, a unit known by its acronym, a village with a name in
+ each language: the other names are a declared text field, so the search index
+ and `@` reach them without a migration."""
+ rows = {row["type"]: row for row in client.get("/api/cases/entity-types").json()}
+ alias = next(attr for attr in rows[type_]["attrs"] if attr["key"] == "aliases")
+ assert alias["kind"] == "text"
+
+ cid = client.post("/api/cases", json={"name": f"Aliases {type_}"}).json()["id"]
+ made = client.post(
+ f"/api/cases/{cid}/entities",
+ json={"type": type_, "label": "Plain name", "attrs": {"aliases": "Кі́ров; Άλφα, Nord Star"}},
+ )
+ assert made.status_code == 200, made.text
+ for term in ("кіров", "αλφα", "nord star"):
+ found = client.get(f"/api/cases/{cid}/catalog/entities", params={"q": term}).json()["items"]
+ assert [entity["id"] for entity in found] == [made.json()["id"]], term
diff --git a/tests/test_geo_api.py b/tests/test_geo_api.py
index 96c4993..89f5ebc 100644
--- a/tests/test_geo_api.py
+++ b/tests/test_geo_api.py
@@ -300,6 +300,25 @@ def test_sky_validates_at_the_edge(client, params):
assert client.get("/api/geo/sky", params=params).status_code == 422
+# -- /api/geo/zone --------------------------------------------------------------
+
+
+ ("lat", "lon", "name"),
+ [(49.99, 36.23, "Europe/Kyiv"), (40.71, -74.0, "America/New_York"), (-90, 0, "UTC")],
+)
+def test_zone_names_the_civil_zone_at_a_point(client, lat, lon, name):
+ response = client.get("/api/geo/zone", params={"lat": lat, "lon": lon})
+ assert response.status_code == 200
+ # The name alone: the offset belongs to an instant, which the browser holds.
+ assert response.json() == {"name": name}
+
+
[email protected]("params", [{"lat": 91, "lon": 0}, {"lat": 0, "lon": 181}, {"lat": 0}])
+def test_zone_validates_at_the_edge(client, params):
+ assert client.get("/api/geo/zone", params=params).status_code == 422
+
+
# -- /api/geo/daylight ----------------------------------------------------------
#
# The geometry is covered in tests/test_sky.py. What matters here is the contract the
diff --git a/tests/test_inspect_work.py b/tests/test_inspect_work.py
index 343511c..6f82ab1 100644
--- a/tests/test_inspect_work.py
+++ b/tests/test_inspect_work.py
@@ -421,6 +421,165 @@ def test_deleting_a_collage_leaves_its_exported_picture(client):
assert graph_read.entity(cid, path=exported) is not None
+def _preview(size=(320, 160), mode="RGBA", fmt="PNG") -> bytes:
+ buf = io.BytesIO()
+ Image.new(mode, size, (200, 40, 40, 255) if mode == "RGBA" else (200, 40, 40)).save(buf, fmt)
+ return buf.getvalue()
+
+
+def _put_preview(client, cid, name, data=None):
+ return client.put(
+ f"/api/cases/{cid}/collages/{name}/thumb",
+ files={"file": ("preview.png", io.BytesIO(data or _preview()), "image/png")},
+ )
+
+
+def test_a_collage_with_no_preview_lists_its_outline(client):
+ cid = _case(client)
+ photo = _upload(client, cid, "roof.png")
+ offset = {**_piece(photo, "nd_2"), "quad": [[100, 20], [180, 20], [180, 80], [100, 80]]}
+ _save_collage(client, cid, "Strip", [_piece(photo), offset])
+
+ [row] = client.get(f"/api/cases/{cid}/collages").json()
+
+ assert "thumb" not in row
+ assert row["outline"]["width"] == 180
+ assert row["outline"]["height"] == 80
+ assert row["outline"]["quads"][1][0] == [100, 20]
+
+
+def test_a_preview_is_filed_beside_its_collage_and_listed(client):
+ cid = _case(client)
+ photo = _upload(client, cid, "roof.png")
+ _save_collage(client, cid, "Strip", [_piece(photo)])
+
+ saved = _put_preview(client, cid, "Strip", _preview((900, 300)))
+
+ assert saved.status_code == 200, saved.text
+ assert saved.json()["thumb"] == ".collages/Strip.webp"
+ on_disk = Case.open(cid).tool_root / ".collages" / "Strip.webp"
+ with Image.open(on_disk) as image:
+ assert image.format == "WEBP"
+ assert max(image.size) == inspectwork.THUMB_EDGE # shrunk, never stored larger
+ [row] = client.get(f"/api/cases/{cid}/collages").json()
+ assert row["thumb"] == ".collages/Strip.webp"
+ assert isinstance(row["thumb_v"], int)
+ assert "outline" not in row
+ [entity] = _of_type(cid, "collage")
+ assert entity["attrs"]["thumb"] == ".collages/Strip.webp"
+
+
+def test_an_entity_picker_shows_a_collage_by_its_preview(client):
+ cid = _case(client)
+ photo = _upload(client, cid, "roof.png")
+ _save_collage(client, cid, "Strip", [_piece(photo)])
+ _put_preview(client, cid, "Strip")
+
+ found = client.get(
+ f"/api/cases/{cid}/catalog/entities", params={"type": "collage", "previews": True}
+ ).json()["items"]
+
+ assert found[0]["thumb"] == ".collages/Strip.webp"
+
+
+ "data",
+ [b"not an image", _preview(fmt="JPEG", mode="RGB"), _preview((2000, 2000))],
+ ids=["garbage", "jpeg", "too-many-pixels"],
+)
+def test_a_preview_that_is_not_a_small_png_is_refused(client, data):
+ cid = _case(client)
+ photo = _upload(client, cid, "roof.png")
+ _save_collage(client, cid, "Strip", [_piece(photo)])
+
+ res = _put_preview(client, cid, "Strip", data)
+
+ assert res.status_code == 400
+ assert not (Case.open(cid).tool_root / ".collages" / "Strip.webp").exists()
+
+
+def test_an_emptied_collage_stops_showing_its_old_preview(client):
+ cid = _case(client)
+ photo = _upload(client, cid, "roof.png")
+ _save_collage(client, cid, "Strip", [_piece(photo)])
+ _put_preview(client, cid, "Strip")
+
+ _save_collage(client, cid, "Strip", [], name="Strip")
+
+ [row] = client.get(f"/api/cases/{cid}/collages").json()
+ assert "thumb" not in row
+ assert row["outline"] is None
+
+
+def test_a_preview_for_no_collage_is_refused(client):
+ cid = _case(client)
+
+ res = _put_preview(client, cid, "Nothing")
+
+ assert res.status_code == 404
+ assert not (Case.open(cid).tool_root / ".collages" / "Nothing.webp").exists()
+
+
[email protected]("new_title", ["Harbour strip", "strip"], ids=["rename", "change-of-case"])
+def test_a_renamed_collage_takes_its_preview_along(client, new_title):
+ cid = _case(client)
+ photo = _upload(client, cid, "roof.png")
+ _save_collage(client, cid, "Strip", [_piece(photo)])
+ _put_preview(client, cid, "Strip")
+
+ _save_collage(client, cid, new_title, [_piece(photo)], name="Strip")
+
+ folder = Case.open(cid).tool_root / ".collages"
+ assert [p.name for p in folder.glob("*.webp")] == [f"{new_title}.webp"]
+ [row] = client.get(f"/api/cases/{cid}/collages").json()
+ assert row["thumb"] == f".collages/{new_title}.webp"
+ [entity] = _of_type(cid, "collage")
+ assert entity["attrs"]["thumb"] == f".collages/{new_title}.webp"
+
+
+def test_a_deleted_collage_takes_its_preview_to_the_trash_and_back(client):
+ cid = _case(client)
+ photo = _upload(client, cid, "roof.png")
+ _save_collage(client, cid, "Strip", [_piece(photo)])
+ _put_preview(client, cid, "Strip")
+ preview = Case.open(cid).tool_root / ".collages" / "Strip.webp"
+
+ deleted = client.delete(f"/api/cases/{cid}/collages/Strip").json()
+ assert not preview.exists()
+
+ client.post(f"/api/cases/{cid}/trash/{deleted['trash']}/restore")
+ assert preview.is_file()
+ [row] = client.get(f"/api/cases/{cid}/collages").json()
+ assert row["thumb"] == ".collages/Strip.webp"
+
+
+def test_the_list_says_when_the_exported_picture_is_the_layout_as_it_stands(client):
+ cid = _case(client)
+ photo = _upload(client, cid, "roof.png")
+ piece = _piece(photo)
+ exported = client.post(
+ f"/api/cases/{cid}/inspect/compose",
+ json={"width": 80, "height": 60, "label": "Strip",
+ "nodes": [{"src": piece["save"], "quad": piece["quad"]}]},
+ ).json()["item"]["path"]
+ # The browser's own JSON of the pieces, spaced nothing like Python's.
+ signature = json.dumps([[piece["save"], piece["quad"]]], separators=(",", ":"))
+ filed = {"path": exported, "signature": signature}
+ listed = lambda: client.get(f"/api/cases/{cid}/collages").json()[0]["filed"] # noqa: E731
+
+ _save_collage(client, cid, "Strip", [piece], exported=filed)
+ assert listed() is True
+
+ moved = {**piece, "quad": [[5, 0], [85, 0], [85, 60], [5, 60]]}
+ _save_collage(client, cid, "Strip", [moved], name="Strip", exported=filed)
+ assert listed() is False # edited since the export
+
+ _save_collage(client, cid, "Strip", [piece], name="Strip", exported=filed)
+ entity = graph_read.entity(cid, path=exported)
+ client.delete(f"/api/cases/{cid}/entities/{entity['id']}")
+ assert listed() is False # the picture went to the Trash
+
+
def test_a_piece_without_a_source_is_refused(client):
cid = _case(client)
diff --git a/tests/test_layout.py b/tests/test_layout.py
index 5351a6d..548800b 100644
--- a/tests/test_layout.py
+++ b/tests/test_layout.py
@@ -101,6 +101,7 @@ def _tool_relative(slug: int, media: int) -> dict[str, int]:
"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)),
+ "collage preview": len(layout.collage_thumb_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_map_layers.py b/tests/test_map_layers.py
index 6f6d171..b0fa1d8 100644
--- a/tests/test_map_layers.py
+++ b/tests/test_map_layers.py
@@ -481,6 +481,42 @@ def test_the_legend_survives_a_reload_and_the_switch_is_not_stored(client, case_
assert "enabled" not in spec
+def test_the_dragged_order_is_kept_and_a_new_layer_lands_on_top(client, case_id):
+ """The list reads as the map stacks, first on top, and the order is stored
+ on each layer so it travels with it."""
+ names = [
+ add(client, case_id, KML, f"{stem}.kml", title=stem)["name"]
+ for stem in ("North", "South", "East")
+ ]
+ wanted = [names[1], names[2], names[0]]
+
+ ordered = client.put(f"/api/cases/{case_id}/map-layers/order", json={"names": wanted})
+
+ assert ordered.status_code == 200
+ assert [entry["name"] for entry in ordered.json()] == wanted
+ listed = client.get(f"/api/cases/{case_id}/map-layers").json()
+ assert [entry["name"] for entry in listed] == wanted
+ newest = add(client, case_id, GEOJSON, "west.geojson", title="West")["name"]
+ listed = client.get(f"/api/cases/{case_id}/map-layers").json()
+ assert [entry["name"] for entry in listed] == [newest, *wanted]
+
+
+def test_reordering_skips_a_name_the_case_does_not_hold(client, case_id):
+ row = add(client, case_id, KML, "sightings.kml")
+
+ ordered = client.put(
+ f"/api/cases/{case_id}/map-layers/order",
+ json={"names": ["../elsewhere", "Nothing", row["name"]]},
+ )
+
+ assert ordered.status_code == 200
+ assert [entry["name"] for entry in ordered.json()] == [row["name"]]
+ spec = json.loads(
+ Case.open(case_id).resolve_inside(layout.layer_spec_rel(row["name"])).read_text()
+ )
+ assert spec["position"] == 0
+
+
def test_a_local_file_is_never_stale(client, case_id):
"""It is exactly what the analyst opened, and it was never going to change."""
row = add(client, case_id, KML, "sightings.kml")
diff --git a/tests/test_merges.py b/tests/test_merges.py
new file mode 100644
index 0000000..bd6b2c1
--- /dev/null
+++ b/tests/test_merges.py
@@ -0,0 +1,315 @@
+"""Merge subjects through the public API, then follow and undo every reference."""
+from __future__ import annotations
+
+import io
+import json
+from contextlib import closing
+import sqlite3
+
+import pytest
+from PIL import Image
+
+from azimut.workspace import Case
+from azimut.engine import bundles, merge, sheets, satellite
+from azimut.store.merges import rewrite_view_spec
+
+
+def case(client):
+ cid = client.post('/api/cases', json={'name': 'Merge checks'}).json()['id']
+ return Case.open(cid)
+
+
+def subject(case, label, type_='person', **attrs):
+ return case.add_entity(type_, label, attrs, by='user')
+
+
+def rated_link(case, a, b, confidence, nature):
+ link = case.add_link(a['id'], b['id'], 'associated-with', by='user')
+ case.update_link(link['id'], {'confidence': confidence, 'nature': nature})
+
+
+def post(client, case, keep, other):
+ response = client.post(f'/api/cases/{case.id}/entities/{keep["id"]}/merge', json={'other': other['id']})
+ assert response.status_code == 200, response.text
+ return response.json()
+
+
+def undo(client, case, result):
+ response = client.post(f'/api/cases/{case.id}/merges/{result["merge"]}/undo')
+ assert response.status_code == 200, response.text
+ return response.json()
+
+
+def test_preview_is_read_only_even_in_batch_and_matches_commit(client, case):
+ a = subject(case, 'Subject A', aliases='First', notes='Original')
+ b = subject(case, 'Subject B', aliases='Second', notes='Other note')
+ claim = subject(case, 'Observed', 'claim', when='2026-03-12')
+ edge = case.add_link(claim['id'], b['id'], 'about', by='user')
+ before = case.list_entities(), case.list_links(), case.temporal_projection_status()
+ with case.batch():
+ preview = merge.preview(case, a['id'], b['id'])
+ assert (case.list_entities(), case.list_links(), case.temporal_projection_status()) == before
+ assert case.merges_into(a['id']) == []
+ result = post(client, case, a, b)
+ assert result['links'] == preview['links']
+ assert result['survivor']['attrs']['aliases'] == 'First; Subject B; Second'
+ assert 'Other note' in result['survivor']['attrs']['notes']
+ assert case.links_of(claim['id'])[0]['id'] == edge['id']
+ assert case.links_of(claim['id'])[0]['to'] == a['id']
+ assert case.temporal_projection_status()['consistent']
+ read = client.get(f'/api/cases/{case.id}/entities/{b["id"]}/chain').json()
+ assert read['entity']['id'] == a['id']
+ assert read['merged_from']['id'] == b['id']
+ restored = undo(client, case, result)
+ assert restored['lost'] == []
+ assert case.get_entity(a['id']) == a
+ assert case.get_entity(b['id']) == b
+ assert case.list_links() == before[1]
+ assert case.entity_redirects() == {}
+ assert case.merges_into(a['id']) == []
+
+
[email protected]('type_', ['claim', 'media', 'note', 'proof', 'bookmark'])
+def test_non_subjects_refused(client, case, type_):
+ a, b = subject(case, 'A', type_), subject(case, 'B', type_)
+ response = client.post(f'/api/cases/{case.id}/entities/{a["id"]}/merge', json={'other': b['id']})
+ assert response.status_code == 409
+ assert case.get_entity(b['id']) == b
+
+
+def test_self_and_different_types_refused(client, case):
+ a, b = subject(case, 'A'), subject(case, 'B', 'organization')
+ for other in (a, b):
+ assert client.post(f'/api/cases/{case.id}/entities/{a["id"]}/merge', json={'other': other['id']}).status_code == 409
+
+
+def test_duplicate_and_loop_edges_restore_without_losing_assessments(client, case):
+ a, b, c = [subject(case, label, 'organization') for label in ('A', 'B', 'C')]
+ rated_link(case, a, c, 1, 'partner')
+ rated_link(case, b, c, 1, 'partner')
+ rated_link(case, b, c, 2, 'supplier')
+ case.add_link(a['id'], b['id'], 'associated-with', by='user')
+ before = case.list_links()
+ result = post(client, case, a, b)
+ assert result['links'] == {'moved': 1, 'twins': 1, 'loops': 1, 'refused': 0}
+ assert {edge.get('nature') for edge in case.list_links()} == {'partner', 'supplier'}
+ undo(client, case, result)
+ assert sorted(case.list_links(), key=lambda e: e['id']) == sorted(before, key=lambda e: e['id'])
+
+
+def test_cycle_refuses_entire_merge_in_preview_and_commit(client, case):
+ a, b, c = [subject(case, label, 'organization') for label in ('A', 'B', 'C')]
+ case.add_link(a['id'], c['id'], 'part-of', by='user')
+ case.add_link(c['id'], b['id'], 'part-of', by='user')
+ before = case.list_links()
+ assert merge.preview(case, a['id'], b['id'])['refused']
+ response = client.post(f'/api/cases/{case.id}/entities/{a["id"]}/merge', json={'other': b['id']})
+ assert response.status_code == 409
+ assert case.list_links() == before
+ assert case.get_entity(b['id']) == b
+
+
+def test_compressed_redirects_and_successive_undo(client, case):
+ a, b, c = [subject(case, label) for label in ('A', 'B', 'C')]
+ first = post(client, case, b, a)
+ second = post(client, case, c, b)
+ assert case.entity_redirects([a['id']])[a['id']]['id'] == c['id']
+ assert client.post(f'/api/cases/{case.id}/merges/{first["merge"]}/undo').status_code == 409
+ undo(client, case, second)
+ assert case.entity_redirects([a['id']])[a['id']]['id'] == b['id']
+ undo(client, case, first)
+ assert case.entity_redirects() == {}
+
+
+def test_partial_undo_preserves_later_notes_and_reports_deleted_edge(client, case):
+ a, b, c = [subject(case, label) for label in ('A', 'B', 'C')]
+ edge = case.add_link(b['id'], c['id'], 'associated-with', by='user')
+ result = post(client, case, a, b)
+ case.update_entity(a['id'], {'attrs': {'aliases': 'Written later'}})
+ case.remove_link(edge['id'])
+ answer = undo(client, case, result)
+ assert len(answer['lost']) == 2
+ assert case.get_entity(a['id'])['attrs']['aliases'] == 'Written later'
+
+
+def test_photos_and_graph_positions_round_trip(client, case):
+ a, b = subject(case, 'A'), subject(case, 'B')
+ media = subject(case, 'Frame', 'media', kind='image', path='media/frame.png')
+ for owner in (a, b):
+ answer = client.post(f'/api/cases/{case.id}/entities/{owner["id"]}/images', json={'media_ids': [media['id']]})
+ assert answer.status_code == 200, answer.text
+ picture = io.BytesIO()
+ Image.new('RGB', (8, 8), 'red').save(picture, format='PNG')
+ response = client.post(f'/api/cases/{case.id}/entities/{b["id"]}/images/upload', files={'file': ('photo.png', picture.getvalue(), 'image/png')})
+ assert response.status_code == 200, response.text
+ before = {e['id']: case.entity_images(e['id']) for e in (a, b)}
+ case.pin_entities('all', {a['id']: (1, 2), b['id']: (3, 4)})
+ case.pin_entities('ownership', {b['id']: (5, 6)})
+ result = post(client, case, a, b)
+ assert len(case.entity_images(a['id'])) == 2
+ assert sum(row['primary'] for row in case.entity_images(a['id'])) == 1
+ assert case.graph_pins('all') == {a['id']: (1, 2)}
+ assert case.graph_pins('ownership') == {a['id']: (5, 6)}
+ undo(client, case, result)
+ assert {e['id']: case.entity_images(e['id']) for e in (a, b)} == before
+ assert case.graph_pins('all') == {a['id']: (1, 2), b['id']: (3, 4)}
+
+
+def test_sheet_references_recover_and_undo_without_changing_csv(client, case, monkeypatch):
+ a, b = subject(case, 'A'), subject(case, 'B')
+ sheet = client.post(f'/api/cases/{case.id}/sheets', json={'title': 'Worklist'}).json()
+ saved = client.put(f'/api/cases/{case.id}/sheets/{sheet["id"]}', json={'columns': ['id', 'Subject'], 'rows': [['r1', 'B']], 'meta': {'links': {'r1': {'Subject': b['id']}}, 'values': {'Subject': {'B': b['id']}}, 'attachments': {'r1': [b['id'], a['id']]}}})
+ assert saved.status_code == 200, saved.text
+ csv, path = sheets._paths(case, sheet)
+ before, csv_before = json.loads(path.read_text()), csv.read_bytes()
+ original = sheets.write_atomic
+ def fail(*args, **kwargs):
+ raise OSError('locked file')
+ monkeypatch.setattr(sheets, 'write_atomic', fail)
+ result = merge.merge(case, a['id'], b['id'])
+ assert result['warnings']
+ assert case.pending_merge_work()
+ monkeypatch.setattr(sheets, 'write_atomic', original)
+ Case.open(case.id)
+ assert not case.pending_merge_work()
+ after = json.loads(path.read_text())
+ assert after['links']['r1']['Subject'] == a['id']
+ assert after['attachments']['r1'] == [a['id']]
+ assert all(edge['to'] != b['id'] for edge in case.links_of(sheet['id']))
+ undo(client, case, result)
+ assert json.loads(path.read_text()) == before
+ assert csv.read_bytes() == csv_before
+
+
+def test_places_keep_both_coordinate_keys(client, case):
+ a = subject(case, 'A', 'place', lat=1, lon=2)
+ b = subject(case, 'B', 'place', lat=3, lon=4, enrich_coord_key=satellite.coord_key(3, 4))
+ result = post(client, case, a, b)
+ assert satellite.place_at(case, 3, 4)['id'] == a['id']
+ assert satellite.place_at(case, 1, 2, keyed_only=False)['id'] == a['id']
+ undo(client, case, result)
+ assert satellite.place_at(case, 3, 4)['id'] == b['id']
+
+
+def test_merge_preserves_names_kept_from_an_earlier_type(client, case):
+ a = subject(case, 'A', 'vehicle', aliases='Earlier A', _retained_fields={'aliases': 'person'})
+ b = subject(case, 'B', 'vehicle', aliases='Earlier B', _retained_fields={'aliases': 'person'})
+ result = post(client, case, a, b)
+ assert result['survivor']['attrs']['aliases'] == 'Earlier A'
+ assert 'Earlier B' in result['survivor']['attrs']['notes']
+ undo(client, case, result)
+ assert case.get_entity(b['id']) == b
+
+
+def test_merge_preserves_the_original_enrichment_key_after_a_place_was_corrected(client, case):
+ a = subject(case, 'A', 'place', lat=1, lon=2)
+ b = subject(case, 'B', 'place', lat=3, lon=4, enrich_coord_key=satellite.coord_key(5, 6))
+ post(client, case, a, b)
+ assert satellite.place_at(case, 5, 6)['id'] == a['id']
+
+
+def test_trash_restore_resolves_old_subject_and_purge_clears_journal(client, case):
+ a, b = subject(case, 'A'), subject(case, 'B')
+ claim = subject(case, 'Observation', 'claim')
+ case.add_link(claim['id'], b['id'], 'about', by='user')
+ deleted = client.delete(f'/api/cases/{case.id}/entities/{claim["id"]}').json()
+ result = post(client, case, a, b)
+ from azimut.engine import trash
+ trash.restore(case, deleted['trash'])
+ assert case.links_of(claim['id'])[0]['to'] == a['id']
+ deleted = client.delete(f'/api/cases/{case.id}/entities/{a["id"]}').json()
+ assert client.post(f'/api/cases/{case.id}/merges/{result["merge"]}/undo').status_code == 409
+ report = client.get(f'/api/cases/{case.id}/doctor').json()
+ assert not any(i['kind'] == 'redirect-dangling' for i in report['issues'])
+ trash.purge(case, deleted['trash'])
+ assert case.entity_redirects() == {}
+ assert case.merges_into(a['id']) == []
+
+
+def test_bundle_keeps_redirects_and_finalizes_merge(client, case):
+ a, b = subject(case, 'A'), subject(case, 'B')
+ result = post(client, case, a, b)
+ exported = bundles.export_case(case)
+ destination = Case.create('Imported')
+ bundles.import_into(destination, exported)
+ imported = Case.open(destination.id)
+ assert imported.entity_redirects()[b['id']]['id'] == a['id']
+ assert imported.get_merge(result['merge']) is None
+ assert case.get_merge(result['merge']) is not None
+
+
+def test_doctor_repairs_only_dangling_redirect(client, case):
+ a, b = subject(case, 'A'), subject(case, 'B')
+ post(client, case, a, b)
+ route = f'/api/cases/{case.id}/doctor/repair'
+ assert client.post(route, json={'action': 'drop-redirect', 'entity_id': b['id']}).status_code == 409
+ with closing(sqlite3.connect(case.db_path)) as conn, conn:
+ conn.execute('DELETE FROM entities WHERE id = ?', (a['id'],))
+ answer = client.post(route, json={'action': 'drop-redirect', 'entity_id': b['id']})
+ assert answer.status_code == 200, answer.text
+ assert case.entity_redirects() == {}
+
+
+def test_composite_temporal_ids_are_repointed_without_substring_replacement():
+ before = {'timeline': {'entity': {'id': 'old', 'label': 'Old'}, 'tracks': [{'pinned': ['temporal:activity:old:filed', 'temporal:activity:older:filed'], 'hidden': []}]}}
+ after, changed = rewrite_view_spec(before, 'old', 'new')
+ assert changed
+ assert after['timeline']['tracks'][0]['pinned'] == ['temporal:activity:new:filed', 'temporal:activity:older:filed']
+ assert before['timeline']['entity']['id'] == 'old'
+
+
+def test_live_views_follow_merge_snapshots_stay_frozen_and_undo_keeps_later_edits(client, case):
+ a, b = subject(case, 'A'), subject(case, 'B')
+ specs = {
+ 'graph': {'graph': {'root': b['id'], 'kept': [a['id'], b['id']], 'expanded': [b['id']],
+ 'putAway': {b['id']: [b['id']]}, 'arrangement': [{'id': b['id'], 'x': 1, 'y': 2}]}},
+ 'timeline': {'timeline': {'entity': {'id': b['id'], 'label': 'B'}, 'tracks': [
+ {'pinned': [f'temporal:activity:{b["id"]}:filed'], 'hidden': []}]}},
+ 'frozen': {'snapshot': {'entities': [b]}, 'graph': {'root': b['id']}},
+ }
+ before = {}
+ for name, spec in specs.items():
+ before[name] = case.save_analysis_view({'id': name, 'name': name, 'mode': 'snapshot' if name == 'frozen' else 'live',
+ 'surface': 'timeline' if name == 'timeline' else 'graph', 'spec': spec, 'created_at': '2026-09-01', 'updated_at': '2026-09-01'})
+ result = post(client, case, a, b)
+ graph = case.get_analysis_view('graph')
+ assert graph['spec']['graph']['root'] == a['id']
+ assert graph['spec']['graph']['kept'] == [a['id']]
+ assert graph['spec']['graph']['putAway'] == {a['id']: [a['id']]}
+ assert case.get_analysis_view('timeline')['spec']['timeline']['entity'] == {'id': a['id'], 'label': 'A'}
+ assert case.get_analysis_view('frozen') == before['frozen']
+ graph['spec']['graph']['expanded'] = []
+ case.save_analysis_view(graph)
+ answer = undo(client, case, result)
+ assert any('graph' in loss for loss in answer['lost'])
+ assert case.get_analysis_view('graph') == graph
+ assert case.get_analysis_view('timeline') == before['timeline']
+ assert case.get_analysis_view('frozen') == before['frozen']
+
+
+def test_interrupted_undo_replays_once_on_reopen_and_blocks_bundle(client, case, monkeypatch):
+ a, b = subject(case, 'A'), subject(case, 'B')
+ sheet = client.post(f'/api/cases/{case.id}/sheets', json={'title': 'Worklist'}).json()
+ response = client.put(f'/api/cases/{case.id}/sheets/{sheet["id"]}', json={
+ 'columns': ['id', 'Subject'], 'rows': [['r1', 'B']], 'meta': {'links': {'r1': {'Subject': b['id']}}}})
+ assert response.status_code == 200
+ _, path = sheets._paths(case, sheet)
+ before = json.loads(path.read_text())
+ result = post(client, case, a, b)
+ original = sheets.write_atomic
+ def fail(*args, **kwargs):
+ raise OSError('locked file')
+ monkeypatch.setattr(sheets, 'write_atomic', fail)
+ assert merge.undo(case, result['merge'])['lost']
+ assert case.get_entity(b['id']) == b
+ assert case.pending_merge_work()
+ with pytest.raises(bundles.BundleError, match='sheet'):
+ bundles.export_case(case)
+ monkeypatch.setattr(sheets, 'write_atomic', original)
+ Case.open(case.id)
+ assert json.loads(path.read_text()) == before
+ assert not case.pending_merge_work()
+ assert case.get_merge(result['merge']) is None
+ Case.open(case.id)
+ assert json.loads(path.read_text()) == before
diff --git a/tests/test_proofs_api.py b/tests/test_proofs_api.py
index 7f3105f..2b6a593 100644
--- a/tests/test_proofs_api.py
+++ b/tests/test_proofs_api.py
@@ -1550,6 +1550,235 @@ def test_the_stated_date_shows_on_the_file_it_is_about(client):
assert "taken_at" not in item
+def test_a_proofs_date_is_drawn_once_on_the_timeline(client):
+ """The date is the footage's, stated by a Claim that cites the proof. While that
+ Claim says the proof's date, the proof's own row would be the same date twice."""
+ cid = client.post("/api/cases", json={"name": "Drawn once"}).json()["id"]
+ video = _collected_clip(cid)
+ client.post(
+ f"/api/cases/{cid}/proofs",
+ json={"title": "Dated proof", "spec": {**_panels(video), "when": "2024-03-11"}},
+ )
+
+ def statements():
+ page = client.get(
+ f"/api/cases/{cid}/timeline", params={"categories": "statement"}
+ ).json()
+ return page["total"], [(row["kind"], row["raw"]) for row in page["items"]]
+
+ assert statements() == (1, [("claim", "2024-03-11")])
+
+ # Restated by hand, the Claim is the analyst's own reading and no longer the
+ # proof's date, so the two are two dates again and both are drawn.
+ claim = _claims(cid)[0]
+ client.patch(f"/api/cases/{cid}/timeline/claims/{claim['id']}", json={"when": "2024-03-12"})
+ total, rows = statements()
+ assert total == 2
+ assert sorted(rows) == [("claim", "2024-03-12"), ("taken", "2024-03-11")]
+
+
+def test_the_event_a_proof_dates_names_the_footage_it_puts_in_time(client):
+ """The Timeline's Media lane draws a file where an event dates it: the event says
+ which file, the one it is about before the proof it cites."""
+ import json as json_module
+
+ cid = client.post("/api/cases", json={"name": "Situated footage"}).json()["id"]
+ video = _collected_clip(cid)
+ client.post(
+ f"/api/cases/{cid}/proofs",
+ json={"title": "Dated proof", "spec": {**_panels(video), "when": "2024-03-11"}},
+ )
+ media = next(e for e in graph_read.entities(cid) if e["type"] == "media")
+ page = client.get(
+ f"/api/cases/{cid}/timeline",
+ params={"category": "statement", "track": json_module.dumps({"as_files": "sources"})},
+ ).json()
+
+ [row] = page["items"]
+ assert row["kind"] == "claim"
+ assert row["file"]["id"] == media["id"]
+ assert row["file"]["type"] == "media"
+ assert row["file"]["label"] == media["label"]
+
+
+def test_the_media_lane_holds_the_sources_and_the_imagery_lane_what_was_seen_from_above(client):
+ """A Compare render or the picture Detect keeps is not a source's footage: the
+ events that date one are drawn on the Imagery lane, and only there. An event about
+ a video that cites a render is the video on one lane and the render on the other."""
+ import json as json_module
+
+ from azimut.engine import media as media_engine
+
+ cid = client.post("/api/cases", json={"name": "Two file lanes"}).json()["id"]
+ video = _collected_clip(cid)
+ rendered = media_engine.import_image(
+ Case.open(cid), Image.new("RGB", (48, 32), (90, 90, 90)), "render.png",
+ {"type": "compare"}, by="compare",
+ )["item"]["path"]
+ ids = {
+ entity["attrs"]["path"]: entity["id"]
+ for entity in graph_read.entities(cid) if entity["type"] == "media"
+ }
+
+ def claim(statement, **connectors):
+ client.post(
+ f"/api/cases/{cid}/timeline/claims",
+ json={"statement": statement, "when": "2024-03-11", **connectors},
+ ).raise_for_status()
+
+ claim("Seen in the video", about=[ids[video]])
+ claim("A crater in the render", cites=[ids[rendered]])
+ claim("The video's crater", about=[ids[video]], cites=[ids[rendered]])
+
+ def lane(kind):
+ page = client.get(
+ f"/api/cases/{cid}/timeline",
+ params={"category": "statement", "track": json_module.dumps({"as_files": kind})},
+ ).json()
+ return {row["label"]: row["file"]["id"] for row in page["items"]}
+
+ assert lane("sources") == {
+ "Seen in the video": ids[video], "The video's crater": ids[video],
+ }
+ assert lane("imagery") == {
+ "A crater in the render": ids[rendered], "The video's crater": ids[rendered],
+ }
+ # a lane that draws no files names none
+ plain = client.get(
+ f"/api/cases/{cid}/timeline", params={"category": "statement"}
+ ).json()["items"]
+ assert len(plain) == 3 and not any("file" in row for row in plain)
+
+
+def test_a_proofs_date_is_read_on_the_clock_of_its_point(client):
+ """Footage from Kyiv is dated on Kyiv's clock unless the analyst says otherwise:
+ the day spans Kyiv's midnights on the Timeline, for the proof and for the footage."""
+ cid = client.post("/api/cases", json={"name": "Zoned proof"}).json()["id"]
+ video = _collected_clip(cid)
+ saved = client.post(
+ f"/api/cases/{cid}/proofs",
+ json={
+ "title": "Kyiv",
+ "spec": {**_with_coords("50.4501, 30.5234", None, video), "when": "2024-03-12"},
+ },
+ ).json()
+
+ assert saved["when_zone"] == "Europe/Kyiv"
+ proof = next(e for e in graph_read.entities(cid) if e["type"] == "proof")
+ assert proof["attrs"]["when_zone"] == "Europe/Kyiv"
+ assert _claims(cid)[0]["attrs"]["when_zone"] == "Europe/Kyiv"
+ rows = client.get(
+ f"/api/cases/{cid}/timeline", params={"categories": "statement"}
+ ).json()["items"]
+ assert {(row["earliest"], row["tz"]) for row in rows} == {
+ ("2024-03-11T22:00:00.000000Z", "Europe/Kyiv"),
+ }
+
+ # Left at the point's, the spec keeps no pick, so moving the point moves the zone.
+ spec = client.get(f"/api/cases/{cid}/proofs/Kyiv").json()
+ assert spec.get("whenZone") is None
+ assert spec["whenZoneStated"] == "Europe/Kyiv"
+
+
+def test_a_proof_date_read_in_another_zone_than_its_claim_is_drawn_twice(client):
+ """The footage's Claim moved to UTC's day no longer says what the proof says,
+ so the proof's own Kyiv day comes back beside it."""
+ cid = client.post("/api/cases", json={"name": "Two clocks"}).json()["id"]
+ video = _collected_clip(cid)
+ client.post(
+ f"/api/cases/{cid}/proofs",
+ json={
+ "title": "Kyiv",
+ "spec": {**_with_coords("50.4501, 30.5234", None, video), "when": "2024-03-12"},
+ },
+ )
+ claim = _claims(cid)[0]
+ moved = client.patch(
+ f"/api/cases/{cid}/timeline/claims/{claim['id']}", json={"when_zone": "UTC"}
+ )
+ assert moved.status_code == 200, moved.text
+
+ rows = client.get(
+ f"/api/cases/{cid}/timeline", params={"categories": "statement"}
+ ).json()["items"]
+ assert sorted((row["kind"], row["tz"]) for row in rows) == [
+ ("claim", "UTC"), ("taken", "Europe/Kyiv"),
+ ]
+
+
+def test_a_time_typed_on_the_proof_is_placed_once_its_zone_is_known(client):
+ cid = client.post("/api/cases", json={"name": "Local clock"}).json()["id"]
+ client.post(
+ f"/api/cases/{cid}/proofs",
+ json={
+ "title": "Clock",
+ "spec": {**_with_coords("50.4501, 30.5234"), "when": "2024-07-12T14:30:00"},
+ },
+ )
+
+ rows = client.get(
+ f"/api/cases/{cid}/timeline", params={"categories": "statement"}
+ ).json()["items"]
+ assert [(row["earliest"], row["zone"]) for row in rows] == [
+ ("2024-07-12T11:30:00.000000Z", "named"),
+ ]
+
+
+def test_the_analyst_can_state_the_proofs_date_in_utc_instead(client):
+ cid = client.post("/api/cases", json={"name": "UTC proof"}).json()["id"]
+ client.post(
+ f"/api/cases/{cid}/proofs",
+ json={
+ "title": "Stamp",
+ "spec": {**_with_coords("50.4501, 30.5234"), "when": "2024-03-12", "whenZone": "UTC"},
+ },
+ )
+
+ spec = client.get(f"/api/cases/{cid}/proofs/Stamp").json()
+ assert spec["whenZone"] == "UTC"
+ proof = next(e for e in graph_read.entities(cid) if e["type"] == "proof")
+ assert proof["attrs"]["when_zone"] == "UTC"
+
+ refused = client.post(
+ f"/api/cases/{cid}/proofs",
+ json={"title": "Stamp", "spec": {**SPEC, "when": "2024-03-12", "whenZone": "Mars/Base"}},
+ )
+ assert refused.status_code == 422
+
+
+def test_a_zone_set_in_details_opens_as_the_analysts_pick(client):
+ cid = client.post("/api/cases", json={"name": "Zone from Details"}).json()["id"]
+ client.post(
+ f"/api/cases/{cid}/proofs",
+ json={"title": "Kyiv", "spec": {**_with_coords("50.4501, 30.5234"), "when": "2024-03-12"}},
+ )
+ proof = next(e for e in graph_read.entities(cid) if e["type"] == "proof")
+ patched = client.patch(
+ f"/api/cases/{cid}/entities/{proof['id']}", json={"attrs": {"when_zone": "Europe/Warsaw"}}
+ )
+ assert patched.status_code == 200, patched.text
+
+ spec = client.get(f"/api/cases/{cid}/proofs/Kyiv").json()
+ assert spec["whenZone"] == "Europe/Warsaw"
+ assert spec["whenZoneStated"] == "Europe/Warsaw"
+
+
+def test_a_proof_with_no_point_keeps_a_utc_day_and_no_zone(client):
+ cid = client.post("/api/cases", json={"name": "Nowhere yet"}).json()["id"]
+ saved = client.post(
+ f"/api/cases/{cid}/proofs",
+ json={"title": "Undated place", "spec": {**_panels(), "when": "2024-03-12"}},
+ ).json()
+
+ assert saved["when_zone"] is None
+ proof = next(e for e in graph_read.entities(cid) if e["type"] == "proof")
+ assert "when_zone" not in proof["attrs"]
+ rows = client.get(
+ f"/api/cases/{cid}/timeline", params={"categories": "statement"}
+ ).json()["items"]
+ assert [row["earliest"] for row in rows] == ["2024-03-12T00:00:00.000000Z"]
+
+
def test_a_satellite_capture_is_never_dated_by_the_proof(client, sat_tiles):
cid = client.post("/api/cases", json={"name": "Reference imagery"}).json()["id"]
cap = _sat(client, cid, 50.4501, 30.5234)
diff --git a/tests/test_release_gate.py b/tests/test_release_gate.py
index 36cf536..b2668cb 100644
--- a/tests/test_release_gate.py
+++ b/tests/test_release_gate.py
@@ -206,8 +206,8 @@ def test_storage_and_jobs_add_no_new_runtime_dependency():
# than stopping at the file the class happens to live in.
files = [src / "sqlite_backend.py", src / "engine" / "thumbnails.py"]
files += sorted((src / "store").glob("*.py"))
- text = "".join(path.read_text() for path in files)
- assert "import sqlite3" in (src / "sqlite_backend.py").read_text()
+ text = "".join(path.read_text(encoding="utf-8") for path in files)
+ assert "import sqlite3" in (src / "sqlite_backend.py").read_text(encoding="utf-8")
for banned in ("import numpy", "import pandas", "import redis", "import celery"):
assert banned not in text # no heavyweight queue/DB dependency slipped in
diff --git a/tests/test_repository.py b/tests/test_repository.py
index b0f85ea..73ce1af 100644
--- a/tests/test_repository.py
+++ b/tests/test_repository.py
@@ -820,6 +820,29 @@ def test_every_case_wide_ordering_is_served_by_an_index(repo):
assert "USING INDEX" in detail.upper(), f"{order} has no index to walk: {detail}"
+def test_a_counted_ordering_costs_one_index_search_per_row_of_its_types(repo):
+ """"Most noted" cannot walk an index, so it is asked of a type set only, and each
+ row it orders costs one search on `links.to_id` rather than a scan of the links."""
+ from azimut.store.cursors import _COUNTED_ORDERS
+
+ repo.add_entity("person", "Ada", by="user")
+ with repo._sqlite._connect() as conn:
+ for order, (expression, _key, descending) in _COUNTED_ORDERS.items():
+ direction = "DESC" if descending else "ASC"
+ plan = " | ".join(
+ row[-1] for row in conn.execute(
+ "EXPLAIN QUERY PLAN SELECT rowid AS _rowid, *"
+ f", {expression} AS _sort FROM entities WHERE type IN (?)"
+ f" ORDER BY {expression} {direction}, rowid {direction} LIMIT ?",
+ ("person", 41),
+ )
+ ).upper()
+ assert "USING INDEX IDX_ENTITIES_TYPE" in plan, f"{order} scans the case: {plan}"
+ assert "SEARCH N USING INDEX IDX_LINKS_TO" in plan, f"{order} scans links: {plan}"
+ with pytest.raises(CaseError):
+ repo.page_entities(order="-events")
+
+
def test_an_ordered_page_reads_the_case_in_order_and_pages_without_repeating(repo):
"""The ordering covers the whole case rather than the page, and the cursor keys
on the sort plus the row's own seat, so the second page starts where the first
diff --git a/tests/test_retype.py b/tests/test_retype.py
new file mode 100644
index 0000000..9b1c93c
--- /dev/null
+++ b/tests/test_retype.py
@@ -0,0 +1,143 @@
+"""Changing what a subject is: refused whenever something would be lost."""
+
+from __future__ import annotations
+
+import io
+
+import pytest
+from PIL import Image
+
+from azimut.workspace import Case
+
+
+def _case(client) -> str:
+ return client.post("/api/cases", json={"name": "Retype"}).json()["id"]
+
+
+def _entity(client, case_id, type_, label, attrs=None):
+ response = client.post(
+ f"/api/cases/{case_id}/entities",
+ json={"type": type_, "label": label, "attrs": attrs or {}},
+ )
+ assert response.status_code == 200, response.text
+ return response.json()
+
+
+def _retype(client, case_id, entity_id, type_):
+ return client.patch(f"/api/cases/{case_id}/entities/{entity_id}", json={"type": type_})
+
+
+ ("type_", "label", "attrs", "into", "reason"),
+ [
+ ("place", "Crossroads", {"lat": 1, "lon": 2}, "person", "a place keeps its type"),
+ ("person", "Subject A", {}, "place", "nothing can become a place"),
+ ("person", "Subject A", {}, "claim", "nothing can become a claim"),
+ ("claim", "Seen", {}, "person", "a claim keeps its type"),
+ ("person", "Subject A", {}, "media", "nothing can become a media"),
+ ("bookmark", "Page", {"url": "https://x.test"}, "person", "a bookmark keeps its type"),
+ ("person", "Subject A", {}, "unheard-of", "'unheard-of' is not a type this case knows"),
+ ],
+)
+def test_a_type_outside_the_named_subjects_never_changes(client, type_, label, attrs, into, reason):
+ case_id = _case(client)
+ entity = _entity(client, case_id, type_, label, attrs)
+
+ refused = _retype(client, case_id, entity["id"], into)
+
+ assert refused.status_code == 409, refused.text
+ assert reason in refused.json()["detail"]
+ assert Case.open(case_id).get_entity(entity["id"])["type"] == type_
+
+
+def test_a_relation_the_new_type_cannot_hold_is_named_and_kept(client):
+ case_id = _case(client)
+ unit = _entity(client, case_id, "organization", "4th brigade")
+ subject_a = _entity(client, case_id, "person", "Subject A")
+ joined = client.post(
+ f"/api/cases/{case_id}/links",
+ json={"from_id": subject_a["id"], "to_id": unit["id"], "type": "member-of"},
+ )
+ assert joined.status_code == 200, joined.text
+
+ refused = _retype(client, case_id, unit["id"], "person")
+
+ assert refused.status_code == 409
+ assert refused.json()["detail"] == ["“Subject A” is a member of it"]
+ case = Case.open(case_id)
+ assert case.get_entity(unit["id"])["type"] == "organization"
+ assert [link["type"] for link in case.links_of(unit["id"])] == ["member-of"]
+
+
+def test_photos_hold_back_a_type_with_no_gallery(client):
+ case_id = _case(client)
+ person = _entity(client, case_id, "person", "Subject A")
+ picture = io.BytesIO()
+ Image.new("RGB", (8, 8), "red").save(picture, format="PNG")
+ added = client.post(
+ f"/api/cases/{case_id}/entities/{person['id']}/images/upload",
+ files={"file": ("face.png", picture.getvalue(), "image/png")},
+ )
+ assert added.status_code == 200, added.text
+
+ refused = _retype(client, case_id, person["id"], "account")
+
+ assert refused.status_code == 409
+ assert refused.json()["detail"] == ["an account has no photos, and this one has 1"]
+
+
+def test_fields_are_kept_through_a_change_and_come_back_on_return(client):
+ case_id = _case(client)
+ truck = _entity(client, case_id, "vehicle", "Bridge truck", {"plate": "AA1234", "notes": "blue cab"})
+
+ moved = _retype(client, case_id, truck["id"], "vessel")
+
+ assert moved.status_code == 200, moved.text
+ assert moved.json()["type"] == "vessel"
+ assert moved.json()["attrs"]["plate"] == "AA1234"
+ case = Case.open(case_id)
+ # The index follows the type: the plate is no longer a declared field of it.
+ found = case.page_entities(query="vessel")["items"]
+ assert [entity["id"] for entity in found] == [truck["id"]]
+ assert case.page_entities(query="AA1234")["items"] == []
+
+ back = _retype(client, case_id, truck["id"], "vehicle")
+ assert back.status_code == 200
+ assert [entity["id"] for entity in case.page_entities(query="AA1234")["items"]] == [truck["id"]]
+
+ # A field kept from another type is let go of by clearing it.
+ _retype(client, case_id, truck["id"], "vessel")
+ cleared = client.patch(
+ f"/api/cases/{case_id}/entities/{truck['id']}", json={"attrs": {"plate": None}}
+ )
+ assert cleared.status_code == 200
+ assert "plate" not in cleared.json()["attrs"]
+ assert cleared.json()["attrs"]["notes"] == "blue cab"
+
+
+def test_an_identifier_the_case_already_holds_is_reported_not_refused(client):
+ case_id = _case(client)
+ account = _entity(client, case_id, "account", "@spotter")
+ person = _entity(client, case_id, "person", "spotter")
+
+ moved = _retype(client, case_id, person["id"], "account")
+
+ assert moved.status_code == 200, moved.text
+ assert moved.json()["type"] == "account"
+ assert moved.json()["twin"]["id"] == account["id"]
+
+
+def test_a_change_that_passes_keeps_every_relation(client):
+ case_id = _case(client)
+ unit = _entity(client, case_id, "organization", "Crew")
+ subject_a = _entity(client, case_id, "person", "Subject A")
+ client.post(
+ f"/api/cases/{case_id}/links",
+ json={"from_id": subject_a["id"], "to_id": unit["id"], "type": "associated-with"},
+ )
+
+ moved = _retype(client, case_id, unit["id"], "person")
+
+ assert moved.status_code == 200, moved.text
+ assert "twin" in moved.json()
+ assert [link["type"] for link in Case.open(case_id).links_of(unit["id"])] == ["associated-with"]
diff --git a/tests/test_settings_api.py b/tests/test_settings_api.py
index 3845eae..18b77f4 100644
--- a/tests/test_settings_api.py
+++ b/tests/test_settings_api.py
@@ -827,6 +827,27 @@ def test_display_prefs_default_and_round_trip(client):
assert reloaded["post_target"] == "bluesky"
+def test_post_template_default_is_none_and_round_trips(client):
+ assert client.get("/api/settings").json()["post_template"] == ""
+
+ saved = client.put("/api/settings/prefs", json={"post_template": "tpl_1-A"})
+ assert saved.json()["post_template"] == "tpl_1-A"
+ assert client.get("/api/settings").json()["post_template"] == "tpl_1-A"
+ # a PUT about something else leaves it as it was
+ client.put("/api/settings/prefs", json={"units": "imperial"})
+ assert client.get("/api/settings").json()["post_template"] == "tpl_1-A"
+ # the empty string is how the analyst goes back to the classic layout
+ assert client.put("/api/settings/prefs", json={"post_template": ""}).json()["post_template"] == ""
+
+
+def test_post_template_rejects_anything_that_is_not_an_id(client):
+ client.put("/api/settings/prefs", json={"post_template": "keep"})
+ for bad in ("../x", "has space", "a" * 65, "tpl/1", "é"):
+ res = client.put("/api/settings/prefs", json={"post_template": bad})
+ assert res.status_code == 422, bad
+ assert client.get("/api/settings").json()["post_template"] == "keep"
+
+
def test_extension_hand_off_switches_default_on_and_round_trip(client):
"""Both are on out of the box, because with no extension installed neither
changes anything: Publish opens the intent page and a Reverse Search button
diff --git a/tests/test_settings_backup.py b/tests/test_settings_backup.py
index e4d4839..1daa5d9 100644
--- a/tests/test_settings_backup.py
+++ b/tests/test_settings_backup.py
@@ -368,6 +368,31 @@ def test_a_backup_naming_a_dropped_target_still_restores(client):
assert client.put("/api/settings/prefs", json={"post_target": "mastodon"}).status_code == 422
+def test_default_post_template_travels_with_the_backup(client):
+ client.put("/api/settings/prefs", json={"post_template": "tpl_house"})
+ blob = client.get("/api/settings/export").json()
+ assert blob["settings"]["post_template"] == "tpl_house"
+
+ client.put("/api/settings/prefs", json={"post_template": ""})
+ res = client.post("/api/settings/import", json=blob)
+ assert res.status_code == 200, res.text
+ assert "post_template" in res.json()["imported"]
+ assert client.get("/api/settings").json()["post_template"] == "tpl_house"
+
+
+def test_a_backup_with_an_unreadable_template_id_still_restores(client):
+ """The default template is one preference among a machine's keys and presets,
+ so an id no template can carry reads as none instead of refusing the rest."""
+ res = client.post(
+ "/api/settings/import",
+ json={"settings": {"post_template": "../not an id", "post_mention": "@kept"}},
+ )
+ assert res.status_code == 200, res.text
+ body = client.get("/api/settings").json()
+ assert body["post_template"] == ""
+ assert body["post_mention"] == "@kept"
+
+
def test_a_backup_naming_the_retired_labels_layer_still_imports(client):
res = client.post(
"/api/settings/import",
diff --git a/tests/test_sqlite_backend.py b/tests/test_sqlite_backend.py
index e99dd44..bd93f8c 100644
--- a/tests/test_sqlite_backend.py
+++ b/tests/test_sqlite_backend.py
@@ -346,6 +346,90 @@ def test_schema_9_rebuilds_the_index_for_rows_written_before_it(tmp_path):
assert [e["id"] for e in reopened.page_entities(query="AB-123")["items"]] == [truck["id"]]
+def test_a_search_finds_a_name_whatever_marks_it_was_written_with(tmp_path):
+ """`Cafe` finds `Café`, and the Cyrillic, Arabic and Hebrew a reader types
+ without its stress marks or vowels finds the label written with them. A mark
+ that changes the letter, like a Devanagari vowel sign, still has to match."""
+ store = SqliteCase.create(tmp_path / "case.db", name="Folded search")
+ cafe = store.add_entity("place", "Café du Port", {}, by="user")
+ kyiv = store.add_entity("place", "Ки́їв", {}, by="user")
+ name = store.add_entity("person", "مُحَمَّد", {"aliases": "Мухаммед"}, by="user")
+ peace = store.add_entity("organization", "שָׁלוֹם", {}, by="user")
+ hindi = store.add_entity("organization", "हिंदी", {}, by="user")
+
+ def found(query):
+ return [e["id"] for e in store.page_entities(query=query)["items"]]
+
+ assert found("cafe") == [cafe["id"]]
+ assert found("CAFÉ") == [cafe["id"]]
+ assert found("київ") == [kyiv["id"]]
+ assert found("محمد") == [name["id"]]
+ assert found("мухаммед") == [name["id"]]
+ assert found("שלום") == [peace["id"]]
+ assert found("हिंदी") == [hindi["id"]]
+ assert found("हदी") == []
+
+ store.upsert_media_item(
+ {"path": "media/quai.jpg", "filename": "quai.jpg", "kind": "image",
+ "added_at": "2026-01-01T00:00:00Z", "title": "Arrivée au quai"},
+ entity_id="e_quai",
+ )
+ assert [i["path"] for i in store.page_media_items(q="arrivee")["items"]] == ["media/quai.jpg"]
+
+
+def test_schema_19_folds_the_indexes_written_before_it(tmp_path):
+ """0.3.1 stored its search text with every accent kept, so without the rebuild a
+ name filed before the update would answer only its exact spelling."""
+ db = tmp_path / "case.db"
+ store = SqliteCase.create(db, name="Old accents")
+ cafe = store.add_entity("place", "Café du Port", {}, by="user")
+ store.upsert_media_item(
+ {"path": "media/quai.jpg", "filename": "quai.jpg", "kind": "image",
+ "added_at": "2026-01-01T00:00:00Z", "title": "Arrivée au quai"},
+ entity_id="e_quai",
+ )
+ schema_rewind.rewind(db, 18)
+ with closing(sqlite3.connect(db)) as conn:
+ stored = conn.execute("SELECT search_text FROM entities WHERE id = ?", (cafe["id"],))
+ assert stored.fetchone()[0].startswith("café")
+
+ reopened = SqliteCase.open(db)
+ assert [e["id"] for e in reopened.page_entities(query="cafe")["items"]] == [cafe["id"]]
+ assert [i["path"] for i in reopened.page_media_items(q="arrivee")["items"]] == ["media/quai.jpg"]
+
+
+def _zones(db) -> list[tuple[str, str | None, str | None]]:
+ with closing(sqlite3.connect(db)) as conn:
+ return conn.execute("SELECT raw, earliest, tz FROM temporal_items WHERE raw IS NOT NULL"
+ " AND category = 'statement'").fetchall()
+
+
+def test_schema_19_reads_a_stated_day_in_its_zone(tmp_path):
+ """0.3.1 had no zone column. The migration adds it and re-reads what the case
+ holds, so a Claim stated in a zone lands on that zone's day on first open."""
+ db = tmp_path / "case.db"
+ store = SqliteCase.create(db, name="Zones")
+ store.add_entity("claim", "Filmed", {"when": "2024-03-12", "when_zone": "Europe/Kyiv"}, by="user")
+ schema_rewind.rewind(db, 18)
+
+ SqliteCase.open(db)
+ assert _zones(db) == [("2024-03-12", "2024-03-11T22:00:00.000000Z", "Europe/Kyiv")]
+
+
+def test_a_development_19_without_the_zone_column_gains_it_on_open(tmp_path):
+ """A case opened by an earlier cut of the unshipped 19 is stamped 19 already, so
+ no migration runs; the open itself adds the column and rebuilds the rows."""
+ db = tmp_path / "case.db"
+ store = SqliteCase.create(db, name="Dev 19")
+ store.add_entity("claim", "Filmed", {"when": "2024-03-12", "when_zone": "Asia/Tokyo"}, by="user")
+ with closing(sqlite3.connect(db)) as conn, conn:
+ schema_rewind.drop_temporal_zones(conn)
+
+ reopened = SqliteCase.open(db)
+ assert _zones(db) == [("2024-03-12", "2024-03-11T15:00:00.000000Z", "Asia/Tokyo")]
+ assert reopened.temporal_projection_status()["consistent"] is True
+
+
# A schema-4 media index: the browse table as it shipped, before the position
# flag. `media_index_ready` is set because a real v4 case has already backfilled;
# without it, open would rescan the (absent) media folder and clear these rows.
diff --git a/tests/test_temporal.py b/tests/test_temporal.py
index c848226..ecf70bb 100644
--- a/tests/test_temporal.py
+++ b/tests/test_temporal.py
@@ -176,3 +176,74 @@ def test_unsupported_or_ambiguous_forms_are_refused(raw):
def test_a_temporal_value_is_always_text(raw):
with pytest.raises(TemporalError):
parse_temporal(raw)
+
+
+ ("raw", "tz", "earliest", "latest"),
+ [
+ # The 12th in Kyiv opens two hours before UTC's.
+ ("2024-03-12", "Europe/Kyiv", "2024-03-11T22:00:00.000000Z", "2024-03-12T22:00:00.000000Z"),
+ # A day the clocks go forward is 23 hours long, and the next midnight ends it.
+ ("2024-03-31", "Europe/Paris", "2024-03-30T23:00:00.000000Z", "2024-03-31T22:00:00.000000Z"),
+ ("2024-03", "Australia/Sydney", "2024-02-29T13:00:00.000000Z", "2024-03-31T13:00:00.000000Z"),
+ ("2024", "America/New_York", "2024-01-01T05:00:00.000000Z", "2025-01-01T05:00:00.000000Z"),
+ ("2024-03-12", "UTC", "2024-03-12T00:00:00.000000Z", "2024-03-13T00:00:00.000000Z"),
+ ],
+)
+def test_a_date_stated_in_a_zone_spans_that_zones_days(raw, tz, earliest, latest):
+ value = parse_temporal(raw, tz=tz)
+
+ assert value.raw == raw
+ assert value.earliest == earliest
+ assert value.latest == latest
+ assert value.zone == "date-only"
+ assert value.tz == tz
+ assert value.sortable is True
+
+
+def test_a_date_interval_stated_in_a_zone_uses_its_midnights_at_both_ends():
+ value = parse_temporal("2024-03-12/2024-03-14~", tz="Asia/Tokyo")
+
+ assert value.earliest == "2024-03-11T15:00:00.000000Z"
+ assert value.latest == "2024-03-14T15:00:00.000000Z"
+ assert value.approximate is True
+
+
+def test_a_local_time_stated_in_a_zone_joins_the_utc_axis():
+ value = parse_temporal("2024-07-12T14:30:00", tz="Europe/Kyiv")
+
+ # Summer: Kyiv is three hours ahead of UTC.
+ assert value.earliest == "2024-07-12T11:30:00.000000Z"
+ assert value.latest == "2024-07-12T11:30:01.000000Z"
+ assert value.zone == "named"
+ assert value.tz == "Europe/Kyiv"
+ assert value.sortable is True
+
+
+def test_a_local_timestamp_interval_is_placed_once_its_zone_is_known():
+ value = parse_temporal("2024-03-12T14:30:00/2024-03-12T15:00:00", tz="Asia/Tokyo")
+
+ assert value.shape == "interval"
+ assert value.earliest == "2024-03-12T05:30:00.000000Z"
+ assert value.latest == "2024-03-12T06:00:00.000000Z"
+ assert value.zone == "named"
+
+
[email protected]("raw", ["2024-03-12T14:30:00Z", "2024-03-12T16:30:00+02:00"])
+def test_a_timestamp_that_says_where_it_stands_keeps_its_own_offset(raw):
+ value = parse_temporal(raw, tz="Asia/Tokyo")
+
+ assert value.earliest == "2024-03-12T14:30:00.000000Z"
+ assert value.tz is None
+ assert value.zone in {"utc", "offset"}
+
+
+def test_without_a_zone_a_date_still_spans_a_utc_day():
+ assert parse_temporal("2024-03-12").tz is None
+ assert parse_temporal("2024-03-12").earliest == "2024-03-12T00:00:00.000000Z"
+
+
[email protected]("tz", ["", "Mars/Olympus", " Europe/Kyiv", "../etc/passwd", "x" * 80])
+def test_an_unknown_zone_is_refused(tz):
+ with pytest.raises(TemporalError):
+ parse_temporal("2024-03-12", tz=tz)
diff --git a/tests/test_textfold.py b/tests/test_textfold.py
new file mode 100644
index 0000000..e78aeb9
--- /dev/null
+++ b/tests/test_textfold.py
@@ -0,0 +1,24 @@
+"""Search folds the same text the same way on the server as in the browser."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+
+from azimut.engine.textfold import fold_text
+
+CASES = json.loads(
+ (Path(__file__).parent / "fixtures" / "fold_cases.json").read_text(encoding="utf-8")
+)["cases"]
+
+
[email protected](("text", "folded", "why"), CASES, ids=[case[2] for case in CASES])
+def test_search_folds_what_a_reader_skips_and_nothing_else(text, folded, why):
+ assert fold_text(text) == folded
+
+
+def test_folding_twice_changes_nothing():
+ for text, folded, _ in CASES:
+ assert fold_text(folded) == folded
diff --git a/tests/test_timeline_api.py b/tests/test_timeline_api.py
index 5fbd421..3abb137 100644
--- a/tests/test_timeline_api.py
+++ b/tests/test_timeline_api.py
@@ -71,6 +71,103 @@ def test_a_bad_connector_rolls_back_the_whole_claim(client):
assert [entity["type"] for entity in entities] == ["person"]
+def test_a_line_creates_the_subjects_it_names_with_its_claim(client):
+ case_id = _case(client)
+ place = _entity(client, case_id, "place", "Crossroads", {"lat": 49.9, "lon": 36.2})
+
+ created = client.post(
+ f"/api/cases/{case_id}/timeline/claims",
+ json={
+ "statement": "4th brigade seen at Crossroads",
+ "at": [place["id"]],
+ "create": [
+ {"slot": "about", "type": "organization", "label": " 4th brigade "},
+ {"slot": "about", "type": "account", "label": "@spotter"},
+ ],
+ },
+ )
+
+ assert created.status_code == 200, created.text
+ body = created.json()
+ made = body["created"]
+ assert [(entry["type"], entry["label"], entry["slot"]) for entry in made] == [
+ ("organization", "4th brigade", "about"),
+ ("account", "@spotter", "about"),
+ ]
+ assert {(link["type"], link["to"]) for link in body["links"]} == {
+ ("at", place["id"]),
+ ("about", made[0]["id"]),
+ ("about", made[1]["id"]),
+ }
+ case = Case.open(case_id)
+ organization = case.get_entity(made[0]["id"])
+ assert organization["provenance"]["by"] == "user"
+ assert organization["provenance"]["status"] == "confirmed"
+
+ # Undo is the grouped delete: the Claim and what it created, as one trash group.
+ undone = client.post(
+ f"/api/cases/{case_id}/entities/delete",
+ json={"ids": [body["entity"]["id"], *(entry["id"] for entry in made)]},
+ )
+ assert undone.status_code == 200, undone.text
+ assert sorted(entity["type"] for entity in case.list_entities()) == ["place"]
+ restored = client.post(f"/api/cases/{case_id}/trash/{undone.json()['trash']}/restore")
+ assert restored.status_code == 200, restored.text
+ assert sorted(entity["type"] for entity in case.list_entities()) == [
+ "account", "claim", "organization", "place",
+ ]
+
+
+ ("entry", "reason"),
+ [
+ ({"slot": "about", "type": "place", "label": "Somewhere"}, "cannot be a 'place'"),
+ ({"slot": "about", "type": "media", "label": "clip.mp4"}, "cannot be a 'media'"),
+ ({"slot": "about", "type": "claim", "label": "Another"}, "cannot be a 'claim'"),
+ ({"slot": "about", "type": "unheard-of", "label": "X"}, "cannot be a 'unheard-of'"),
+ ({"slot": "about", "type": "person", "label": " "}, "needs a name"),
+ # A person is not evidence: the vocabulary refuses the seat, after the
+ # subject was written, and the whole line goes back.
+ ({"slot": "cites", "type": "person", "label": "Witness"}, ""),
+ ],
+)
+def test_a_new_subject_the_line_cannot_create_leaves_nothing(client, entry, reason):
+ case_id = _case(client)
+
+ refused = client.post(
+ f"/api/cases/{case_id}/timeline/claims",
+ json={"statement": "Something seen", "create": [entry]},
+ )
+
+ assert refused.status_code == 400, refused.text
+ assert reason in refused.json()["detail"]
+ assert Case.open(case_id).list_entities() == []
+
+
+def test_a_line_names_at_most_ten_new_subjects(client):
+ case_id = _case(client)
+ entries = [{"slot": "about", "type": "person", "label": f"P{n}"} for n in range(11)]
+
+ refused = client.post(
+ f"/api/cases/{case_id}/timeline/claims",
+ json={"statement": "Crowd", "create": entries},
+ )
+
+ assert refused.status_code == 422
+ assert Case.open(case_id).list_entities() == []
+
+
+def test_a_claim_without_new_subjects_still_posts_the_old_body(client):
+ case_id = _case(client)
+
+ created = client.post(
+ f"/api/cases/{case_id}/timeline/claims", json={"statement": "Plain"}
+ )
+
+ assert created.status_code == 200, created.text
+ assert created.json()["created"] == []
+
+
def test_subsecond_bounds_sort_filter_and_measure_the_extent_chronologically(client):
case_id = _case(client, "Subsecond order")
for statement, when in (
@@ -190,6 +287,69 @@ def test_local_time_is_counted_as_unplaced_instead_of_undated(client):
assert body["items"][0]["zone"] == "local"
+def test_a_day_stated_in_a_zone_is_that_zones_day_on_the_axis(client):
+ """The 12th in Tokyo ends at 15:00 UTC, so a window closing at 16:00 UTC on
+ the 12th holds all of it; read as UTC's day it would spill past the window."""
+ case_id = _case(client)
+ created = client.post(
+ f"/api/cases/{case_id}/timeline/claims",
+ json={"statement": "Filmed", "when": "2024-03-12", "when_zone": "Asia/Tokyo"},
+ )
+ assert created.status_code == 200, created.text
+ row = created.json()["temporal"]
+ assert (row["earliest"], row["latest"], row["tz"]) == (
+ "2024-03-11T15:00:00.000000Z", "2024-03-12T15:00:00.000000Z", "Asia/Tokyo",
+ )
+
+ local = client.post(
+ f"/api/cases/{case_id}/timeline/claims",
+ json={"statement": "Clock", "when": "2024-03-12T09:00:00", "when_zone": "Asia/Tokyo"},
+ )
+ assert local.json()["temporal"]["earliest"] == "2024-03-12T00:00:00.000000Z"
+ assert local.json()["temporal"]["zone"] == "named"
+
+
+def test_a_time_keeps_the_clock_it_was_picked_on_beside_its_offset(client):
+ """A time is written with the offset its zone keeps then, and the row still
+ names the zone, so the Timeline says Kyiv rather than a bare +03:00."""
+ case_id = _case(client)
+ created = client.post(
+ f"/api/cases/{case_id}/timeline/claims",
+ json={"statement": "Strike", "when": "2024-07-12T14:30:00+03:00", "when_zone": "Europe/Kyiv"},
+ )
+ assert created.status_code == 200, created.text
+ row = created.json()["temporal"]
+ assert (row["earliest"], row["zone"], row["tz"]) == (
+ "2024-07-12T11:30:00.000000Z", "offset", "Europe/Kyiv",
+ )
+
+
+def test_a_zone_leaves_with_the_date_it_read(client):
+ case_id = _case(client)
+ claim_id = client.post(
+ f"/api/cases/{case_id}/timeline/claims",
+ json={"statement": "Filmed", "when": "2024-03-12", "when_zone": "Europe/Kyiv"},
+ ).json()["entity"]["id"]
+
+ # Editing the date alone keeps the zone it was stated in.
+ moved = client.patch(
+ f"/api/cases/{case_id}/timeline/claims/{claim_id}", json={"when": "2024-03-13"}
+ )
+ assert moved.json()["entity"]["attrs"]["when_zone"] == "Europe/Kyiv"
+ assert moved.json()["temporal"]["earliest"] == "2024-03-12T22:00:00.000000Z"
+
+ cleared = client.patch(
+ f"/api/cases/{case_id}/timeline/claims/{claim_id}", json={"when": None}
+ )
+ assert "when_zone" not in cleared.json()["entity"]["attrs"]
+
+ refused = client.post(
+ f"/api/cases/{case_id}/timeline/claims",
+ json={"statement": "Nowhere", "when": "2024-03-12", "when_zone": "Mars/Olympus"},
+ )
+ assert refused.status_code == 400
+
+
def test_timestamp_window_uses_the_given_second_as_its_upper_boundary(client):
case_id = _case(client)
for second in (0, 1):
@@ -375,6 +535,67 @@ def test_media_metadata_and_case_activity_are_separate_categories(client):
assert [item["kind"] for item in activity["items"]] == ["added"]
+def test_a_file_row_carries_the_preview_the_case_already_cached(client):
+ """A card on a zoomed axis shows the picture: the row brings the cached thumbnail,
+ and a row whose owner has none, or is not a file, brings nothing."""
+ case_id = _case(client)
+ case = Case.open(case_id)
+ shown = case.add_entity("media", "Frame", {"path": "media/frame.jpg", "kind": "image"}, by="user")
+ bare = case.add_entity("media", "Clip", {"path": "media/clip.mp4", "kind": "video"}, by="user")
+ for entity, path, thumb in ((shown, "media/frame.jpg", ".thumbs/frame.jpg"), (bare, "media/clip.mp4", None)):
+ case.upsert_media_item(
+ {
+ "path": path, "filename": path.rsplit("/", 1)[1], "kind": "image",
+ "taken_at": "2024-02-03T10:11:12Z", "added_at": "2026-08-11T10:00:00Z",
+ **({"thumbnail": thumb} if thumb else {}),
+ },
+ entity_id=entity["id"],
+ )
+ _entity(client, case_id, "claim", "Seen the same day", {"when": "2024-02-03"})
+
+ items = client.get(
+ f"/api/cases/{case_id}/timeline", params={"category": ["media", "statement"]}
+ ).json()["items"]
+ thumbs = {item["owner_id"]: item.get("thumb") for item in items}
+
+ assert thumbs[shown["id"]] == ".thumbs/frame.jpg"
+ assert thumbs[bare["id"]] is None
+ assert all("thumb" not in item for item in items if item["category"] == "statement")
+
+
+def test_a_track_can_hold_back_the_files_the_case_made_itself(client):
+ """The Media Library's working-files switch, on a track: a frame and a capture stay
+ off it, a download stays on, and the file a reading is focused on always shows."""
+ case_id = _case(client, "Working files")
+ case = Case.open(case_id)
+ owners = {}
+ for name, source in (("clip", "download"), ("frame", "inspect"), ("capture", "satellite")):
+ entity = case.add_entity("media", name, {"path": f"media/{name}.jpg", "kind": "image"}, by="user")
+ case.upsert_media_item(
+ {
+ "path": f"media/{name}.jpg", "filename": f"{name}.jpg", "kind": "image",
+ "taken_at": "2024-02-03T10:11:12Z", "added_at": "2026-08-11T10:00:00Z",
+ "source": {"type": source},
+ },
+ entity_id=entity["id"],
+ )
+ owners[entity["id"]] = name
+
+ def read(track, **params):
+ page = client.get(f"/api/cases/{case_id}/timeline", params={
+ "category": "media", "track": json.dumps(track), **params,
+ })
+ assert page.status_code == 200, page.text
+ return {owners[item["owner_id"]]: item["produced_here"] for item in page.json()["items"]}
+
+ assert read({}) == {"clip": False, "frame": True, "capture": True}
+ assert read({"collected_only": True}) == {"clip": False}
+ for spread in ("false", "true"):
+ assert read({"collected_only": True}, spread=spread, limit=1) == {"clip": False}
+ frame = next(owner for owner, name in owners.items() if name == "frame")
+ assert read({"collected_only": True}, entity=frame) == {"frame": True}
+
+
def test_schema_15_backfills_existing_claims_and_media(tmp_path):
db = tmp_path / "case.db"
from azimut.sqlite_backend import SqliteCase
@@ -453,6 +674,17 @@ def test_timeline_track_filters_through_named_claim_connectors(client):
)
assert [item["id"] for item in sourced.json()["items"]] == [first["id"]]
+ # The Board's question about what a claim lacks reaches a track the same way.
+ unsourced = client.get(
+ f"/api/cases/{case_id}/timeline",
+ params={
+ "category": "statement",
+ "track": json.dumps({"relation": "owner", "terms": {"lacks": "source"}}),
+ },
+ )
+ assert unsourced.status_code == 200, unsourced.text
+ assert [item["label"] for item in unsourced.json()["items"]] == ["Unrelated event"]
+
def test_timeline_track_can_filter_role_and_hide_one_entry(client):
case_id = _case(client, "Track role")