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

Add GeoConfirmed and dated layers, and file claims and dates from where you are (#83)

OsintMeThate61fb6d9c0c5
diff --git a/docs/ASSIST_HANDOVER.md b/docs/ASSIST_HANDOVER.md
deleted file mode 100644
index 57e3dcc..0000000
--- a/docs/ASSIST_HANDOVER.md
+++ /dev/null
@@ -1,165 +0,0 @@
-# Compare Detect — working notes
-
-Scratch notes for whoever picks this up next, not a project doc. Delete it when
-the work lands in a release. What is *done* is described in
-[UI.md](UI.md) and [SPEC.md](SPEC.md); only what is open or surprising is here.
-
-## Decisions taken
-
-- **Two computing modes, one column.** `Difference` (the old Change assist) reads
- the pixels on screen; `Detect` sweeps a drawn area at native resolution. They
- sit right of a rule in the mode dock, and share one docked column beside the
- stage. There is no "Assist" button and no cross-link between panels: the dock
- is the only switch. `lib/map/compare.js` carries the grouping.
-- **No machine-learning model, and not as a fallback.** At Sentinel-2's 10 m a
- pixel a 30 m vessel is three pixels: there is no shape to recognise, and a
- detector trained on shapes would do worse than the physics. Every method reads
- a band product (`sentinel.DETECT_PRODUCTS`) and says what it measured.
-- **Detect is Copernicus-only.** Every method measures reflectance, which Wayback
- pictures have already stretched away. Recipes and watches saved against Wayback
- or a picture method still load: `colour`, `brightness` and `smoke` map to
- `surface`, `water_objects` to `vessels`, and a Wayback source comes back undated.
-- **Thresholds come from real scenes.** Calibrated on Bab-el-Mandeb (glint, rough
- sea), Singapore Strait (dense anchorage, cumulus), Gibraltar, Dover Strait
- (empty sea), Rumaila flares, California and Cerrado wildfires, Jebel Ali roofs,
- Egypt's new capital (seven months), Rondônia (dry season) and irrigated desert.
- What each taught is next to the constant it set, in `engine/analyzers.py`:
- - `vessels` needs near *and* short-wave infrared contrast against its own ring
- of sea. Wave crests match hulls in B08 and not in B11. Non-water over 5 ha is
- land. Sen2Cor calls hulls cloud, so classified cloud under 5 ha is ignored.
- - `hotspots` is Murphy et al. 2016 on B8A, which shares B12's grid.
- - `structure` is every band moving the same way with NDVI held; `spots` is a
- change whose wider neighbourhood mostly held, measured against a ring with a
- hole punched in it (`SPOT_GUARD`, `SPOT_RING`) — a median box the size of the
- target read a 90 m mark in the Yemeni desert at 3.5% where it had moved 7%;
- burn scars must end dark, because dry soil also has a negative NBR.
- - The global shift between dates is removed but capped at 3%, or a burn
- covering most of a tile erases itself.
-- **Names say what an analyst looks for.** A candidate carries `margin` (how far
- past its threshold), a `strength` word and a `measure` in units; the catalogue
- words each method's reading. `signal_score` and `confidence` are gone.
-- **Disk follows findings, not area.** `prune_frames` drops the frames of tiles
- that produced no candidate, which is what let `MAX_TILES` go from 256 to 4096
- (313 km a side). The trade is stated in the
- panel and in UI.md: an offline rerun now covers what the tile cache still
- holds, not the whole of a past sweep.
-- **Detect leads the maps.** Inside the mode the A/B source cards are hidden and
- step 2 pushes its imagery onto the stage, so what is on screen is what a run
- would sweep. One analyzer that reads one date shows one map, and its evidence
- is one crop rather than the same picture twice.
-- **Keeping is the review.** The triage is `new → kept | dismissed`, and `kept`
- is set by `promote` itself: one act files the pin, its evidence copy and the
- verdict together, so a candidate cannot be marked kept without being in the
- case or the reverse. `PATCH` refuses to re-triage a candidate whose pin still
- exists; `DELETE …/promote` is the undo, and it sends the pin to Trash. The old
- three-way relevant/ignored/to-review was two decisions where there is one.
-- **An area is grabbed by its edge.** The fill of a zone no longer takes pointer
- events, so dragging inside one pans the map; a transparent wide stroke is the
- move target, and a press under four pixels selects without moving anything.
- Screen positions all go through `project()`, which reads the camera revision,
- so handles and boxes cannot be left behind by a pan.
-- **Detect's drawing stays in Detect.** Areas and candidate layers render only
- in the mode that explains them. A kept candidate is a pin and shows wherever
- case work shows, which is the honest way for a result to outlive the mode.
-- **Difference reads the same sky as Detect.** `skyMask` in
- `lib/map/changeDetect.js` is the browser's copy of `analyzers.sky`: the same
- cloud classes, the same 5 ha floor, the same unsure edge and the same cast
- away from the sun, turned by the map's bearing because a view can be. Both
- sides of that port were calibrated on cumulus over the Beauce and over the
- Kakhovka reservoir bed, which is what turned up the water rule below. The
- browser gets the bytes from `change-*` frames whose alpha must stay the data
- mask, because a canvas premultiplies it.
-- **A band frame is fetched by an act, then held.** Run and the cloud switch are
- the two acts; a pan is not. Each frame is asked for with 20% of the view as
- margin and kept in `changeCapture`, so a reading that follows the camera keeps
- working inside that margin and reports `needsFetch` past it, leaving the last
- reading up and marked out of date. The switch itself runs the reading: leaving
- an unfiltered mask on screen under an "on" switch is how the first version of
- this read as broken. There is no live/manual switch any more — the reading
- always follows the camera, and the only question left is whether a request is
- spent, which only Run and the cloud switch ever do.
-- **Water is only water when both dates say so.** Sen2Cor reads a deep cloud
- shadow as water — a fifth of the Ukrainian scene — and a cast that spares
- water found 0.3% of the shadow instead of 13.7%. Where a second pass exists,
- `sky(…, other)` asks it; a single-date method (`vessels`) still spares water,
- which is the sea it works on.
-- **Matching tones is off on Sentinel-2.** The default is `auto`: nothing on
- Sentinel-2, a histogram on Esri releases. Two L2A passes are corrected and
- rendered by one formula, so a match can only eat real change — it erased the
- Cerrado burn, 74% of a tile, leaving 0.3% highlighted where 71% had been. Esri
- releases carry two renderings and a median tone shift of 15 levels between
- them, a quarter of the pairs past 25, so there a match still earns its place.
- Cloud is left out of the estimate either way.
-- **A spectral index is thresholded, not split.** Otsu always finds a line, and
- after the cloud came out it found one in the noise: 19% of a clear Amazon week
- highlighted at the floor. Both modes now draw the line at a stated index
- change, 0.25 at the default sensitivity.
-- **The picture cloud guess is gone.** "Bright and colourless, near-black"
- marked 94% of Gibraltar and 100% of Dover as shadow — sea and forest — and
- caught a fifth of the real cloud in Amazonia. The filter now appears on a
- Sentinel-2 pair only, where a classification exists.
-- **"Watch" is the UI word for a follow-up.** The entity type id stays
- `analysis-follow-up`; renaming storage for a word nobody reads is not worth a
- migration.
-
-## Still open
-
-1. **The tile halo is 32 px.** Products are read with `PAD` pixels of the
- neighbours, enough for the vessel ring and a coastline, and a candidate
- crossing a seam is merged and previewed as one stitched picture. Clouds more
- than 306 m past the edge still cast no shadow into the tile.
-2. **The promoted place carries `evidence` as an attribute** rather than a
- formal link to the filed media. `PREVIEW_EDGE`/`PREVIEW_MARGIN` decide how far
- the crop is enlarged; the zoom is a whole number and nearest-neighbour on
- purpose, and that is worth keeping whatever else changes there.
-3. **Preserved frames are trusted by filename.** `frame` reuses any
- `runs-*.assets/<key>.png` it finds without checking the recorded `sha256`
- against the bytes. The key is derived from the source and tile, not the
- content, so an imported bundle could supply the file. Verify before reading.
-4. **Polygon validation** catches empty and zero-area geometry, not every
- self-crossing.
-5. **Coverage is sampled, not clipped.** `sentinel.acquisitions` measures how
- much of the drawn areas a pass reaches by testing a few hundred points inside
- the rings against the granule footprints, so a share is accurate to about a
- percent and `FULL_COVER = 0.98` is what counts as whole. It answers about the
- granule footprints, which is where imagery exists — not about cloud inside
- them, for which the scene's own figure is the only number on offer and it
- covers a 110 km granule, not the area drawn. The distinction is in the UI
- copy; keep it.
-6. **`CLP`/`CLM` are not read.** On Copernicus Data Space they were zeros for
- some acquisitions, a thick cloud included. If they become reliable they would
- help thin cloud edges, but over desert they also flagged dark fields.
-7. **Calibration is visual, not a benchmark.** The scenes above were reviewed by
- eye in true colour and SWIR, with no AIS or fire perimeter as ground truth.
- Small boats and whitecaps stay hard to part at the Small size, and seasonal
- urban shadows read as construction between February and September.
-8. **A size band drops what it finds, silently.** A candidate outside
- `min_area`/`max_area` is found and then filtered, so a mark between two bands
- reads as "nothing found". The bands are now written under the buttons and
- **All** sets neither bound; what is still missing is a count of what the band
- dropped, which would turn "nothing" into "three, all larger than Small".
-9. **Thin veils the classification misses still highlight.** A haze that neither
- Sen2Cor nor its unsure class calls cloud leaves change around it. The
- published multitemporal test (MAJA: blue reflectance rising against the other
- date) was tried and dropped: on the Amazon pair it grew the mask from 33% to
- 48% of the scene for no drop in what was highlighted, and it would cost a
- band and split the two modes' masks apart.
-10. **A cloud smaller than 5 ha in a zoomed-in view is not masked.** The floor is
- ground area, so a small cumulus crossing a close view is ignored the same way
- a white roof is. Detect has the same floor on a fixed grid, where it is the
- right call; here the view can be anything.
-
-## Verification at handover (Detect)
-
-- Backend: `2813 passed` (`pytest -q tests/ -p no:randomly`, 17 min).
- One caveat: under `pytest-randomly`'s default ordering a single unrelated test,
- `test_updates.py::test_the_extension_version_moves_only_when_the_extension_does`,
- failed once. It passes standalone, in its own file group, and in deterministic
- order. Nothing in this work touches `extension/` or `extinstall`. Worth finding
- the polluting test, separately.
-- Frontend: `262 files, 5036 tests`, no unhandled errors.
-- Browser: `e2e/compare.spec.js`, 8 passed on Chromium and Firefox.
-- `ruff check src/ tests/`, `mypy` on the changed modules, `svelte-check`: clean.
-- `npm run build`: clean, with the existing MapLibre chunk-size warning.
-
-No commit, PR, tag or wheel has been produced for this work.
diff --git a/docs/IMAGERY_PROVIDERS.md b/docs/IMAGERY_PROVIDERS.md
index 946c9ca..028fa12 100644
--- a/docs/IMAGERY_PROVIDERS.md
+++ b/docs/IMAGERY_PROVIDERS.md
@@ -466,6 +466,40 @@ Checked 2026-09-13.
| Night lights | NASA GIBS WMTS, `VIIRS_NOAA20_DayNightBand_At_Sensor_Radiance` (from 2024-03-25), `VIIRS_SNPP_…` (from 2020-11-18, with gaps), `VIIRS_Black_Marble` 2016 | public domain | Level 8 (750 m); opaque, drawn lowest at 85% |
| Active fires | NASA FIRMS, keyed, through the app | see above | |
+## GeoConfirmed is a query, not a feed
+
+An added layer (`engine/geoconfirmed.py`), not an overlay: the backend reads it
+and the case keeps the copy. GeoConfirmed's public read-only API needs no key,
+calls itself free to use, and asks for a User-Agent that names the integration
+and for its cache headers to be respected. It states no licence, so every
+layer is credited to geoconfirmed.org on the map and on each card. Checked
+2026-09-19.
+
+| Call | When | What it gives |
+|---|---|---|
+| `GET /api/Conflict` | the GeoConfirmed dialog opens | the public conflicts; the export is addressed by `shortName` |
+| `GET /api/Conflict/{shortName}` | add, Refresh, first switch-on of a session | factions and their colours; `204` for a name it does not know |
+| `POST /api/Map/export/{shortName}` | add, Refresh, first switch-on of a session | a KMZ of approved placemarks, filtered by `start`, `end` and GeoJSON `polygons`; both null for the whole history, which skips the switch-on read |
+
+- **The KMZ over the site's own JSON.** `/api/Placemark/{c}/geojson` is 16 MB
+ for Ukraine and holds no descriptions; the export is filtered server-side,
+ and bundles every icon it uses (`api/icons/<colour>/<invert>/template/<n>.png`,
+ 56 px discs), so one request dresses the layer.
+- **What the export leaves out.** No faction field: the icon path's colour is
+ matched against the conflict's factions, and factions sharing a colour (Israel
+ and the US on the Iran map) are one legend row. No date field: the placemark
+ name is `13 SEP 2026`. Placemarks with no name are reference sites (bases,
+ plants) sent whatever the dates asked for: 512 of 530 on the Iran map for
+ six weeks of August and September 2026.
+- **Folders are relative ages** ("B. Last 7 days"), true only on the day of the
+ export, so they are dropped for the factions.
+- **The hotspot is 16,16 px**, the middle of a 32 px icon, on 56 px discs. It is
+ dropped and the disc centred on its point.
+- **Sizes seen.** A month of Ukraine is ~800 placemarks, 83 icons and 330 kB.
+ The whole Ukraine map is 60,000 placemarks and 333 icons, under both
+ `MAX_FEATURES` and `MAX_ICONS`: 6.4 MB on the wire, about 4 s to read, 1.6 s
+ to compose the icons and 38 MB of GeoJSON handed to the browser.
+
## Deliberately not basemaps
Street View and Google Photorealistic 3D Tiles are not basemap providers. They
diff --git a/docs/ONTOLOGY.md b/docs/ONTOLOGY.md
index 1cb8dce..520adbe 100644
--- a/docs/ONTOLOGY.md
+++ b/docs/ONTOLOGY.md
@@ -218,7 +218,8 @@ Three modelling calls the table alone does not show:
`annex` beside `note` and `sheet` rather than `attestation`, because an
attestation folds into the edge carrying its provenance and a layer that nothing
links to would fold into nothing. Its `source` is a path *or* a URL, which is
- what makes a dropped KMZ and a followed My Maps one type instead of two. Its
+ what makes a dropped KMZ, a followed My Maps and a GeoConfirmed query one type
+ instead of three. Its
features never enter the graph: they are what somebody else claims, and the day
one of them becomes a `place` of this case (SPEC §6) the layer is what that
place cites — which is the reason it is an entity at all.
diff --git a/docs/SPEC.md b/docs/SPEC.md
index 8730cd2..46dff3c 100644
--- a/docs/SPEC.md
+++ b/docs/SPEC.md
@@ -171,6 +171,8 @@ 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, roads, railways, power lines, sea marks, GPS traces), NASA FIRMS fires and VIIRS night lights for a chosen day, and filters drawn pins by kind and folder. |
| ✅ **Added map layers** | Opens a KML, KMZ, GeoJSON or GPX file, or follows a public My Maps or map URL refreshed only while enabled, and draws it with its own colours, optionally its own icons composed once at import, a legend that filters and a search that goes to one feature — read, cited and never adopted into the case. |
+| ✅ **Dates on a layer** | Narrows a dated added layer (GeoConfirmed, KML timestamps, GPX waypoints) to a period dragged on a strip of its events over time or picked on a calendar, kept with the legend. |
+| ✅ **GeoConfirmed layer** | Adds one GeoConfirmed conflict over a window of days or dates or its whole history, optionally only the view, in GeoConfirmed's own icons, grouped by faction with each event's sources and geolocation one click away. |
| ✅ **Media on the map** | Draws the case's located photos and videos where a relation, a GPS reading or a proof puts them, opens the Map panel, the home map and the extension on them, and plays the stack in the panel beside the imagery. |
| ✅ **Imagery Wayback** | Browses every Esri World Imagery release, narrowed to the ones that changed the point, and dates the pixels apart from the release. |
| ✅ **Satellite Compare** | Aligns and annotates two dated views, assists matched-product change reading, saves editable sessions and files or exports attributed PNG/GIF outputs. |
@@ -184,6 +186,12 @@ proof for publication.
| ✅ **Site hand-offs** | Fills the X or Bluesky composer with a prepared thread and uploads a case picture straight into Lens, Yandex, Bing or TinEye. |
| ✅ **Home & Guide** | Opens on a case dashboard or a front door when no case is open, and `?` opens the Guide on the current tab. |
| ✅ **Case to-do lists** | Named lists on Home with editable tasks, checkboxes, progress counts and case-bundle persistence. |
+| ✅ **Compare from the ground** | Right-clicking a point opens Compare on the last two Esri Wayback pictures of it, or on its last two Copernicus passes. |
+| ✅ **Marks that number and hide** | Stamps numbered markers counting a series per colour, and blur boxes that redraw the picture under them, on a proof's panels and on a comparison's ground alike. |
+| ✅ **A date in one field** | Reads a day, a month, a year, a time or a range from one line of text, or builds one from a calendar with its marks of doubt, and says what it understood. |
+| ✅ **Words that hold still** | One name for a Claim on every surface, a tooltip on every icon, a stated reason on a layer that cannot be switched on, the recent work first on Home, and Coords & Sky opening on the point the map is on. |
+| ✅ **A picture sent to Reverse Search** | Opens Reverse Search on a Media Library file, from a row's Open in… menu, or on an Inspect frame as it is cropped, saved or not. |
+| ✅ **A claim from where you are** | Files a claim from Details, a Board row or a Graph node with the entity already seated, asking a count and a condition where its family calls for them and writing the sentence from the fields. |
---
@@ -203,7 +211,6 @@ Each version delivers one complete daily workflow. Firm ideas move here from
| **Image Compare** | Overlay two images with opacity, swipe and pixel diff. Assist satellite-to-screen alignment without presenting a verdict. |
| **Georeferenced overlay** | Pins an image to the ground by three or four matching points: a commercial satellite shot from a post, a drone frame, an old plan. It draws under the map's own marks with an opacity slider, reprojects as the map pans, and is saved in the case with its control points so the fit can be checked. |
| **Adopt a feature** | Turns a feature of an added layer into a `place` of the case, carrying the layer and the feature it came from as provenance. |
-| **GeoConfirmed layer** | Queries GeoConfirmed for a chosen conflict, date or viewport only when enabled, opens each event's original sources and lets selected events enter the case. |
| **Source directory** | Keeps the accounts, channels and pages worth following for this case, searchable by platform, area and topic, with notes and source reliability; monitoring remains a later opt-in workflow. |
| **Metadata follow-up** | Explains which common image/video fields were stripped and proposes events from capture times. |
| **Edit Provenance** | Reads a rendered video's own edit history: which source clips it was cut from, in what order, and the GPS, dates and cameras those clips still carry. |
@@ -217,7 +224,7 @@ Each version delivers one complete daily workflow. Firm ideas move here from
| **Audio Transcript** | Transcribe and translate speech offline; flag acoustic context such as bells, adhan, aircraft or language. |
| **Ground Imagery** | Ground-level photos: Panoramax/Mapillary/KartaView key-less first; Street View easy link, optional keyed in-app view. |
| **Panorama** | Stitch a video window / frame set. Auto-stitch already in Inspect; still to do: sample a video window directly, seam blending. |
-| **Proof annotation** | Grow the Geo Proof toolbox: dashed strokes, numbered markers, a redaction/blur box; a document-level free layer so shapes cross panels and reach the margins; callout / zoom insets. |
+| **Proof annotation** | Grow the Geo Proof toolbox: dashed strokes; a document-level free layer so shapes cross panels and reach the margins; callout / zoom insets. |
| **Detached tool windows** | The rule the map already follows, applied to the rest: a read-and-work surface (Board, Graph, Timeline) opens as many tabs as wanted and the tab it left stays live; a document editor opens one window per document and is greyed out where it was. Cross-tool handoffs route to wherever the tool now lives. |
| **Command palette** | Ctrl+K reaches a tool, a case or an artifact. |
@@ -429,10 +436,19 @@ stops making sense.
unofficial key-less endpoints of keyed services (the `mt1.google.com` case), and
the distinction drawn is that this is the sharing mechanism the map's own
creator switched on, not a way around a quota. It is fetched only when the
- analyst subscribes, presses Refresh, or opens a case holding an enabled layer
- that asked to be re-read; a shape it stops answering in fails with a sentence
- rather than drawing nothing. The map's search bar answers from
- a bundled gazetteer and never reaches out on a keystroke; its geocoder layer
+ analyst subscribes, presses Refresh, or switches the layer on for the first
+ time in a session, when it asked to be re-read then. Every added layer starts
+ off when the app or the page opens again, so a layer heavy enough to take the
+ tab down does not take it down again on reload; a shape it stops answering in
+ fails with a sentence
+ rather than drawing nothing. A GeoConfirmed layer rides on those same three
+ acts, plus one: its dialog reads the conflict list when the analyst opens it.
+ Each read is GeoConfirmed's documented, key-less public API, through the
+ backend and under a User-Agent naming the app, as it asks integrations to do;
+ its `robots.txt` disallows `/api/` for crawlers, which a read the analyst asked
+ for is not. The icons arrive inside the export, so they cost no request. The
+ map's search bar answers from a bundled gazetteer and never reaches out on a
+ keystroke; its geocoder layer
waits for a pause, and a request the one-per-second pace cannot take is dropped
rather than queued. Two things reach out on mount and no
others. The startup update check: opt-out, and read-only against GitHub's
diff --git a/docs/UI.md b/docs/UI.md
index 1890876..8ab4a3b 100644
--- a/docs/UI.md
+++ b/docs/UI.md
@@ -56,16 +56,19 @@ before; **Guide** is for somebody who has not.
lists before saving again.
- **With a case open, the page is a reading, laid out as a dashboard.** The case name
- and when it was last touched, then a two-column grid: *what is waiting* and the
- recent work on the left, the case's points and the case by family on the right. It
+ and when it was last touched, then a two-column grid: the recent work and the to-do
+ lists on the left, the case's points, *what is waiting* and the case by family on the
+ right. **What was just filed comes first**, because that is what somebody coming back
+ reaches for; the counts under it are upkeep, read second. It
runs to 1180px rather than a 760px reading column, because this page is scanned
rather than read and four counts hanging in a ribbon on a wide screen is the emptiest
an app can look. Below ~980px the grid stacks in that same order.
- **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, because a number is read at a glance
- or it is not read. Pressing one hands the **question** to the surface that answers it,
+ count. 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.
- **A count of nothing stops being a control.** It is dimmed and says zero rather than
@@ -321,7 +324,7 @@ a subject before it is a set of statements — a conflict followed over months h
single root to expand from. Expansion is the drill-down.
- **Lenses** are the readings, and each one chooses both which verbs are drawn and
- which nodes: **Everything · Subjects · Ground · Statements** read the case, and **My
+ which nodes: **Everything · Subjects · Ground · Claims** read the case, and **My
work** reads the filing — what you wrote, what it was made from, and what it points
at. They are resolved from the verb registry and the type roles, never listed here,
so a relation or a type added to the engine joins its lens with no edit.
@@ -945,6 +948,23 @@ 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
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
@@ -1056,7 +1076,7 @@ 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 Statements can create Claims; Media-only and Case activity
+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,
@@ -1068,7 +1088,7 @@ It shows the readable and raw date, precision, timezone, authority, role, status
confidence, reasoning and named subjects, places and evidence. 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 assessment. It changes no selection, so a pair being measured survives it, and the
+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
date; saving creates a sourced Claim about the media and does not rewrite its sidecar.
@@ -1176,6 +1196,21 @@ The row action for an image, a video or an audio file opens it; for anything the
app cannot display it opens the folder the file sits in, so the original is opened
in whatever program owns it rather than copied into Downloads.
+**Open in…** is one button per picture or video, and the tools it can go on to
+sit behind it: Inspect, Reverse Search, and Geo Proof for a picture. Side by side
+they made the widest row seven buttons and a small card more buttons than card, so
+only what acts on the file itself stays out — the map pin, Details, opening the
+file, Delete. The menu is placed against the window rather than inside the row,
+because a card clips what overflows it and the last row of a scrolled list would
+cut the menu off.
+
+**Reverse Search opens on the picture it was sent.** From a Media Library row it
+is the case file; from Inspect's Frame tab it is the frame as it reads there —
+turned, adjusted and cropped — rendered by the tray's own route and filed nowhere,
+and the tool says so under the preview. The crop is the point: an engine matches a
+subject better than the picture it sits in. The handoff is spent once, on the tab
+it was meant for, and a case change drops it with every other handoff.
+
Every media row and card shows the file's human-readable stem, without its
extension and without a second title line. Editing that name in Details renames
the file; the backend returns the portable stem after replacing forbidden
@@ -1194,11 +1229,14 @@ cards are as wide as the maps under them, so the split between A and B is one
line down the tool. Both Layers buttons open the same A/B sheet, including each
side's FIRMS period, VIIRS night and saved case work.
-The mode dock holds two kinds of choice, separated by a rule. Left of it, how the
-pair is *read*: side by side, through a swipe, with B faded over A, or as
-alternating whole frames. Blink has three speeds and can pause on either side.
-Right of it, what gets *computed* over the pair: **Difference** and **Detect**.
-Keys 1–6 switch modes; Space pauses blink. Dragging, zooming or rotating either
+The mode dock holds two kinds of choice, in two named groups. **View**: side by
+side, through a swipe, with B faded over A, or as alternating whole frames. Blink
+has three speeds and can pause on either side. **Analysis**: **Difference** and
+**Detect**, each marked when it cannot run yet — Difference when the two sides are
+not a matched pair, Detect when Copernicus credentials are missing — with the
+reason as its tooltip and, for Detect, at the head of its own panel beside a way
+into Settings. Detect still opens, because the areas and runs already saved are
+read there. Keys 1–6 switch modes; Space pauses blink. Dragging, zooming or rotating either
map moves the other in the same frame. Both stop at the lower provider zoom
ceiling. **Swap A and B** exchanges the complete source stacks and annotation
sides. One compass in the bar reads the shared turn, resets it to north and takes
@@ -1350,17 +1388,26 @@ candidate is a pin, and pins show wherever case work shows.
Annotations store longitude/latitude points and stay on their ground through pan,
zoom and rotation. Notes, arrows, boxes, ellipses, lines, freehand strokes, distance
-measures and polygons can belong to A, B or both. Polygon drawing ends with a
-double-click or Enter; Escape cancels. Select a mark to move it or edit its style,
+measures, polygons, **numbered markers and symbols** can belong to A, B or both.
+The last two are the Proof Maker's stamps, put down on the ground with one press
+and keeping the tool in hand: a marker counts a series per colour and starts back
+at 1 for the next one, and the symbol button opens the same grid of glyphs. Both
+are sized by their own number rather than by a line width, and a symbol drawn in
+outline takes a second control for how heavy that line is. Polygon drawing ends
+with a double-click or Enter; Escape cancels. Select a mark to move it or edit its style,
double-click a note to edit its text, and use Undo/Redo for annotation changes. A
selected mark shows its corner handles, so its geometry is corrected where it was
drawn rather than deleted and redrawn; a note is dragged whole and has none.
Every mark carries a wide invisible band along its outline, because a four-pixel
-arrow is a target nobody hits twice. Clicking the ground beside a mark lets it go;
+arrow is a target nobody hits twice. The wheel still belongs to the map wherever
+the pointer is: the marks are drawn over it rather than in it, and a zoom that
+stopped on whatever had been drawn read as a map that had frozen. Clicking the ground beside a mark lets it go;
dragging the map is a pan and keeps it. The tool rail packs into two columns, like
Proof Maker's, so it stays short enough to fit a laptop window. Its colour, width
and fill panels close on Escape, on their own button, on a press anywhere else,
-and with the button behind them when the selection is dropped.
+and with the button behind them when the selection is dropped. **Pressing the tool
+already in hand puts it down** and gives the cursor back, on this rail and on Proof
+Maker's: the way out of a drawing tool is the button you are already on.
**Right-click the ground** here too, on either map, for the acts Compare can
honour: copy the point in every coordinate format, ask what is there, save a
@@ -1510,7 +1557,7 @@ 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, Reveal file and Remove. See
+ legend that filters, and Refresh and Remove. 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
@@ -1568,8 +1615,8 @@ stack, slightly see-through so the lit street can be named, and the row says
that cloud hides lights too.
**Added map layers** are somebody else's map over this one: a KML, KMZ, GeoJSON
-or GPX file opened from the computer, or a public My Maps or map URL followed.
-Both land in the same section, because the question the row answers is who put
+or GPX file opened from the computer, a public My Maps or map URL followed, or a
+GeoConfirmed conflict. All of them land in the same section, because the question the row answers is who put
this on my map. **A layer is drawn and never adopted** — clicking a feature opens
what the source says about it, its name, its group and its description, with
nothing to confirm and no way from there into the case. A description written as
@@ -1594,6 +1641,21 @@ The row states five things:
groups are its folders, which is how a My Maps is built; a GPX's are waypoints,
tracks and routes; a GeoJSON states none, so the file is one group named after
itself rather than a grouping guessed out of whichever property looked like one.
+- **Its dates, when it has any.** A layer that is on and whose features are
+ dated (GeoConfirmed's events, a KML's TimeStamp or TimeSpan, a GPX waypoint's
+ time) draws its events over time as a strip of bars under the counts: a bar a
+ day for up to three months, a week for up to two years, a month past that.
+ The period is set on the strip itself. Drag across the bars to draw one, drag
+ either handle to move a bound, slide the band between them, or click a bar to
+ keep its day, week or month. Clicking one of the two dates under the strip
+ opens a calendar; the arrow keys move a focused handle by a day, Page Up and
+ Page Down by a week. The map, the counter and each group's count follow while
+ the strip moves, and the period is kept with the legend when it is let go. A
+ bound left on the layer's own first or last day stays open, so a followed
+ layer's new events are not filtered out by a period nobody narrowed. An
+ undated feature is outside any period. A double click on the strip, or the
+ cross beside the dates, lets every date back in, and so does picking a search
+ match outside the period.
- **A search, in the legend's own slot.** Typing puts the matches where the
groups were, and the two are never on screen at once: the legend is the filter
the case keeps, the search is a way of looking that leaves nothing behind. The
@@ -1631,13 +1693,32 @@ 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, Reveal file and Remove** sit under the row. A followed map is re-read
-when it is added, when Refresh is pressed, and when a case opens holding it
-enabled — never on a timer, and never while it is switched off. A read that finds
+**Refresh and Remove** sit under the row. 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
+again, whatever it was before: the switch is not saved with the case, so a layer
+heavy enough to take the tab down does not take it down again on reload. A read that finds
nothing new rewrites nothing, a read that fails leaves the last copy on the map,
and the copy the layer was drawn from is kept in the case, so it draws offline and
travels in the bundle. Removing a layer takes that copy with it, to the trash.
+**GeoConfirmed** is the third way in, behind *Choose a conflict* in the add
+dialog. Its own dialog reads GeoConfirmed's conflict list when it opens, then
+asks for one conflict, a window (7, 30 or 90 days, a year, the whole history, or
+a range of dates), and whether to keep to the area in view. A number of days
+counts back from each read, so a layer of the last 30 days stays that; a range
+stays put. The whole history (60,000 events for Ukraine) is read again only on
+Refresh, never just because it was switched on. The layer
+wears GeoConfirmed's own icons, which come inside its export, with no tick to
+ask for them. Its groups are the conflict's factions, read off each icon's
+colour, and factions GeoConfirmed paints alike share one row. An event is named
+by its date and its first line, and its card keeps the sources and the
+geolocation as links. The reference sites GeoConfirmed sends whatever the dates
+(bases, plants) are grouped as *Undated sites* and start switched off. The row
+says *GeoConfirmed*, or *GeoConfirmed · limited area*, and links to the
+conflict's map on geoconfirmed.org.
+
A date is picked from a calendar the app draws, in the panel rather than over
it. The browser's own opens at its own size, in its own locale, and half
outside a panel docked to this edge — and a field reading `12/09/2026` in an app
@@ -1656,6 +1737,18 @@ body is under the horizon. The anchor is a point and not the map centre, so pann
leaves the path alone. Coords & Sky opens the same mode with its own point, date
and time, and hands over no computed value.
+**Coords & Sky opens on the point the map is on.** The map publishes the point it
+records — its moved pin, else its centre — once it has been moved off the view it
+opened at, and the tab converts that point rather than opening on an empty field.
+A view nobody has moved yet is a setting rather than a finding, so it offers
+nothing. The conversion is local and that is all that happens: naming the place is
+a geocoder call, so the row offers **Name this place** instead of making it.
+
+The tab **follows the map** rather than filling once: the map moving is you looking
+somewhere else, and a tab still reading the point before it answers about the wrong
+ground. Between two moves the field is yours — what you typed, or the point you
+picked out of the case, stands.
+
The saved-work layer answers two questions under its own switch: **what kind**
(all, places, captures, proofs, media) and **which folder**, offered only where the
case has more than one to choose between. They are the Saved panel's own
@@ -1729,7 +1822,10 @@ nothing, and a tile Esri refused is left alone until **Refresh** is pressed, so
panning never hammers a service that is down. A first history takes some seconds
(Esri's metadata service is slow) and the picker offers nothing while it comes,
since every release is not what *Changes here* was asked for; the changes it
-already has stay on the slider while the next tile's are read. A history that
+already has stay on the slider while the next tile's are read. **The chip itself
+says it is waiting**, spinner and all, because both reads run with the picker shut
+and a basemap that answers nothing for ten seconds without saying so reads as a
+broken one. A history that
fails falls back to every release, which is the honest answer to not knowing.
The release rides on the provider id (`esri-wayback~64776`), so tiles are cached
and captures credited under it.
@@ -1738,13 +1834,23 @@ and captures credited under it.
centre: copy it in every coordinate format, the analyst's own first; ask what
is there, answered inside the menu; save a place there; start a distance from
it; anchor the sun and moon on it; open its Wayback history; centre the map
-on it; or open it in another map site. A right-click on a shape that answers
+on it; compare it across time; or open it in another map site. A right-click on a shape that answers
its own (a search-grid cell) stays that shape's. The menu flips away from the
map's edges, walks with the arrow keys, and closes on Escape, a press outside,
or a zoom that moves the ground from under it.
-**Open in…** is the one row that opens a list, and it opens it *beside* the
-menu. A list unfolding inside would make the menu taller, and a menu already
+**Compare here…** asks an archive which two pictures of *this point* are the
+last two, and opens Compare on the pair: Esri Wayback for the two releases that
+changed it, Copernicus for the two most recent passes over it, the second only
+where a key for it is in Settings. The lookup happens before the tab changes, so
+an archive that holds nothing to compare says so on the map instead of costing
+the view. It says it is working for as long as it takes rather than for a guessed
+few seconds: the walk through Esri's releases is slow, and a message that went out
+halfway through left the map looking like nothing was happening. Compare receives it the way it receives a saved comparison — older on
+A, newer on B — unsaved and unnamed, because nothing has been filed.
+
+**Compare here…** and **Open in…** are the two rows that open a list, and they
+open it *beside* the menu. A list unfolding inside would make the menu taller, and a menu already
placed against the frame's edge answers that by moving — which slides the next
row out from under the cursor that was about to press it. So the menu is placed
once, from its measured size, and never again: the submenu flies out to the
@@ -1834,9 +1940,12 @@ marker never reorders anything, or ticking it would take a coordinate out of a
tweet without saying so. A single-point proof is the field it has always been.
**A panel that carries a place adds it**, under the point already on screen rather
than in place of it — two captures of one point stay one point, and the answer the
-panels gave is written down before the new one joins it. **The pin beside a row
+panels gave is written down before the new one joins it. **The pin at the end of a row
opens it on the map**: the basemaps and the reference layers of the Map tool, the
-mark on what the row says, and a click to move it. A row added with `+` opens on
+mark on what the row says, and a click to move it. It sits inside the row's own box,
+behind a hairline and on a panel of its own, which is how every field here offers
+the one act that belongs to it — the map on a coordinate, the eye that says the
+camera stood there, the tab a source opens in, the calendar that builds a date. A row added with `+` opens on
the point above it, which is the only thing that says which ground it belongs on.
The exported picture prints them only when asked (Advanced → Show coordinates):
unnamed points share one line, a named one takes its own, and the plate grows by
@@ -1846,7 +1955,8 @@ all. A saved house style carries both, and one saved before they existed leaves
proof's own answer alone. Posting from the proof carries every point into the tweet, one
per line, while the place, the plus code and the map links stay the conclusion's.
-**Source is a list**, one box per address, with a
+**Source is a list**, one box per address, each with a press that **opens it in a
+new tab** — a source is read far more often than it is typed — and a
`+` to add one — a proof read from a thread rests on the post that published it, the
photos beside it and the clip under those. Editing a traced box turns the whole list
into the proof's own and the traced ones come along, so stating a fourth address never
@@ -1877,7 +1987,20 @@ and reopening the proof shows the edit, not the copy the file was written with.
The **date** is when the material was taken, in the same profile a Claim's *When*
uses — a day, a month, a year, a timestamp or a range, with `~` for approximate and
-`?` for uncertain — edited in the same editor, folded to fit the column.
+`?` 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
+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
+not used anywhere a date is stated: it writes its placeholder in the browser's
+language, which is how an English interface came to ask for `jj/mm/aaaa`.
+
+The calendar beside the field **builds the common answer** for anyone who would
+rather point at a day than spell one. It is the app's own month grid, drawn under
+the field rather than over it, and it opens on the day the field holds — else on the
+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.
**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
@@ -1956,6 +2079,39 @@ symbol is a disc behind the glyph rather than paint inside it — a thin stroke
over aerial imagery needs something to sit on — and how opaque that disc goes
stays your call, because it covers the picture.
+**Numbered markers.** A filled disc carrying a number, stamped like a symbol and
+keeping the tool in hand for the same reason. **Each colour counts its own series**
+and starts back at 1, because colour is what this composer says "same feature" with
+everywhere else. The number is the **first one free** in that series, so deleting #2
+and stamping again fills that hole rather than leaving a proof that counts 1, 3, 4;
+recolouring a marker moves it into the series it joins. The numeral takes a
+contrasting ink off the disc's own colour, since it has to be read over whatever it
+is standing on. It resizes from its corners and turns like a symbol; there is no
+line in it, so the width control stays away.
+
+**Blur boxes.** A box dragged over a face, a plate or a name, which **redraws the
+picture under it through a blur** rather than covering it: what comes out of the
+export is the picture's own pixels made unreadable, at full resolution, not a
+rectangle laid over evidence. It lives in the panel's space like every other mark,
+so it follows the panel's turn, crop and scale. The blur is as strong as the box is
+big, and the filter reads a margin of ground around the box that the box then clips
+away — cut exactly to its own edge, a blur mixes in the transparency past it and
+comes out washed out at the border, which is the one place a redaction has to hold.
+It keys no legend row and **carries no colour at all**: it hides something rather
+than pointing at it, so the swatch stays away while one is drawn or picked. It
+resizes from every handle and turns like a box, and a turned one still reads the
+ground it stands on — the patch is taken upright and turned back level inside the
+box. Over a surface whose picture has not loaded it draws solid, because a blur box
+that shows nothing hides nothing.
+
+**The order they stack in.** The side column's **Elements** list runs front-first,
+the way the Panels list above it does: the row on top is the mark on top of the
+picture. A row is **dragged to reorder it**, and the two arrows bring it forward or
+send it back one place. The order is one order for the whole proof, while what an
+element is drawn *over* is decided inside its own picture — two marks on two panels
+are stacked by the panels — so once more than one picture holds elements each row
+carries the picture it belongs to, and the list says so underneath.
+
**Picking several.** Shift adds an element to the ones already picked, on the
canvas and on the rows in the side column alike. A rectangle dragged over the
page picks everything it touches, and in grid layout it can be dragged across a
diff --git a/frontend/e2e/app.fixture.js b/frontend/e2e/app.fixture.js
index 2b2c5ff..98a4c68 100644
--- a/frontend/e2e/app.fixture.js
+++ b/frontend/e2e/app.fixture.js
@@ -129,7 +129,7 @@ export const graphLenses = {
{ id: 'all', label: 'Everything', hint: 'every connection between the things the case is about', types: ['derived-from', 'depends-on', 'located-at', 'depicts', 'owns', 'part-of', 'member-of', 'posted', 'appears-in', 'sited-at', 'instance-of', 'in-network', 'same-image-as', 'mentions', 'about', 'at', 'cites'], hides: GRAPH_FILED },
{ id: 'subjects', label: 'Subjects', hint: 'who owns, belongs to, posted or appears in what', types: ['owns', 'part-of', 'member-of', 'posted', 'appears-in', 'instance-of', 'in-network', 'same-image-as'], hides: GRAPH_FILED },
{ id: 'ground', label: 'Ground', hint: 'what is tied to a place on the map', types: ['located-at', 'depicts', 'sited-at'], hides: GRAPH_FILED },
- { id: 'claims', label: 'Statements', hint: 'what is asserted, and what it rests on', types: ['about', 'at', 'cites'], hides: GRAPH_FILED },
+ { id: 'claims', label: 'Claims', hint: 'what is asserted, and what it rests on', types: ['about', 'at', 'cites'], hides: GRAPH_FILED },
{ id: 'work', label: 'My work', hint: 'what you wrote, what it was made from, and what it points at', types: ['derived-from', 'depends-on', 'mentions'], hides: [] },
],
orders: [
@@ -401,7 +401,7 @@ export const relationTypes = [
{ type: 'in-network', label: 'is in network', inverse_label: 'contains', hint: 'the address or subnet belongs inside this network', group: '', action: 'relation', from_types: ['ip', 'network'], to_types: ['network'], from_media_kinds: [], to_media_kinds: [], manual: true, ratable: true },
{ type: 'same-image-as', label: 'is the same image as', inverse_label: 'is the same image as', hint: 'enrichment matched the perceptual hashes', group: '', action: 'relation', from_types: ['media'], to_types: ['media'], from_media_kinds: ['image'], to_media_kinds: ['image'], manual: false, ratable: false },
{ type: 'mentions', label: 'mentions', inverse_label: 'is mentioned by', hint: 'the document refers to the entity', group: 'Mentions', action: 'mention', from_types: ['bookmark', 'note', 'post', 'proof'], to_types: ['account', 'aircraft', 'bookmark', 'capture', 'claim', 'domain', 'email', 'inspect-session', 'ip', 'media', 'network', 'note', 'organization', 'person', 'phone', 'place', 'post', 'proof', 'structure', 'vehicle', 'vessel'], from_media_kinds: [], to_media_kinds: [], manual: true, ratable: false },
- { type: 'about', label: 'is about', inverse_label: 'has claim', hint: 'what the statement concerns', group: '', action: 'claim', from_types: ['claim'], to_types: ['account', 'aircraft', 'capture', 'domain', 'email', 'ip', 'media', 'network', 'organization', 'person', 'phone', 'place', 'structure', 'vehicle', 'vessel'], from_media_kinds: [], to_media_kinds: [], manual: true, ratable: false },
+ { type: 'about', label: 'is about', inverse_label: 'has claim', hint: 'what the statement concerns', group: '', action: 'claim', from_types: ['claim'], to_types: ['account', 'aircraft', 'capture', 'domain', 'email', 'equipment-type', 'ip', 'media', 'network', 'organization', 'person', 'phone', 'place', 'structure', 'vehicle', 'vessel'], from_media_kinds: [], to_media_kinds: [], manual: true, ratable: false },
{ type: 'at', label: 'places it at', inverse_label: 'is a claim location', hint: 'where the statement places its subject or event', group: '', action: 'claim', from_types: ['claim'], to_types: ['place'], from_media_kinds: [], to_media_kinds: [], manual: true, ratable: false },
{ type: 'cites', label: 'cites', inverse_label: 'supports claim', hint: 'the evidence the statement relies on', group: '', action: 'claim', from_types: ['claim'], to_types: ['bookmark', 'capture', 'media', 'note', 'proof'], from_media_kinds: [], to_media_kinds: [], manual: true, ratable: false },
{ type: 'contradicts', label: 'contradicts', inverse_label: 'is contradicted by', hint: 'the two statements cannot both hold', group: '', action: 'claim', from_types: ['claim'], to_types: ['claim'], from_media_kinds: [], to_media_kinds: [], manual: true, ratable: false },
@@ -447,6 +447,12 @@ const entityTypes = [
{ key: 'colour', label: 'Colour', kind: 'text', rungs: [], options: [], minimum: null, maximum: null },
],
},
+ {
+ type: 'equipment-type', label: 'Equipment type', family: 'class', icon: 'stack', manual: true, group: '',
+ identity_label: 'Model', identity_placeholder: 'T-72B3',
+ hint: 'a model the case counts with, never one particular object', family_reads: 'a model the case counts with, never one particular object',
+ attrs: [],
+ },
{
type: 'account', label: 'Account', family: 'identifier', icon: 'at', manual: true, group: '',
identity_label: 'Handle', identity_placeholder: '@handle',
@@ -487,9 +493,11 @@ const entityTypes = [
{
type: 'claim', label: 'Claim', family: 'claim', icon: 'note', manual: true, group: 'Reasoning',
hint: 'something you are saying about the case',
- identity_label: 'Statement', identity_placeholder: 'What are you asserting?',
+ identity_label: 'Claim', identity_placeholder: 'What are you asserting?',
family_reads: 'a statement about the rest of the case, carrying its own reasoning',
attrs: [
+ { key: 'count', label: 'How many', hint: 'how many of the one thing this claim counts', kind: 'number', rungs: [], options: [], minimum: 1, maximum: 100000, whole: true, group: 'What it states' },
+ { key: 'condition', label: 'Condition', hint: 'the state at the moment this claim describes', kind: 'choice', rungs: [], options: [{ value: 'intact', label: 'Intact' }, { value: 'damaged', label: 'Damaged' }, { value: 'destroyed', label: 'Destroyed' }, { value: 'abandoned', label: 'Abandoned' }], minimum: null, maximum: null },
{ key: 'confidence', label: 'Confidence', hint: 'how strongly the statement is supported', kind: 'choice', rungs: [], options: [{ value: 'certain', label: 'Certain' }, { value: 'probable', label: 'Probable' }, { value: 'possible', label: 'Possible' }, { value: 'refuted', label: 'Ruled out' }], minimum: null, maximum: null },
{ key: 'method', label: 'How this was worked out', hint: 'the reasoning a reader would need to check this', kind: 'text', rungs: [], options: [], minimum: null, maximum: null },
{ key: 'verbatim', label: 'As the source put it', hint: 'the original wording, quoted rather than paraphrased', kind: 'text', rungs: [], options: [], minimum: null, maximum: null },
diff --git a/frontend/e2e/board.spec.js b/frontend/e2e/board.spec.js
index 6e62403..9cdc6d6 100644
--- a/frontend/e2e/board.spec.js
+++ b/frontend/e2e/board.spec.js
@@ -192,7 +192,7 @@ test('creates a claim, which nothing else in the app can do', async ({ page }) =
await page.getByRole('button', { name: 'New entity' }).click();
await expect(page.getByRole('heading', { name: 'New entity' })).toBeVisible();
await page.getByLabel('Type').selectOption('claim');
- await page.getByLabel('Statement').fill('Where was this shot?');
+ await page.getByLabel('Claim', { exact: true }).fill('Where was this shot?');
// the fields come from the registry, not from a form written per type
await page.getByLabel('How this was worked out').fill('spans counted against imagery');
await page.getByRole('button', { name: 'Create', exact: true }).click();
@@ -205,7 +205,66 @@ test('creates a claim, which nothing else in the app can do', async ({ page }) =
});
// 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('Statement')).toHaveValue('Where was this shot?');
+ await expect(page.getByRole('dialog').getByLabel('Claim', { exact: true })).toHaveValue('Where was this shot?');
+});
+
+test('files a counted observation from a model’s row in one form', async ({ page }) => {
+ const model = {
+ id: 'model-1',
+ type: 'equipment-type',
+ label: 'T-72B3',
+ attrs: {},
+ provenance: { by: 'user', at: '2026-08-04T09:00:00Z', status: 'confirmed' },
+ };
+ const fixture = await openBoard(page, { catalog: [...catalog, model] });
+
+ 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();
+
+ const form = page.getByRole('dialog').locator('.quick-claim');
+ await expect(form.getByLabel('Claim', { exact: true })).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.poll(() => fixture.timelineWrites.length).toBe(1);
+ expect(fixture.timelineWrites[0].body).toMatchObject({
+ statement: '2 × T-72B3 destroyed',
+ count: 2,
+ condition: 'destroyed',
+ about: ['model-1'],
+ at: [],
+ cites: [],
+ });
+ await expect(page.locator('.quick-claim')).toHaveCount(0);
+});
+
+test('files a claim from a place as where it was seen', async ({ page }) => {
+ const fixture = await openBoard(page);
+
+ 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();
+
+ const form = page.getByRole('dialog').locator('.quick-claim');
+ await expect(form.getByLabel('Claim', { exact: true })).toHaveValue('Seen at checkpoint north');
+ // a place is never counted and has no condition of its own to state
+ 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 expect.poll(() => fixture.timelineWrites.length).toBe(1);
+ expect(fixture.timelineWrites[0].body).toMatchObject({
+ statement: 'Convoy seen at checkpoint north',
+ about: [],
+ at: ['place-1'],
+ count: null,
+ condition: null,
+ });
});
test('shows an entity’s typed fields directly in Details', async ({ page }) => {
diff --git a/frontend/e2e/compare.spec.js b/frontend/e2e/compare.spec.js
index da390fd..edbe57c 100644
--- a/frontend/e2e/compare.spec.js
+++ b/frontend/e2e/compare.spec.js
@@ -70,6 +70,57 @@ test('linked maps keep annotations on the ground through pan, modes and save', a
expect(errors).toEqual([]);
});
+test('stamps a numbered marker and a symbol on the ground, and saves both', async ({ page }) => {
+ const { errors, saved } = await openCompare(page);
+ const canvas = page.getByLabel('Annotations on imagery A', { exact: true });
+ const box = await canvas.boundingBox();
+ const at = (dx, dy) => [box.x + box.width / 2 + dx, box.y + box.height / 2 + dy];
+
+ // Two markers: one press each, the tool staying in hand between them.
+ await page.getByTitle('Numbered marker (N)', { exact: true }).click();
+ await page.mouse.click(...at(-40, 0));
+ await page.mouse.click(...at(40, 0));
+ await expect(canvas.locator('.numeral')).toHaveCount(2);
+ expect(await canvas.locator('.numeral').allTextContents()).toEqual(['1', '2']);
+
+ // A colour picked with the stamp still in hand is for the *next* marker, so
+ // its series starts at 1 and the two already down keep the colour they have.
+ await page.getByTitle('Annotation colour', { exact: true }).click();
+ await page.getByLabel('Colour #22c55e').click();
+ await page.mouse.click(...at(0, -40));
+ expect(await canvas.locator('.numeral').allTextContents()).toEqual(['1', '2', '1']);
+
+ // The symbol button opens its grid with the tool; a glyph picked, then stamped.
+ await page.getByTitle('Symbol (S)', { exact: true }).click();
+ await page.locator('.flyout.glyphs .glyph-button').nth(2).click();
+ await page.mouse.click(...at(0, 50));
+ await expect(canvas.locator('.mark')).toHaveCount(4);
+
+ // The symbol button is also its picker: with the stamp in hand it opens the
+ // grid again, and the press with the grid open is the one that puts it down.
+ await page.getByTitle('Symbol (S)', { exact: true }).click();
+ await expect(page.locator('.flyout.glyphs')).toBeVisible();
+ await page.getByTitle('Symbol (S)', { exact: true }).click();
+ await expect(page.getByTitle('Select and move (V)', { exact: true })).toHaveAttribute('aria-pressed', 'true');
+ // …and every other tool puts itself down on the second press
+ await page.getByTitle('Numbered marker (N)', { exact: true }).click();
+ await page.getByTitle('Numbered marker (N)', { exact: true }).click();
+ await expect(page.getByTitle('Select and move (V)', { exact: true })).toHaveAttribute('aria-pressed', 'true');
+
+ await page.getByRole('button', { name: 'Save comparison', exact: true }).click();
+ await page.getByRole('dialog').getByRole('button', { name: 'Save comparison', exact: true }).click();
+ await expect.poll(() => saved.length).toBe(1);
+ const marks = saved[0].spec.annotations;
+ expect(marks.map((mark) => mark.kind)).toEqual(['number', 'number', 'number', 'icon']);
+ expect(marks.map((mark) => mark.number)).toEqual([1, 2, 1, 1]);
+ expect(marks.map((mark) => mark.colour)).toEqual(
+ ['#f6a81a', '#f6a81a', '#22c55e', '#22c55e']
+ );
+ expect(marks[2].glyph).toBeTruthy();
+ expect(marks[0].points).toHaveLength(1);
+ expect(errors).toEqual([]);
+});
+
test('an export frame can be drawn across every overlaid reading mode', async ({ page }) => {
const { errors, saved } = await openCompare(page);
diff --git a/frontend/e2e/proof-layers.spec.js b/frontend/e2e/proof-layers.spec.js
new file mode 100644
index 0000000..8d677c0
--- /dev/null
+++ b/frontend/e2e/proof-layers.spec.js
@@ -0,0 +1,123 @@
+import { test, expect } from '@playwright/test';
+import { installAppFixture, openProofWithPanel } from './app.fixture.js';
+
+/**
+ * The Elements list as an order, driven on the real panel.
+ *
+ * Which end of the list is the front is the whole of what this is about, and it
+ * is only answerable in a running app: the list is turned round against the
+ * array it reads, so an assertion on the source could agree with itself while
+ * the rows on screen said the opposite of what pressing them does.
+ */
+
+const RED = '#ff5252';
+const WHITE = '#ffffff';
+const BLUE = '#40c4ff';
+
+/** Draw one box at an offset, in a colour picked from the palette. */
+async function box(page, box0, dx, color) {
+ await page.getByTitle('Box (r)').click();
+ if (color) {
+ await page.getByTitle('Annotation colour').click();
+ await page.getByLabel(`color ${color}`).click();
+ }
+ const cx = box0.x + box0.width / 2 + dx;
+ const cy = box0.y + box0.height / 2;
+ await page.mouse.move(cx - 30, cy - 20);
+ await page.mouse.down();
+ await page.mouse.move(cx + 10, cy + 20, { steps: 6 });
+ await page.mouse.up();
+}
+
+const colours = (page) => page.evaluate(() =>
+ [...document.querySelectorAll('.shape-row .chip')].map((chip) => getComputedStyle(chip).backgroundColor));
+
+/** The middle of a row's label, which is the part of it that starts a drag.
+ * Scrolled into view first: the mouse is driven in viewport coordinates, and
+ * the side column is taller than the window. */
+async function labelAt(page, seat) {
+ const label = page.locator('.shape-row .el-label').nth(seat);
+ await label.scrollIntoViewIfNeeded();
+ const at = await label.boundingBox();
+ return { x: at.x + at.width / 2, y: at.y + at.height / 2 };
+}
+
+test('the list runs front-first, and its arrows say which way that is', async ({ page }) => {
+ const fixture = await installAppFixture(page);
+ await openProofWithPanel(page);
+ const canvas = await page.locator('.konva canvas').first().boundingBox();
+
+ await box(page, canvas, -90, null); // red, drawn first: the one at the back
+ await box(page, canvas, -30, WHITE);
+ await box(page, canvas, 30, BLUE); // drawn last: the one in front
+
+ await expect(page.locator('.shape-row')).toHaveCount(3);
+ // The row on top is the mark on top of the picture, the way the Panels list
+ // above it reads and the way every layer list anywhere reads.
+ expect(await colours(page)).toEqual([
+ 'rgb(64, 196, 255)', 'rgb(255, 255, 255)', 'rgb(255, 82, 82)',
+ ]);
+ expect(await page.locator('.shape-row .el-label').first().textContent()).toContain('#1');
+
+ await page.getByRole('button', { name: 'Save proof', exact: true }).click();
+ await expect.poll(() => fixture.proofSaves.length).toBe(1);
+ // …while the spec keeps the order it always had: last drawn, drawn last
+ expect(fixture.proofSaves[0].spec.shapes.map((s) => s.color)).toEqual([RED, WHITE, BLUE]);
+
+ // The bottom row is the one at the back, and bringing it forward moves it up
+ const back = page.locator('.shape-row').last();
+ await back.getByTitle(/^Bring forward/).click();
+ expect(await colours(page)).toEqual([
+ 'rgb(64, 196, 255)', 'rgb(255, 82, 82)', 'rgb(255, 255, 255)',
+ ]);
+
+ await page.getByRole('button', { name: 'Save proof', exact: true }).click();
+ await expect.poll(() => fixture.proofSaves.length).toBe(2);
+ expect(fixture.proofSaves[1].spec.shapes.map((s) => s.color)).toEqual([WHITE, RED, BLUE]);
+ fixture.expectNoUnexpectedRequests();
+});
+
+test('a row dragged to the top puts its element in front of the rest', async ({ page }) => {
+ const fixture = await installAppFixture(page);
+ await openProofWithPanel(page);
+ const canvas = await page.locator('.konva canvas').first().boundingBox();
+
+ await box(page, canvas, -90, null);
+ await box(page, canvas, -30, WHITE);
+ await box(page, canvas, 30, BLUE);
+ await expect(page.locator('.shape-row')).toHaveCount(3);
+
+ const from = await labelAt(page, 2); // the red box, at the back
+ const to = await labelAt(page, 0);
+ await page.mouse.move(from.x, from.y);
+ await page.mouse.down();
+ await page.mouse.move(from.x, from.y - 8, { steps: 3 }); // past the threshold
+ await page.mouse.move(to.x, to.y, { steps: 8 });
+ await page.mouse.up();
+
+ expect(await colours(page)).toEqual([
+ 'rgb(255, 82, 82)', 'rgb(64, 196, 255)', 'rgb(255, 255, 255)',
+ ]);
+
+ await page.getByRole('button', { name: 'Save proof', exact: true }).click();
+ await expect.poll(() => fixture.proofSaves.length).toBe(1);
+ expect(fixture.proofSaves[0].spec.shapes.map((s) => s.color)).toEqual([WHITE, BLUE, RED]);
+ fixture.expectNoUnexpectedRequests();
+});
+
+test('a press that never moved picks the element instead of reordering it', async ({ page }) => {
+ const fixture = await installAppFixture(page);
+ await openProofWithPanel(page);
+ const canvas = await page.locator('.konva canvas').first().boundingBox();
+
+ await box(page, canvas, -60, null);
+ await box(page, canvas, 20, WHITE);
+ await expect(page.locator('.shape-row')).toHaveCount(2);
+
+ const at = await labelAt(page, 1);
+ await page.mouse.click(at.x, at.y);
+
+ await expect(page.locator('.shape-row.selected')).toHaveCount(1);
+ expect(await colours(page)).toEqual(['rgb(255, 255, 255)', 'rgb(255, 82, 82)']);
+ fixture.expectNoUnexpectedRequests();
+});
diff --git a/frontend/e2e/proof-marks.spec.js b/frontend/e2e/proof-marks.spec.js
new file mode 100644
index 0000000..d319f75
--- /dev/null
+++ b/frontend/e2e/proof-marks.spec.js
@@ -0,0 +1,195 @@
+import { test, expect } from '@playwright/test';
+import { installAppFixture, openProofWithPanel } from './app.fixture.js';
+
+/**
+ * The two marks that are neither a line nor a word, driven on the real canvas.
+ *
+ * Both used to be handed to the code that moves a polyline, where reading the
+ * points they have none of threw inside the drop handler: the move was never
+ * written down, and the mark sprang back to where it had been picked up on the
+ * next redraw. Neither was given transformer handles either, so neither could be
+ * resized or turned. None of that is visible in the source — it is Konva
+ * answering a gesture — so it is held here.
+ */
+
+/** Where the stage put the one node the transformer holds. */
+const pickedAt = (page) => page.evaluate(() => {
+ const tr = window.Konva.stages[0].find('Transformer')[0];
+ return tr.nodes()[0]?.getAbsolutePosition() ?? null;
+});
+
+/** The handles on offer, the turn knob, and the frame in the picked node's own
+ * pixels — a panel is drawn at its own scale inside a stage that has one too. */
+const handles = (page) => page.evaluate(() => {
+ const tr = window.Konva.stages[0].find('Transformer')[0];
+ const scale = tr.nodes()[0]?.getAbsoluteScale() ?? { x: 1, y: 1 };
+ return {
+ anchors: tr.enabledAnchors().length,
+ rotates: tr.rotateEnabled(),
+ width: tr.width() / scale.x,
+ height: tr.height() / scale.y,
+ };
+});
+
+const settle = (page) => page.evaluate(() => new Promise((resolve) => {
+ requestAnimationFrame(() => requestAnimationFrame(resolve));
+}));
+
+test('a numbered marker stays where it is dropped, and resizes and turns', async ({ page }) => {
+ const fixture = await installAppFixture(page);
+ await openProofWithPanel(page);
+
+ const canvas = page.locator('.konva canvas').first();
+ const box = await canvas.boundingBox();
+ const cx = box.x + box.width / 2;
+ const cy = box.y + box.height / 2;
+
+ await page.getByTitle('Numbered marker (n)').click();
+ await page.mouse.click(cx - 50, cy);
+ await page.mouse.click(cx + 50, cy); // the stamp keeps the tool in hand
+ await expect(page.locator('.shape-row')).toHaveCount(2);
+
+ // The list runs front-first, so the marker stamped first is its last row.
+ await page.locator('.shape-row').last().click(); // takes the hand back to Select
+ await page.getByRole('button', { name: 'Save proof', exact: true }).click();
+ await expect.poll(() => fixture.proofSaves.length).toBe(1);
+ const before = fixture.proofSaves[0].spec.shapes;
+ expect(before.map((s) => [s.kind, s.n])).toEqual([['number', 1], ['number', 2]]);
+
+ // A marker is a disc: corners only, with the ratio kept, and a turn knob.
+ await settle(page);
+ expect(await handles(page)).toMatchObject({ anchors: 4, rotates: true });
+
+ const at = await pickedAt(page);
+ await page.mouse.move(box.x + at.x, box.y + at.y);
+ await page.mouse.down();
+ await page.mouse.move(box.x + at.x + 70, box.y + at.y + 45, { steps: 8 });
+ await page.mouse.up();
+
+ await page.getByRole('button', { name: 'Save proof', exact: true }).click();
+ await expect.poll(() => fixture.proofSaves.length).toBe(2);
+ const moved = fixture.proofSaves[1].spec.shapes.find((s) => s.n === 1);
+ expect(moved.x).toBeGreaterThan(before[0].x + 20);
+ expect(moved.y).toBeGreaterThan(before[0].y + 10);
+
+ // and the corner grows it rather than stretching it
+ await settle(page);
+ const corner = await page.evaluate(() => {
+ const tr = window.Konva.stages[0].find('Transformer')[0];
+ return { x: tr.x() + tr.width(), y: tr.y() + tr.height() };
+ });
+ await page.mouse.move(box.x + corner.x, box.y + corner.y);
+ await page.mouse.down();
+ await page.mouse.move(box.x + corner.x + 40, box.y + corner.y + 40, { steps: 8 });
+ await page.mouse.up();
+
+ await page.getByRole('button', { name: 'Save proof', exact: true }).click();
+ await expect.poll(() => fixture.proofSaves.length).toBe(3);
+ const grown = fixture.proofSaves[2].spec.shapes.find((s) => s.n === 1);
+ expect(grown.size).toBeGreaterThan(moved.size);
+ fixture.expectNoUnexpectedRequests();
+});
+
+test('each colour numbers its own series from 1', async ({ page }) => {
+ const fixture = await installAppFixture(page);
+ await openProofWithPanel(page);
+
+ const canvas = page.locator('.konva canvas').first();
+ const box = await canvas.boundingBox();
+ const cx = box.x + box.width / 2;
+ const cy = box.y + box.height / 2;
+
+ await page.getByTitle('Numbered marker (n)').click();
+ await page.mouse.click(cx - 60, cy);
+ await page.mouse.click(cx - 20, cy);
+
+ // A second colour is a second feature, so its count starts over
+ await page.getByTitle('Annotation colour').click();
+ await page.getByLabel('color #40c4ff').click();
+ await page.mouse.click(cx + 20, cy);
+ await expect(page.locator('.shape-row')).toHaveCount(3);
+
+ await page.getByTitle('Select / move (v)').click();
+ await page.getByRole('button', { name: 'Save proof', exact: true }).click();
+ await expect.poll(() => fixture.proofSaves.length).toBe(1);
+ expect(fixture.proofSaves[0].spec.shapes.map((s) => [s.color, s.n])).toEqual([
+ ['#ff5252', 1],
+ ['#ff5252', 2],
+ ['#40c4ff', 1],
+ ]);
+ fixture.expectNoUnexpectedRequests();
+});
+
+test('a blur box moves, resizes, and is framed on its own edges', async ({ page }) => {
+ const fixture = await installAppFixture(page);
+ await openProofWithPanel(page);
+
+ const canvas = page.locator('.konva canvas').first();
+ const box = await canvas.boundingBox();
+ const cx = box.x + box.width / 2;
+ const cy = box.y + box.height / 2;
+
+ await page.getByTitle('Blur box (b)').click();
+ await page.mouse.move(cx - 60, cy - 40);
+ await page.mouse.down();
+ await page.mouse.move(cx + 10, cy + 20, { steps: 8 });
+ await page.mouse.up();
+ await expect(page.locator('.shape-row')).toHaveCount(1);
+
+ await page.getByRole('button', { name: 'Save proof', exact: true }).click();
+ await expect.poll(() => fixture.proofSaves.length).toBe(1);
+ const drawn = fixture.proofSaves[0].spec.shapes[0];
+ expect(drawn.kind).toBe('blur');
+ // it hides rather than points, so it carries no ink at all
+ expect(drawn.color).toBeUndefined();
+
+ // A box: every handle, and a turn knob. The frame is the box itself — Konva
+ // measures a group by its children and would have added the blur's margin.
+ await settle(page);
+ const frame = await handles(page);
+ expect(frame).toMatchObject({ anchors: 8, rotates: true });
+ expect(frame.width).toBeCloseTo(drawn.w, 0);
+ expect(frame.height).toBeCloseTo(drawn.h, 0);
+
+ const at = await pickedAt(page);
+ await page.mouse.move(box.x + at.x + 20, box.y + at.y + 20);
+ await page.mouse.down();
+ await page.mouse.move(box.x + at.x + 80, box.y + at.y + 60, { steps: 8 });
+ await page.mouse.up();
+
+ await page.getByRole('button', { name: 'Save proof', exact: true }).click();
+ await expect.poll(() => fixture.proofSaves.length).toBe(2);
+ const moved = fixture.proofSaves[1].spec.shapes[0];
+ expect(moved.x).toBeGreaterThan(drawn.x + 20);
+ expect(moved.y).toBeGreaterThan(drawn.y + 10);
+ expect(moved.w).toBeCloseTo(drawn.w, 3); // a move is not a resize
+
+ await settle(page);
+ const corner = await page.evaluate(() => {
+ const tr = window.Konva.stages[0].find('Transformer')[0];
+ return { x: tr.x() + tr.width(), y: tr.y() + tr.height() };
+ });
+ await page.mouse.move(box.x + corner.x, box.y + corner.y);
+ await page.mouse.down();
+ await page.mouse.move(box.x + corner.x + 50, box.y + corner.y + 30, { steps: 8 });
+ await page.mouse.up();
+
+ await page.getByRole('button', { name: 'Save proof', exact: true }).click();
+ await expect.poll(() => fixture.proofSaves.length).toBe(3);
+ const grown = fixture.proofSaves[2].spec.shapes[0];
+ expect(grown.w).toBeGreaterThan(moved.w);
+ expect(grown.h).toBeGreaterThan(moved.h);
+ fixture.expectNoUnexpectedRequests();
+});
+
+test('the colour swatch stays away from a blur box', async ({ page }) => {
+ const fixture = await installAppFixture(page);
+ await openProofWithPanel(page);
+
+ await page.getByTitle('Blur box (b)').click();
+ await expect(page.getByTitle('Annotation colour')).toHaveCount(0);
+
+ await page.getByTitle('Numbered marker (n)').click();
+ await expect(page.getByTitle('Annotation colour')).toHaveCount(1);
+ fixture.expectNoUnexpectedRequests();
+});
diff --git a/frontend/e2e/timeline.spec.js b/frontend/e2e/timeline.spec.js
index e892198..d8431c7 100644
--- a/frontend/e2e/timeline.spec.js
+++ b/frontend/e2e/timeline.spec.js
@@ -285,13 +285,13 @@ test('asks an entry what can be done with it, without choosing it', async ({ pag
await page.getByRole('button', { name: /Witness arrived/ }).click({ button: 'right' });
await menu.getByRole('button', { name: 'Details' }).click();
const details = page.getByRole('dialog', { name: 'Details' });
- await expect(details.getByLabel('Statement')).toHaveValue(timelineItem('claim-1').label);
+ await expect(details.getByLabel('Claim', { exact: true })).toHaveValue(timelineItem('claim-1').label);
await details.getByRole('button', { name: 'Close' }).click();
await page.getByRole('button', { name: /Witness arrived/ }).click({ button: 'right' });
- await menu.getByRole('button', { name: 'Edit assessment' }).click();
- const editor = page.getByRole('dialog', { name: 'Edit time assessment' });
- await expect(editor.getByLabel('Statement')).toHaveValue(timelineItem('claim-1').label);
+ await menu.getByRole('button', { name: 'Edit claim' }).click();
+ const editor = page.getByRole('dialog', { name: 'Edit claim' });
+ await expect(editor.getByLabel('Claim', { exact: true })).toHaveValue(timelineItem('claim-1').label);
await editor.getByRole('button', { name: 'Cancel' }).click();
await page.getByRole('button', { name: /Witness arrived/ }).click({ button: 'right' });
@@ -383,11 +383,11 @@ test('creates a dated statement from a point on the axis', async ({ 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 assessment' });
+ const dialog = page.getByRole('dialog', { name: 'Add claim' });
await expect(dialog).toBeVisible();
await expect(dialog.getByLabel('When')).not.toHaveValue('');
- await dialog.getByLabel('Statement').fill('A second witness reached the checkpoint');
- await dialog.getByRole('button', { name: 'Add assessment' }).click();
+ await dialog.getByLabel('Claim', { exact: true }).fill('A second witness reached the checkpoint');
+ await dialog.getByRole('button', { name: 'Add claim' }).click();
await expect.poll(() => fixture.timelineWrites.length).toBe(1);
expect(fixture.timelineWrites[0]).toMatchObject({
@@ -462,13 +462,13 @@ 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 assessment' });
+ 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('Statement').fill('Traffic peaked around the checkpoint');
- await dialog.getByRole('button', { name: 'Add assessment' }).click();
+ await dialog.getByLabel('Claim', { exact: true }).fill('Traffic peaked around the checkpoint');
+ await dialog.getByRole('button', { name: 'Add claim' }).click();
await expect.poll(() => fixture.timelineWrites.length).toBe(1);
expect(fixture.timelineWrites[0].body.when).toMatch(
@@ -492,12 +492,12 @@ test('creates and resizes an hourly period on a day view', async ({ page }) => {
expect(fixture.timelineWrites[1].body.when).toContain('T');
});
-test('keeps creation on Statements and offers the list 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();
await page.mouse.click(box.x + box.width * .7, box.y + box.height - 8);
- await expect(page.getByRole('dialog', { name: 'Add assessment' })).toHaveCount(0);
+ await expect(page.getByRole('dialog', { name: 'Add claim' })).toHaveCount(0);
await page.getByRole('button', { name: 'List' }).click();
await expect(page.getByRole('region', { name: 'Timeline list' })).toBeVisible();
@@ -512,11 +512,11 @@ test('starts a media correction from the captured date', async ({ page }) => {
await expect(correction).toBeEnabled();
await correction.click();
- const dialog = page.getByRole('dialog', { name: 'Add assessment' });
+ const dialog = page.getByRole('dialog', { name: 'Add claim' });
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 assessment' }).click();
+ await dialog.getByRole('button', { name: 'Add claim' }).click();
await expect.poll(() => fixture.timelineWrites.length).toBe(1);
expect(fixture.timelineWrites[0]).toMatchObject({
@@ -564,7 +564,7 @@ test('moves and resizes the overview window', async ({ page }) => {
await expect.poll(() => axisWindowText(page)).not.toBe(narrowed);
});
-test('moves and shortens a selected assessment on the axis', async ({ page }) => {
+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();
@@ -596,13 +596,13 @@ test('moves and shortens a selected assessment on the axis', async ({ page }) =>
test('validates advanced syntax before saving', async ({ page }) => {
await openTimeline(page);
- await page.getByRole('button', { name: 'Add assessment' }).click();
- const dialog = page.getByRole('dialog', { name: 'Add assessment' });
- await dialog.getByLabel('Statement').fill('A dated observation');
+ 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');
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 assessment' })).toBeDisabled();
+ await expect(dialog.getByRole('button', { name: 'Add claim' })).toBeDisabled();
await dialog.getByText('Syntax guide').click();
await expect(dialog.getByRole('region', { name: 'Supported date syntax' })).toBeVisible();
});
@@ -625,10 +625,10 @@ test('keeps entity history in the same three-tab Details model', async ({ page }
await expect(details.getByRole('tab')).toHaveText(['Info', 'Connections', 'Time']);
await details.getByRole('tab', { name: 'Time' }).click();
- await expect(details.getByRole('heading', { name: 'Statements about this' })).toBeVisible();
+ await expect(details.getByRole('heading', { name: 'Claims about this' })).toBeVisible();
await expect(details.getByText(timelineItem('claim-1').label, { exact: true })).toBeVisible();
await expect(details.getByText(timelineItem('claim-3').label, { exact: true })).toBeVisible();
- await expect(details.getByRole('button', { name: 'Add time assessment' })).toBeVisible();
+ await expect(details.getByRole('button', { name: 'Add dated claim' })).toBeVisible();
fixture.expectNoUnexpectedRequests();
});
@@ -654,7 +654,7 @@ test('opens the row handed over from the Time tab', async ({ page }) => {
await expect(inspector.getByText('2026-06-23T18:42:11Z')).toBeVisible();
});
-test('edits an existing assessment from the Time tab', async ({ page }) => {
+test('edits an existing claim from the Time tab', async ({ page }) => {
const fixture = await installAppFixture(page, {
catalog: [person, source],
timelineItems,
@@ -672,10 +672,10 @@ test('edits an existing assessment from the Time tab', async ({ page }) => {
await details.getByRole('tab', { name: 'Time' }).click();
await details.getByRole('button', { name: `Edit ${timelineItem('claim-1').label}` }).click();
- const editor = details.getByRole('region', { name: 'Edit time assessment' });
- await expect(editor.getByLabel('Statement')).toHaveValue(timelineItem('claim-1').label);
- await editor.getByLabel('Statement').fill('Witness reached the north checkpoint');
- await editor.getByRole('button', { name: 'Update assessment' }).click();
+ const editor = details.getByRole('region', { name: 'Edit claim' });
+ await expect(editor.getByLabel('Claim', { exact: true })).toHaveValue(timelineItem('claim-1').label);
+ await editor.getByLabel('Claim', { exact: true }).fill('Witness reached the north checkpoint');
+ await editor.getByRole('button', { name: 'Update claim' }).click();
await expect.poll(() => fixture.timelineWrites.length).toBe(1);
expect(fixture.timelineWrites[0]).toMatchObject({
@@ -685,7 +685,7 @@ test('edits an existing assessment from the Time tab', async ({ page }) => {
});
});
-test('starts a new assessment from an empty form after editing one', async ({ page }) => {
+test('starts a new claim from an empty form after editing one', async ({ page }) => {
await installAppFixture(page, {
catalog: [person, source],
timelineItems,
@@ -703,16 +703,16 @@ test('starts a new assessment from an empty form after editing one', async ({ pa
await details.getByRole('tab', { name: 'Time' }).click();
await details.getByRole('button', { name: `Edit ${timelineItem('claim-1').label}` }).click();
- const editing = details.getByRole('region', { name: 'Edit time assessment' });
- await expect(editing.getByLabel('Statement')).toHaveValue(timelineItem('claim-1').label);
+ const editing = details.getByRole('region', { name: 'Edit claim' });
+ await expect(editing.getByLabel('Claim', { exact: true })).toHaveValue(timelineItem('claim-1').label);
- await details.getByRole('button', { name: 'Add time assessment' }).click();
- const adding = details.getByRole('region', { name: 'Add time assessment' });
- await expect(adding.getByLabel('Statement')).toHaveValue('');
+ await details.getByRole('button', { name: 'Add dated claim' }).click();
+ const adding = details.getByRole('region', { name: 'Add dated claim' });
+ await expect(adding.getByLabel('Claim', { exact: true })).toHaveValue('');
await expect(adding.getByLabel('When')).toHaveValue('');
});
-test('shows an undated Claim as a missing statement date, not an existing assessment', async ({ page }) => {
+test('shows an undated Claim as a missing claim date, not an existing one', async ({ page }) => {
const fixture = await installAppFixture(page, {
catalog: [undatedClaim],
timelineItems,
@@ -725,15 +725,15 @@ test('shows an undated Claim as a missing statement date, not an existing assess
const details = page.getByRole('dialog', { name: 'Details' });
await details.getByRole('tab', { name: 'Time' }).click();
- await expect(details.getByText('This statement has no date yet.')).toBeVisible();
- await expect(details.getByText('A statement has one date or range.')).toBeVisible();
+ await expect(details.getByText('This claim has no date yet.')).toBeVisible();
+ await expect(details.getByText('A claim has one date or range.')).toBeVisible();
await expect(details.getByText('Undated', { exact: true })).toHaveCount(0);
- await details.getByRole('button', { name: 'Set statement date' }).click();
+ await details.getByRole('button', { name: 'Set claim date' }).click();
- const editor = details.getByRole('region', { name: 'Set statement date' });
- await expect(editor.getByLabel('Statement')).toHaveValue(undatedClaim.label);
+ const editor = details.getByRole('region', { name: 'Set claim date' });
+ await expect(editor.getByLabel('Claim', { exact: true })).toHaveValue(undatedClaim.label);
await editor.getByLabel('When').fill('2026-08-12');
- await editor.getByRole('button', { name: 'Update assessment' }).click();
+ await editor.getByRole('button', { name: 'Update claim' }).click();
await expect.poll(() => fixture.timelineWrites.length).toBe(1);
expect(fixture.timelineWrites[0]).toMatchObject({
diff --git a/frontend/src/app.css b/frontend/src/app.css
index af19487..d97ee20 100644
--- a/frontend/src/app.css
+++ b/frontend/src/app.css
@@ -354,6 +354,65 @@ a:hover {
font-size: var(--fs-xs);
}
+/* A field and the one act that belongs to it, in a single box: the calendar that
+ builds a date, the map that moves a point, the tab a source opens in, the
+ mark that says a point is where the camera stood.
+
+ One box rather than two, split by a hairline: the act is a property of what is
+ typed beside it, and a separate square read as a second field. The darker
+ panel behind the icon is what says it can be pressed at all. */
+.field-with-act {
+ display: flex;
+ align-items: stretch;
+ min-width: 0;
+ border: 1px solid var(--border);
+ border-radius: var(--r-sm);
+ background: var(--bg-2);
+ transition: border-color 0.15s var(--ease), box-shadow 0.15s var(--ease);
+}
+.field-with-act:focus-within {
+ border-color: var(--accent);
+ box-shadow: 0 0 0 2px var(--accent-soft);
+}
+.field-with-act.warn {
+ border-color: color-mix(in srgb, var(--warn, #e8a33d) 55%, transparent);
+}
+/* The input inside gives up its own box to the one around it. */
+.field-with-act > .input {
+ flex: 1;
+ min-width: 0;
+ border: 0;
+ border-radius: 0;
+ background: transparent;
+}
+.field-with-act > .input:focus {
+ box-shadow: none;
+}
+.field-act {
+ display: grid;
+ place-items: center;
+ flex-shrink: 0;
+ width: 26px;
+ border-left: 1px solid var(--border);
+ border-radius: 0 3px 3px 0;
+ background: var(--bg-3);
+ color: var(--text-3);
+ cursor: pointer;
+}
+.field-act:hover:not(:disabled, .disabled) {
+ color: var(--text-1);
+ background: var(--bg-2);
+}
+.field-act.on {
+ color: var(--accent);
+ background: var(--accent-soft);
+}
+.field-act:disabled,
+.field-act.disabled {
+ opacity: 0.4;
+ cursor: default;
+}
+
.input,
.textarea,
.select {
diff --git a/frontend/src/components/ClaimConnections.svelte b/frontend/src/components/ClaimConnections.svelte
index 7c83b85..d25d419 100644
--- a/frontend/src/components/ClaimConnections.svelte
+++ b/frontend/src/components/ClaimConnections.svelte
@@ -35,7 +35,7 @@
type: 'cites',
way: 'in',
label: 'Supports',
- hint: 'statements that rest on this one',
+ hint: 'claims that rest on this one',
},
{ type: 'contradicts', label: 'Contradictions', add: 'Add contradiction' },
];
diff --git a/frontend/src/components/ClaimConnections.test.js b/frontend/src/components/ClaimConnections.test.js
index 562a4ea..8ebd9d2 100644
--- a/frontend/src/components/ClaimConnections.test.js
+++ b/frontend/src/components/ClaimConnections.test.js
@@ -17,7 +17,7 @@ describe('Claim connections', () => {
// this statement resting on that one is a different fact from that one resting on
// this, so the two readings are two groups
expect(editor).toContain("label: 'Supports'");
- expect(editor).toContain("hint: 'statements that rest on this one'");
+ expect(editor).toContain("hint: 'claims that rest on this one'");
expect(editor).toContain('row.direction === group.way');
});
diff --git a/frontend/src/components/DateBuilder.svelte b/frontend/src/components/DateBuilder.svelte
new file mode 100644
index 0000000..29ea4c7
--- /dev/null
+++ b/frontend/src/components/DateBuilder.svelte
@@ -0,0 +1,325 @@
+<script>
+ /**
+ * A date built by pointing at it, for the analyst who would rather not spell
+ * one out.
+ *
+ * It says the same things the field's own text says (`lib/looseDate.js`) and
+ * nothing more: how deep the answer goes — a day, a month, a year — whether it
+ * is one date or a period, and the two marks of doubt the case's profile
+ * carries, `~` for about and `?` for unsure. A timestamp is not offered: an
+ * hour is typed, and a builder of hours would be the three-list form this whole
+ * field replaced.
+ *
+ * Three rows and no more, in that order, because that is the order the answer
+ * is decided in: how precise, which date, and how sure.
+ */
+ import { untrack } from 'svelte';
+ import Icon from './Icon.svelte';
+ import MonthGrid from './MonthGrid.svelte';
+ import { shiftMonth, today, yearMonths, yearPage } from '../lib/calendar.js';
+ import { composeLooseDate, decomposeLooseDate } from '../lib/looseDate.js';
+
+ let {
+ /** The stored value the builder opens on. */
+ value = '',
+ /** Names the group for a reader that cannot see the field above it. */
+ label = 'Date',
+ /** Called with the stored value every time the answer changes. */
+ onbuild,
+ } = $props();
+
+ const DEPTHS = [
+ { id: 'day', label: 'Day' },
+ { id: 'month', label: 'Month' },
+ { id: 'year', label: 'Year' },
+ ];
+
+ /** How deep a `YYYY[-MM[-DD]]` token goes. */
+ const depthOf = (token) => (token?.length >= 10 ? 'day' : token?.length >= 7 ? 'month' : token ? 'year' : '');
+ /** …and that token cut back to a depth, so changing your mind keeps the answer. */
+ const cut = (token, depth) =>
+ token.slice(0, depth === 'day' ? 10 : depth === 'month' ? 7 : 4);
+
+ // What the field held when the builder opened, and only that: it is mounted by
+ // the press that opens it, so from here on the pieces below are the answer and
+ // the field is what they write into.
+ const opened = untrack(() => decomposeLooseDate(value)) ?? {};
+ let start = $state(opened.start ?? '');
+ let end = $state(opened.end ?? '');
+ let approximate = $state(opened.approximate ?? false);
+ let uncertain = $state(opened.uncertain ?? false);
+ let period = $state(Boolean(opened.end));
+ let depth = $state(depthOf(opened.start) || 'day');
+ // Which end the next press fills. A period is picked start-first, which is the
+ // way it is read, and the line under the grid says which one is being waited for.
+ let picking = $state('start');
+ // The year the month and year grids are showing, kept here because neither is
+ // a calendar month and `MonthGrid` owns its own cursor.
+ let year = $state(Number((opened.start || today()).slice(0, 4)));
+
+ const shown = $derived(picking === 'end' ? end || start : start);
+ const months = $derived(yearMonths(year));
+ const years = $derived(yearPage(year));
+
+ /**
+ * Hand the answer up, once there is one to hand up.
+ *
+ * Nothing is written until a date has been picked: the builder opens blank on a
+ * value it cannot draw — a timestamp, say — and a press on *How precise* would
+ * otherwise have written that blank over what was typed.
+ */
+ function send() {
+ if (!start) return;
+ onbuild?.(composeLooseDate({ start, end: period ? end : '', approximate, uncertain }));
+ }
+
+ /** Take a pick. A period picked backwards is a period all the same: the two
+ * ends swap rather than being refused. */
+ function take(token) {
+ if (period && picking === 'end') {
+ const pair = [start, token].sort();
+ [start, end] = pair;
+ } else if (period) {
+ start = token;
+ if (end && end < token) end = '';
+ picking = 'end';
+ } else {
+ start = token;
+ end = '';
+ }
+ year = Number(token.slice(0, 4));
+ send();
+ }
+
+ function setDepth(next) {
+ depth = next;
+ start = cut(start, next);
+ end = cut(end, next);
+ send();
+ }
+
+ function setPeriod(on) {
+ period = on;
+ picking = on && start ? 'end' : 'start';
+ if (!on) end = '';
+ send();
+ }
+
+ /** Take the date back out. The one press that writes an empty field on purpose. */
+ function clear() {
+ start = '';
+ end = '';
+ picking = 'start';
+ onbuild?.('');
+ }
+</script>
+
+<div class="builder" role="group" aria-label="{label} builder">
+ <div class="row">
+ <div class="seg" role="group" aria-label="How precise">
+ {#each DEPTHS as entry (entry.id)}
+ <button
+ type="button"
+ class="chip"
+ class:on={depth === entry.id}
+ aria-pressed={depth === entry.id}
+ onclick={() => setDepth(entry.id)}
+ >{entry.label}</button>
+ {/each}
+ </div>
+ <span class="gap"></span>
+ <button
+ type="button"
+ class="chip mark"
+ class:on={approximate}
+ aria-pressed={approximate}
+ title="About this date"
+ onclick={() => { approximate = !approximate; send(); }}
+ >~</button>
+ <button
+ type="button"
+ class="chip mark"
+ class:on={uncertain}
+ aria-pressed={uncertain}
+ title="Not sure of this date"
+ onclick={() => { uncertain = !uncertain; send(); }}
+ >?</button>
+ </div>
+
+ {#if depth === 'day'}
+ <MonthGrid value={shown} {label} onpick={(iso) => iso && take(iso)} />
+ {:else}
+ <div class="cal">
+ <div class="head">
+ <button
+ type="button"
+ class="step"
+ aria-label={depth === 'month' ? 'Previous year' : 'Earlier years'}
+ title={depth === 'month' ? 'Previous year' : 'Earlier years'}
+ onclick={() => (year -= depth === 'month' ? 1 : 12)}
+ ><Icon name="chevronLeft" size={12} /></button>
+ <span class="title">{depth === 'month' ? year : `${years[0]}–${years[years.length - 1]}`}</span>
+ <button
+ type="button"
+ class="step"
+ aria-label={depth === 'month' ? 'Next year' : 'Later years'}
+ title={depth === 'month' ? 'Next year' : 'Later years'}
+ onclick={() => (year += depth === 'month' ? 1 : 12)}
+ ><Icon name="chevronRight" size={12} /></button>
+ </div>
+ <div class="cells">
+ {#if depth === 'month'}
+ {#each months as entry (entry.iso)}
+ <button
+ type="button"
+ class="cell"
+ class:on={entry.iso === shown}
+ title={entry.iso}
+ onclick={() => take(entry.iso)}
+ >{entry.label}</button>
+ {/each}
+ {:else}
+ {#each years as entry (entry)}
+ <button
+ type="button"
+ class="cell"
+ class:on={entry === shown}
+ title={entry}
+ onclick={() => take(entry)}
+ >{entry}</button>
+ {/each}
+ {/if}
+ </div>
+ </div>
+ {/if}
+
+ <div class="row foot">
+ <button
+ type="button"
+ class="chip"
+ class:on={period}
+ aria-pressed={period}
+ title="From one date to another"
+ onclick={() => setPeriod(!period)}
+ >Period</button>
+ {#if period}
+ <span class="said">
+ {#if picking === 'end'}Pick the end{:else}Pick the start{/if}
+ </span>
+ {/if}
+ <span class="gap"></span>
+ <button type="button" class="chip" disabled={!start} onclick={clear}>Clear</button>
+ </div>
+</div>
+
+<style>
+ /* In flow like the month it holds: the field above is often in a column with
+ an edge close by, and nothing here may be cut by it. */
+ .builder {
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ }
+ .row {
+ display: flex;
+ align-items: center;
+ gap: 3px;
+ }
+ .gap {
+ flex: 1;
+ }
+ .seg {
+ display: flex;
+ gap: 3px;
+ }
+ .chip {
+ padding: 2px 7px;
+ border: 1px solid var(--border);
+ border-radius: var(--r-sm);
+ background: var(--bg-2);
+ color: var(--text-2);
+ font-size: 10px;
+ white-space: nowrap;
+ cursor: pointer;
+ }
+ .chip:hover:not(:disabled) {
+ border-color: var(--border-strong);
+ color: var(--text-1);
+ }
+ .chip.on {
+ border-color: var(--accent);
+ background: var(--accent-soft);
+ color: var(--accent);
+ }
+ .chip:disabled {
+ opacity: 0.4;
+ cursor: default;
+ }
+ .mark {
+ width: 22px;
+ padding: 2px 0;
+ text-align: center;
+ font-weight: 700;
+ }
+ .said {
+ font-size: 10px;
+ color: var(--text-3);
+ }
+ /* The month and year pages are the same box the calendar draws, so the three
+ precisions read as one control rather than three. */
+ .cal {
+ display: flex;
+ flex-direction: column;
+ gap: 3px;
+ padding: 5px;
+ border: 1px solid var(--border);
+ border-radius: var(--r-sm);
+ background: var(--bg-2);
+ }
+ .head {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ }
+ .title {
+ font-size: 10px;
+ font-weight: 600;
+ color: var(--text-1);
+ font-variant-numeric: tabular-nums;
+ }
+ .step {
+ display: grid;
+ place-items: center;
+ width: 18px;
+ height: 18px;
+ border-radius: var(--r-sm);
+ color: var(--text-2);
+ cursor: pointer;
+ }
+ .step:hover {
+ color: var(--text-1);
+ background: var(--bg-3);
+ }
+ .cells {
+ display: grid;
+ grid-template-columns: repeat(4, 1fr);
+ gap: 2px;
+ }
+ .cell {
+ padding: 4px 0;
+ border-radius: var(--r-sm);
+ color: var(--text-2);
+ font-size: 10px;
+ font-variant-numeric: tabular-nums;
+ cursor: pointer;
+ }
+ .cell:hover {
+ background: var(--bg-3);
+ color: var(--text-1);
+ }
+ .cell.on {
+ background: var(--accent-soft);
+ color: var(--accent);
+ box-shadow: inset 0 0 0 1px var(--accent);
+ }
+</style>
diff --git a/frontend/src/components/DateField.render.svelte.test.js b/frontend/src/components/DateField.render.svelte.test.js
new file mode 100644
index 0000000..833b09d
--- /dev/null
+++ b/frontend/src/components/DateField.render.svelte.test.js
@@ -0,0 +1,216 @@
+// @vitest-environment happy-dom
+import { afterEach, describe, expect, it } from 'vitest';
+import { flushSync, mount, unmount } from 'svelte';
+import DateField from './DateField.svelte';
+
+let target;
+let app;
+
+function open(props) {
+ target = document.createElement('div');
+ document.body.append(target);
+ const sent = [];
+ const state = $state({ value: '', ...props });
+ app = mount(DateField, {
+ target,
+ props: {
+ get value() {
+ return state.value;
+ },
+ get day() {
+ return state.day ?? false;
+ },
+ get calendar() {
+ return state.calendar ?? false;
+ },
+ onchange: (next) => {
+ sent.push(next);
+ state.value = next;
+ },
+ },
+ });
+ flushSync();
+ return { sent, state };
+}
+
+const field = () => target.querySelector('input');
+const said = () => target.querySelector('.said')?.textContent.trim() ?? '';
+
+function type(text) {
+ field().value = text;
+ field().dispatchEvent(new Event('input', { bubbles: true }));
+ flushSync();
+}
+
+afterEach(() => {
+ if (app) unmount(app);
+ target?.remove();
+ app = null;
+});
+
+describe('the date field', () => {
+ it('opens on a stored date written day-first', () => {
+ open({ value: '2025-10-24~' });
+ expect(field().value).toBe('~24/10/2025');
+ expect(field().getAttribute('placeholder')).toBe('dd/mm/yyyy');
+ });
+
+ it('hands on what it read, and says it under the field', () => {
+ const { sent } = open();
+ type('24 oct 2025');
+ expect(sent.at(-1)).toBe('2025-10-24');
+ expect(said()).toBe('24 Oct 2025');
+ type('~Oct 2025?');
+ expect(sent.at(-1)).toBe('2025-10%');
+ expect(said()).toBe('Oct 2025 · Approximate · Uncertain');
+ });
+
+ it('shows the kept form once the field is left', () => {
+ open();
+ type('24.10.2025');
+ field().dispatchEvent(new Event('blur'));
+ flushSync();
+ expect(field().value).toBe('24/10/2025');
+ });
+
+ it('passes unreadable text on as typed, so the save refuses it, and says why now', () => {
+ const { sent } = open();
+ type('31/02/2025');
+ expect(sent.at(-1)).toBe('31/02/2025');
+ expect(said()).toBe('That date does not exist.');
+ expect(field().getAttribute('aria-invalid')).toBe('true');
+ });
+
+ it('follows a value cleared from outside', () => {
+ const { state } = open({ value: '2025-10-24' });
+ state.value = '';
+ flushSync();
+ expect(field().value).toBe('');
+ expect(said()).toBe('');
+ });
+
+ it('keeps one plain day when it computes from it, and hands on nothing else', () => {
+ const { sent } = open({ day: true });
+ type('Oct 2025');
+ expect(sent).toEqual([]);
+ expect(said()).toBe('Give one full day, like 24/10/2025.');
+ type('24/10/2025');
+ expect(sent).toEqual(['2025-10-24']);
+ });
+});
+
+describe('the builder beside it', () => {
+ const button = () => target.querySelector('.field-act');
+ const builder = () => target.querySelector('.builder');
+ const day = (iso) => [...target.querySelectorAll('.day')].find((b) => b.title === iso);
+ const cell = (title) => [...target.querySelectorAll('.cell')].find((b) => b.title === title);
+ const chip = (text) =>
+ [...target.querySelectorAll('.chip')].find((b) => b.textContent.trim() === text);
+
+ function press(element) {
+ element.click();
+ flushSync();
+ }
+
+ it('stays away from a field that was not offered one', () => {
+ open({ value: '2025-10-24' });
+ expect(button()).toBe(null);
+ expect(builder()).toBe(null);
+ });
+
+ it('opens on the date the field holds, and writes the day it is pressed on', () => {
+ const { sent } = open({ value: '2025-10-24', calendar: true });
+ press(button());
+
+ expect(builder()).not.toBe(null);
+ expect(target.querySelector('.month').textContent).toBe('Oct 2025');
+ expect(day('2025-10-24').classList.contains('on')).toBe(true);
+
+ press(day('2025-10-09'));
+ expect(sent).toEqual(['2025-10-09']);
+ expect(field().value).toBe('09/10/2025');
+ // it stays open: a date is built in two or three presses, not one
+ expect(builder()).not.toBe(null);
+ });
+
+ it('goes only as deep as the answer does', () => {
+ const { sent } = open({ value: '2025-10-24', calendar: true });
+ press(button());
+
+ press(chip('Month'));
+ expect(sent.at(-1)).toBe('2025-10'); // the day is dropped, the month kept
+ press(cell('2025-03'));
+ expect(sent.at(-1)).toBe('2025-03');
+ expect(field().value).toBe('Mar 2025');
+
+ press(chip('Year'));
+ expect(sent.at(-1)).toBe('2025');
+ press(cell('2023'));
+ expect(sent.at(-1)).toBe('2023');
+ });
+
+ it('carries the two marks of doubt', () => {
+ const { sent } = open({ value: '2025-10-24', calendar: true });
+ press(button());
+
+ press(chip('~'));
+ expect(sent.at(-1)).toBe('2025-10-24~');
+ press(chip('?'));
+ expect(sent.at(-1)).toBe('2025-10-24%'); // both, which the profile writes %
+ press(chip('~'));
+ expect(sent.at(-1)).toBe('2025-10-24?');
+ });
+
+ it('builds a period from two presses, whichever order they come in', () => {
+ const { sent } = open({ value: '2025-10-24', calendar: true });
+ press(button());
+
+ press(chip('Period'));
+ press(day('2025-10-09')); // picked second but earlier: the ends swap
+ expect(sent.at(-1)).toBe('2025-10-09/2025-10-24');
+ expect(field().value).toBe('09/10/2025 to 24/10/2025');
+ });
+
+ it('opens on what a looser answer named, marks and all', () => {
+ open({ value: '2025-03~', calendar: true });
+ press(button());
+
+ // a month answer opens the month page, not a calendar of days
+ expect(target.querySelector('.title').textContent).toBe('2025');
+ expect(cell('2025-03').classList.contains('on')).toBe(true);
+ expect(chip('Month').getAttribute('aria-pressed')).toBe('true');
+ expect(chip('~').getAttribute('aria-pressed')).toBe('true');
+ });
+
+ it('leaves a date it cannot draw alone until a day is actually picked', () => {
+ // a timestamp is typed, not built; the builder opens blank on one, and a
+ // press on the precision chips used to write that blank over it
+ const { sent } = open({ value: '2025-10-24T14:30:00Z', calendar: true });
+ press(button());
+
+ press(chip('Month'));
+ press(chip('~'));
+ expect(sent).toEqual([]);
+ expect(field().value).toBe('24/10/2025 14:30 UTC');
+
+ // …and the first month actually pressed is what replaces it, marks and all
+ press(target.querySelector('.cell'));
+ expect(sent.at(-1)).toMatch(/^\d{4}-\d{2}~$/);
+ });
+
+ it('empties the field only when Clear is the press', () => {
+ const { sent } = open({ value: '2025-10-24', calendar: true });
+ press(button());
+ press(chip('Clear'));
+ expect(sent.at(-1)).toBe('');
+ expect(field().value).toBe('');
+ });
+
+ it('is drawn in the panel rather than over it, like every other month here', () => {
+ open({ calendar: true });
+ press(button());
+
+ expect(getComputedStyle(builder()).position).not.toBe('absolute');
+ expect(getComputedStyle(builder()).position).not.toBe('fixed');
+ });
+});
diff --git a/frontend/src/components/DateField.svelte b/frontend/src/components/DateField.svelte
new file mode 100644
index 0000000..934f92d
--- /dev/null
+++ b/frontend/src/components/DateField.svelte
@@ -0,0 +1,178 @@
+<script>
+ /**
+ * A date typed as one line of text, shown day-first, and stored in the case's
+ * temporal profile (`lib/looseDate.js` does the reading).
+ *
+ * The browser's own date input writes its placeholder in the browser's
+ * language and its value in the browser's order, so an English interface read
+ * `jj/mm/aaaa` on a French machine. This one says `dd/mm/yyyy` everywhere and
+ * says, under the field, what it understood.
+ *
+ * `day` narrows it to one plain day, for a field that computes from a date
+ * (the sky over a point) rather than stating one: a month, a range or a mark
+ * of doubt is refused there rather than guessed at.
+ *
+ * Outside `day`, text it cannot read is still handed on as typed, which is
+ * what the old advanced mode did: the save refuses it with the reason, and
+ * the line under the field has already said it.
+ */
+ import Icon from './Icon.svelte';
+ import DateBuilder from './DateBuilder.svelte';
+ import { formatTemporalValue } from '../lib/timeline.js';
+ import { LOOSE_DATE_HINT, friendlyDate, parseLooseDate } from '../lib/looseDate.js';
+
+ let {
+ id = undefined,
+ /** The stored value: `2025-10-24`, `2025-10~`, `…T14:30:00Z`, `a/b`, or ''. */
+ value = '',
+ day = false,
+ placeholder = 'dd/mm/yyyy',
+ label = 'Date',
+ disabled = false,
+ /** Whether to say, under the field, what it was read as. A reason it
+ * could not be read is said either way. */
+ reading = true,
+ /** Whether a calendar can be opened beside the field, for a date somebody
+ * 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,
+ onchange,
+ } = $props();
+
+ let text = $state('');
+ let sent = $state(null);
+
+ $effect(() => {
+ const incoming = value ?? '';
+ if (incoming !== sent) {
+ text = friendlyDate(incoming);
+ sent = incoming;
+ }
+ });
+
+ function readText(input) {
+ const parsed = parseLooseDate(input);
+ if (!day || parsed.error || !parsed.value) return parsed;
+ return /^\d{4}-\d{2}-\d{2}$/.test(parsed.value)
+ ? parsed
+ : { value: null, error: 'Give one full day, like 24/10/2025.' };
+ }
+
+ const parsed = $derived(readText(text));
+ const said = $derived.by(() => {
+ if (!text.trim()) return '';
+ if (parsed.error) return parsed.error;
+ const format = formatTemporalValue(parsed.value);
+ return [format.label, ...format.qualifiers].join(' · ');
+ });
+
+ function commit(next) {
+ if (next === sent) return;
+ sent = next;
+ onchange?.(next);
+ }
+
+ function input(event) {
+ text = event.currentTarget.value;
+ const read = readText(text);
+ if (read.value !== null) commit(read.value);
+ else if (!day) commit(text.trim());
+ }
+
+ // Once the field is left, a date it understood is shown the way it is kept,
+ // so what stays on screen is what was saved.
+ function settle() {
+ if (parsed.value) text = friendlyDate(parsed.value);
+ }
+
+ // The builder, when the field offers one. It stays open while it is being
+ // used — a date is built in two or three presses, precision then day then
+ // doubt, and a panel that shut after the first would be re-opened for each.
+ let open = $state(false);
+
+ function build(next) {
+ text = friendlyDate(next);
+ commit(next);
+ }
+</script>
+
+<div class="date-field">
+ <div class="line" class:field-with-act={calendar}>
+ <input
+ {id}
+ class="input input-sm mono"
+ type="text"
+ inputmode="text"
+ autocomplete="off"
+ spellcheck="false"
+ aria-label={label}
+ aria-invalid={Boolean(parsed.error)}
+ title={day ? 'One day, as dd/mm/yyyy' : LOOSE_DATE_HINT}
+ {placeholder}
+ {disabled}
+ value={text}
+ oninput={input}
+ onblur={settle}
+ onkeydown={(event) => { if (event.key === 'Enter') settle(); }}
+ />
+ {#if calendar}
+ <button
+ type="button"
+ class="field-act"
+ class:on={open}
+ {disabled}
+ aria-expanded={open}
+ aria-label="Build the date"
+ title="Build the date"
+ onclick={() => (open = !open)}
+ >
+ <Icon name="calendar" size={14} />
+ </button>
+ {/if}
+ </div>
+ {#if calendar && open}
+ <DateBuilder value={parsed.value ?? ''} {label} onbuild={build} />
+ {/if}
+ {#if said && (reading || parsed.error)}
+ <p class="said" class:bad={Boolean(parsed.error)} aria-live="polite">{said}</p>
+ {/if}
+</div>
+
+<style>
+ .date-field {
+ display: grid;
+ gap: 3px;
+ min-width: 0;
+ }
+ .date-field input {
+ width: 100%;
+ min-width: 0;
+ }
+ /* Stretch, not centre: the act at the end is a panel of the field's own box
+ and has to be as tall as it. Centring left it a short tab floating in the
+ middle of the right-hand edge. */
+ .line {
+ display: flex;
+ align-items: stretch;
+ min-width: 0;
+ }
+ .line input {
+ flex: 1;
+ min-width: 0;
+ }
+ /* A field whose text cannot be read says so on the box around it, which with
+ the calendar beside it is the box they share. */
+ .date-field :global(.field-with-act:has(input[aria-invalid='true'])),
+ .date-field input[aria-invalid='true'] {
+ border-color: var(--warn);
+ }
+ .said {
+ margin: 0;
+ font-size: var(--fs-xs);
+ color: var(--text-3);
+ line-height: 1.4;
+ }
+ .said.bad {
+ color: var(--warn);
+ }
+</style>
diff --git a/frontend/src/components/DayPicker.svelte b/frontend/src/components/DayPicker.svelte
index 16baab6..edfa4b6 100644
--- a/frontend/src/components/DayPicker.svelte
+++ b/frontend/src/components/DayPicker.svelte
@@ -2,28 +2,12 @@
/**
* A day, picked from a calendar drawn inside the panel it belongs to.
*
- * `<input type="date">` was the obvious answer and the wrong one here: its
- * calendar is browser chrome, so it opens at the browser's size, in the
- * browser's locale, and *over* the page — which in a panel docked to the
- * right edge of the window means half of it outside the window, and a date
- * reading `12/09/2026` in an app that writes `2026-09-12` everywhere else.
- *
- * So the month is drawn here, in flow: it pushes the rows under it down
- * rather than floating over them, which is the whole of why it cannot be
- * clipped. The arithmetic is `lib/calendar.js`, and the extension's panel
- * draws the same grid from its own copy of it.
+ * The field is the whole control here: the day it holds is all it says, and
+ * pressing it opens the month under it. The grid itself is `MonthGrid.svelte`,
+ * which `DateField` opens from an icon beside a date that can also be typed.
*/
import Icon from './Icon.svelte';
- import {
- WEEKDAYS,
- monthDays,
- monthLabel,
- monthOf,
- monthOutOfRange,
- outOfRange,
- shiftMonth,
- today as todayOf,
- } from '../lib/calendar.js';
+ import MonthGrid from './MonthGrid.svelte';
let {
/** The day being shown, `YYYY-MM-DD`, or '' for none. */
@@ -43,18 +27,6 @@
} = $props();
let open = $state(false);
- let cursor = $state('');
-
- const today = $derived(todayOf());
- const month = $derived(cursor || monthOf(value));
- const cells = $derived(monthDays(month));
- const canGoBack = $derived(!monthOutOfRange(shiftMonth(month, -1), min, max));
- const canGoOn = $derived(!monthOutOfRange(shiftMonth(month, 1), min, max));
-
- function toggle() {
- open = !open;
- if (open) cursor = monthOf(value); // reopened on the day it holds, not where it was left
- }
function pick(iso) {
onpick?.(iso);
@@ -66,71 +38,17 @@
<button
type="button"
class="field"
- class:empty={!value}
+ class:unset={!value}
aria-expanded={open}
aria-label={label}
- onclick={toggle}
+ onclick={() => (open = !open)}
>
<span>{value || placeholder}</span>
<Icon name={open ? 'chevronUp' : 'chevronDown'} size={11} />
</button>
{#if open}
- <div class="cal" role="group" aria-label="{label} calendar">
- <div class="head">
- <button
- type="button"
- class="step"
- disabled={!canGoBack}
- aria-label="Previous month"
- onclick={() => (cursor = shiftMonth(month, -1))}
- >
- <Icon name="chevronLeft" size={12} />
- </button>
- <span class="month">{monthLabel(month)}</span>
- <button
- type="button"
- class="step"
- disabled={!canGoOn}
- aria-label="Next month"
- onclick={() => (cursor = shiftMonth(month, 1))}
- >
- <Icon name="chevronRight" size={12} />
- </button>
- </div>
-
- <div class="week">
- {#each WEEKDAYS as day, i (i)}<span>{day}</span>{/each}
- </div>
-
- <div class="days">
- {#each cells as cell (cell.iso)}
- <button
- type="button"
- class="day"
- class:out={!cell.inMonth}
- class:on={cell.iso === value}
- class:today={cell.iso === today}
- disabled={outOfRange(cell.iso, min, max)}
- aria-current={cell.iso === value ? 'date' : undefined}
- title={cell.iso}
- onclick={() => pick(cell.iso)}
- >{cell.day}</button>
- {/each}
- </div>
-
- <div class="acts">
- <button
- type="button"
- class="act"
- disabled={outOfRange(today, min, max)}
- onclick={() => pick(today)}
- >Today</button>
- {#if clearable}
- <button type="button" class="act" disabled={!value} onclick={() => pick('')}>Clear</button>
- {/if}
- </div>
- </div>
+ <MonthGrid {value} {min} {max} {label} {clearable} onpick={pick} />
{/if}
</div>
@@ -159,110 +77,13 @@
.field:hover {
border-color: var(--border-strong);
}
- .field.empty {
+ /* Not `.empty`: that is the app-wide empty-state block (app.css), which would
+ turn an unset field into a padded column. */
+ .field.unset {
color: var(--text-3);
}
.field[aria-expanded='true'] {
border-color: var(--accent);
color: var(--accent);
}
- /* in flow, never over: the row under it moves down, and nothing can push it
- past an edge it would be cut at */
- .cal {
- display: flex;
- flex-direction: column;
- gap: 3px;
- padding: 5px;
- border: 1px solid var(--border);
- border-radius: var(--r-sm);
- background: var(--bg-2);
- }
- .head {
- display: flex;
- align-items: center;
- justify-content: space-between;
- }
- .month {
- font-size: 10px;
- font-weight: 600;
- color: var(--text-1);
- }
- .step {
- display: grid;
- place-items: center;
- width: 18px;
- height: 18px;
- border-radius: var(--r-sm);
- color: var(--text-2);
- cursor: pointer;
- }
- .step:hover:not(:disabled) {
- color: var(--text-1);
- background: var(--bg-3);
- }
- .step:disabled {
- opacity: 0.3;
- cursor: default;
- }
- .week,
- .days {
- display: grid;
- grid-template-columns: repeat(7, 1fr);
- gap: 1px;
- }
- .week span {
- text-align: center;
- font-size: 9px;
- color: var(--text-3);
- }
- .day {
- padding: 2px 0;
- border-radius: var(--r-sm);
- color: var(--text-2);
- font-size: 10px;
- font-variant-numeric: tabular-nums;
- cursor: pointer;
- }
- .day:hover:not(:disabled) {
- background: var(--bg-3);
- color: var(--text-1);
- }
- .day.out {
- color: var(--text-3);
- opacity: 0.5;
- }
- .day.today {
- box-shadow: inset 0 0 0 1px var(--border-strong);
- }
- .day.on {
- background: var(--accent-soft);
- color: var(--accent);
- box-shadow: inset 0 0 0 1px var(--accent);
- }
- .day:disabled {
- opacity: 0.25;
- cursor: default;
- }
- .acts {
- display: flex;
- justify-content: flex-end;
- gap: 4px;
- }
- .act {
- padding: 2px 7px;
- border: 1px solid var(--border);
- border-radius: var(--r-sm);
- background: var(--bg-2);
- color: var(--text-2);
- font-size: 10px;
- cursor: pointer;
- }
- .act:hover:not(:disabled) {
- border-color: var(--border-strong);
- color: var(--text-1);
- }
- .act:disabled {
- opacity: 0.4;
- cursor: default;
- }
</style>
diff --git a/frontend/src/components/EntityDetails.svelte b/frontend/src/components/EntityDetails.svelte
index a4e6e68..4344625 100644
--- a/frontend/src/components/EntityDetails.svelte
+++ b/frontend/src/components/EntityDetails.svelte
@@ -53,6 +53,8 @@
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';
let {
entityId,
@@ -282,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' | null
+ let connectionComposer = $state(null); // 'relation' | 'mention' | 'claim' | null
let connectionSaving = $state(false);
loadRelationTypes();
loadEntityTypes();
@@ -294,6 +296,8 @@
);
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(', ')}.`
);
@@ -651,12 +655,12 @@
>Info</button>
<button
class="ed-tab" class:on={tab === 'connections'} role="tab" aria-selected={tab === 'connections'}
- title="Relations, statements and lineage"
+ title="Relations, claims and lineage"
onclick={() => (tab = 'connections')}
>Connections</button>
<button
class="ed-tab" class:on={tab === 'time'} role="tab" aria-selected={tab === 'time'}
- title="Dates and time assessments"
+ title="Dates and dated claims"
onclick={() => (tab = 'time')}
>Time</button>
</div>
@@ -858,7 +862,7 @@
{#if tab === 'connections'}
<div class="case-layout">
- {#if canRelate || canMention || hasRelations || lineageCount || placedPoints.length}
+ {#if canRelate || canMention || claimSeatHere || hasRelations || lineageCount || placedPoints.length}
<section class="connections">
<div class="card-head connections-head"><h3>Connections</h3></div>
@@ -984,9 +988,29 @@
onchanged={reloadCase}
/>
</div>
- {:else if claimRelations.length}
+ {:else if claimSeatHere || claimRelations.length}
<div class="connection-group">
- <div class="connection-head"><h4>Claims</h4></div>
+ <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}
+ </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
@@ -1005,7 +1029,7 @@
{/if}
<p class="stated-notes">
{stated.statements}
- {stated.statements === 1 ? 'statement' : 'statements'}
+ {stated.statements === 1 ? 'claim' : 'claims'}
{#if sure}<span>· {sure}</span>{/if}
{#each notes as note (note)}<span>· {note}</span>{/each}
</p>
@@ -1074,7 +1098,7 @@
</section>
{/if}
- {#if !canRelate && !canMention && !hasRelations && !lineageCount && !placedPoints.length}
+ {#if !canRelate && !canMention && !claimSeatHere && !hasRelations && !lineageCount && !placedPoints.length}
<div class="case-card empty-card">
<Icon name="link" size={16} />
<p>No connections yet.</p>
@@ -1445,6 +1469,13 @@
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 7773219..b6dd1cb 100644
--- a/frontend/src/components/EntityDetails.test.js
+++ b/frontend/src/components/EntityDetails.test.js
@@ -68,12 +68,23 @@ 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 || hasRelations || lineageCount || placedPoints.length}'
+ '{#if canRelate || canMention || claimSeatHere || 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('files a connection from its own Add action rather than the panel Save', () => {
expect(source).toContain('async function addConnection(choice)');
expect(source).toContain('await saveRelation(caseState.current.id, entity.id, choice);');
diff --git a/frontend/src/components/EntityTime.svelte b/frontend/src/components/EntityTime.svelte
index b246564..004799a 100644
--- a/frontend/src/components/EntityTime.svelte
+++ b/frontend/src/components/EntityTime.svelte
@@ -38,8 +38,8 @@
);
const assessmentLabel = $derived(
entity.type === 'claim'
- ? ownStatement?.raw ? 'Edit statement date' : 'Set statement date'
- : entity.type === 'media' ? 'Add capture assessment' : 'Add time assessment'
+ ? ownStatement?.raw ? 'Edit claim date' : 'Set claim date'
+ : entity.type === 'media' ? 'Claim a capture date' : 'Add dated claim'
);
async function load({ more = false } = {}) {
@@ -96,7 +96,7 @@
function kindLabel(item) {
return {
captured: 'Captured', published: 'Published', imagery: 'Imagery',
- collected: 'Collected', added: 'Added to case', filed: 'Filed in case', claim: 'Assessment',
+ collected: 'Collected', added: 'Added to case', filed: 'Filed in case', claim: 'Claim',
}[item.kind] ?? item.kind;
}
@@ -116,7 +116,7 @@
<span class="time-value" class:undated={!item.raw} title={item.raw || undefined}>{timeLabel(item)}</span>
</button>
{#if editable}
- <button class="time-row-action" aria-label={`Edit ${item.label}`} title="Edit assessment" onclick={() => (editor = item)}><Icon name="edit" size={12} /></button>
+ <button class="time-row-action" aria-label={`Edit ${item.label}`} title="Edit claim" onclick={() => (editor = item)}><Icon name="edit" size={12} /></button>
{/if}
</div>
{/snippet}
@@ -127,17 +127,17 @@
<button class="btn btn-ghost btn-sm" onclick={() => openTimeline()}><Icon name="clock" size={12} />Open in Timeline</button>
</div>
{#if entity.type === 'claim'}
- <p class="claim-time-rule">A statement has one date or range. Use another statement for a separate assessment.</p>
+ <p class="claim-time-rule">A claim has one date or range. File another claim for a separate date.</p>
{/if}
{#if editor}
<section
class="time-editor"
- aria-label={entity.type === 'claim' ? assessmentLabel : editor === 'new' ? assessmentLabel : 'Edit time assessment'}
+ aria-label={entity.type === 'claim' ? assessmentLabel : editor === 'new' ? assessmentLabel : 'Edit claim'}
>
<header>
- <h3>{entity.type === 'claim' ? assessmentLabel : editor === 'new' ? assessmentLabel : 'Edit time assessment'}</h3>
- <button class="btn btn-ghost btn-sm" aria-label="Close editor" onclick={() => (editor = null)}>
+ <h3>{entity.type === 'claim' ? assessmentLabel : editor === 'new' ? assessmentLabel : 'Edit claim'}</h3>
+ <button class="btn btn-ghost btn-sm" aria-label="Close editor" title="Close editor" onclick={() => (editor = null)}>
<Icon name="x" size={13} />
</button>
</header>
@@ -162,20 +162,20 @@
<div class="time-empty">Loading time history…</div>
{:else}
{#if ownStatement?.raw}
- <section><h3>Statement date <span>1</span></h3>{@render row(ownStatement, true)}</section>
+ <section><h3>Claim date <span>1</span></h3>{@render row(ownStatement, true)}</section>
{:else if entity.type === 'claim'}
- <div class="time-empty compact"><Icon name="clock" size={18} /><p>This statement has no date yet.</p></div>
+ <div class="time-empty compact"><Icon name="clock" size={18} /><p>This claim has no date yet.</p></div>
{/if}
{#if about.length}
- <section><h3>Statements about this <span>{about.length}</span></h3>{#each about as item (item.id)}{@render row(item, true)}{/each}</section>
+ <section><h3>Claims about this <span>{about.length}</span></h3>{#each about as item (item.id)}{@render row(item, true)}{/each}</section>
{/if}
{#if placed.length}
- <section><h3>Statements placed here <span>{placed.length}</span></h3>{#each placed as item (item.id)}{@render row(item, true)}{/each}</section>
+ <section><h3>Claims placed here <span>{placed.length}</span></h3>{#each placed as item (item.id)}{@render row(item, true)}{/each}</section>
{/if}
{#if evidence.length}
<section>
<h3>Evidence for <span>{evidence.length}</span></h3>
- <p class="section-note">These dates belong to statements this item supports.</p>
+ <p class="section-note">These dates belong to claims this item supports.</p>
{#each evidence as item (item.id)}{@render row(item, true)}{/each}
</section>
{/if}
@@ -192,7 +192,7 @@
<section class="undated"><h3>Undated <span>{visibleUndated.length}</span></h3>{#each visibleUndated as item (item.id)}{@render row(item, item.category === 'statement')}{/each}</section>
{/if}
{#if !visibleCount && entity.type !== 'claim'}
- <div class="time-empty"><Icon name="clock" size={18} /><p>No dates or time assessments yet.</p></div>
+ <div class="time-empty"><Icon name="clock" size={18} /><p>No dates or dated claims yet.</p></div>
{/if}
{#if cursor}<button class="btn btn-ghost btn-sm more" disabled={loading} onclick={() => load({ more: true })}>{loading ? 'Loading…' : 'Show more'}</button>{/if}
{/if}
diff --git a/frontend/src/components/EntityTime.test.js b/frontend/src/components/EntityTime.test.js
index be6b266..da9eacd 100644
--- a/frontend/src/components/EntityTime.test.js
+++ b/frontend/src/components/EntityTime.test.js
@@ -15,11 +15,11 @@ describe('entity Time tab', () => {
it('does not attribute a cited statement date to its evidence', () => {
expect(source).toContain("item.sources.includes(entity.id)");
expect(source).toContain('Evidence for <span>{evidence.length}</span>');
- expect(source).toContain('These dates belong to statements this item supports.');
+ expect(source).toContain('These dates belong to claims this item supports.');
});
it('prefills a media capture assessment without changing file metadata', () => {
- expect(source).toContain("entity.type === 'media' ? 'Add capture assessment'");
+ expect(source).toContain("entity.type === 'media' ? 'Claim a capture date'");
expect(source).toContain("initialStatement={entity.type === 'media' ? 'This media was captured' : ''}");
expect(source).toContain("initialRole={entity.type === 'media' ? 'observed' : ''}");
});
@@ -32,7 +32,7 @@ describe('entity Time tab', () => {
it('opens an existing assessment in an explicit inline editor', () => {
expect(source).toContain('aria-label={`Edit ${item.label}`}');
expect(source).toContain('class="time-editor"');
- expect(source).toContain("'Edit time assessment'");
+ expect(source).toContain("'Edit claim'");
expect(source).not.toContain('<Modal');
});
@@ -45,10 +45,10 @@ describe('entity Time tab', () => {
});
it('edits the Claim date instead of creating an impossible nested assessment', () => {
- expect(source).toContain("ownStatement?.raw ? 'Edit statement date' : 'Set statement date'");
+ expect(source).toContain("ownStatement?.raw ? 'Edit claim date' : 'Set claim date'");
expect(source).toContain("editor = entity.type === 'claim'");
- expect(source).toContain('This statement has no date yet.');
- expect(source).toContain('A statement has one date or range. Use another statement for a separate assessment.');
+ expect(source).toContain('This claim has no date yet.');
+ expect(source).toContain('A claim has one date or range. File another claim for a separate date.');
expect(source).toContain('visibleUndated = $derived(undated.filter');
});
});
@@ -58,7 +58,7 @@ describe('entity Time tab — which date reads first', () => {
// A proof that dates its footage states it here, and a stated date is the
// answer: the file's own clock is what the analyst was correcting or filling
// in. Pinned, because the order is the whole of the priority.
- const about = source.indexOf('Statements about this');
+ const about = source.indexOf('Claims about this');
const media = source.indexOf('Media dates');
expect(about).toBeGreaterThan(-1);
expect(media).toBeGreaterThan(about);
diff --git a/frontend/src/components/Icon.svelte b/frontend/src/components/Icon.svelte
index 64d75c8..3a4a4bc 100644
--- a/frontend/src/components/Icon.svelte
+++ b/frontend/src/components/Icon.svelte
@@ -59,6 +59,10 @@
audio: 'M9 18V6l10-2v11.5M9 18a2.5 2.5 0 1 1-5 0 2.5 2.5 0 0 1 5 0Zm10-2.5a2.5 2.5 0 1 1-5 0 2.5 2.5 0 0 1 5 0Z',
file: 'M6 3h9l5 5v13a1 1 0 0 1-1 1H6a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1Zm8 0v6h6',
hash: 'M9 4 7 20M17 4l-2 16M4 9h17M3 15h17',
+ // a numeral in a ring, and a box of blurred dots: the two marks a proof
+ // makes that are neither a line nor a word
+ numbered: 'M12 3a9 9 0 1 1 0 18 9 9 0 0 1 0-18ZM10.4 9.6 12.4 8.2V16M10.6 16h3.6',
+ blurBox: 'M4.5 4.5h15v15h-15zM9 9h.01M15 9h.01M9 15h.01M15 15h.01M12 12h.01',
globe: 'M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18Zm-9 9h18M12 3c2.5 2.5 3.8 5.7 3.8 9S14.5 18.5 12 21c-2.5-2.5-3.8-5.7-3.8-9S9.5 5.5 12 3Z',
// a page the case points at, not a hostname: `domain` keeps the globe, and the
// two stopped being the same row at a glance
@@ -96,6 +100,9 @@
ghost: 'M12 3a8 8 0 0 0-8 8v10l4-2 4 2 4-2 4 2V11a8 8 0 0 0-8-8Zm-3 8h.01m5.99 0H15',
info: 'M12 22a10 10 0 1 0 0-20 10 10 0 0 0 0 20Zm0-11v6m0-10h.01',
clock: 'M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18Zm0 4v5l3.5 2',
+ // a month with its head rule: what a field opens when a date is built rather
+ // than typed
+ calendar: 'M4 6.5a1 1 0 0 1 1-1h14a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1v-13Zm4-3v4m8-4v4M4 10h16',
play: 'm8 5 11 7-11 7V5Z',
pause: 'M8 5v14m8-14v14',
volume: 'M5 10v4h3l4 4V6L8 10H5Zm11-2a6 6 0 0 1 0 8m2.5-10.5a9 9 0 0 1 0 13',
diff --git a/frontend/src/components/Modal.svelte b/frontend/src/components/Modal.svelte
index 353d9eb..e1e2eb6 100644
--- a/frontend/src/components/Modal.svelte
+++ b/frontend/src/components/Modal.svelte
@@ -24,7 +24,7 @@
<div class="modal" style:width role="dialog" aria-label={title}>
<header>
<h3>{title}</h3>
- <button class="btn btn-ghost btn-sm" onclick={onclose} aria-label="Close">
+ <button class="btn btn-ghost btn-sm" onclick={onclose} aria-label="Close" title="Close">
<Icon name="x" size={15} />
</button>
</header>
diff --git a/frontend/src/components/MonthGrid.svelte b/frontend/src/components/MonthGrid.svelte
new file mode 100644
index 0000000..7241d2d
--- /dev/null
+++ b/frontend/src/components/MonthGrid.svelte
@@ -0,0 +1,213 @@
+<script>
+ /**
+ * One month of days, drawn in the panel it belongs to.
+ *
+ * `<input type="date">` was the obvious answer and the wrong one: its calendar
+ * is browser chrome, so it opens at the browser's size, in the browser's
+ * locale, and *over* the page — which in a panel docked to the right edge of
+ * the window means half of it outside the window, and a date reading
+ * `12/09/2026` in an app that writes `2026-09-12` everywhere else.
+ *
+ * So the month is drawn here, in flow: it pushes the rows under it down rather
+ * than floating over them, which is the whole of why it cannot be clipped. The
+ * arithmetic is `lib/calendar.js`, and the extension's panel draws the same
+ * grid from its own copy of it.
+ *
+ * The month on screen lives here rather than in the field above: mounted when
+ * it opens, it starts on the day it holds every time instead of where it was
+ * left.
+ */
+ import Icon from './Icon.svelte';
+ import {
+ WEEKDAYS,
+ monthDays,
+ monthLabel,
+ monthOf,
+ monthOutOfRange,
+ outOfRange,
+ shiftMonth,
+ today as todayOf,
+ } from '../lib/calendar.js';
+
+ let {
+ /** The day it opens on and marks, `YYYY-MM-DD`, or '' for none. A `YYYY-MM`
+ * opens that month without marking a day in it. */
+ value = '',
+ /** Bounds, either of which may be empty for "no bound". */
+ min = '',
+ max = '',
+ /** Names the grid for a reader that cannot see the field beside it. */
+ label = 'Date',
+ /** Whether the day can be taken back out, for a field that means "and no
+ * further" as much as it means a date. */
+ clearable = false,
+ /** Called with the chosen day, or '' when it is cleared. */
+ onpick,
+ } = $props();
+
+ let cursor = $state('');
+
+ const today = $derived(todayOf());
+ const month = $derived(cursor || monthOf(value));
+ const cells = $derived(monthDays(month));
+ const canGoBack = $derived(!monthOutOfRange(shiftMonth(month, -1), min, max));
+ const canGoOn = $derived(!monthOutOfRange(shiftMonth(month, 1), min, max));
+</script>
+
+<div class="cal" role="group" aria-label="{label} calendar">
+ <div class="head">
+ <button
+ type="button"
+ class="step"
+ disabled={!canGoBack}
+ aria-label="Previous month" title="Previous month"
+ onclick={() => (cursor = shiftMonth(month, -1))}
+ >
+ <Icon name="chevronLeft" size={12} />
+ </button>
+ <span class="month">{monthLabel(month)}</span>
+ <button
+ type="button"
+ class="step"
+ disabled={!canGoOn}
+ aria-label="Next month" title="Next month"
+ onclick={() => (cursor = shiftMonth(month, 1))}
+ >
+ <Icon name="chevronRight" size={12} />
+ </button>
+ </div>
+
+ <div class="week">
+ {#each WEEKDAYS as day, i (i)}<span>{day}</span>{/each}
+ </div>
+
+ <div class="days">
+ {#each cells as cell (cell.iso)}
+ <button
+ type="button"
+ class="day"
+ class:out={!cell.inMonth}
+ class:on={cell.iso === value}
+ class:today={cell.iso === today}
+ disabled={outOfRange(cell.iso, min, max)}
+ aria-current={cell.iso === value ? 'date' : undefined}
+ title={cell.iso}
+ onclick={() => onpick?.(cell.iso)}
+ >{cell.day}</button>
+ {/each}
+ </div>
+
+ <div class="acts">
+ <button
+ type="button"
+ class="act"
+ disabled={outOfRange(today, min, max)}
+ onclick={() => onpick?.(today)}
+ >Today</button>
+ {#if clearable}
+ <button type="button" class="act" disabled={!value} onclick={() => onpick?.('')}>Clear</button>
+ {/if}
+ </div>
+</div>
+
+<style>
+ /* in flow, never over: the row under it moves down, and nothing can push it
+ past an edge it would be cut at */
+ .cal {
+ display: flex;
+ flex-direction: column;
+ gap: 3px;
+ padding: 5px;
+ border: 1px solid var(--border);
+ border-radius: var(--r-sm);
+ background: var(--bg-2);
+ }
+ .head {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ }
+ .month {
+ font-size: 10px;
+ font-weight: 600;
+ color: var(--text-1);
+ }
+ .step {
+ display: grid;
+ place-items: center;
+ width: 18px;
+ height: 18px;
+ border-radius: var(--r-sm);
+ color: var(--text-2);
+ cursor: pointer;
+ }
+ .step:hover:not(:disabled) {
+ color: var(--text-1);
+ background: var(--bg-3);
+ }
+ .step:disabled {
+ opacity: 0.3;
+ cursor: default;
+ }
+ .week,
+ .days {
+ display: grid;
+ grid-template-columns: repeat(7, 1fr);
+ gap: 1px;
+ }
+ .week span {
+ text-align: center;
+ font-size: 9px;
+ color: var(--text-3);
+ }
+ .day {
+ padding: 2px 0;
+ border-radius: var(--r-sm);
+ color: var(--text-2);
+ font-size: 10px;
+ font-variant-numeric: tabular-nums;
+ cursor: pointer;
+ }
+ .day:hover:not(:disabled) {
+ background: var(--bg-3);
+ color: var(--text-1);
+ }
+ .day.out {
+ color: var(--text-3);
+ opacity: 0.5;
+ }
+ .day.today {
+ box-shadow: inset 0 0 0 1px var(--border-strong);
+ }
+ .day.on {
+ background: var(--accent-soft);
+ color: var(--accent);
+ box-shadow: inset 0 0 0 1px var(--accent);
+ }
+ .day:disabled {
+ opacity: 0.25;
+ cursor: default;
+ }
+ .acts {
+ display: flex;
+ justify-content: flex-end;
+ gap: 4px;
+ }
+ .act {
+ padding: 2px 7px;
+ border: 1px solid var(--border);
+ border-radius: var(--r-sm);
+ background: var(--bg-2);
+ color: var(--text-2);
+ font-size: 10px;
+ cursor: pointer;
+ }
+ .act:hover:not(:disabled) {
+ border-color: var(--border-strong);
+ color: var(--text-1);
+ }
+ .act:disabled {
+ opacity: 0.4;
+ cursor: default;
+ }
+</style>
diff --git a/frontend/src/components/QuickClaim.render.test.js b/frontend/src/components/QuickClaim.render.test.js
new file mode 100644
index 0000000..c2b595f
--- /dev/null
+++ b/frontend/src/components/QuickClaim.render.test.js
@@ -0,0 +1,200 @@
+// @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
new file mode 100644
index 0000000..a273a56
--- /dev/null
+++ b/frontend/src/components/QuickClaim.svelte
@@ -0,0 +1,217 @@
+<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/SearchInput.svelte b/frontend/src/components/SearchInput.svelte
index 89f78d0..9574ef0 100644
--- a/frontend/src/components/SearchInput.svelte
+++ b/frontend/src/components/SearchInput.svelte
@@ -26,7 +26,7 @@
/>
{#if count != null}<span class="search-count">{count}</span>{/if}
{#if value}
- <button class="search-clear" onclick={clear} aria-label="Clear search">
+ <button class="search-clear" onclick={clear} aria-label="Clear search" title="Clear search">
<Icon name="x" size={12} />
</button>
{/if}
diff --git a/frontend/src/components/SheetToCase.svelte b/frontend/src/components/SheetToCase.svelte
index 85ffa96..8df657e 100644
--- a/frontend/src/components/SheetToCase.svelte
+++ b/frontend/src/components/SheetToCase.svelte
@@ -348,7 +348,7 @@
const LAYERS = {
row: 'Rows',
value: 'Words',
- statement: 'Statements',
+ statement: 'Claims',
'row-edges': 'Row edges',
};
diff --git a/frontend/src/components/TemporalClaimEditor.svelte b/frontend/src/components/TemporalClaimEditor.svelte
index 3e90426..938421a 100644
--- a/frontend/src/components/TemporalClaimEditor.svelte
+++ b/frontend/src/components/TemporalClaimEditor.svelte
@@ -87,7 +87,7 @@
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 ? 'Time assessment updated' : 'Time assessment added', 'ok', 1800);
+ toast(item ? 'Claim updated' : 'Claim added', 'ok', 1800);
onsaved?.(saved);
} catch (error) {
toast(error.message, 'danger');
@@ -99,10 +99,10 @@
<div class="claim-editor">
{#if loading}
- <div class="loading">Loading assessment…</div>
+ <div class="loading">Loading claim…</div>
{/if}
- <label class="modal-label" for="temporal-statement">Statement</label>
+ <label class="modal-label" for="temporal-statement">Claim</label>
<textarea
id="temporal-statement"
class="textarea"
@@ -147,7 +147,7 @@
{caseId}
relationType="about"
label="About"
- hint="Who or what this statement concerns"
+ hint="Who or what this claim concerns"
bind:selected={about}
locked={lockedAbout}
/>
@@ -162,7 +162,7 @@
{caseId}
relationType="cites"
label="Evidence"
- hint="Files, notes or statements supporting this date"
+ hint="Files, notes or claims supporting this date"
bind:selected={cites}
/>
</section>
@@ -178,7 +178,7 @@
<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 assessment' : 'Add assessment'}
+ {saving ? 'Saving…' : item ? 'Update claim' : 'Add claim'}
</button>
</div>
</div>
diff --git a/frontend/src/components/TimelineTrackEditor.svelte b/frontend/src/components/TimelineTrackEditor.svelte
index b4b5d5d..4b054da 100644
--- a/frontend/src/components/TimelineTrackEditor.svelte
+++ b/frontend/src/components/TimelineTrackEditor.svelte
@@ -157,7 +157,7 @@
<fieldset>
<legend>Timeline entries</legend>
<div class="checks">
- {#each [['statement', 'Statements'], ['media', 'Media'], ['case_activity', 'Case activity']] as option}
+ {#each [['statement', 'Claims'], ['media', 'Media'], ['case_activity', 'Case activity']] as option}
<label><input type="checkbox" checked={categories.has(option[0])} onchange={() => toggleCategory(option[0])} />{option[1]}</label>
{/each}
</div>
diff --git a/frontend/src/components/iconButtons.test.js b/frontend/src/components/iconButtons.test.js
new file mode 100644
index 0000000..a6ebfd3
--- /dev/null
+++ b/frontend/src/components/iconButtons.test.js
@@ -0,0 +1,47 @@
+import { describe, expect, it } from 'vitest';
+import { readdirSync, readFileSync, statSync } from 'node:fs';
+import { join, relative } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+// Every button that shows only an icon says what it does on hover. An
+// aria-label names it for a screen reader, but a sighted analyst never sees
+// one, so the rule is walked over every component rather than trusted to review.
+
+const SRC = fileURLToPath(new URL('..', import.meta.url));
+
+function svelteFiles(dir) {
+ return readdirSync(dir).flatMap((name) => {
+ if (name === 'node_modules') return [];
+ const path = join(dir, name);
+ if (statSync(path).isDirectory()) return svelteFiles(path);
+ return name.endsWith('.svelte') ? [path] : [];
+ });
+}
+
+// An opening tag's attributes may hold `{…}` expressions, one level of nesting deep.
+const CONTROL = /<(button|a)\b((?:[^>{]|\{(?:[^{}]|\{[^{}]*\})*\})*)>([\s\S]*?)<\/\1>/g;
+
+function iconOnly(body) {
+ if (!/<Icon\b|Glyph\b/.test(body)) return false;
+ const text = body
+ .replace(/<Icon\b[^>]*\/>/g, '')
+ .replace(/<(ProofGlyph|MoonGlyph)\b[^>]*\/>/g, '')
+ .replace(/\{#if[^}]*\}|\{:else[^}]*\}|\{\/if\}/g, '');
+ return !text.trim();
+}
+
+describe('icon-only buttons', () => {
+ it('all carry a hover tooltip', () => {
+ const missing = [];
+ for (const file of svelteFiles(SRC)) {
+ const source = readFileSync(file, 'utf8');
+ for (const match of source.matchAll(CONTROL)) {
+ const [, , attrs, body] = match;
+ if (!iconOnly(body) || /\btitle=/.test(attrs)) continue;
+ const line = source.slice(0, match.index).split('\n').length;
+ missing.push(`${relative(SRC, file)}:${line}`);
+ }
+ }
+ expect(missing).toEqual([]);
+ });
+});
diff --git a/frontend/src/lib/calendar.js b/frontend/src/lib/calendar.js
index ec622ba..9cef8d2 100644
--- a/frontend/src/lib/calendar.js
+++ b/frontend/src/lib/calendar.js
@@ -24,6 +24,8 @@ const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', '
const DAY = /^\d{4}-\d{2}-\d{2}$/;
const MONTH = /^\d{4}-\d{2}$/;
+const pad = (value) => String(value).padStart(2, '0');
+
/** A `YYYY-MM-DD` as a UTC date, or null — the same strictness as the service
* routes, so a half-typed field never becomes a request. */
export function parseDay(iso) {
@@ -86,6 +88,23 @@ export function monthDays(cursor) {
return cells;
}
+/** The twelve months of a year, as the cells a month is picked from. */
+export function yearMonths(year) {
+ const number = Number(String(year).slice(0, 4)) || Number(today().slice(0, 4));
+ return MONTHS.map((label, index) => ({
+ iso: `${number}-${pad(index + 1)}`,
+ label,
+ }));
+}
+
+/** A page of years around `cursor`, in rows the same width as the months grid,
+ * so the three precisions are three drawings of one box. */
+export function yearPage(cursor, size = 12) {
+ const year = Number(String(cursor ?? '').slice(0, 4)) || Number(today().slice(0, 4));
+ const first = year - Math.floor(size / 2);
+ return Array.from({ length: size }, (_, index) => String(first + index));
+}
+
/** Whether a day is outside what the field accepts — an empty bound is no
* bound, which is how a range with no end is stated. */
export function outOfRange(iso, min = '', max = '') {
diff --git a/frontend/src/lib/calendar.test.js b/frontend/src/lib/calendar.test.js
index 0aae8c6..388611a 100644
--- a/frontend/src/lib/calendar.test.js
+++ b/frontend/src/lib/calendar.test.js
@@ -9,6 +9,8 @@ import {
parseDay,
shiftMonth,
today,
+ yearMonths,
+ yearPage,
} from './calendar.js';
describe('reading a day', () => {
@@ -93,3 +95,23 @@ describe('what the field will not accept', () => {
expect(monthOutOfRange('2026-09', '2026-09-20', '2026-09-30')).toBe(false);
});
});
+
+describe('the other two depths a date can be built at', () => {
+ it('lays a year out as its twelve months, each named and stored', () => {
+ const months = yearMonths(2025);
+ expect(months).toHaveLength(12);
+ expect(months[0]).toEqual({ iso: '2025-01', label: 'Jan' });
+ expect(months[9]).toEqual({ iso: '2025-10', label: 'Oct' });
+ });
+
+ it('reads the year off a stored token of any depth', () => {
+ expect(yearMonths('2019-07-14')[0].iso).toBe('2019-01');
+ });
+
+ it('pages years around the one being shown, in the months grid’s own shape', () => {
+ const years = yearPage('2025');
+ expect(years).toHaveLength(12);
+ expect(years[0]).toBe('2019');
+ expect(years).toContain('2025');
+ });
+});
diff --git a/frontend/src/lib/composer.js b/frontend/src/lib/composer.js
index 43a706b..be3f22d 100644
--- a/frontend/src/lib/composer.js
+++ b/frontend/src/lib/composer.js
@@ -377,12 +377,15 @@ export function panelsBottom(panels, captionSize = CAPTION_SIZE, layout = 'grid'
/**
* Distinct colors in order of first use → feature numbering (same color = same
- * feature). Text labels are excluded — they annotate, they aren't features.
+ * feature). Text labels are excluded — they annotate, they aren't features. So
+ * is a blur box: it hides something rather than pointing at it, and its colour
+ * is never drawn, so a legend row for it would key a feature on a colour the
+ * plate does not show.
*/
export function featureColors(shapes) {
const seen = [];
for (const s of shapes) {
- if (s.kind === 'text') continue;
+ if (s.kind === 'text' || s.kind === 'blur') continue;
if (!seen.includes(s.color)) seen.push(s.color);
}
return seen;
@@ -745,6 +748,25 @@ export function footerLines(proof, format = 'dd') {
return [...printed, ...credit];
}
+/**
+ * A source row as a link the browser may open, or '' when it is not one.
+ *
+ * The field takes whatever says where the material came from — an address, a
+ * case number, a sentence — so the press that opens a tab is offered only for
+ * the rows that are web addresses. Anything else, `javascript:` included, is not
+ * a link here.
+ */
+export function openableSource(text) {
+ const value = String(text ?? '').trim();
+ if (!value) return '';
+ try {
+ const url = new URL(value);
+ return url.protocol === 'http:' || url.protocol === 'https:' ? url.toString() : '';
+ } catch {
+ return '';
+ }
+}
+
/** Effective source line for a proof/spec: the stated addresses, else the traced ones.
*
* Always one line, whatever the proof holds: a plate, a post and a report all read a
diff --git a/frontend/src/lib/composer.test.js b/frontend/src/lib/composer.test.js
index 93752a9..9fe6a05 100644
--- a/frontend/src/lib/composer.test.js
+++ b/frontend/src/lib/composer.test.js
@@ -311,6 +311,18 @@ describe('orderedFeatureColors + legendLines — manual legend order', () => {
expect(orderedFeatureColors(shapes)).toEqual(['#ff5252', '#40c4ff', '#ffd740']);
});
+ it('keeps what hides or labels out of the legend, and what marks in it', () => {
+ // a blur box hides a face; it points at no feature, and its colour is never
+ // drawn. A numbered marker does mark one, so it keys a row like any shape.
+ const mixed = [
+ ...shapes,
+ { kind: 'blur', color: '#00e676', panel: 'p1' },
+ { kind: 'text', color: '#7c4dff', panel: 'p1' },
+ { kind: 'number', color: '#b388ff', panel: 'p1', n: 1 },
+ ];
+ expect(orderedFeatureColors(mixed)).toEqual(['#ff5252', '#40c4ff', '#ffd740', '#b388ff']);
+ });
+
it('respects an explicit legendOrder', () => {
const order = ['#ffd740', '#ff5252', '#40c4ff'];
expect(orderedFeatureColors(shapes, order)).toEqual(order);
diff --git a/frontend/src/lib/guide.js b/frontend/src/lib/guide.js
index 0652200..8c646a5 100644
--- a/frontend/src/lib/guide.js
+++ b/frontend/src/lib/guide.js
@@ -162,6 +162,10 @@ export const GUIDE = [
label: 'Reverse Search picks no engine for you',
text: 'It prepares an image or a frame, and nothing moves until you press an engine. With the capture extension that press opens the engine with the picture already in its uploader.',
},
+ {
+ label: 'Send a picture from where you are looking at it',
+ text: 'Open in… on a Media Library row sends the file, and the Frame tab in Inspect sends the frame as you cropped it, saved or not.',
+ },
],
},
{
@@ -171,8 +175,8 @@ export const GUIDE = [
tools: ['inspect'],
points: [
{
- label: 'Four modes on one file',
- text: 'Selection crops and adjusts, Frame pulls stills out of a video, Collage stitches, and Analyze runs the error-level view.',
+ label: 'Four tabs for a video, two for a picture',
+ text: 'Selection pulls stills out of a clip, Frame adjusts and crops one picture with the error-level view folded inside, Collage stitches, and Save files what you made. A still image opens on Frame and Save.',
},
{
label: 'What you make is case material',
@@ -200,7 +204,11 @@ export const GUIDE = [
},
{
label: 'Layers cost nothing until they are on',
- text: 'Roads, railways, power lines, sea marks, GPS traces, fires and night lights are listed in the Saved panel, and none of them is fetched before its switch is pressed. Borders are the one layer the map opens with.',
+ text: 'Roads, railways, power lines, sea marks, GPS traces, fires and night lights are listed in the Layers tab of the side panel, and none of them is fetched before its switch is pressed. Borders are the one layer the map opens with.',
+ },
+ {
+ label: 'Somebody else’s map over yours',
+ text: 'Add a layer opens a KML, KMZ, GeoJSON or GPX file, follows a public My Maps, or brings in a GeoConfirmed conflict by dates and area. Its legend and its time strip filter it, and nothing in it joins the case.',
},
{
label: 'The search bar answers before it asks',
@@ -216,7 +224,7 @@ export const GUIDE = [
},
{
label: 'Compare keeps the ground fixed',
- text: 'Read two locked views side by side, by swipe, opacity or blink. Matched products also get Difference and Detect; notes and shapes stay editable in the saved comparison and appear in its outputs.',
+ text: 'Read two locked views side by side, by swipe, opacity or blink. Matched products also get Difference and Detect; notes, shapes and stamped markers stay editable in the saved comparison and appear in its outputs.',
},
{
label: 'Coords & Sky keeps calculations separate',
@@ -238,6 +246,10 @@ export const GUIDE = [
label: 'Geo Proof stays editable',
text: 'Panels, marks and boxes are saved as a spec beside the exported PNG, so a proof exported last week can be reopened and changed.',
},
+ {
+ label: 'Marks that number and marks that hide',
+ text: 'A numbered marker ties a spot to a line in your text, and each colour counts its own series from 1. A blur box redraws the picture under it through a blur, so what is hidden is hidden in the exported file, not covered by a rectangle.',
+ },
{
label: 'A proof can argue several points',
text: 'Each place is optionally named and one of them can be the camera. They are filed as places and carried into the thread and onto the picture.',
@@ -274,13 +286,17 @@ export const GUIDE = [
label: 'The Graph never writes to the case',
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: '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: 'Sheet works on real CSV files',
- text: 'The sheets the case holds, in a grid. A declared sheet can be promoted into entities, places and dated statements, read as a plan first.',
+ text: 'The sheets the case holds, in a grid. A declared sheet can be promoted into entities, places and dated claims, read as a plan first.',
},
],
},
@@ -296,6 +312,7 @@ 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' },
],
},
{
@@ -335,7 +352,7 @@ export const GUIDE = [
{
where: 'Geo Proof',
keys: [
- { combo: 'V R E A L C D T S', does: 'picks select, rectangle, ellipse, arrow, line, curve, freehand, text and icon' },
+ { combo: 'V R E A L C D T S N B', does: 'picks select, rectangle, ellipse, arrow, line, curve, freehand, text, icon, numbered marker and blur box' },
{ combo: 'F', does: 'fits the document' },
{ combo: 'Space (held)', does: 'pans, whatever tool is in hand' },
{ combo: 'Delete', does: 'removes what is selected' },
diff --git a/frontend/src/lib/looseDate.js b/frontend/src/lib/looseDate.js
new file mode 100644
index 0000000..31e9284
--- /dev/null
+++ b/frontend/src/lib/looseDate.js
@@ -0,0 +1,271 @@
+/**
+ * One text field for a date, read the way people write one.
+ *
+ * The case stores dates in one profile (`lib/timeline.js`: `2025-10-24~`,
+ * `2025-10`, `2025-10-24T14:30:00Z`, `start/end`), and the backend refuses
+ * anything else. Asking an analyst to pick a format, a precision and a
+ * certainty from three lists before typing a day was the long way round, so
+ * this reads what they type into that same profile:
+ *
+ * - anything already in the stored profile is kept exactly as typed, so the
+ * advanced syntax still works and nothing a proof holds can be re-read into
+ * something else;
+ * - otherwise a day is day-first (`24/10/2025`, `24.10.2025`), a month is
+ * `10/2025` or a name (`Oct 2025`, `octobre 2025`), a year is four digits;
+ * - `~` or "about" means approximate, a `?` means uncertain, both mean both;
+ * - a time (`14:30`, `14h30`) makes it a timestamp, local unless a zone
+ * follows (`UTC`, `Z`, `+02:00`, `UTC+2`);
+ * - two of them joined by "to" or a spaced dash make a range.
+ *
+ * `friendlyDate` writes a stored value back in that everyday form, and reading
+ * it again gives the same stored value — `looseDate.test.js` holds both
+ * directions to every example the profile documents.
+ */
+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.
+const MONTH_WORDS = new Map(
+ [
+ ['january', 'jan', 'janvier', 'janv'],
+ ['february', 'feb', 'fevrier', 'fevr', 'fev'],
+ ['march', 'mar', 'mars'],
+ ['april', 'apr', 'avril', 'avr'],
+ ['may', 'mai'],
+ ['june', 'jun', 'juin'],
+ ['july', 'jul', 'juillet', 'juil'],
+ ['august', 'aug', 'aout'],
+ ['september', 'sep', 'sept', 'septembre'],
+ ['october', 'oct', 'octobre'],
+ ['november', 'nov', 'novembre'],
+ ['december', 'dec', 'decembre'],
+ ].flatMap((words, index) => words.map((word) => [word, index + 1]))
+);
+
+export const LOOSE_DATE_HINT =
+ 'A day as dd/mm/yyyy, or Oct 2025, or 2025. Start with ~ for about, end with ? if unsure. A time like 14:30 UTC, or two dates joined by "to", work too.';
+
+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 pad = (value, size = 2) => String(value).padStart(size, '0');
+
+/** `{ value }` in the stored profile, or `{ value: null, error }`. Empty reads as ''. */
+export function parseLooseDate(input) {
+ const text = String(input ?? '').trim().replace(/\s+/g, ' ');
+ if (!text) return { value: '', error: '' };
+ if (validateTemporalValue(text).valid) return { value: text, error: '' };
+
+ const parts = splitRange(text);
+ if (parts.length === 2) {
+ const [first, second] = parts.map(readOne);
+ if (first.error || second.error) return fail(first.error || second.error);
+ let [a, b] = [first, second];
+ // "24/10/2025 10:00 to 12:30 UTC": the end borrows the start's day, and a
+ // zone written once is meant for both ends.
+ if (b.timeOnly && a.time) b = { ...b, date: a.date, timeOnly: false };
+ if (a.time && b.time && Boolean(a.zone) !== Boolean(b.zone)) {
+ a = { ...a, zone: a.zone || b.zone };
+ b = { ...b, zone: b.zone || a.zone };
+ }
+ if (a.timeOnly || b.timeOnly) return fail(HELP);
+ return checked(`${write(a)}/${write(b)}`);
+ }
+
+ const one = readOne(text);
+ if (one.error) return fail(one.error);
+ if (one.timeOnly) return fail('Give the day this time belongs to.');
+ return checked(write(one));
+}
+
+/** A stored value, written the way `parseLooseDate` reads it back. */
+export function friendlyDate(raw) {
+ const value = String(raw ?? '');
+ if (!value || !validateTemporalValue(value).valid) return value;
+ const parts = value.split('/');
+ return parts.map(friendlyPart).join(' to ');
+}
+
+const BUILT = /^(\d{4}(?:-\d{2}(?:-\d{2})?)?)([~?%])?$/;
+
+/**
+ * A stored value from the pieces a builder collects: one or two dates, each as
+ * deep as the analyst went (a year, a month, a day), and the two marks of doubt.
+ *
+ * The marks ride on both ends of a range, because they describe how well the
+ * date is known rather than which end of it is meant.
+ */
+export function composeLooseDate({ start = '', end = '', approximate = false, uncertain = false } = {}) {
+ if (!start) return '';
+ const marker = approximate && uncertain ? '%' : approximate ? '~' : uncertain ? '?' : '';
+ const one = `${start}${marker}`;
+ return end ? `${one}/${end}${marker}` : one;
+}
+
+/**
+ * …and back, so a builder opens on what the field already holds.
+ *
+ * Null for anything it cannot draw — a timestamp, a range of two times — which
+ * is the builder saying "type that", not the field refusing it.
+ */
+export function decomposeLooseDate(raw) {
+ const value = String(raw ?? '').trim();
+ if (!value) return { start: '', end: '', approximate: false, uncertain: false };
+ const parts = value.split('/');
+ if (parts.length > 2) return null;
+ const read = parts.map((part) => BUILT.exec(part));
+ if (read.some((match) => !match)) return null;
+ const marker = read[0][2] ?? '';
+ return {
+ start: read[0][1],
+ end: read[1]?.[1] ?? '',
+ approximate: marker === '~' || marker === '%',
+ uncertain: marker === '?' || marker === '%',
+ };
+}
+
+function friendlyPart(part) {
+ const date = /^(\d{4})(?:-(\d{2})(?:-(\d{2}))?)?([~?%])?$/.exec(part);
+ if (date) {
+ const [, year, month, day, marker = ''] = date;
+ const body = day ? `${day}/${month}/${year}` : month ? `${MONTH_ABBR[Number(month) - 1]} ${year}` : year;
+ const approx = marker === '~' || marker === '%' ? '~' : '';
+ const unsure = marker === '?' || marker === '%' ? '?' : '';
+ return `${approx}${body}${unsure}`;
+ }
+ const stamp = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(\.\d{1,6})?(Z|[+-]\d{2}:\d{2})?$/.exec(part);
+ if (!stamp) return part;
+ const [, year, month, day, hour, minute, second, fraction = '', zone = ''] = stamp;
+ const seconds = second !== '00' || fraction ? `:${second}${fraction}` : '';
+ const where = zone === 'Z' ? ' UTC' : zone ? ` ${zone}` : '';
+ return `${day}/${month}/${year} ${hour}:${minute}${seconds}${where}`;
+}
+
+function fail(error) {
+ return { value: null, error };
+}
+
+function checked(value) {
+ const check = validateTemporalValue(value);
+ if (check.valid) return { value, error: '' };
+ // The parts were written in the stored shape, so a generic refusal here means
+ // the calendar said no: a 31 February, a 25:00.
+ return fail(check.error === 'Use a supported date or timestamp.' ? 'That date does not exist.' : check.error);
+}
+
+function splitRange(text) {
+ const between = /^(?:between|from|entre|du)\s+(.+?)\s+(?:and|to|et|au)\s+(.+)$/i.exec(text);
+ if (between) return [between[1], between[2]];
+ // A dash only joins two dates with a space on both sides, so the minus of a
+ // UTC offset ("14:30 -05:00") is never read as one.
+ const joined = text.split(/\s+(?:to|until|till|au|à)\s+|\s+[-–—]\s+/i);
+ return joined.length === 2 ? joined : [text];
+}
+
+/** One date or one timestamp, into its parts; never a range. */
+function readOne(input) {
+ let text = input.trim();
+ let approx = false;
+ let unsure = false;
+ for (;;) {
+ const lead = /^(?:~|about|approx\.?|approximately|around|circa|c\.|ca\.|vers|environ)\s*/i.exec(text);
+ if (lead && lead[0]) {
+ approx = true;
+ text = text.slice(lead[0].length);
+ continue;
+ }
+ if (text.startsWith('%')) {
+ approx = unsure = true;
+ text = text.slice(1).trim();
+ continue;
+ }
+ if (text.startsWith('?')) {
+ unsure = true;
+ text = text.slice(1).trim();
+ continue;
+ }
+ break;
+ }
+ for (;;) {
+ if (/[?]$/.test(text)) unsure = true;
+ else if (/[~]$/.test(text)) approx = true;
+ else if (/[%]$/.test(text)) approx = unsure = true;
+ else break;
+ text = text.slice(0, -1).trim();
+ }
+
+ const time = readTime(text);
+ if (time.error) return time;
+ text = time.rest;
+ if (time.time && (approx || unsure)) {
+ return fail('A time cannot be marked ~ or ?. Drop the time, or the mark.');
+ }
+ if (!text) {
+ return time.time ? { timeOnly: true, time: time.time, zone: time.zone } : fail(HELP);
+ }
+ const date = readDate(text);
+ if (date.error) return date;
+ if (time.time && date.precision !== 'day') return fail('A time needs a full day before it.');
+ return { ...date, approx, unsure, time: time.time, zone: time.zone };
+}
+
+// A time and the zone after it, taken off the end: "14:30", "14h30",
+// "14:30:05.25", then "Z", "UTC", "GMT", "+02:00", "UTC+2", "-0530".
+const TIME =
+ /(?:^|[\sT])(\d{1,2})(?::|h)(\d{2})(?::(\d{2})(\.\d{1,6})?)?\s*(z|utc|gmt)?\s*(?:([+-])(\d{1,2})(?::?(\d{2}))?)?$/i;
+
+function readTime(text) {
+ const match = TIME.exec(text);
+ if (!match) return { rest: text, time: '', zone: '' };
+ const [whole, hour, minute, second = '00', fraction = '', named, sign, offHour, offMinute = '00'] = match;
+ if (Number(hour) > 23 || Number(minute) > 59 || Number(second) > 59) return fail('That time does not exist.');
+ let zone = '';
+ if (sign) zone = `${sign}${pad(offHour)}:${pad(offMinute)}`;
+ else if (named) zone = 'Z';
+ if (zone === '+00:00' && named) zone = 'Z';
+ return {
+ rest: text.slice(0, text.length - whole.length).replace(/[\s,T]+$/, '').trim(),
+ time: `${pad(hour)}:${minute}:${second}${fraction}`,
+ zone,
+ };
+}
+
+function readDate(text) {
+ let match = /^(\d{4})-(\d{1,2})(?:-(\d{1,2}))?$/.exec(text);
+ if (match) return day(match[1], match[2], match[3]);
+ match = /^(\d{1,2})[/.-](\d{1,2})[/.-](\d{2,4})$/.exec(text);
+ if (match) return day(match[3], match[2], match[1]);
+ match = /^(\d{1,2})[/.-](\d{2,4})$/.exec(text);
+ if (match) return day(match[2], match[1]);
+ match = /^(\d{2,4})$/.exec(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);
+ let year = '';
+ let month = 0;
+ let dayOf = '';
+ for (const token of tokens) {
+ const word = MONTH_WORDS.get(token);
+ 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, '');
+ else return fail(HELP);
+ }
+ if (!year || !month) return fail(HELP);
+ return day(year, String(month), dayOf || undefined);
+}
+
+function day(year, month, dayOf) {
+ if (year.length !== 4) return fail('Write the year in full, like 2025.');
+ const precision = dayOf ? 'day' : month ? 'month' : 'year';
+ const date = [year, month && pad(month), dayOf && pad(dayOf)].filter(Boolean).join('-');
+ return { date, precision };
+}
+
+function write(part) {
+ if (part.time) return `${part.date}T${part.time}${part.zone}`;
+ const marker = part.approx && part.unsure ? '%' : part.approx ? '~' : part.unsure ? '?' : '';
+ return `${part.date}${marker}`;
+}
diff --git a/frontend/src/lib/looseDate.test.js b/frontend/src/lib/looseDate.test.js
new file mode 100644
index 0000000..d088f08
--- /dev/null
+++ b/frontend/src/lib/looseDate.test.js
@@ -0,0 +1,177 @@
+import { describe, expect, it } from 'vitest';
+import {
+ composeLooseDate,
+ decomposeLooseDate,
+ friendlyDate,
+ parseLooseDate,
+} from './looseDate.js';
+import { TEMPORAL_SYNTAX } from './temporalInput.js';
+import { validateTemporalValue } from './timeline.js';
+
+const read = (text) => parseLooseDate(text).value;
+
+// Everything the old three-list editor could write, and every example the
+// stored profile documents: the one field must keep each of them exactly.
+const STORED = [
+ '2025', '2025~', '2025?', '2025%',
+ '2025-10', '2025-10~', '2025-10?', '2025-10%',
+ '2025-10-24', '2025-10-24~', '2025-10-24?', '2025-10-24%',
+ '2025-10-24T14:30:00', '2025-10-24T14:30:05', '2025-10-24T14:30:00Z',
+ '2025-10-24T14:30:00+02:00', '2025-10-24T14:30:00-05:30', '2025-10-24T14:30:00.123Z',
+ '2025-10-24T14:30:05.250000+01:00',
+ '2025-10-24/2025-10-26', '2025-10~/2025-12?', '2025/2026%',
+ '2025-10-24T10:00:00Z/2025-10-24T12:30:00Z',
+ '2025-10-24T10:00:00+02:00/2025-10-25T09:00:00+02:00',
+ '0001', '9998-12-31',
+ ...TEMPORAL_SYNTAX.map((row) => row.example),
+];
+
+describe('a stored value', () => {
+ it('is kept exactly as typed', () => {
+ for (const value of STORED) {
+ expect(validateTemporalValue(value).valid, value).toBe(true);
+ expect(read(value), value).toBe(value);
+ }
+ });
+
+ it('is written back in a form that reads as the same value', () => {
+ for (const value of STORED) {
+ const shown = friendlyDate(value);
+ expect(read(shown), `${value} shown as ${shown}`).toBe(value);
+ }
+ });
+
+ it('is shown day-first, the way it was asked for', () => {
+ expect(friendlyDate('2025-10-24')).toBe('24/10/2025');
+ expect(friendlyDate('2025-10')).toBe('Oct 2025');
+ expect(friendlyDate('2025')).toBe('2025');
+ expect(friendlyDate('2025-10-24~')).toBe('~24/10/2025');
+ expect(friendlyDate('2025-10-24?')).toBe('24/10/2025?');
+ expect(friendlyDate('2025-10-24%')).toBe('~24/10/2025?');
+ expect(friendlyDate('2025-10-24T14:30:00Z')).toBe('24/10/2025 14:30 UTC');
+ expect(friendlyDate('2025-10-24T14:30:05+02:00')).toBe('24/10/2025 14:30:05 +02:00');
+ expect(friendlyDate('2025-10-24T14:30:00')).toBe('24/10/2025 14:30');
+ expect(friendlyDate('2025-10-24/2025-10-26')).toBe('24/10/2025 to 26/10/2025');
+ });
+
+ it('is left alone when it is not one, so the save still refuses it', () => {
+ expect(friendlyDate('last tuesday')).toBe('last tuesday');
+ expect(friendlyDate('')).toBe('');
+ });
+});
+
+describe('what an analyst types', () => {
+ it('reads a day, day first, whatever the separator', () => {
+ for (const text of ['24/10/2025', '24.10.2025', '24-10-2025', '24/10/2025 ', '2025-10-24']) {
+ expect(read(text), text).toBe('2025-10-24');
+ }
+ expect(read('1/2/2025')).toBe('2025-02-01');
+ });
+
+ it('reads a month and a year', () => {
+ expect(read('10/2025')).toBe('2025-10');
+ expect(read('Oct 2025')).toBe('2025-10');
+ expect(read('october 2025')).toBe('2025-10');
+ expect(read('octobre 2025')).toBe('2025-10');
+ expect(read('août 2025')).toBe('2025-08');
+ expect(read('2025')).toBe('2025');
+ });
+
+ it('reads a day written in words, in either order', () => {
+ expect(read('24 Oct 2025')).toBe('2025-10-24');
+ expect(read('Oct 24, 2025')).toBe('2025-10-24');
+ expect(read('24th October 2025')).toBe('2025-10-24');
+ expect(read('1er décembre 2025')).toBe('2025-12-01');
+ });
+
+ it('reads how sure the analyst is', () => {
+ expect(read('~24/10/2025')).toBe('2025-10-24~');
+ expect(read('about Oct 2025')).toBe('2025-10~');
+ expect(read('circa 2025')).toBe('2025~');
+ expect(read('24/10/2025?')).toBe('2025-10-24?');
+ expect(read('~Oct 2025?')).toBe('2025-10%');
+ });
+
+ it('reads a time, local unless a zone follows it', () => {
+ expect(read('24/10/2025 14:30')).toBe('2025-10-24T14:30:00');
+ expect(read('24/10/2025 14h30')).toBe('2025-10-24T14:30:00');
+ expect(read('24/10/2025 14:30 UTC')).toBe('2025-10-24T14:30:00Z');
+ expect(read('24/10/2025 14:30Z')).toBe('2025-10-24T14:30:00Z');
+ expect(read('24/10/2025 14:30 +02:00')).toBe('2025-10-24T14:30:00+02:00');
+ expect(read('24/10/2025 14:30 UTC+2')).toBe('2025-10-24T14:30:00+02:00');
+ expect(read('24/10/2025 14:30 -0530')).toBe('2025-10-24T14:30:00-05:30');
+ expect(read('2025-10-24T14:30')).toBe('2025-10-24T14:30:00');
+ expect(read('24 Oct 2025 09:05:07')).toBe('2025-10-24T09:05:07');
+ });
+
+ it('reads two dates as a range', () => {
+ expect(read('24/10/2025 to 26/10/2025')).toBe('2025-10-24/2025-10-26');
+ expect(read('Oct 2025 - Dec 2025')).toBe('2025-10/2025-12');
+ expect(read('between 2024 and 2025')).toBe('2024/2025');
+ expect(read('~Oct 2025 to Dec 2025?')).toBe('2025-10~/2025-12?');
+ expect(read('24/10/2025 10:00 to 12:30 UTC')).toBe('2025-10-24T10:00:00Z/2025-10-24T12:30:00Z');
+ });
+
+ it('never reads the minus of an offset as a range', () => {
+ expect(read('24/10/2025 14:30 -05:00')).toBe('2025-10-24T14:30:00-05:00');
+ });
+});
+
+describe('what cannot be read', () => {
+ const error = (text) => parseLooseDate(text).error;
+
+ it('says why, and stores nothing in its place', () => {
+ expect(parseLooseDate('last tuesday').value).toBeNull();
+ expect(error('last tuesday')).toMatch(/Try 24\/10\/2025/);
+ expect(error('31/02/2025')).toBe('That date does not exist.');
+ expect(error('24/10/25')).toBe('Write the year in full, like 2025.');
+ expect(error('~24/10/2025 14:30')).toMatch(/cannot be marked/);
+ expect(error('Oct 2025 14:30')).toMatch(/full day/);
+ expect(error('14:30')).toMatch(/day this time/);
+ expect(error('26/10/2025 to 24/10/2025')).toBe('The end must come after the start.');
+ expect(error('24/10/2025 10:00 to 24/10/2025 12:00')).toMatch(/timezones/);
+ });
+
+ it('reads an empty field as no date at all', () => {
+ expect(parseLooseDate(' ')).toEqual({ value: '', error: '' });
+ });
+});
+
+describe('a date built by pointing at it', () => {
+ it('writes the pieces the builder collects into the stored profile', () => {
+ expect(composeLooseDate({ start: '2025-10-24' })).toBe('2025-10-24');
+ expect(composeLooseDate({ start: '2025-10', approximate: true })).toBe('2025-10~');
+ expect(composeLooseDate({ start: '2025', uncertain: true })).toBe('2025?');
+ expect(composeLooseDate({ start: '2025-10-24', approximate: true, uncertain: true }))
+ .toBe('2025-10-24%');
+ // the marks describe how well the date is known, so both ends carry them
+ expect(composeLooseDate({ start: '2025-10', end: '2025-12', approximate: true }))
+ .toBe('2025-10~/2025-12~');
+ expect(composeLooseDate({ start: '' })).toBe('');
+ });
+
+ it('is read back the same way, so the builder opens on what is there', () => {
+ expect(decomposeLooseDate('2025-10-24%')).toEqual({
+ start: '2025-10-24', end: '', approximate: true, uncertain: true,
+ });
+ expect(decomposeLooseDate('2025-10~/2025-12~')).toEqual({
+ start: '2025-10', end: '2025-12', approximate: true, uncertain: false,
+ });
+ expect(decomposeLooseDate('')).toEqual({
+ start: '', end: '', approximate: false, uncertain: false,
+ });
+ });
+
+ it('refuses to draw what it cannot build, rather than dropping half of it', () => {
+ // an hour is typed: a builder of hours is the three-list form this replaced
+ expect(decomposeLooseDate('2025-10-24T14:30:00Z')).toBeNull();
+ expect(decomposeLooseDate('nonsense')).toBeNull();
+ });
+
+ it('round-trips through the field, whatever was built', () => {
+ for (const value of ['2025', '2025-10~', '2025-10-24%', '2025-10~/2025-12~']) {
+ expect(composeLooseDate(decomposeLooseDate(value))).toBe(value);
+ expect(parseLooseDate(friendlyDate(value)).value).toBe(value);
+ }
+ });
+});
diff --git a/frontend/src/lib/map/addedLayer.js b/frontend/src/lib/map/addedLayer.js
index 92ecbdc..192f96a 100644
--- a/frontend/src/lib/map/addedLayer.js
+++ b/frontend/src/lib/map/addedLayer.js
@@ -267,6 +267,21 @@ export function visibilityFilter(hidden = []) {
return ['!', ['in', ['get', 'category'], ['literal', [...hidden]]]];
}
+/**
+ * The row's time filter as a MapLibre filter, or null for every date.
+ *
+ * Days are `YYYY-MM-DD`, which sort as strings the way they sort as dates, so the
+ * comparison needs no parsing on the engine's side. A feature with no date is
+ * outside any period.
+ */
+export function periodFilter(period = null) {
+ if (!period?.start && !period?.end) return null;
+ const rule = ['all', ['has', 'date']];
+ if (period.start) rule.push(['>=', ['get', 'date'], period.start]);
+ if (period.end) rule.push(['<=', ['get', 'date'], period.end]);
+ return rule;
+}
+
/**
* @param {object} engine the façade from `engine.js`
* @param {object} [opts]
@@ -294,6 +309,7 @@ export function createAddedLayer(
let built = false;
let shown = true;
+ let filtered = ''; // the filter last applied, so the same one is not re-applied
let categories = [];
let collection = null; // what was last drawn, so a feature can be found by number
let open = null; // the read-only card, so it can be closed by name
@@ -512,7 +528,7 @@ export function createAddedLayer(
* Put a parsed collection on the map. Every feature, every time: the source
* is the whole layer and the engine culls what is off screen.
*/
- async set(data, { categories: groups = [], hidden = [], attribution } = {}) {
+ async set(data, { categories: groups = [], hidden = [], period = null, attribution } = {}) {
build(attribution);
categories = groups;
collection = data;
@@ -543,18 +559,26 @@ export function createAddedLayer(
const property = layer === MARK ? 'icon-color' : layer === FILL ? 'fill-color' : layer === DOT ? 'circle-color' : 'line-color';
map.setPaintProperty(layer, property, featureColour(colour));
}
- this.filter(hidden);
+ filtered = '';
+ this.filter(hidden, period);
},
/**
- * Hide exactly the categories named, and nothing else.
+ * Hide exactly the categories named and the days outside the period, and
+ * nothing else.
*
* A filter rather than a second source: the features stay loaded, so the row
- * can keep saying how many there are while saying how many are drawn.
+ * can keep saying how many there are while saying how many are drawn. The
+ * same filter twice is applied once, since a dragged time strip asks on every
+ * frame and a card opened on the map would otherwise close under it.
*/
- filter(hidden = []) {
+ filter(hidden = [], period = null) {
if (!built) return;
- const rule = visibilityFilter(hidden);
+ const key = JSON.stringify([hidden, period?.start ?? '', period?.end ?? '']);
+ if (key === filtered) return;
+ filtered = key;
+ const rules = [visibilityFilter(hidden), periodFilter(period)].filter(Boolean);
+ const rule = rules.length > 1 ? ['all', ...rules] : rules[0];
const base = {
[FILL]: ['==', ['geometry-type'], 'Polygon'],
[LINE]: ['!=', ['geometry-type'], 'Point'],
diff --git a/frontend/src/lib/map/addedLayer.test.js b/frontend/src/lib/map/addedLayer.test.js
index 66b965c..0436dbf 100644
--- a/frontend/src/lib/map/addedLayer.test.js
+++ b/frontend/src/lib/map/addedLayer.test.js
@@ -7,6 +7,7 @@ import {
featureExtent,
iconName,
kindOf,
+ periodFilter,
registerIcons,
visibilityFilter,
} from './addedLayer.js';
@@ -387,6 +388,43 @@ describe('an added layer on the map', () => {
expect(source.data.features).toHaveLength(2);
});
+ it('keeps to a period by comparing days, and leaves the undated out of it', async () => {
+ expect(periodFilter(null)).toBeNull();
+ expect(periodFilter({ start: '', end: '' })).toBeNull();
+ expect(periodFilter({ start: '2026-09-01', end: '' })).toEqual([
+ 'all',
+ ['has', 'date'],
+ ['>=', ['get', 'date'], '2026-09-01'],
+ ]);
+
+ const engine = stubEngine();
+ const layer = createAddedLayer(engine);
+ await layer.set(COLLECTION, { categories: CATEGORIES });
+ layer.filter(['Damage'], { start: '2026-09-01', end: '2026-09-18' });
+
+ for (const drawn of engine.map.layers.values()) {
+ const rule = JSON.stringify(drawn.filter);
+ expect(rule).toContain('Damage');
+ expect(rule).toContain('2026-09-18');
+ }
+ });
+
+ it('applies the same filter once, however often a dragged strip asks', async () => {
+ // a card opened on the map closes on every new filter, so an unchanged one
+ // must not count as new
+ const engine = stubEngine();
+ const layer = createAddedLayer(engine);
+ await layer.set(COLLECTION, { categories: CATEGORIES });
+ const setFilter = vi.spyOn(engine.map, 'setFilter');
+
+ layer.filter([], { start: '2026-09-01', end: '' });
+ const once = setFilter.mock.calls.length;
+ layer.filter([], { start: '2026-09-01', end: '' });
+
+ expect(once).toBeGreaterThan(0);
+ expect(setFilter.mock.calls.length).toBe(once);
+ });
+
it('puts the filter back when the category is switched on again', 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 8a8b4c3..90d28a3 100644
--- a/frontend/src/lib/map/addedLayers.js
+++ b/frontend/src/lib/map/addedLayers.js
@@ -16,6 +16,7 @@
*/
import { timeAgo } from '../analysisViews.js';
import { matchesTerms } from '../folderBrowse.js';
+import { inPeriod } from './layerDates.js';
/**
* Colours for a category whose source painted it nothing.
@@ -39,6 +40,16 @@ export const PALETTE = [
/** Past this a snapshot is old enough that the row says so before it redraws. */
export const FRESH_FOR_HOURS = 24;
+/**
+ * Whether a layer follows its source rather than holding a file: a pasted
+ * address, or a GeoConfirmed conflict. Those are re-read on Refresh and on case
+ * open, and go stale; a file does neither.
+ */
+export function followed(layer) {
+ const kind = layer?.source?.kind;
+ return kind === 'url' || kind === 'geoconfirmed';
+}
+
/**
* The colour a category is drawn in: what the source said, else the palette.
*
@@ -53,9 +64,11 @@ export function categoryColour(category, index) {
* own order of weight. `on` is what the eye beside it shows. */
export function legend(layer) {
const hidden = new Set(layer?.hidden ?? []);
+ // while a period is set, each group counts what the period leaves of it
+ const inPeriod = layer?.shownBy;
return (layer?.categories ?? []).map((category, index) => ({
name: category.name,
- count: category.count ?? 0,
+ count: inPeriod ? (inPeriod[category.name] ?? 0) : (category.count ?? 0),
kinds: category.kinds ?? [],
colour: categoryColour(category, index),
on: !hidden.has(category.name),
@@ -73,6 +86,8 @@ export function legend(layer) {
*/
export function counts(layer) {
const loaded = layer?.features ?? 0;
+ // a period set on the row, counted by the store from the features in hand
+ if (typeof layer?.shown === 'number') return { loaded, visible: layer.shown };
const hidden = new Set(layer?.hidden ?? []);
const dropped = (layer?.categories ?? [])
.filter((category) => hidden.has(category.name))
@@ -113,7 +128,7 @@ export function countLabel(layer) {
*/
export function freshness(layer, now = Date.now()) {
if (!layer) return '';
- if (layer.source?.kind !== 'url') {
+ if (!followed(layer)) {
const at = timeAgo(layer.fetched_at, now);
return at ? `opened ${at}` : '';
}
@@ -126,6 +141,9 @@ export function freshness(layer, now = Date.now()) {
/** Where a row came from, in the width a row has. */
export function sourceLabel(layer) {
const source = layer?.source ?? {};
+ if (source.kind === 'geoconfirmed') {
+ return source.area ? 'GeoConfirmed · limited area' : 'GeoConfirmed';
+ }
if (source.kind !== 'url') return source.name || 'a file on this computer';
if (source.my_maps) return 'Google My Maps';
try {
@@ -145,17 +163,19 @@ export function sourceLabel(layer) {
export function attribution(layer) {
const title = layer?.title || 'Added layer';
const source = layer?.source ?? {};
+ if (source.kind === 'geoconfirmed') return `${title} — geoconfirmed.org`;
if (source.my_maps) return `${title} — Google My Maps`;
if (source.kind === 'url') return `${title} — ${sourceLabel(layer)}`;
return `${title} — added by the analyst`;
}
-/** Which layers a case open should re-read: enabled, subscribed, and asked to. */
-export function refreshable(layers = []) {
- return layers.filter(
- (layer) =>
- layer.enabled && layer.source?.kind === 'url' && layer.refresh?.on_open !== false
- );
+/**
+ * Whether switching this layer on for the first time in a session re-reads it:
+ * a followed layer that did not ask to move only on Refresh. The spec still
+ * calls that `on_open`, from when it happened on case open.
+ */
+export function renewsOnShow(layer) {
+ return followed(layer) && layer?.refresh?.on_open !== false;
}
/** Which layers the map should actually be drawing. */
@@ -202,7 +222,7 @@ export const SEARCH_LIMIT = 25;
* search rather than scroll it.
*/
export function searchFeatures(collection, query, options = {}) {
- const { categories = [], hidden = [], limit = SEARCH_LIMIT } = options;
+ const { categories = [], hidden = [], period = null, limit = SEARCH_LIMIT } = options;
const terms = String(query ?? '').trim();
if (!terms) return { total: 0, results: [] };
@@ -228,9 +248,10 @@ export function searchFeatures(collection, query, options = {}) {
// The source's own colour where it painted one, its group's where it did
// not — the same rule the marks are drawn by (`addedLayer.js`).
colour: properties.colour || colours.get(category) || categoryColour(null, 0),
- // A match in a group the legend switched off: it is a real feature, it is
- // simply not on the map until that group comes back.
- hidden: off.has(category),
+ // A match in a group the legend switched off, or outside the period: it
+ // is a real feature, it is simply not on the map until that comes back.
+ hidden: off.has(category) || !inPeriod(properties.date, period),
+ outside: !inPeriod(properties.date, period),
});
});
return { total, results };
diff --git a/frontend/src/lib/map/addedLayers.test.js b/frontend/src/lib/map/addedLayers.test.js
index 1cec949..e9b0e8e 100644
--- a/frontend/src/lib/map/addedLayers.test.js
+++ b/frontend/src/lib/map/addedLayers.test.js
@@ -6,12 +6,13 @@ import {
countLabel,
counts,
drawable,
+ followed,
GROUP_SPACE,
freshness,
legend,
looksLikeUrl,
PALETTE,
- refreshable,
+ renewsOnShow,
searchFeatures,
SEARCH_LIMIT,
sourceLabel,
@@ -71,6 +72,36 @@ describe('the counter states both numbers', () => {
});
});
+describe('a period set on the row', () => {
+ it('is what the counter states, as the store counted it', () => {
+ expect(countLabel(layer({ shown: 212 }))).toBe(`3${GROUP_SPACE}200 features · 212 shown`);
+ });
+
+ it('is what each legend group counts', () => {
+ const rows = legend(layer({ shownBy: { Checkpoints: 40 } }));
+
+ expect(rows.map((row) => row.count)).toEqual([40, 0]);
+ });
+
+ it('marks a match outside it, which going to lets every date back in', () => {
+ const found = searchFeatures(
+ {
+ features: [
+ { properties: { name: 'Early gate', category: 'Checkpoints', date: '2026-08-01', index: 0 } },
+ { properties: { name: 'Late gate', category: 'Checkpoints', date: '2026-09-10', index: 1 } },
+ ],
+ },
+ 'gate',
+ { period: { start: '2026-09-01', end: '' } }
+ );
+
+ expect(found.results.map((hit) => [hit.name, hit.outside, hit.hidden])).toEqual([
+ ['Early gate', true, true],
+ ['Late gate', false, false],
+ ]);
+ });
+});
+
describe('the legend is the filter', () => {
it('is one row per category, with its colour and its count', () => {
expect(legend(layer())).toEqual([
@@ -151,28 +182,62 @@ describe('where a row says it came from', () => {
});
});
-describe('what the map draws and what a case open re-reads', () => {
+describe('a GeoConfirmed layer', () => {
+ const geoconfirmed = (source = {}) =>
+ layer({
+ title: 'GeoConfirmed · Ukraine · last 30 days',
+ source: { kind: 'geoconfirmed', url: 'https://geoconfirmed.org/map/ukraine', ...source },
+ });
+
+ it('is followed, like an address, and a file is not', () => {
+ expect(followed(geoconfirmed())).toBe(true);
+ expect(followed(layer({ source: { kind: 'url', url: 'https://x.test/a.kml' } }))).toBe(true);
+ expect(followed(layer())).toBe(false);
+ });
+
+ it('says when it was last read rather than when it was opened', () => {
+ expect(freshness(geoconfirmed(), NOW)).toBe('read 2 h ago');
+ });
+
+ it('names GeoConfirmed, and says when it keeps to one area', () => {
+ expect(sourceLabel(geoconfirmed())).toBe('GeoConfirmed');
+ expect(sourceLabel(geoconfirmed({ area: [30, 44, 40, 52] }))).toBe(
+ 'GeoConfirmed · limited area'
+ );
+ });
+
+ it('credits geoconfirmed.org on the map', () => {
+ expect(attribution(geoconfirmed())).toBe(
+ 'GeoConfirmed · Ukraine · last 30 days — geoconfirmed.org'
+ );
+ });
+
+ it('is re-read when first switched on, like any followed map', () => {
+ expect(renewsOnShow(geoconfirmed())).toBe(true);
+ });
+
+ it('is not when it holds the whole history, which asked to move only on Refresh', () => {
+ expect(renewsOnShow({ ...geoconfirmed(), refresh: { on_open: false } })).toBe(false);
+ });
+});
+
+describe('what the map draws and what switching on re-reads', () => {
it('draws the enabled layers and nothing else', () => {
const rows = [layer(), layer({ name: 'Off', enabled: false })];
expect(drawable(rows).map((row) => row.name)).toEqual(['Sightings']);
});
- it('re-reads only a subscription that is enabled and asked to be', () => {
- // the network boundary, stated as data: a file has nothing to read, a
- // disabled layer costs nothing, and a subscription can opt out
- const rows = [
- layer({ name: 'File' }),
- layer({ name: 'Off', enabled: false, source: { kind: 'url', url: 'https://x.test/1' } }),
- layer({
- name: 'Manual',
- source: { kind: 'url', url: 'https://x.test/2' },
- refresh: { on_open: false },
- }),
- layer({ name: 'Followed', source: { kind: 'url', url: 'https://x.test/3' } }),
- ];
-
- expect(refreshable(rows).map((row) => row.name)).toEqual(['Followed']);
+ it('re-reads only a subscription that did not opt out', () => {
+ // the network boundary, stated as data: a file has nothing to read, and a
+ // subscription can ask to move only when Refresh is pressed
+ expect(renewsOnShow(layer({ name: 'File' }))).toBe(false);
+ expect(
+ renewsOnShow(
+ layer({ source: { kind: 'url', url: 'https://x.test/2' }, refresh: { on_open: false } })
+ )
+ ).toBe(false);
+ expect(renewsOnShow(layer({ source: { kind: 'url', url: 'https://x.test/3' } }))).toBe(true);
});
});
diff --git a/frontend/src/lib/map/changeAssist.js b/frontend/src/lib/map/changeAssist.js
index 3fa2cc5..b59d32b 100644
--- a/frontend/src/lib/map/changeAssist.js
+++ b/frontend/src/lib/map/changeAssist.js
@@ -207,7 +207,10 @@ export function changeCompatibility(a, b) {
const releaseA = a.provider === 'esri-wayback' ? a.waybackRelease : 'current';
const releaseB = b.provider === 'esri-wayback' ? b.waybackRelease : 'current';
if (a.provider === b.provider && releaseA === releaseB) {
- return refuse('Choose two different Esri releases.');
+ // Not "Difference needs two Esri releases": it reads Sentinel-2 passes and
+ // VIIRS nights too, and a refusal that named one road sent analysts looking
+ // for a second Wayback release they did not need.
+ return refuse('Both sides show the same picture. Pick another Esri release, or two dated Sentinel-2 passes.');
}
if (!same(layerReading(a), layerReading(b))) {
return refuse('Match the reference layers on A and B before comparing pixels.');
diff --git a/frontend/src/lib/map/compareAnnotations.js b/frontend/src/lib/map/compareAnnotations.js
index 950ff93..c7828a4 100644
--- a/frontend/src/lib/map/compareAnnotations.js
+++ b/frontend/src/lib/map/compareAnnotations.js
@@ -13,6 +13,9 @@
*/
import { formatArea, formatDistance, haversine, polygonArea } from '../measure.js';
+import {
+ ICON_BOX, PROOF_ICONS, glyphInk, iconByName, iconOrigin, isSolidIcon,
+} from '../proofIcons.js';
export const ANNOTATION_COLOURS = Object.freeze([
'#f6a81a', '#22c55e', '#ef4444', '#38bdf8', '#e879f9', '#f4f5f6', '#111827',
@@ -29,12 +32,20 @@ export const ANNOTATION_TOOLS = Object.freeze([
{ id: 'line', icon: 'line', label: 'Line', shortcut: 'L', points: 2 },
{ id: 'freehand', icon: 'freehand', label: 'Freehand', shortcut: 'D', points: 'drag' },
{ id: 'text', icon: 'text', label: 'Note', shortcut: 'T', points: 1 },
+ // The two the Proof Maker stamps, on the ground instead of on a panel: one
+ // press each, and the tool stays in hand because numbering four things or
+ // marking six vehicles is one act rather than four or six.
+ { id: 'number', icon: 'numbered', label: 'Numbered marker', shortcut: 'N', points: 1, stamp: true },
+ { id: 'icon', icon: 'pin', label: 'Symbol', shortcut: 'S', points: 1, stamp: true },
]);
+/** The kinds stamped whole with one press, rather than dragged out. */
+export const STAMPED = new Set(ANNOTATION_TOOLS.filter((tool) => tool.stamp).map((tool) => tool.id));
+
const KINDS = new Set(ANNOTATION_TOOLS.filter((tool) => tool.points).map((tool) => tool.id));
const LIMITS = {
text: [1, 1], arrow: [2, 2], line: [2, 2], measure: [2, 2], rect: [2, 2], ellipse: [2, 2],
- freehand: [2, 400], polygon: [3, 200],
+ freehand: [2, 400], polygon: [3, 200], number: [1, 1], icon: [1, 1],
};
export const canFill = (kind) => kind === 'rect' || kind === 'ellipse' || kind === 'polygon';
@@ -75,6 +86,11 @@ export function comparisonAnnotations(value) {
fill_opacity: canFill(raw.kind) ? bounded(raw.fill_opacity, 0, 0, 1) : 0,
font_size: Math.round(bounded(raw.font_size, 16, 8, 72)),
text,
+ // What a stamp carries: its number, or the glyph it draws. A glyph this
+ // build does not know is drawn as the first one rather than as nothing,
+ // so a comparison made on a newer version still shows a mark there.
+ number: Math.round(bounded(raw.number, 1, 1, 999)),
+ glyph: iconByName(raw.glyph) ? String(raw.glyph) : PROOF_ICONS[0].name,
}];
});
}
@@ -82,6 +98,53 @@ export function comparisonAnnotations(value) {
/** Whether a mark is drawn on the picture of one side. */
export const onSide = (mark, letter) => mark.side === 'both' || mark.side === letter;
+/**
+ * How wide a stamped mark is drawn, in screen pixels.
+ *
+ * Its own size number, which is the one the rail's slider sets — a stamp has no
+ * stroke to widen and no ground extent to read, so the control that sizes a
+ * note's letters sizes these.
+ */
+export const markSize = (mark) => Math.max(12, Math.round((mark.font_size ?? 16) * 1.8));
+
+/** The ink a numeral takes over a disc of the mark's own colour: it has to be
+ * read over whatever the disc is standing on. */
+export const stampInk = (mark) => glyphInk(mark.colour, 1);
+
+/**
+ * Where a symbol's 24-unit box lands on screen, given the point it is pinned to.
+ *
+ * The glyph keeps the point it names rather than the corner it occupies, the way
+ * the Proof Maker's does, so a pin's tip is on the ground it was put on.
+ */
+export function glyphBox(mark, [x, y], scale = 1) {
+ const size = markSize(mark) * scale;
+ const origin = iconOrigin(markGlyph(mark).name, size);
+ return { x: x + origin.x, y: y + origin.y, size, scale: size / ICON_BOX };
+}
+
+/** The glyph a symbol draws, always one this build knows. */
+export const markGlyph = (mark) => iconByName(mark.glyph) ?? PROOF_ICONS[0];
+
+/**
+ * The first number no marker of this colour holds.
+ *
+ * Counted per colour, as the Proof Maker counts them: colour is what says "same
+ * feature" on both surfaces, so a second colour is a second series and starts
+ * back at 1. A gap left by a deleted marker is refilled.
+ */
+export function nextMarkNumber(marks, colour) {
+ const taken = new Set(
+ (marks ?? [])
+ .filter((mark) => mark.kind === 'number' && mark.colour === colour)
+ .map((mark) => Number(mark.number))
+ .filter(Number.isFinite)
+ );
+ let n = 1;
+ while (taken.has(n)) n += 1;
+ return n;
+}
+
const asLatLon = ([lon, lat]) => ({ lat, lon });
/** An ellipse inscribed in the ground box of two corners, as a ring of ground points. */
@@ -224,6 +287,52 @@ function drawPlate(ctx, text, x, y, { colour, fontSize, scale, centred }) {
});
}
+/**
+ * A stamped mark on a 2D context: a numbered disc, or a symbol in its box.
+ *
+ * Drawn from the same numbers the map's own SVG draws from, so what the export
+ * holds is what was on screen.
+ */
+function drawStamp(ctx, mark, [x, y], scale) {
+ const size = markSize(mark) * scale;
+ ctx.save();
+ ctx.shadowColor = 'rgba(0,0,0,.55)';
+ ctx.shadowBlur = 3 * scale;
+ if (mark.kind === 'number') {
+ const ink = stampInk(mark);
+ ctx.beginPath();
+ ctx.arc(x, y, size / 2, 0, Math.PI * 2);
+ ctx.fillStyle = mark.colour;
+ ctx.fill();
+ ctx.lineWidth = Math.max(1, size * 0.05);
+ ctx.strokeStyle = ink;
+ ctx.stroke();
+ ctx.shadowBlur = 0;
+ ctx.fillStyle = ink;
+ ctx.font = `700 ${Math.round(size * 0.58)}px system-ui, -apple-system, "Segoe UI", sans-serif`;
+ ctx.textAlign = 'center';
+ ctx.textBaseline = 'middle';
+ ctx.fillText(String(mark.number), x, y);
+ } else {
+ const entry = markGlyph(mark);
+ const box = glyphBox(mark, [x, y], scale);
+ ctx.translate(box.x, box.y);
+ ctx.scale(box.scale, box.scale);
+ const path = new Path2D(entry.path);
+ if (isSolidIcon(entry.name)) {
+ ctx.fillStyle = mark.colour;
+ ctx.fill(path, 'evenodd');
+ } else {
+ ctx.strokeStyle = mark.colour;
+ // the glyph is drawn scaled, so the width is divided back out: a bigger
+ // symbol is a bigger drawing, not a fatter outline
+ ctx.lineWidth = Math.max(1.5, mark.stroke_width * scale) / box.scale;
+ ctx.stroke(path);
+ }
+ }
+ ctx.restore();
+}
+
/**
* Burn marks into an exported picture. `project` maps `[lon, lat]` to that
* picture's pixels; `scale` is its pixels per CSS pixel, so strokes and labels
@@ -239,7 +348,9 @@ export function drawAnnotations(ctx, marks, project, { scale = 1, units = 'metri
const shape = projectMark(mark, project);
ctx.lineWidth = Math.max(1, mark.stroke_width * scale);
ctx.strokeStyle = mark.colour;
- if (mark.kind !== 'text') {
+ if (STAMPED.has(mark.kind)) {
+ drawStamp(ctx, mark, shape.anchor, scale);
+ } else if (mark.kind !== 'text') {
// a thin dark casing keeps a light stroke readable on bright ground
ctx.save();
ctx.shadowColor = 'rgba(0,0,0,.55)';
diff --git a/frontend/src/lib/map/compareAnnotations.test.js b/frontend/src/lib/map/compareAnnotations.test.js
index 5df701f..27d35ef 100644
--- a/frontend/src/lib/map/compareAnnotations.test.js
+++ b/frontend/src/lib/map/compareAnnotations.test.js
@@ -3,9 +3,13 @@ import {
comparisonAnnotations,
drawAnnotations,
ellipseRing,
+ glyphBox,
+ markGlyph,
markLabel,
markMetric,
+ markSize,
movedMark,
+ nextMarkNumber,
onSide,
projectMark,
} from './compareAnnotations.js';
@@ -25,6 +29,7 @@ describe('ground annotations', () => {
])).toEqual([{
id: 'm', kind: 'rect', side: 'both', colour: '#ff0000',
points: [[2, 48], [2.1, 48.1]], stroke_width: 3, fill_opacity: 1, font_size: 16, text: '',
+ number: 1, glyph: 'point',
}]);
});
@@ -82,3 +87,50 @@ describe('ground annotations', () => {
expect(ctx.fillText.mock.calls.map((call) => call[0])).toEqual(['1.11 km', 'Before']);
});
});
+
+describe('the two marks stamped on one point', () => {
+ const stamp = (extra) => mark({ kind: 'number', points: [[2, 48]], ...extra });
+
+ it('counts a series per colour, refilling the gaps a deletion leaves', () => {
+ const marks = [
+ stamp({ id: 'a', colour: '#ef4444', number: 1 }),
+ stamp({ id: 'b', colour: '#ef4444', number: 3 }),
+ stamp({ id: 'c', colour: '#22c55e', number: 1 }),
+ mark({ kind: 'rect', colour: '#ef4444', points: [[0, 0], [1, 1]] }),
+ ];
+ expect(nextMarkNumber(marks, '#ef4444')).toBe(2);
+ // a second colour is a second feature, so it starts over
+ expect(nextMarkNumber(marks, '#38bdf8')).toBe(1);
+ expect(nextMarkNumber([], '#ef4444')).toBe(1);
+ });
+
+ it('is sized by its own number, having no line to widen', () => {
+ expect(markSize({ font_size: 16 })).toBe(29);
+ expect(markSize({ font_size: 8 })).toBe(14);
+ });
+
+ it('hangs a symbol on the point it names rather than on a corner', () => {
+ const pin = { ...stamp({ kind: 'icon', glyph: 'point' }), font_size: 20 };
+ const box = glyphBox(pin, [100, 200]);
+ // the point glyph hangs from its tip, so the box sits above the ground point
+ expect(box.x).toBe(100 - box.size / 2);
+ expect(box.y).toBeLessThan(200);
+ expect(box.scale).toBeCloseTo(box.size / 24, 6);
+ // and a glyph this build does not know is still drawn as something
+ expect(markGlyph({ glyph: 'not-a-symbol' }).name).toBe('point');
+ });
+
+ it('burns a numbered disc into an export at the point it was stamped on', () => {
+ const ctx = {
+ save: vi.fn(), restore: vi.fn(), beginPath: vi.fn(), moveTo: vi.fn(), lineTo: vi.fn(),
+ closePath: vi.fn(), fill: vi.fn(), stroke: vi.fn(), arc: vi.fn(), arcTo: vi.fn(),
+ fillText: vi.fn(), translate: vi.fn(), scale: vi.fn(), setLineDash: vi.fn(),
+ measureText: (text) => ({ width: text.length * 7 }),
+ };
+ drawAnnotations(ctx, [stamp({ number: 4, font_size: 16 })],
+ ([lon, lat]) => [lon * 10, lat * 10], { scale: 2 });
+
+ expect(ctx.arc).toHaveBeenCalledWith(20, 480, 29, 0, Math.PI * 2);
+ expect(ctx.fillText).toHaveBeenCalledWith('4', 20, 480);
+ });
+});
diff --git a/frontend/src/lib/map/comparePair.js b/frontend/src/lib/map/comparePair.js
new file mode 100644
index 0000000..10e0714
--- /dev/null
+++ b/frontend/src/lib/map/comparePair.js
@@ -0,0 +1,116 @@
+/**
+ * Two dated views of one point, chosen where the analyst clicked.
+ *
+ * Compare's cold start was the reason: it opened on two empty panes, at the
+ * world view, and asked for a provider and a date for each side before it could
+ * show anything — while the analyst was already looking at the place they
+ * wanted compared. This answers "what did this point look like before?" from
+ * the map's own right-click menu: the app asks the archive which two pictures
+ * are the last two *of that point*, and hands Compare the pair.
+ *
+ * Two archives, because they answer different questions. Esri Wayback holds
+ * high-resolution pictures years apart, and a release only counts here when it
+ * actually changed this point. Copernicus holds a pass every few days at 10 m,
+ * which is what a fortnight-old change needs.
+ *
+ * Each side comes out in the shape a saved comparison stores, so the tool
+ * applies a handoff through the same `applySide` it applies a session with.
+ * Nothing is fetched until a row is pressed: both lookups are requests.
+ */
+import { WAYBACK_ID } from '../wayback.js';
+
+export const SENTINEL_ID = 'sentinel2';
+
+/** How far back a Copernicus lookup asks. A pass every few days, so half a
+ * year is generous even where cloud hides most of them. */
+export const SENTINEL_WINDOW_DAYS = 180;
+
+/** The sources a point can be compared across, in the order the menu lists them. */
+export const COMPARE_SOURCES = [
+ {
+ id: 'wayback',
+ label: 'Esri Wayback',
+ detail: 'the last two pictures of this point',
+ },
+ {
+ id: 'sentinel',
+ label: 'Copernicus',
+ detail: 'the last two passes over this point',
+ /** Only offered when Sentinel-2 is configured. */
+ provider: SENTINEL_ID,
+ },
+];
+
+const day = (date) => date.toISOString().slice(0, 10);
+
+/** `start` and `end` for a Copernicus lookup ending today. */
+export function sentinelWindow(today = new Date()) {
+ const start = new Date(today);
+ start.setUTCDate(start.getUTCDate() - SENTINEL_WINDOW_DAYS);
+ return { start: day(start), end: day(today) };
+}
+
+/**
+ * The two most recent Esri Wayback pictures of a point.
+ *
+ * `/wayback/changes` already answers with the distinct pictures, newest first,
+ * which is the narrowing the Wayback picker calls "only what changed here".
+ */
+export async function waybackPair(api, { lat, lon, zoom }) {
+ const answer = await api.get(
+ `/api/satellite/wayback/changes?lat=${lat}&lon=${lon}&zoom=${Math.max(1, Math.min(22, Math.round(zoom)))}`
+ );
+ const changes = answer?.changes ?? [];
+ if (changes.length < 2) {
+ throw new Error(
+ changes.length
+ ? 'Esri has published one picture of this point. There is nothing to compare it with.'
+ : 'Esri has no dated picture of this point.'
+ );
+ }
+ const [newer, older] = changes;
+ return {
+ title: 'Wayback · this point',
+ a: { provider: WAYBACK_ID, wayback_release: older.release, present: true },
+ b: { provider: WAYBACK_ID, wayback_release: newer.release, present: true },
+ dates: [older.acquired, newer.acquired],
+ };
+}
+
+/**
+ * The two most recent Copernicus passes over a point.
+ *
+ * Cloud is reported rather than acted on: a cloudy pass is still the pass that
+ * happened, and which two dates are worth comparing is the analyst's call.
+ */
+export async function sentinelPair(api, { lat, lon }, today = new Date()) {
+ const { start, end } = sentinelWindow(today);
+ const answer = await api.get(
+ `/api/satellite/sentinel/dates?lat=${lat}&lon=${lon}&start=${start}&end=${end}`
+ );
+ const dates = answer?.dates ?? [];
+ if (dates.length < 2) {
+ throw new Error(
+ `Copernicus has ${dates.length ? 'one pass' : 'no pass'} over this point in the last six months.`
+ );
+ }
+ const [newer, older] = dates;
+ const side = (entry) => ({
+ provider: SENTINEL_ID,
+ sentinel: { date: entry.date, layer: 'TRUE_COLOR', maxcc: 100 },
+ present: true,
+ });
+ return {
+ title: 'Copernicus · this point',
+ a: side(older),
+ b: side(newer),
+ dates: [older.date, newer.date],
+ };
+}
+
+/** The pair for one source id, at one point. */
+export function comparePair(api, source, at, today = new Date()) {
+ if (source === 'wayback') return waybackPair(api, at);
+ if (source === 'sentinel') return sentinelPair(api, at, today);
+ return Promise.reject(new Error(`unknown comparison source: ${source}`));
+}
diff --git a/frontend/src/lib/map/comparePair.test.js b/frontend/src/lib/map/comparePair.test.js
new file mode 100644
index 0000000..3236639
--- /dev/null
+++ b/frontend/src/lib/map/comparePair.test.js
@@ -0,0 +1,79 @@
+import { describe, expect, it, vi } from 'vitest';
+import { comparePair, sentinelPair, sentinelWindow, waybackPair } from './comparePair.js';
+
+const api = (answers) => ({
+ get: vi.fn(async (url) => {
+ for (const [fragment, answer] of Object.entries(answers)) {
+ if (url.includes(fragment)) return answer;
+ }
+ throw new Error(`unexpected request: ${url}`);
+ }),
+});
+
+describe('two pictures of one point', () => {
+ it('takes the last two Wayback releases that changed it, older as A', async () => {
+ const client = api({
+ '/wayback/changes': {
+ changes: [
+ { release: 55, acquired: '2025-02-20', source: 'Maxar' },
+ { release: 41, acquired: '2023-06-11', source: 'Maxar' },
+ { release: 12, acquired: '2019-01-02', source: 'Maxar' },
+ ],
+ },
+ });
+ const pair = await waybackPair(client, { lat: 33.2597, lon: -117.4365, zoom: 16.4 });
+ expect(client.get.mock.calls[0][0]).toContain('zoom=16');
+ expect(pair.a).toEqual({ provider: 'esri-wayback', wayback_release: 41, present: true });
+ expect(pair.b).toEqual({ provider: 'esri-wayback', wayback_release: 55, present: true });
+ expect(pair.dates).toEqual(['2023-06-11', '2025-02-20']);
+ });
+
+ it('says so when the archive holds nothing to compare', async () => {
+ await expect(
+ waybackPair(api({ '/wayback/changes': { changes: [{ release: 55, acquired: '2025-02-20' }] } }), {
+ lat: 1, lon: 2, zoom: 16,
+ })
+ ).rejects.toThrow(/one picture of this point/);
+ await expect(
+ waybackPair(api({ '/wayback/changes': { changes: [] } }), { lat: 1, lon: 2, zoom: 16 })
+ ).rejects.toThrow(/no dated picture/);
+ });
+
+ it('takes the last two Copernicus passes, older as A, cloud and all', async () => {
+ const client = api({
+ '/sentinel/dates': {
+ dates: [
+ { date: '2026-09-11', cloud: 62, granules: 1 },
+ { date: '2026-09-06', cloud: 4, granules: 2 },
+ ],
+ },
+ });
+ const pair = await sentinelPair(client, { lat: 33.2597, lon: -117.4365 }, new Date('2026-09-18T10:00:00Z'));
+ expect(client.get.mock.calls[0][0]).toContain('start=2026-03-22&end=2026-09-18');
+ expect(pair.a.sentinel.date).toBe('2026-09-06');
+ expect(pair.b.sentinel.date).toBe('2026-09-11');
+ expect(pair.a.provider).toBe('sentinel2');
+ expect(pair.a.sentinel.maxcc).toBe(100);
+ });
+
+ it('says so when six months hold fewer than two passes', async () => {
+ await expect(
+ sentinelPair(api({ '/sentinel/dates': { dates: [{ date: '2026-09-11' }] } }), { lat: 1, lon: 2 })
+ ).rejects.toThrow(/one pass over this point/);
+ });
+
+ it('asks the archive the choice named, and nothing else', async () => {
+ const client = api({ '/wayback/changes': { changes: [] } });
+ await expect(comparePair(client, 'nonsense', { lat: 1, lon: 2, zoom: 16 })).rejects.toThrow(/unknown/);
+ expect(client.get).not.toHaveBeenCalled();
+ });
+});
+
+describe('the Copernicus window', () => {
+ it('ends today and reaches half a year back', () => {
+ expect(sentinelWindow(new Date('2026-01-10T00:00:00Z'))).toEqual({
+ start: '2025-07-14',
+ end: '2026-01-10',
+ });
+ });
+});
diff --git a/frontend/src/lib/map/geoconfirmed.js b/frontend/src/lib/map/geoconfirmed.js
new file mode 100644
index 0000000..c0d18b9
--- /dev/null
+++ b/frontend/src/lib/map/geoconfirmed.js
@@ -0,0 +1,78 @@
+/**
+ * What the GeoConfirmed dialog asks the backend for (`engine/geoconfirmed.py`).
+ *
+ * A window of days counts back from each read, so a layer asked for the last
+ * 30 days is still that a month later; a range of dates stays where it was put;
+ * the whole history is every event the conflict has. The area is the map's view
+ * at the moment of adding, kept for every refresh.
+ */
+
+/** A span of the whole history, as a press. */
+export const ALL = 'all';
+/** …and of a range of dates, picked below the presses. */
+export const RANGE = 'range';
+
+/** The spans offered as one press each: a number of days, or the whole history. */
+export const WINDOWS = [
+ { span: 7, label: '7 days' },
+ { span: 30, label: '30 days' },
+ { span: 90, label: '90 days' },
+ { span: 365, label: 'A year' },
+ { span: ALL, label: 'All history' },
+];
+
+export const DEFAULT_SPAN = 30;
+
+/** The conflict the list opens on when it holds it: by far the busiest map. */
+export const DEFAULT_CONFLICT = 'Ukraine';
+
+/** Six decimals, about ten centimetres: finer says nothing about a view. */
+const round = (value) => Math.round(value * 1e6) / 1e6;
+
+/**
+ * The map's view as `[west, south, east, north]`, or null for one that is not a
+ * box GeoConfirmed can be asked about — a view across the antimeridian wraps, and
+ * its west comes out east of its east.
+ */
+export function areaOf(bounds) {
+ if (!bounds) return null;
+ const west = Math.max(-180, bounds.west);
+ const east = Math.min(180, bounds.east);
+ const south = Math.max(-90, bounds.south);
+ const north = Math.min(90, bounds.north);
+ if (![west, south, east, north].every(Number.isFinite)) return null;
+ if (!(west < east && south < north)) return null;
+ return [round(west), round(south), round(east), round(north)];
+}
+
+/**
+ * The body the backend is posted, or null while the form cannot be sent.
+ *
+ * @param {object} form
+ * @param {string} form.conflict the conflict's short name
+ * @param {number | 'all' | 'range'} form.span a number of days, `ALL` or `RANGE`
+ * @param {string} form.start the first day of a range, `YYYY-MM-DD`
+ * @param {string} form.end its last day, or '' for "until the day it is read"
+ * @param {boolean} form.limited whether to keep to the view
+ * @param {object | null} form.bounds the view, as `facade.viewBounds()` gives it
+ */
+export function layerRequest({ conflict, span, start, end, limited, bounds }) {
+ if (!conflict) return null;
+ const body = { conflict };
+ if (span === ALL) {
+ body.everything = true;
+ } else if (typeof span === 'number' && span > 0) {
+ body.days = span;
+ } else if (span === RANGE && start) {
+ body.start = start;
+ if (end) body.end = end;
+ } else {
+ return null;
+ }
+ if (limited) {
+ const area = areaOf(bounds);
+ if (!area) return null;
+ body.area = area;
+ }
+ return body;
+}
diff --git a/frontend/src/lib/map/geoconfirmed.test.js b/frontend/src/lib/map/geoconfirmed.test.js
new file mode 100644
index 0000000..c208fb9
--- /dev/null
+++ b/frontend/src/lib/map/geoconfirmed.test.js
@@ -0,0 +1,87 @@
+import { describe, expect, it } from 'vitest';
+import { ALL, areaOf, DEFAULT_SPAN, layerRequest, RANGE, WINDOWS } from './geoconfirmed.js';
+
+/**
+ * What the GeoConfirmed dialog posts. The backend checks all of it again
+ * (`engine/geoconfirmed.py`); this is what keeps the Add button honest about
+ * whether there is anything to send.
+ */
+
+const VIEW = { west: 30.1234567, south: 44, east: 40, north: 52 };
+
+describe('the windows on offer', () => {
+ it('open on thirty days, which is one of the presses', () => {
+ expect(WINDOWS.map((entry) => entry.span)).toContain(DEFAULT_SPAN);
+ });
+
+ it('end on the whole history', () => {
+ expect(WINDOWS.at(-1)).toEqual({ span: ALL, label: 'All history' });
+ });
+});
+
+describe('the area', () => {
+ it('is the view as west, south, east, north, to six decimals', () => {
+ expect(areaOf(VIEW)).toEqual([30.123457, 44, 40, 52]);
+ });
+
+ it('refuses a view across the antimeridian, whose west lands east of its east', () => {
+ expect(areaOf({ west: 170, south: 0, east: -170, north: 10 })).toBeNull();
+ });
+
+ it('holds a view wider than the world to the world', () => {
+ expect(areaOf({ west: -200, south: -95, east: 200, north: 95 })).toEqual([
+ -180, -90, 180, 90,
+ ]);
+ });
+
+ it('has nothing to say without a view', () => {
+ expect(areaOf(null)).toBeNull();
+ });
+});
+
+describe('the request', () => {
+ it('asks for a number of days', () => {
+ expect(layerRequest({ conflict: 'Ukraine', span: 30 })).toEqual({
+ conflict: 'Ukraine',
+ days: 30,
+ });
+ });
+
+ it('asks for the whole history with no dates at all', () => {
+ expect(layerRequest({ conflict: 'Ukraine', span: ALL, start: '2026-08-01' })).toEqual({
+ conflict: 'Ukraine',
+ everything: true,
+ });
+ });
+
+ it('asks for a range, with or without its last day', () => {
+ expect(layerRequest({ conflict: 'Iran', span: RANGE, start: '2026-08-01', end: '' })).toEqual(
+ { conflict: 'Iran', start: '2026-08-01' }
+ );
+ expect(
+ layerRequest({ conflict: 'Iran', span: RANGE, start: '2026-08-01', end: '2026-08-31' })
+ ).toEqual({ conflict: 'Iran', start: '2026-08-01', end: '2026-08-31' });
+ });
+
+ it('carries the view only when asked to keep to it', () => {
+ expect(layerRequest({ conflict: 'Ukraine', span: 7, limited: false, bounds: VIEW }).area).toBe(
+ undefined
+ );
+ expect(
+ layerRequest({ conflict: 'Ukraine', span: 7, limited: true, bounds: VIEW }).area
+ ).toEqual([30.123457, 44, 40, 52]);
+ });
+
+ it('has nothing to send without a conflict, a window, or a usable view', () => {
+ expect(layerRequest({ conflict: '', span: 7 })).toBeNull();
+ expect(layerRequest({ conflict: 'Ukraine', span: RANGE, start: '' })).toBeNull();
+ expect(
+ layerRequest({
+ conflict: 'Ukraine',
+ span: 7,
+ limited: true,
+ bounds: { west: 170, south: 0, east: -170, north: 10 },
+ })
+ ).toBeNull();
+ });
+});
diff --git a/frontend/src/lib/map/layerDates.js b/frontend/src/lib/map/layerDates.js
new file mode 100644
index 0000000..7cc3fdd
--- /dev/null
+++ b/frontend/src/lib/map/layerDates.js
@@ -0,0 +1,181 @@
+/**
+ * The arithmetic behind an added layer's time filter.
+ *
+ * A layer's features carry a day, `date: 'YYYY-MM-DD'`, when their source dated
+ * them (`engine/maplayers.py`): every GeoConfirmed event, a KML placemark with a
+ * TimeStamp, a GPX waypoint. The filter is a period, `{ start, end }`, either
+ * bound '' for open, compared as days on the map (`addedLayer.js`) and counted
+ * here.
+ *
+ * **Indexed once per snapshot, then asked cheaply.** A layer holds up to a
+ * hundred thousand features and the strip is redrawn on every drag, so the days
+ * are sorted once per group and every question after that — how many in this
+ * bar, how many in this period — is two binary searches per group.
+ */
+
+const DAY_MS = 86_400_000;
+
+/** A day as a number of days since 1970-01-01, or null for anything else. */
+export function dayNumber(iso) {
+ const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(String(iso ?? ''));
+ if (!match) return null;
+ const ms = Date.UTC(Number(match[1]), Number(match[2]) - 1, Number(match[3]));
+ return Number.isFinite(ms) ? Math.round(ms / DAY_MS) : null;
+}
+
+/** …and back. */
+export function isoDay(number) {
+ return new Date(number * DAY_MS).toISOString().slice(0, 10);
+}
+
+const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
+
+/** `12 Aug 2026`, the way GeoConfirmed and the rest of the row write a day. */
+export function dayLabel(iso) {
+ const number = dayNumber(iso);
+ if (number === null) return '';
+ const date = new Date(number * DAY_MS);
+ return `${date.getUTCDate()} ${MONTHS[date.getUTCMonth()]} ${date.getUTCFullYear()}`;
+}
+
+/**
+ * Every dated feature's day, sorted per group, or null for a layer with none.
+ *
+ * @param {{ features?: object[] } | null} collection
+ * @returns {{ first: number, last: number, groups: Map<string, Int32Array> } | null}
+ */
+export function indexDates(collection) {
+ const lists = new Map();
+ let first = Infinity;
+ let last = -Infinity;
+ for (const feature of collection?.features ?? []) {
+ const day = dayNumber(feature?.properties?.date);
+ if (day === null) continue;
+ const group = feature.properties.category ?? '';
+ if (!lists.has(group)) lists.set(group, []);
+ lists.get(group).push(day);
+ if (day < first) first = day;
+ if (day > last) last = day;
+ }
+ if (!lists.size) return null;
+ const groups = new Map();
+ for (const [group, days] of lists) groups.set(group, Int32Array.from(days).sort());
+ return { first, last, groups };
+}
+
+/** The first position in a sorted list holding a value at or past `value`. */
+function lowerBound(sorted, value) {
+ let low = 0;
+ let high = sorted.length;
+ while (low < high) {
+ const middle = (low + high) >> 1;
+ if (sorted[middle] < value) low = middle + 1;
+ else high = middle;
+ }
+ return low;
+}
+
+/** How many of a sorted list fall on days `from` to `to`, both included. */
+function between(sorted, from, to) {
+ return lowerBound(sorted, to + 1) - lowerBound(sorted, from);
+}
+
+/**
+ * The bars the strip is drawn in: a day each for up to three months, a week each
+ * for up to two years, a month each past that — so a strip holds between one and
+ * about a hundred bars whatever the layer spans.
+ *
+ * @returns {Array<{ from: number, to: number }>} days, both included
+ */
+export function bars(first, last) {
+ const span = last - first + 1;
+ if (span <= 92) return steps(first, last, 1);
+ if (span <= 731) return steps(first, last, 7);
+ const out = [];
+ const start = new Date(first * DAY_MS);
+ let year = start.getUTCFullYear();
+ let month = start.getUTCMonth();
+ for (;;) {
+ const from = Math.round(Date.UTC(year, month, 1) / DAY_MS);
+ const to = Math.round(Date.UTC(year, month + 1, 1) / DAY_MS) - 1;
+ if (from > last) break;
+ out.push({ from: Math.max(from, first), to: Math.min(to, last) });
+ month += 1;
+ if (month === 12) {
+ month = 0;
+ year += 1;
+ }
+ }
+ return out;
+}
+
+function steps(first, last, size) {
+ const out = [];
+ for (let from = first; from <= last; from += size) {
+ out.push({ from, to: Math.min(from + size - 1, last) });
+ }
+ return out;
+}
+
+/** How many features of the groups not switched off fall in each bar. */
+export function histogram(index, hidden = [], edges = []) {
+ if (!index) return edges.map(() => 0);
+ const off = new Set(hidden);
+ const lists = [...index.groups].filter(([group]) => !off.has(group)).map(([, days]) => days);
+ return edges.map(({ from, to }) =>
+ lists.reduce((total, days) => total + between(days, from, to), 0)
+ );
+}
+
+/** Whether a period narrows anything at all. */
+export function active(period) {
+ return Boolean(period?.start || period?.end);
+}
+
+/** A period as the days it spans, its open bounds filled with the layer's own. */
+export function span(period, index) {
+ const from = dayNumber(period?.start) ?? index?.first ?? -Infinity;
+ const to = dayNumber(period?.end) ?? index?.last ?? Infinity;
+ return { from, to };
+}
+
+/**
+ * How many dated features of the visible groups fall in the period, in all and
+ * per group — what the row's counter and the legend say while a period is set.
+ */
+export function within(index, hidden = [], period = null) {
+ const byGroup = {};
+ let total = 0;
+ if (!index) return { total, byGroup };
+ const off = new Set(hidden);
+ const { from, to } = span(period, index);
+ for (const [group, days] of index.groups) {
+ const count = between(days, from, to);
+ byGroup[group] = count;
+ if (!off.has(group)) total += count;
+ }
+ return { total, byGroup };
+}
+
+/** Whether one day is inside a period. An undated feature is outside any. */
+export function inPeriod(iso, period) {
+ if (!active(period)) return true;
+ const day = dayNumber(iso);
+ if (day === null) return false;
+ const from = dayNumber(period.start);
+ const to = dayNumber(period.end);
+ return (from === null || day >= from) && (to === null || day <= to);
+}
+
+/**
+ * Two days as the period the strip hands back: a bound sitting on the layer's
+ * own edge is left open, so a period dragged back out to both ends is no
+ * period at all rather than one that silently excludes whatever is added next.
+ */
+export function periodFrom(from, to, index) {
+ const low = Math.min(from, to);
+ const high = Math.max(from, to);
+ const start = index && low <= index.first ? '' : isoDay(low);
+ const end = index && high >= index.last ? '' : isoDay(high);
+ return start || end ? { start, end } : null;
+}
diff --git a/frontend/src/lib/map/layerDates.test.js b/frontend/src/lib/map/layerDates.test.js
new file mode 100644
index 0000000..361a6fa
--- /dev/null
+++ b/frontend/src/lib/map/layerDates.test.js
@@ -0,0 +1,148 @@
+import { describe, expect, it } from 'vitest';
+import {
+ active,
+ bars,
+ dayLabel,
+ dayNumber,
+ histogram,
+ indexDates,
+ inPeriod,
+ isoDay,
+ periodFrom,
+ within,
+} from './layerDates.js';
+
+/**
+ * The arithmetic under an added layer's time filter. What matters is that the
+ * strip, the counter and the map agree about which features a period holds.
+ */
+
+const at = (date, category = 'Russia') => ({
+ type: 'Feature',
+ geometry: { type: 'Point', coordinates: [37, 48] },
+ properties: { name: date, category, ...(date ? { date } : {}) },
+});
+
+const EVENTS = {
+ type: 'FeatureCollection',
+ features: [
+ at('2026-09-01'),
+ at('2026-09-01', 'Ukraine'),
+ at('2026-09-05'),
+ at('2026-09-10', 'Ukraine'),
+ at('2026-09-18'),
+ at(''), // an undated site
+ ],
+};
+
+describe('days', () => {
+ it('round-trip through the number the strip is laid out in', () => {
+ expect(isoDay(dayNumber('2026-09-18'))).toBe('2026-09-18');
+ expect(dayNumber('2026-09-19') - dayNumber('2026-09-18')).toBe(1);
+ });
+
+ it('refuse anything that is not a day', () => {
+ expect(dayNumber('')).toBeNull();
+ expect(dayNumber('Sept 18')).toBeNull();
+ expect(dayNumber(undefined)).toBeNull();
+ });
+
+ it('are written the way the row writes them, whatever the locale', () => {
+ expect(dayLabel('2026-08-12')).toBe('12 Aug 2026');
+ });
+});
+
+describe('the index', () => {
+ it('spans the first and last dated feature, and leaves the undated out', () => {
+ const index = indexDates(EVENTS);
+
+ expect(isoDay(index.first)).toBe('2026-09-01');
+ expect(isoDay(index.last)).toBe('2026-09-18');
+ expect([...index.groups.keys()].sort()).toEqual(['Russia', 'Ukraine']);
+ });
+
+ it('is nothing for a layer that dates nothing, so no strip is drawn', () => {
+ expect(indexDates({ features: [at('')] })).toBeNull();
+ expect(indexDates(null)).toBeNull();
+ });
+});
+
+describe('the bars', () => {
+ it('are days for a month, weeks for a year and months past two', () => {
+ expect(bars(dayNumber('2026-09-01'), dayNumber('2026-09-30'))).toHaveLength(30);
+ expect(bars(dayNumber('2025-09-19'), dayNumber('2026-09-18'))).toHaveLength(53);
+ expect(bars(dayNumber('2022-02-24'), dayNumber('2026-09-18'))).toHaveLength(56);
+ });
+
+ it('cover the span exactly, first day to last', () => {
+ const first = dayNumber('2022-02-24');
+ const last = dayNumber('2026-09-18');
+ const edges = bars(first, last);
+
+ expect(edges[0].from).toBe(first);
+ expect(edges.at(-1).to).toBe(last);
+ for (let i = 1; i < edges.length; i += 1) expect(edges[i].from).toBe(edges[i - 1].to + 1);
+ });
+
+ it('count the visible groups only', () => {
+ const index = indexDates(EVENTS);
+ const edges = bars(index.first, index.last);
+
+ expect(histogram(index, [], edges).reduce((a, b) => a + b, 0)).toBe(5);
+ expect(histogram(index, ['Ukraine'], edges).reduce((a, b) => a + b, 0)).toBe(3);
+ expect(histogram(index, [], edges)[0]).toBe(2); // two events on the first day
+ });
+});
+
+describe('a period', () => {
+ const index = indexDates(EVENTS);
+
+ it('counts what it holds, in all and per group', () => {
+ const counted = within(index, [], { start: '2026-09-02', end: '2026-09-10' });
+
+ expect(counted.total).toBe(2);
+ expect(counted.byGroup).toEqual({ Russia: 1, Ukraine: 1 });
+ });
+
+ it('includes both of its days', () => {
+ expect(within(index, [], { start: '2026-09-01', end: '2026-09-01' }).total).toBe(2);
+ });
+
+ it('runs to the layer’s own edge where a bound is open', () => {
+ expect(within(index, [], { start: '2026-09-05', end: '' }).total).toBe(3);
+ expect(within(index, [], { start: '', end: '2026-09-05' }).total).toBe(3);
+ });
+
+ it('leaves a hidden group out of the total and in its own count', () => {
+ const counted = within(index, ['Ukraine'], { start: '2026-09-01', end: '2026-09-30' });
+
+ expect(counted.total).toBe(3);
+ expect(counted.byGroup.Ukraine).toBe(2);
+ });
+
+ it('keeps an undated feature out, and keeps everything in when there is no period', () => {
+ expect(inPeriod('', { start: '2026-09-01', end: '' })).toBe(false);
+ expect(inPeriod('', null)).toBe(true);
+ expect(inPeriod('2026-09-05', { start: '2026-09-01', end: '2026-09-05' })).toBe(true);
+ expect(inPeriod('2026-09-06', { start: '2026-09-01', end: '2026-09-05' })).toBe(false);
+ });
+
+ it('dragged back out to both edges is no period at all', () => {
+ expect(periodFrom(index.first, index.last, index)).toBeNull();
+ expect(active(periodFrom(index.first, index.last, index))).toBe(false);
+ });
+
+ it('left on the last day stays open, so a refresh’s new events are in it', () => {
+ expect(periodFrom(dayNumber('2026-09-05'), index.last, index)).toEqual({
+ start: '2026-09-05',
+ end: '',
+ });
+ });
+
+ it('comes out the right way round whichever handle was dragged past the other', () => {
+ expect(periodFrom(dayNumber('2026-09-10'), dayNumber('2026-09-05'), index)).toEqual({
+ start: '2026-09-05',
+ end: '2026-09-10',
+ });
+ });
+});
diff --git a/frontend/src/lib/navigate.js b/frontend/src/lib/navigate.js
index f5259db..d64510c 100644
--- a/frontend/src/lib/navigate.js
+++ b/frontend/src/lib/navigate.js
@@ -8,6 +8,7 @@ import { caseState, toast, uiState } from './state.svelte.js';
import { mediaKindOf } from './entityIcon.js';
import { GUIDE, guideFor } from './guide.js';
import { revealMediaFolder } from './reveal.js';
+import { normalizeReverseTarget } from './reverseSearch.js';
/**
* A number an entity actually recorded, or NaN when it recorded nothing.
@@ -201,6 +202,25 @@ export function openGuide(tool) {
uiState.tool = 'guide';
}
+/**
+ * Hand a picture to Reverse Search and go there.
+ *
+ * The press is made where the picture is being looked at, so the tab opens on it
+ * rather than on an empty picker. `target` is a case file (`{ path, kind, label,
+ * time? }`) or a picture held only in memory (`{ blob, label }`); see
+ * `normalizeReverseTarget`. Returns whether the tab was changed.
+ */
+export function openInReverseSearch(target) {
+ const picture = normalizeReverseTarget(target);
+ if (!picture) {
+ toast('This picture cannot be searched', 'warn');
+ return false;
+ }
+ uiState.reverseTarget = picture;
+ uiState.tool = 'reverse';
+ return true;
+}
+
/** Fly the Satellite map to a capture's recorded coordinates (its marker). */
export function gotoCapture(entity) {
const lat = Number(entity.attrs?.lat);
diff --git a/frontend/src/lib/navigate.test.js b/frontend/src/lib/navigate.test.js
index 7aba06e..5f466a3 100644
--- a/frontend/src/lib/navigate.test.js
+++ b/frontend/src/lib/navigate.test.js
@@ -4,9 +4,8 @@ const post = vi.fn().mockResolvedValue({ path: '/cases/c1/azimut/media' });
vi.mock('./api.js', () => ({ api: { post: (...a) => post(...a), get: vi.fn() } }));
const { caseState, uiState } = await import('./state.svelte.js');
-const { gotoCapture, gotoPoint, openEntity, openGuide, opensInFileManager } = await import(
- './navigate.js'
-);
+const { gotoCapture, gotoPoint, openEntity, openGuide, openInReverseSearch, opensInFileManager } =
+ await import('./navigate.js');
beforeEach(() => {
uiState.tool = 'media';
@@ -14,6 +13,7 @@ beforeEach(() => {
uiState.focusCapture = null;
uiState.openBoardEntity = null;
uiState.openCompare = null;
+ uiState.reverseTarget = null;
post.mockClear();
caseState.current = { id: 'c1', name: 'Case', entities: [], links: [], folders: [] };
vi.stubGlobal('window', { open: vi.fn() });
@@ -34,6 +34,26 @@ describe('openGuide', () => {
});
});
+describe('openInReverseSearch', () => {
+ it('opens Reverse Search on the picture it was pressed from', () => {
+ expect(openInReverseSearch({ path: 'media/clip.mp4', kind: 'video', label: 'Clip', time: 3 })).toBe(true);
+ expect(uiState.tool).toBe('reverse');
+ expect(uiState.reverseTarget).toEqual({
+ path: 'media/clip.mp4',
+ blob: null,
+ kind: 'video',
+ label: 'Clip',
+ time: 3,
+ });
+ });
+
+ it('stays put, and queues nothing, for a picture it cannot hand over', () => {
+ expect(openInReverseSearch({ path: 'media/report.pdf', kind: 'file' })).toBe(false);
+ expect(uiState.tool).toBe('media');
+ expect(uiState.reverseTarget).toBeNull();
+ });
+});
+
describe('openEntity', () => {
it('opens bookmarks and external captures in a new browser tab', () => {
openEntity({ type: 'bookmark', attrs: { url: 'https://example.test/bookmark' } });
diff --git a/frontend/src/lib/overview.js b/frontend/src/lib/overview.js
index 72168fc..c4cc86f 100644
--- a/frontend/src/lib/overview.js
+++ b/frontend/src/lib/overview.js
@@ -69,7 +69,7 @@ export const WAITING = [
{
id: 'undated',
label: 'No date yet',
- hint: 'a statement the timeline has nowhere to put',
+ hint: 'a claim the timeline has nowhere to put',
icon: 'clock',
surface: 'timeline',
read: ({ timeline }) => timeline?.undated ?? 0,
diff --git a/frontend/src/lib/proofSurface.js b/frontend/src/lib/proofSurface.js
index cd9f22a..c8db8e9 100644
--- a/frontend/src/lib/proofSurface.js
+++ b/frontend/src/lib/proofSurface.js
@@ -96,3 +96,95 @@ export function shiftProofShape(shape, dx, dy) {
export function mapSurfaceShapes(shapes, surfaceId, edit) {
return (shapes ?? []).map((shape) => (shape.panel === surfaceId ? edit(shape) : shape));
}
+
+/**
+ * The upright rectangle that contains a `w`×`h` box placed at (x, y) and turned
+ * by `deg` about that corner.
+ */
+function uprightCover(x, y, w, h, deg) {
+ const radians = (Number(deg) || 0) * Math.PI / 180;
+ const cos = Math.cos(radians);
+ const sin = Math.sin(radians);
+ const xs = [];
+ const ys = [];
+ for (const [cx, cy] of [[0, 0], [w, 0], [w, h], [0, h]]) {
+ xs.push(x + cx * cos - cy * sin);
+ ys.push(y + cx * sin + cy * cos);
+ }
+ const left = Math.min(...xs);
+ const top = Math.min(...ys);
+ return { x: left, y: top, w: Math.max(...xs) - left, h: Math.max(...ys) - top };
+}
+
+/**
+ * The patch of a surface a blur box covers, in that surface's own drawn pixels
+ * and in the source's.
+ *
+ * A blur is not paint: it redraws the picture under the box through a filter, so
+ * the box has to name the source pixels it stands over. The surface's drawn space
+ * starts at the crop's top-left, so a box at (x, y) there is at (crop.x + x,
+ * crop.y + y) in the file.
+ *
+ * Clamped to the picture, because a box dragged half off the panel would
+ * otherwise ask for pixels the file does not have — and a crop past the edge is
+ * drawn as whatever happens to be in memory. What comes back is the part that
+ * overlaps, positioned relative to the box itself, or null when none of it does.
+ *
+ * `margin` widens the patch that is *read* without widening what is drawn: a
+ * blur mixes in what surrounds each pixel, so a patch cut exactly to the box
+ * mixes in the transparency past its own edge and comes out washed out at the
+ * border — the one place a redaction has to hold. The caller clips the box back
+ * to size, so the margin is context for the filter and nothing else.
+ *
+ * A turned box (`rect.rotation`) reads the upright rectangle that contains it and
+ * hands back the `turn` that puts the patch level with the picture again: the
+ * pixels have to come from the ground the box stands on, and the ground does not
+ * turn with it. `dx`/`dy` are always in the box's own space, so the caller seats
+ * the patch inside the box and lets the clip do the rest.
+ */
+export function blurPatch(rect, natural, crop, margin = 0) {
+ const [width, height] = surfaceImageSize(natural, crop);
+ const kept = normalizeSourceCrop(crop, sourceSize(natural));
+ const turn = normalizeSurfaceAngle(rect?.rotation);
+ const left = Number(rect?.x) || 0;
+ const top = Number(rect?.y) || 0;
+ const cover = uprightCover(left, top, Number(rect?.w) || 0, Number(rect?.h) || 0, turn);
+ const x = clamp(cover.x, 0, width);
+ const y = clamp(cover.y, 0, height);
+ const right = clamp(cover.x + cover.w, 0, width);
+ const bottom = clamp(cover.y + cover.h, 0, height);
+ if (right - x < 1 || bottom - y < 1) return null;
+ const pad = Math.max(0, Math.round(Number(margin) || 0));
+ const ex = clamp(x - pad, 0, width);
+ const ey = clamp(y - pad, 0, height);
+ const ew = clamp(right + pad, 0, width) - ex;
+ const eh = clamp(bottom + pad, 0, height) - ey;
+ // where the patch sits inside the box, so the node can be a child of it
+ const radians = turn * Math.PI / 180;
+ const cos = Math.cos(radians);
+ const sin = Math.sin(radians);
+ const offX = ex - left;
+ const offY = ey - top;
+ return {
+ dx: offX * cos + offY * sin,
+ dy: offY * cos - offX * sin,
+ turn: -turn || 0,
+ w: ew,
+ h: eh,
+ crop: { x: (kept?.x ?? 0) + ex, y: (kept?.y ?? 0) + ey, width: ew, height: eh },
+ };
+}
+
+/**
+ * How hard a blur box blurs, in the surface's own pixels.
+ *
+ * Proportional to the box, so a licence plate and a whole street get a blur of
+ * the same strength *relative to what they hide*; a fixed radius either leaves a
+ * small box legible or costs a fortune on a large one. The floor is what makes
+ * a thumbnail-sized box unreadable; the ceiling is where Konva's own blur stops
+ * improving.
+ */
+export function blurRadiusFor(rect) {
+ const side = Math.min(Math.abs(Number(rect?.w) || 0), Math.abs(Number(rect?.h) || 0));
+ return clamp(Math.round(side / 5), 6, 80);
+}
diff --git a/frontend/src/lib/proofSurface.test.js b/frontend/src/lib/proofSurface.test.js
index a4620a9..2897f29 100644
--- a/frontend/src/lib/proofSurface.test.js
+++ b/frontend/src/lib/proofSurface.test.js
@@ -1,5 +1,7 @@
import { describe, expect, it } from 'vitest';
import {
+ blurPatch,
+ blurRadiusFor,
mapSurfaceShapes,
normalizeSourceCrop,
normalizeSurfaceAngle,
@@ -74,3 +76,59 @@ describe('annotations follow their surface', () => {
expect(result[1]).toBe(other);
});
});
+
+describe('a blur box over a surface', () => {
+ it('names the source pixels under it, through the surface\'s own crop', () => {
+ expect(blurPatch({ x: 10, y: 20, w: 50, h: 40 }, [800, 600], null)).toEqual({
+ dx: 0, dy: 0, turn: 0, w: 50, h: 40, crop: { x: 10, y: 20, width: 50, height: 40 },
+ });
+ // the drawn space starts at the crop, so the file's pixels are offset by it
+ expect(blurPatch({ x: 10, y: 20, w: 50, h: 40 }, [800, 600], { x: 100, y: 60, w: 400, h: 300 })).toEqual({
+ dx: 0, dy: 0, turn: 0, w: 50, h: 40, crop: { x: 110, y: 80, width: 50, height: 40 },
+ });
+ });
+
+ it('keeps only the part that overlaps the picture', () => {
+ // half off the left edge: the box still draws, the patch starts at 0
+ expect(blurPatch({ x: -20, y: 10, w: 50, h: 40 }, [800, 600], null)).toEqual({
+ dx: 20, dy: 0, turn: 0, w: 30, h: 40, crop: { x: 0, y: 10, width: 30, height: 40 },
+ });
+ // past the bottom-right: clipped to the picture
+ expect(blurPatch({ x: 780, y: 580, w: 60, h: 60 }, [800, 600], null)).toMatchObject({
+ w: 20, h: 20, crop: { x: 780, y: 580, width: 20, height: 20 },
+ });
+ // wholly outside: nothing to blur
+ expect(blurPatch({ x: 900, y: 10, w: 50, h: 40 }, [800, 600], null)).toBeNull();
+ });
+
+ it('reads a margin of ground around the box without drawing one', () => {
+ // the filter needs real pixels past the edge, or the border comes out washed
+ // out — the one place a redaction has to hold
+ expect(blurPatch({ x: 100, y: 100, w: 50, h: 40 }, [800, 600], null, 10)).toEqual({
+ dx: -10, dy: -10, turn: 0, w: 70, h: 60, crop: { x: 90, y: 90, width: 70, height: 60 },
+ });
+ // at the picture's edge there is no margin to take, and the patch stops there
+ expect(blurPatch({ x: 0, y: 0, w: 50, h: 40 }, [800, 600], null, 10)).toEqual({
+ dx: 0, dy: 0, turn: 0, w: 60, h: 50, crop: { x: 0, y: 0, width: 60, height: 50 },
+ });
+ });
+
+ it('reads a turned box off the ground it stands on, not off a turned picture', () => {
+ // 40×20 turned a quarter turn: it covers 20×40 of upright picture, reaching
+ // left of its own origin, and the patch is turned back level inside the box
+ const patch = blurPatch({ x: 100, y: 100, w: 40, h: 20, rotation: 90 }, [800, 600], null);
+
+ expect(patch).toMatchObject({
+ w: 20, h: 40, turn: -90, crop: { x: 80, y: 100, width: 20, height: 40 },
+ });
+ // where it sits inside the box, in the box's own turned space
+ expect(patch.dx).toBeCloseTo(0, 6);
+ expect(patch.dy).toBeCloseTo(20, 6);
+ });
+
+ it('blurs in proportion to what it hides, between a floor and a ceiling', () => {
+ expect(blurRadiusFor({ w: 200, h: 100 })).toBe(20);
+ expect(blurRadiusFor({ w: 10, h: 10 })).toBe(6);
+ expect(blurRadiusFor({ w: 4000, h: 3000 })).toBe(80);
+ });
+});
diff --git a/frontend/src/lib/quickClaim.js b/frontend/src/lib/quickClaim.js
new file mode 100644
index 0000000..4a058c0
--- /dev/null
+++ b/frontend/src/lib/quickClaim.js
@@ -0,0 +1,90 @@
+/**
+ * A Claim filed from the entity it is about — the pure half of `QuickClaim.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,
+ * `cites` the material. Starting from any one of those, the entity already has a
+ * seat on it, and the form only asks for the rest.
+ */
+
+/**
+ * The connectors an entity can take a seat on, most specific first.
+ *
+ * A place can be what a statement is `about` as well as where it happened, and a
+ * video can be its subject as well as its evidence. Filed from the place or the
+ * video, the everyday reading is the second one — *seen here*, *seen in this* — so
+ * `at` and `cites` are tried before `about`.
+ */
+export const SEAT_ORDER = ['at', 'cites', 'about'];
+
+/**
+ * Where an entity goes on a Claim filed from it, and which of the statement's own
+ * fields are worth asking for. Null when the vocabulary gives it no seat at all,
+ * as for a post or a saved session.
+ *
+ * `accepts(verb)` answers from the relation registry, so the seat follows the verb
+ * table rather than a second copy of it. The fields follow the family: a count is
+ * of a model (`class`) and never of one named object, which is one; a condition is
+ * a state a model's instances or a named object can be in.
+ */
+export function quickClaimSeat(family, accepts) {
+ const slot = SEAT_ORDER.find((verb) => accepts(verb)) ?? null;
+ if (!slot) return null;
+ return {
+ slot,
+ count: family === 'class',
+ condition: family === 'class' || family === 'asset',
+ };
+}
+
+/** What the press files, said from where it is pressed: a tooltip per seat. */
+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',
+ }[slot] ?? ''
+ );
+}
+
+const names = (list) => list.map((entry) => String(entry ?? '').trim()).filter(Boolean).join(', ');
+
+/**
+ * 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.
+ */
+export function composeClaimStatement({ count = null, condition = '', subjects = [], places = [] }) {
+ const subject = names(subjects);
+ const place = names(places);
+ const state = String(condition ?? '').trim().toLowerCase();
+ if (!subject) return place ? `Seen at ${place}` : '';
+ const counted = Number.isInteger(count) && count > 0 ? `${count} × ${subject}` : subject;
+ return `${counted} ${state || 'seen'}${place ? ` at ${place}` : ''}`;
+}
+
+/**
+ * The request body the Timeline's claim route takes, from the form's state.
+ *
+ * A date filed with a *seen* statement is when it was seen, so it carries the
+ * `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 }) {
+ const whole = Number(count);
+ return {
+ statement: String(statement ?? '').trim(),
+ when: when || null,
+ time_role: when ? 'observed' : null,
+ confidence: confidence || null,
+ count: seat?.count && Number.isInteger(whole) && whole > 0 ? whole : null,
+ condition: seat?.condition && condition ? condition : null,
+ about: [...new Set(about)],
+ at: [...new Set(at)],
+ cites: [...new Set(cites)],
+ };
+}
diff --git a/frontend/src/lib/quickClaim.test.js b/frontend/src/lib/quickClaim.test.js
new file mode 100644
index 0000000..89660e0
--- /dev/null
+++ b/frontend/src/lib/quickClaim.test.js
@@ -0,0 +1,136 @@
+import { describe, expect, it } from 'vitest';
+import { claimActionTitle, composeClaimStatement, quickClaimBody, quickClaimSeat } from './quickClaim.js';
+
+// What the relation registry answers for a Claim's three connectors, per type,
+// as `engine/links.py` declares them.
+const ACCEPTS = {
+ 'equipment-type': ['about'],
+ vehicle: ['about'],
+ person: ['about'],
+ account: ['about'],
+ place: ['about', 'at'],
+ media: ['about', 'cites'],
+ proof: ['cites'],
+ claim: ['cites'],
+ post: [],
+};
+const seatOf = (type, family) => quickClaimSeat(family, (verb) => ACCEPTS[type].includes(verb));
+
+describe('quickClaimSeat', () => {
+ it('puts a model on what the claim is about, and asks how many and in what state', () => {
+ expect(seatOf('equipment-type', 'class')).toEqual({ slot: 'about', count: true, condition: true });
+ });
+
+ it('asks a named object for its state, never for a count', () => {
+ expect(seatOf('vehicle', 'asset')).toEqual({ slot: 'about', count: false, condition: true });
+ });
+
+ it('asks a person or an account for neither', () => {
+ expect(seatOf('person', 'actor')).toEqual({ slot: 'about', count: false, condition: false });
+ expect(seatOf('account', 'identifier')).toEqual({ slot: 'about', count: false, condition: false });
+ });
+
+ it('seats a place where the thing was seen, not as what it is about', () => {
+ expect(seatOf('place', 'place').slot).toBe('at');
+ });
+
+ it('seats material as the evidence, not as the subject', () => {
+ expect(seatOf('media', 'collected').slot).toBe('cites');
+ expect(seatOf('proof', 'document').slot).toBe('cites');
+ expect(seatOf('claim', 'claim').slot).toBe('cites');
+ });
+
+ it('gives no seat where the vocabulary has none', () => {
+ expect(seatOf('post', 'document')).toBeNull();
+ });
+});
+
+describe('composeClaimStatement', () => {
+ it('reads the filed observation as one sentence', () => {
+ expect(
+ composeClaimStatement({ count: 2, condition: 'Destroyed', subjects: ['T-72B3'], places: ['Crossroads'] })
+ ).toBe('2 × T-72B3 destroyed at Crossroads');
+ });
+
+ it('says seen when no state was given, and leaves out what was not counted', () => {
+ expect(composeClaimStatement({ subjects: ['T-72B3'] })).toBe('T-72B3 seen');
+ expect(composeClaimStatement({ count: 3, subjects: ['T-72B3'] })).toBe('3 × T-72B3 seen');
+ expect(composeClaimStatement({ count: 0, subjects: ['T-72B3'] })).toBe('T-72B3 seen');
+ expect(composeClaimStatement({ condition: 'damaged', subjects: ['Bridge 4'] })).toBe('Bridge 4 damaged');
+ });
+
+ it('starts from the place when that is all there is', () => {
+ expect(composeClaimStatement({ places: ['Crossroads'] })).toBe('Seen at Crossroads');
+ });
+
+ it('names several of each', () => {
+ expect(composeClaimStatement({ subjects: ['A', 'B'], places: ['X', ' '] })).toBe('A, B seen at X');
+ });
+
+ it('offers nothing with nothing to say', () => {
+ expect(composeClaimStatement({})).toBe('');
+ expect(composeClaimStatement({ count: 2, condition: 'destroyed' })).toBe('');
+ });
+});
+
+describe('quickClaimBody', () => {
+ const seat = { slot: 'about', count: true, condition: true };
+
+ it('files the observation in the shape the claim route takes', () => {
+ expect(
+ quickClaimBody({
+ statement: ' 2 × T-72B3 destroyed at Crossroads ',
+ when: '2026-08~',
+ confidence: 'probable',
+ count: '2',
+ condition: 'destroyed',
+ about: ['model', 'model'],
+ at: ['crossroads'],
+ cites: ['video'],
+ seat,
+ })
+ ).toEqual({
+ statement: '2 × T-72B3 destroyed at Crossroads',
+ when: '2026-08~',
+ time_role: 'observed',
+ confidence: 'probable',
+ count: 2,
+ condition: 'destroyed',
+ about: ['model'],
+ at: ['crossroads'],
+ cites: ['video'],
+ });
+ });
+
+ it('states no role without a date, and no count that is not a whole number', () => {
+ const body = quickClaimBody({ statement: 'x', count: '1.5', about: [], at: [], cites: [], seat });
+ expect(body.when).toBeNull();
+ expect(body.time_role).toBeNull();
+ expect(body.count).toBeNull();
+ expect(body.condition).toBeNull();
+ expect(body.confidence).toBeNull();
+ });
+
+ it('sends no count or condition the form did not ask for', () => {
+ const body = quickClaimBody({
+ statement: 'Ivan seen',
+ count: 4,
+ condition: 'destroyed',
+ about: ['ivan'],
+ at: [],
+ cites: [],
+ seat: { slot: 'about', count: false, condition: false },
+ });
+ expect(body.count).toBeNull();
+ expect(body.condition).toBeNull();
+ });
+});
+
+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(null)).toBe('');
+ });
+});
diff --git a/frontend/src/lib/reverseSearch.js b/frontend/src/lib/reverseSearch.js
index f899819..c0df92a 100644
--- a/frontend/src/lib/reverseSearch.js
+++ b/frontend/src/lib/reverseSearch.js
@@ -56,3 +56,37 @@ export const UPLOAD_PAGES = ENGINES.map((e) => ({
paste: e.paste,
fill: e.fill,
}));
+
+/**
+ * A picture handed to Reverse Search from another tool, or null when it cannot be
+ * one.
+ *
+ * Two shapes, because two kinds of picture are worth searching. A **case file** is
+ * named by its case-relative path and is an image or a video — a video may say
+ * which moment to open on. A **picture that exists nowhere on disk** — an Inspect
+ * frame not yet saved, a proof panel as it is cropped and turned — travels as the
+ * PNG itself, since there is no path to read it back from.
+ *
+ * Everything is checked here rather than where it is consumed: the handoff is
+ * written by three tools and read by one, and a path that climbs out of the case or
+ * a blob that is not an image would otherwise reach the preview as it was sent.
+ */
+export function normalizeReverseTarget(raw) {
+ if (!raw || typeof raw !== 'object') return null;
+ const label = typeof raw.label === 'string' ? raw.label.trim() : '';
+ if (typeof Blob !== 'undefined' && raw.blob instanceof Blob) {
+ if (!raw.blob.size || !raw.blob.type.startsWith('image/')) return null;
+ return { path: null, blob: raw.blob, kind: 'image', label: label || 'Picture', time: null };
+ }
+ const path = typeof raw.path === 'string' ? raw.path.trim() : '';
+ if (!path || /^[/\\]|^[a-z]:/i.test(path) || path.split(/[/\\]/).includes('..')) return null;
+ if (raw.kind !== 'image' && raw.kind !== 'video') return null;
+ const time = raw.kind === 'video' && raw.time != null && Number(raw.time) >= 0 ? Number(raw.time) : null;
+ return {
+ path,
+ blob: null,
+ kind: raw.kind,
+ label: label || path.split('/').pop(),
+ time: Number.isFinite(time) ? time : null,
+ };
+}
diff --git a/frontend/src/lib/reverseSearch.test.js b/frontend/src/lib/reverseSearch.test.js
index ee0945b..15e1022 100644
--- a/frontend/src/lib/reverseSearch.test.js
+++ b/frontend/src/lib/reverseSearch.test.js
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest';
-import { UPLOAD_PAGES } from './reverseSearch.js';
+import { UPLOAD_PAGES, normalizeReverseTarget } from './reverseSearch.js';
describe('UPLOAD_PAGES', () => {
const byId = Object.fromEntries(UPLOAD_PAGES.map((p) => [p.id, p]));
@@ -35,3 +35,54 @@ describe('UPLOAD_PAGES', () => {
expect(byId.tineye.paste).toBe(false);
});
});
+
+describe('normalizeReverseTarget', () => {
+ const png = () => new Blob([new Uint8Array([137, 80, 78, 71])], { type: 'image/png' });
+
+ it('takes a case image by its path, and names it after the file when nothing else does', () => {
+ expect(normalizeReverseTarget({ path: 'media/quai.jpg', kind: 'image' })).toEqual({
+ path: 'media/quai.jpg',
+ blob: null,
+ kind: 'image',
+ label: 'quai.jpg',
+ time: null,
+ });
+ });
+
+ it('keeps the moment a video should open on, and only for a video', () => {
+ expect(normalizeReverseTarget({ path: 'media/clip.mp4', kind: 'video', time: 12.5 }).time).toBe(12.5);
+ expect(normalizeReverseTarget({ path: 'media/clip.mp4', kind: 'video', time: 0 }).time).toBe(0);
+ expect(normalizeReverseTarget({ path: 'media/clip.mp4', kind: 'video' }).time).toBeNull();
+ expect(normalizeReverseTarget({ path: 'media/clip.mp4', kind: 'video', time: -3 }).time).toBeNull();
+ expect(normalizeReverseTarget({ path: 'media/clip.mp4', kind: 'video', time: 'soon' }).time).toBeNull();
+ expect(normalizeReverseTarget({ path: 'media/quai.jpg', kind: 'image', time: 4 }).time).toBeNull();
+ });
+
+ it('refuses what an engine cannot be handed: a document, an audio file, no kind at all', () => {
+ expect(normalizeReverseTarget({ path: 'media/report.pdf', kind: 'file' })).toBeNull();
+ expect(normalizeReverseTarget({ path: 'media/call.mp3', kind: 'audio' })).toBeNull();
+ expect(normalizeReverseTarget({ path: 'media/quai.jpg' })).toBeNull();
+ });
+
+ it('refuses a path that leaves the case, on either separator', () => {
+ for (const path of ['/etc/passwd', '../other/a.jpg', 'media/../../a.jpg', 'media\\..\\a.jpg', 'C:/a.jpg', '']) {
+ expect(normalizeReverseTarget({ path, kind: 'image' }), path).toBeNull();
+ }
+ });
+
+ it('carries a picture held only in memory as the image itself', () => {
+ const blob = png();
+ const picture = normalizeReverseTarget({ blob, label: 'clip.mp4 · 00:12', path: 'ignored.jpg', kind: 'video' });
+ expect(picture).toEqual({ path: null, blob, kind: 'image', label: 'clip.mp4 · 00:12', time: null });
+ });
+
+ it('refuses a blob that is empty or not an image', () => {
+ expect(normalizeReverseTarget({ blob: new Blob([], { type: 'image/png' }) })).toBeNull();
+ expect(normalizeReverseTarget({ blob: new Blob(['x'], { type: 'text/html' }) })).toBeNull();
+ });
+
+ it('answers null for nothing at all', () => {
+ expect(normalizeReverseTarget(null)).toBeNull();
+ expect(normalizeReverseTarget('media/quai.jpg')).toBeNull();
+ });
+});
diff --git a/frontend/src/lib/state.svelte.js b/frontend/src/lib/state.svelte.js
index 870f788..be29bbb 100644
--- a/frontend/src/lib/state.svelte.js
+++ b/frontend/src/lib/state.svelte.js
@@ -235,6 +235,13 @@ export const uiState = $state({
openDraft: null, // draft name to load in the Post Composer
openNotebook: null, // { noteId: string|null }; null noteId opens case notes.md
inspectPath: null, // media path to open in the Inspect tool
+ /**
+ * A picture handed to Reverse Search from wherever it is being looked at, in the
+ * shape `normalizeReverseTarget` (lib/reverseSearch.js) returns: a case file by
+ * its path, or a picture that exists nowhere on disk — an Inspect frame not yet
+ * saved, a proof panel as cropped — as a Blob. Consumed once, session-only.
+ */
+ reverseTarget: null,
focusMedia: null, // media path to highlight & scroll to in the Media Library
openInspect: null, // inspect-session name to reopen in the Inspect tool
openCompare: null, // compare-session name to reopen in the Compare tool
@@ -278,6 +285,23 @@ export const uiState = $state({
// opens its Sun & moon mode there. Session-only, and never part of a capture
// or a proof.
skyAt: null, // { lat, lon, date, time }
+ /**
+ * Where the map is, for the tools that would otherwise open on nothing.
+ *
+ * The point the map records — its moved pin, else its centre — published once
+ * the analyst has moved off the view the map opened at, so a fresh window
+ * never offers the home view as if it were a finding. Session-only, read by
+ * Coords & Sky, and never part of a capture, a proof or a case.
+ */
+ mapPoint: null, // { lat, lon, zoom }
+ /**
+ * A pair of dated views of one point, handed to Compare from the map's own
+ * right-click menu: `{ lat, lon, zoom, a, b, title }`, where each side is the
+ * shape `applySide` already reads off a saved comparison. The dates are
+ * looked up where the menu is pressed, so Compare opens on two pictures
+ * rather than on two empty panes. Consumed once, session-only.
+ */
+ compareAt: null,
focusCapture: null, // case-relative capture path selected from another workspace
// Satellite reference viewers: floating scratch windows holding a media image
// over the map to eyeball against the imagery. Session-only — never captured
@@ -313,13 +337,24 @@ export function persistSidebarWidth() {
let toastSeq = 0;
+/**
+ * Say something at the foot of the window, for `timeout` milliseconds.
+ *
+ * A timeout of 0 holds it up until `dismissToast` takes it down, which is how a
+ * wait of unknown length is said: the message has to outlast the work rather
+ * than a guess at how long the work takes. Returns the id either way.
+ */
export function toast(message, kind = 'info', timeout = 3800, action = null) {
const id = ++toastSeq;
uiState.toasts.push({ id, message, kind, action });
- setTimeout(() => {
- const i = uiState.toasts.findIndex((t) => t.id === id);
- if (i !== -1) uiState.toasts.splice(i, 1);
- }, timeout);
+ if (timeout > 0) setTimeout(() => dismissToast(id), timeout);
+ return id;
+}
+
+/** Take one down early, or take down one that was never given a timeout. */
+export function dismissToast(id) {
+ const i = uiState.toasts.findIndex((t) => t.id === id);
+ if (i !== -1) uiState.toasts.splice(i, 1);
}
export async function refreshCaseList({ q } = {}) {
@@ -519,6 +554,7 @@ function clearCaseHandoffs() {
uiState.openDraft = null;
uiState.openNotebook = null;
uiState.inspectPath = null;
+ uiState.reverseTarget = null;
uiState.focusMedia = null;
uiState.focusCapture = null;
uiState.openInspect = null;
diff --git a/frontend/src/lib/state.test.js b/frontend/src/lib/state.test.js
index 21eec88..80a7079 100644
--- a/frontend/src/lib/state.test.js
+++ b/frontend/src/lib/state.test.js
@@ -38,6 +38,7 @@ describe('closeCase', () => {
uiState.openProof = 'proof-a';
uiState.openDraft = 'draft-a';
uiState.inspectPath = 'media/a.jpg';
+ uiState.reverseTarget = { path: 'media/a.jpg', kind: 'image', label: 'a.jpg' };
uiState.focusMedia = 'media/a.jpg';
uiState.openInspect = 'session-a';
uiState.openAnalyzer = 'runs-123456789abc';
@@ -62,6 +63,7 @@ describe('closeCase', () => {
expect(uiState.openProof).toBeNull();
expect(uiState.openDraft).toBeNull();
expect(uiState.inspectPath).toBeNull();
+ expect(uiState.reverseTarget).toBeNull();
expect(uiState.focusMedia).toBeNull();
expect(uiState.openInspect).toBeNull();
expect(uiState.openAnalyzer).toBeNull();
@@ -334,6 +336,7 @@ describe('case request ownership', () => {
openDraft: 'draft-a',
openNotebook: { noteId: 'note-a' },
inspectPath: 'media/a.jpg',
+ reverseTarget: { path: 'media/a.jpg', kind: 'image', label: 'a.jpg' },
focusMedia: 'media/a.jpg',
focusCapture: 'media/crop.png',
openInspect: 'session-a',
diff --git a/frontend/src/lib/tally.js b/frontend/src/lib/tally.js
index 8f7d85a..675b5e1 100644
--- a/frontend/src/lib/tally.js
+++ b/frontend/src/lib/tally.js
@@ -74,11 +74,11 @@ export function confidenceLine(row, label = (value) => value) {
export function readingNotes(body) {
const notes = [];
if (body?.truncated) {
- notes.push(`Added up ${body.read} of ${body.matched} statements`);
+ notes.push(`Added up ${body.read} of ${body.matched} claims`);
}
const loose = body?.unattributed ?? 0;
if (loose > 0) {
- notes.push(`${loose} ${loose === 1 ? 'statement says' : 'statements say'} nothing about what it concerns`);
+ notes.push(`${loose} ${loose === 1 ? 'claim says' : 'claims say'} nothing about what it concerns`);
}
return notes;
}
diff --git a/frontend/src/lib/tally.test.js b/frontend/src/lib/tally.test.js
index 5921aec..f2c154d 100644
--- a/frontend/src/lib/tally.test.js
+++ b/frontend/src/lib/tally.test.js
@@ -102,15 +102,15 @@ describe('confidenceLine', () => {
describe('readingNotes', () => {
it('states the cut before anything else, because it changes every number under it', () => {
const notes = readingNotes({ read: 2000, matched: 3400, truncated: true, unattributed: 0 });
- expect(notes).toEqual(['Added up 2000 of 3400 statements']);
+ expect(notes).toEqual(['Added up 2000 of 3400 claims']);
});
it('reports the statements that name no subject', () => {
expect(readingNotes({ truncated: false, unattributed: 1 })).toEqual([
- '1 statement says nothing about what it concerns',
+ '1 claim says nothing about what it concerns',
]);
expect(readingNotes({ truncated: false, unattributed: 3 })).toEqual([
- '3 statements say nothing about what it concerns',
+ '3 claims say nothing about what it concerns',
]);
});
diff --git a/frontend/src/lib/timeline.js b/frontend/src/lib/timeline.js
index 220f0e3..628ceaf 100644
--- a/frontend/src/lib/timeline.js
+++ b/frontend/src/lib/timeline.js
@@ -7,7 +7,7 @@ const MIN_WINDOW = 2 * SECOND;
const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
export const TIMELINE_CATEGORIES = [
- { id: 'statement', label: 'Statements', short: 'Statements' },
+ { id: 'statement', label: 'Claims', short: 'Claims' },
{ id: 'media', label: 'Media dates', short: 'Media' },
{ id: 'case_activity', label: 'Case activity', short: 'Activity' },
];
diff --git a/frontend/src/tools/Board.render.test.js b/frontend/src/tools/Board.render.test.js
index f968933..2562970 100644
--- a/frontend/src/tools/Board.render.test.js
+++ b/frontend/src/tools/Board.render.test.js
@@ -32,8 +32,19 @@ const SUMMARY = {
unlinked: 0,
};
+// A Claim's three connectors, as the verb registry serves them: what the row's
+// claim press reads to decide where the row's entity sits.
+const claimVerb = (type, to) => ({ type, label: type, action: 'claim', manual: true, from_types: ['claim'], to_types: to });
+const RELATIONS = [
+ claimVerb('about', ['place', 'media', 'person']),
+ claimVerb('at', ['place']),
+ claimVerb('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 [];
if (url.includes('/catalog/summary')) return SUMMARY;
if (url.includes('/catalog/entities')) {
return { items: ROWS, total: ROWS.length, next_cursor: null };
@@ -278,3 +289,33 @@ describe('deleting what is ticked', () => {
expect(bar().textContent).toContain('1 selected');
});
});
+
+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 () => {
+ 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();
+ });
+});
diff --git a/frontend/src/tools/Board.svelte b/frontend/src/tools/Board.svelte
index e01cf5c..9149e8e 100644
--- a/frontend/src/tools/Board.svelte
+++ b/frontend/src/tools/Board.svelte
@@ -85,10 +85,18 @@
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 { loadRelationTypes } from '../lib/relations.svelte.js';
const PAGE = 100;
loadEntityTypes();
+ // The row's claim press is offered where the verb registry gives the entity 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`).
@@ -261,10 +269,10 @@
hint: snapshotReading
? 'A frozen snapshot holds rows rather than a question to add up'
: nothingToDraw
- ? 'No statement counts anything about a subject yet'
+ ? 'No claim counts anything about a subject yet'
: empty
? 'Nothing in the table to add up'
- : 'What the statements about these come to, per subject',
+ : 'What the claims about these come to, per subject',
},
];
});
@@ -1088,7 +1096,7 @@
statements would be arithmetically right and read as more than it is. -->
{#if nothingTotalled(tally)}
{#if !tallying}
- <p class="empty">No statement in this narrowing.</p>
+ <p class="empty">No claim in this narrowing.</p>
{/if}
{:else}
{#each readingNotes(tally) as note (note)}
@@ -1098,10 +1106,10 @@
<thead>
<tr>
<th>Subject</th>
- <th title="added over the statements that carried a number">
- What the statements come to
+ <th title="added over the ones that carried a number">
+ What the claims come to
</th>
- <th title="how many statements point at this subject">Statements</th>
+ <th title="how many of them point at this subject">Claims</th>
</tr>
</thead>
<tbody>
@@ -1289,6 +1297,20 @@
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"
@@ -1360,6 +1382,17 @@
/>
{/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}
<!-- 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
diff --git a/frontend/src/tools/Board.test.js b/frontend/src/tools/Board.test.js
index ef08d51..7570086 100644
--- a/frontend/src/tools/Board.test.js
+++ b/frontend/src/tools/Board.test.js
@@ -64,7 +64,9 @@ describe('the vocabulary explains itself', () => {
});
it('takes every reading from the registry rather than writing one here', () => {
- const markup = source.slice(source.indexOf('</script>'));
+ // A dialog's heading names the form it holds ("New claim") and reads no type,
+ // so it is left out; every tooltip is still held to the rule.
+ const markup = source.slice(source.indexOf('</script>')).replace(/<Modal title="[^"]*"/g, '');
// the only titles in the markup are either registry readings or the fallback
// that names the control itself
expect(markup).not.toMatch(/title="[a-z ]*(claim|bookmark|capture|actor|material)/i);
@@ -442,7 +444,7 @@ describe('adding the statements up', () => {
// a control you can see and cannot use teaches something; one that is not there
// teaches nothing — the rule the filter menu already follows
expect(source).toContain('disabled: nothingToDraw || empty || snapshotReading,');
- expect(source).toContain("'No statement counts anything about a subject yet'");
+ expect(source).toContain("'No claim counts anything about a subject yet'");
expect(source).toContain("'Nothing in the table to add up'");
});
@@ -544,3 +546,11 @@ describe('several rows at once', () => {
expect(source).toContain('if (snapshotReading || confirmState || !caseState.current');
});
});
+
+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)}');
+ expect(source).toContain('loadRelationTypes();');
+ });
+});
diff --git a/frontend/src/tools/Compare.pair.test.js b/frontend/src/tools/Compare.pair.test.js
new file mode 100644
index 0000000..fbc6047
--- /dev/null
+++ b/frontend/src/tools/Compare.pair.test.js
@@ -0,0 +1,49 @@
+import { describe, expect, it } from 'vitest';
+import { readFileSync } from 'node:fs';
+
+const compare = readFileSync(new URL('./Compare.svelte', import.meta.url), 'utf8');
+const map = readFileSync(new URL('./Satellite.svelte', import.meta.url), 'utf8');
+const state = readFileSync(new URL('../lib/state.svelte.js', import.meta.url), 'utf8');
+
+describe('Compare here', () => {
+ it('asks the archive before the tab changes, so a refusal costs no view', () => {
+ const body = map.slice(map.indexOf('async function comparePoint('));
+ expect(body).toContain('const pair = await comparePair(api, source, { ...point, zoom: center.zoom });');
+ expect(body.indexOf('uiState.tool = \'compare\';')).toBeGreaterThan(
+ body.indexOf('const pair = await comparePair(')
+ );
+ expect(body).toContain("toast(error.message, 'warn', 6000);");
+ });
+
+ it('leaves out an archive this machine has no key for', () => {
+ expect(map).toContain(
+ 'COMPARE_SOURCES.filter((source) => !source.provider || imagery.find(source.provider))'
+ );
+ });
+
+ it('travels as a pair of sides, the shape a saved comparison stores', () => {
+ expect(state).toContain('compareAt: null,');
+ expect(map).toContain('uiState.compareAt = { ...point, zoom: center.zoom, ...pair };');
+ expect(compare).toContain('applySide(a, s2a, wba, pair.a);');
+ expect(compare).toContain('applySide(b, s2b, wbb, pair.b);');
+ });
+
+ it('opens unsaved and unnamed, because nothing was filed', () => {
+ const body = compare.slice(compare.indexOf('async function openPair('));
+ expect(body).toContain('openedSession = null;');
+ expect(body).toContain('savedSignature = null;');
+ expect(body).toContain("mode = 'side';");
+ });
+
+ it('asks before it throws an unsaved comparison away', () => {
+ expect(compare).toContain("discardTarget = { kind: 'pair', pair };");
+ expect(compare).toContain("else if (target?.kind === 'pair') void openPair(target.pair);");
+ });
+
+ it('is consumed once, and only once the providers are known', () => {
+ expect(compare).toContain(
+ "if (uiState.tool !== 'compare' || !uiState.compareAt || !imagery.providers.length) return;"
+ );
+ expect(compare).toContain('uiState.compareAt = null;');
+ });
+});
diff --git a/frontend/src/tools/Compare.svelte b/frontend/src/tools/Compare.svelte
index a8f5a0c..55509b4 100644
--- a/frontend/src/tools/Compare.svelte
+++ b/frontend/src/tools/Compare.svelte
@@ -46,9 +46,13 @@
} from '../lib/map/changeAssist.js';
import {
ANNOTATION_COLOURS,
+ ANNOTATION_TOOLS,
+ STAMPED,
canFill,
+ nextMarkNumber,
comparisonAnnotations,
} from '../lib/map/compareAnnotations.js';
+ import { PROOF_ICONS } from '../lib/proofIcons.js';
import { cropSources, exportFrameSpec, frameSpan } from '../lib/map/exportFrame.js';
import { formatDistance } from '../lib/measure.js';
import { captureTab, extensionVersion } from '../lib/extBridge.js';
@@ -138,13 +142,19 @@
let sessionDialog = $state(false);
let sessionBusy = $state(false);
let sessionList = $state([]);
- let discardTarget = $state(null); // { kind: 'new' | 'open' | 'revert', name? } | null
+ let discardTarget = $state(null); // { kind: 'new' | 'open' | 'revert' | 'pair', name?, pair? } | null
let annotations = $state([]);
let annotationTool = $state('select');
let selectedAnnotationId = $state(null);
let annotationColour = $state(ANNOTATION_COLOURS[0]);
let annotationStroke = $state(4);
let annotationFill = $state(0);
+ // Which symbol the stamp puts down, kept between two of them: marking six
+ // vehicles is one act, and re-picking the glyph each time would make it six.
+ let annotationGlyph = $state(PROOF_ICONS[0].name);
+ // How big the next note or stamp is drawn. One number for all three: they are
+ // the marks with no line to widen, and the rail has one slider.
+ let annotationStampSize = $state(12);
let annotationUndo = $state([]);
let annotationRedo = $state([]);
let annotationPreviewBase = null;
@@ -376,6 +386,22 @@
changeCompatibility(changeSide(a, s2a, wba, shownA), changeSide(b, s2b, wbb, shownB))
);
+ /**
+ * What Detect needs before a run can fetch anything: Sentinel-2, which only
+ * lists once Copernicus credentials are in Settings. Not a lock — the panel
+ * still opens on the areas and runs already saved — only said up front.
+ */
+ const detectStatus = $derived(
+ imagery.providers.length && !imagery.find('sentinel2')
+ ? { ok: false, reason: 'Detect reads Copernicus Sentinel-2: add your credentials in Settings → Imagery.' }
+ : { ok: true, reason: '' }
+ );
+
+ function openImagerySettings() {
+ uiState.settingsTab = 'imagery';
+ uiState.tool = 'settings';
+ }
+
function surfaceOverlays(target) {
return target.overlays
.map((id) => {
@@ -955,6 +981,44 @@
}
}
+ /**
+ * Open on a pair the map already chose: two dated views of one point.
+ *
+ * The same road a saved comparison takes — `applySide` for each side, then the
+ * camera — because a handoff and a session say the same thing. It arrives
+ * unsaved and unnamed: nothing was filed, the analyst is being shown a pair.
+ */
+ async function openPair(pair) {
+ view = { lat: pair.lat, lon: pair.lon, zoom: pair.zoom ?? view.zoom };
+ bearing = 0;
+ mode = 'side';
+ annotations = comparisonAnnotations(null);
+ resetAnnotationHistory();
+ applySide(a, s2a, wba, pair.a);
+ applySide(b, s2b, wbb, pair.b);
+ sessionName = pair.title ?? 'Comparison';
+ openedSession = null;
+ savedSignature = null;
+ await tick();
+ for (const target of [a, b]) {
+ target.engine?.setView(view, view.zoom);
+ target.engine?.setBearing(0);
+ }
+ a.engine?.resize();
+ b.engine?.resize();
+ }
+
+ $effect(() => {
+ if (uiState.tool !== 'compare' || !uiState.compareAt || !imagery.providers.length) return;
+ const pair = uiState.compareAt;
+ uiState.compareAt = null;
+ if (sessionDirty) {
+ discardTarget = { kind: 'pair', pair };
+ return;
+ }
+ void openPair(pair);
+ });
+
function requestOpenSession(name) {
if (sessionDirty) {
discardTarget = { kind: 'open', name };
@@ -1043,6 +1107,7 @@
const target = discardTarget;
discardTarget = null;
if (target?.kind === 'new') newComparison();
+ else if (target?.kind === 'pair') void openPair(target.pair);
else if (target) void openSession(target.name);
}
@@ -1164,6 +1229,17 @@
const selectedAnnotation = $derived(
annotations.find((mark) => mark.id === selectedAnnotationId) ?? null
);
+ /**
+ * The selection as the rail edits it: only Select edits what is already drawn.
+ *
+ * A stamp keeps the tool in hand and leaves the mark it put down selected, so
+ * without this a colour picked for the *next* marker recoloured the last one —
+ * and its series never started back at 1. The Proof Maker's rail follows the
+ * same rule.
+ */
+ const editableAnnotation = $derived(
+ annotationTool === 'select' ? selectedAnnotation : null
+ );
function setAnnotations(next, commit = true) {
if (next.length > 200) { toast('A comparison can hold up to 200 annotations', 'warn'); return; }
@@ -1202,22 +1278,42 @@
}
function patchSelectedAnnotation(patch) {
- if (!selectedAnnotation) return;
+ if (!editableAnnotation) return;
setAnnotations(annotations.map((mark) =>
- mark.id === selectedAnnotation.id ? { ...mark, ...patch } : mark
+ mark.id === editableAnnotation.id ? { ...mark, ...patch } : mark
));
}
function setAnnotationColour(value) {
annotationColour = value;
- if (selectedAnnotation) patchSelectedAnnotation({ colour: value });
+ if (!editableAnnotation) return;
+ // A marker belongs to its colour's series, so one recoloured takes the first
+ // number free in the series it joins (`nextMarkNumber`, and the same rule the
+ // Proof Maker's rail follows).
+ patchSelectedAnnotation(
+ editableAnnotation.kind === 'number' && editableAnnotation.colour !== value
+ ? { colour: value, number: nextMarkNumber(annotations, value) }
+ : { colour: value }
+ );
+ }
+
+ /** How heavy a symbol's own line is. Its size is the slider beside it. */
+ function setAnnotationOutline(value) {
+ if (editableAnnotation) patchSelectedAnnotation({ stroke_width: value });
+ else annotationStroke = value;
}
+ // A note and a stamp are sized by their own number: neither has a line to
+ // widen, so the one slider on the rail sets that instead.
+ const sizedByFont = (kind) => kind === 'text' || STAMPED.has(kind);
+
function setAnnotationStroke(value) {
- if (selectedAnnotation?.kind === 'text') {
- patchSelectedAnnotation({ font_size: value });
- } else if (selectedAnnotation) {
- patchSelectedAnnotation({ stroke_width: value });
+ if (editableAnnotation) {
+ patchSelectedAnnotation(
+ sizedByFont(editableAnnotation.kind) ? { font_size: value } : { stroke_width: value }
+ );
+ } else if (sizedByFont(annotationTool)) {
+ annotationStampSize = value;
} else {
annotationStroke = value;
}
@@ -1225,7 +1321,7 @@
function setAnnotationFill(value) {
annotationFill = value;
- if (selectedAnnotation && canFill(selectedAnnotation.kind)) {
+ if (editableAnnotation && canFill(editableAnnotation.kind)) {
patchSelectedAnnotation({ fill_opacity: value });
}
}
@@ -1239,7 +1335,11 @@
$effect(() => {
if (!both || uiState.tool !== 'compare') return;
- const shortcuts = { v: 'select', r: 'rect', e: 'ellipse', a: 'arrow', l: 'line', d: 'freehand', t: 'text', p: 'polygon', m: 'measure' };
+ // Read off the rail itself, so a tool added there answers to its own letter
+ // without a second list to keep in step.
+ const shortcuts = Object.fromEntries(
+ ANNOTATION_TOOLS.map((entry) => [entry.shortcut.toLowerCase(), entry.id])
+ );
const onKey = (event) => {
if (event.target?.closest?.('input, textarea, select, [contenteditable="true"]')) return;
const key = event.key.toLowerCase();
@@ -1729,7 +1829,7 @@
{#if both}
<div class="compare-bar">
- <ModeDock {mode} change={changeStatus} onmode={setMode} onswap={swapSides} />
+ <ModeDock {mode} change={changeStatus} detect={detectStatus} onmode={setMode} onswap={swapSides} />
<div class="spacer"></div>
<span class="camera-readout mono">z{Number(view.zoom).toFixed(1)}</span>
<!-- One camera, so one compass: it turns both maps and resets them. -->
@@ -1750,20 +1850,24 @@
{#if both && !detecting}
<AnnotationToolbar
bind:tool={annotationTool}
- selected={selectedAnnotation}
+ selected={editableAnnotation}
canUndo={annotationUndo.length > 0}
canRedo={annotationRedo.length > 0}
undo={undoAnnotation}
redo={redoAnnotation}
palette={ANNOTATION_COLOURS}
colour={annotationColour}
+ glyph={annotationGlyph}
+ stampSize={annotationStampSize}
+ setGlyph={(name) => { annotationGlyph = name; if (editableAnnotation?.kind === 'icon') patchSelectedAnnotation({ glyph: name }); }}
strokeWidth={annotationStroke}
fillOpacity={annotationFill}
setColour={setAnnotationColour}
setStroke={setAnnotationStroke}
+ setOutline={setAnnotationOutline}
setFill={setAnnotationFill}
bind:side={annotationSide}
- setSide={(value) => { annotationSide = value; if (selectedAnnotation) patchSelectedAnnotation({ side: value }); }}
+ setSide={(value) => { annotationSide = value; if (editableAnnotation) patchSelectedAnnotation({ side: value }); }}
removeSelected={() => {
if (selectedAnnotationId) setAnnotations(annotations.filter((mark) => mark.id !== selectedAnnotationId));
selectedAnnotationId = null;
@@ -1884,6 +1988,7 @@
<AnnotationCanvas bind:this={canvasA} {annotations} engine={a.engine} letter="a" units={prefs.units}
active={uiState.tool === 'compare'} bind:tool={annotationTool} bind:selectedId={selectedAnnotationId}
colour={annotationColour} strokeWidth={annotationStroke} fillOpacity={annotationFill}
+ glyph={annotationGlyph} stampSize={annotationStampSize}
editVertices={true} {annotationSide} onchange={setAnnotations} />
{/if}
<!-- Detect's own drawing stays in Detect: areas and candidates belong
@@ -1982,6 +2087,7 @@
<AnnotationCanvas bind:this={canvasB} {annotations} engine={b.engine} letter="b" units={prefs.units}
active={uiState.tool === 'compare'} bind:tool={annotationTool} bind:selectedId={selectedAnnotationId}
colour={annotationColour} strokeWidth={annotationStroke} fillOpacity={annotationFill}
+ glyph={annotationGlyph} stampSize={annotationStampSize}
editVertices={true} {annotationSide} onchange={setAnnotations} />
{/if}
{#if detecting && !grabbing && analyzerLayers.some((layer) => layer.visible)}
@@ -2066,6 +2172,7 @@
bind:layers={analyzerLayers} bind:showZones={analyzerAreasVisible}
bind:singleImage={analyzerSingle} bind:selectedResult={analyzerResult}
opening={analyzerOpening} onfocus={focusAnalysis} onusecurrentview={useCurrentView}
+ needs={detectStatus.reason} onsettings={openImagerySettings}
onsources={applyAnalysisSources} onclose={() => setMode('side')} />
{/if}
</div>
@@ -2245,7 +2352,7 @@
<span>{imagery.find(saved.provider_a)?.label ?? saved.provider_a} / {imagery.find(saved.provider_b)?.label ?? saved.provider_b}</span>
<small>{COMPARE_MODES.find((entry) => entry.id === saved.mode)?.label ?? saved.mode}{saved.updated_at ? ` · ${saved.updated_at.replace('T', ' ').replace('Z', '')}` : ''}</small>
</button>
- <button class="btn btn-ghost btn-xs" onclick={() => deleteSession(saved.name)} aria-label={`Delete ${saved.title}`}><Icon name="trash" size={14} /></button>
+ <button class="btn btn-ghost btn-xs" onclick={() => deleteSession(saved.name)} aria-label={`Delete ${saved.title}`} title={`Delete ${saved.title}`}><Icon name="trash" size={14} /></button>
</div>
{/each}
</div>
diff --git a/frontend/src/tools/Coordinates.render.test.js b/frontend/src/tools/Coordinates.render.test.js
new file mode 100644
index 0000000..a15cefe
--- /dev/null
+++ b/frontend/src/tools/Coordinates.render.test.js
@@ -0,0 +1,130 @@
+// @vitest-environment happy-dom
+/**
+ * The tab, mounted, following the map.
+ *
+ * `Coordinates.test.js` holds the handover to its own rules — which point the
+ * map offers and that naming the place stays behind a press. This checks the
+ * one thing only a live component can answer: the tab is never unmounted once
+ * visited, so the prefill has to keep up with a map that moved rather than fill
+ * once and hold the first point forever.
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { flushSync, mount, unmount } from 'svelte';
+
+const post = vi.fn(async (_url, body) => {
+ const [lat, lon] = String(body.text).split(',').map((part) => Number(part.trim()));
+ return { lat, lon, formats: [{ id: 'dd', label: 'Decimal', value: `${lat}, ${lon}` }] };
+});
+// The sky panel under the notations asks for its own point; it is not what this
+// file is about, and it refuses rather than answering with a shape it invented.
+const get = vi.fn(async (url) => {
+ if (url.startsWith('/api/geo/reverse')) return { display_name: 'Somewhere' };
+ throw new Error('not asked here');
+});
+vi.mock('../lib/api.js', () => ({ api: { get, post }, ApiError: Error }));
+
+const toast = vi.fn();
+vi.mock('../lib/state.svelte.js', async () => {
+ const { caseState, uiState } = await import('./coordinates.fixture.svelte.js');
+ return { caseState, uiState, toast };
+});
+
+const { default: Coordinates } = await import('./Coordinates.svelte');
+const { uiState, resetCoordinatesFixture } = await import('./coordinates.fixture.svelte.js');
+
+let live = null;
+let target = null;
+
+async function settle() {
+ for (let index = 0; index < 12; index += 1) await Promise.resolve();
+ flushSync();
+}
+
+async function open() {
+ target = document.createElement('div');
+ document.body.append(target);
+ live = mount(Coordinates, { target });
+ flushSync();
+ await settle();
+ return target;
+}
+
+const field = () => target.querySelector('.go-form .input');
+
+/** The map settling somewhere, which is what writes `uiState.mapPoint`. */
+async function mapMovesTo(lat, lon) {
+ uiState.mapPoint = { lat, lon, zoom: 15 };
+ flushSync();
+ await settle();
+}
+
+async function type(value) {
+ const input = field();
+ input.value = value;
+ input.dispatchEvent(new Event('input', { bubbles: true }));
+ flushSync();
+ await settle();
+}
+
+beforeEach(() => {
+ resetCoordinatesFixture();
+ vi.clearAllMocks();
+});
+
+afterEach(() => {
+ if (live) unmount(live);
+ live = null;
+ target?.remove();
+ target = null;
+});
+
+describe('the point the tab opens on', () => {
+ it('is the one the map is on', async () => {
+ uiState.mapPoint = { lat: 48.8584, lon: 2.2945, zoom: 15 };
+ await open();
+
+ expect(field().value).toBe('48.858400, 2.294500');
+ expect(post).toHaveBeenCalledWith('/api/geo/parse', { text: '48.858400, 2.294500' });
+ // the conversion is local; naming the place is a Nominatim call, and it
+ // stays behind the press that asks for it
+ expect(get.mock.calls.flat().some((url) => url.startsWith('/api/geo/reverse'))).toBe(false);
+ });
+
+ it('follows the map instead of holding the first point it was given', async () => {
+ uiState.mapPoint = { lat: 48.8584, lon: 2.2945, zoom: 15 };
+ await open();
+ await mapMovesTo(50.0755, 14.4378);
+
+ expect(field().value).toBe('50.075500, 14.437800');
+ expect(target.querySelector('.formats .v').textContent).toContain('50.0755');
+ });
+
+ it('leaves a coordinate somebody typed alone until the map moves again', async () => {
+ uiState.mapPoint = { lat: 48.8584, lon: 2.2945, zoom: 15 };
+ await open();
+ await type('12.5, 13.5');
+
+ expect(field().value).toBe('12.5, 13.5');
+
+ await mapMovesTo(50.0755, 14.4378);
+ expect(field().value).toBe('50.075500, 14.437800');
+ });
+
+ it('does not overwrite work already on a tab reached without the map moving', async () => {
+ await open();
+ await type('12.5, 13.5');
+ uiState.mapPoint = { lat: 48.8584, lon: 2.2945, zoom: 15 };
+ flushSync();
+ await settle();
+
+ expect(field().value).toBe('12.5, 13.5');
+ });
+
+ it('stays out of the way while another tool is open', async () => {
+ await open();
+ uiState.tool = 'satellite';
+ await mapMovesTo(50.0755, 14.4378);
+
+ expect(field().value).toBe('');
+ });
+});
diff --git a/frontend/src/tools/Coordinates.svelte b/frontend/src/tools/Coordinates.svelte
index 294d3d4..d783821 100644
--- a/frontend/src/tools/Coordinates.svelte
+++ b/frontend/src/tools/Coordinates.svelte
@@ -36,14 +36,14 @@
// Link labels don't depend on lat/lon, so this also drives the empty-state preview.
const links = $derived(mapLinks(point?.lat ?? 0, point?.lon ?? 0));
- async function parse() {
+ async function parse({ name = true } = {}) {
const value = text.trim();
if (!value || parsing) return;
parsing = true;
place = null;
try {
point = await api.post('/api/geo/parse', { text: value });
- lookupPlace();
+ if (name) lookupPlace();
} catch {
point = null;
toast('Could not read a coordinate from that', 'danger');
@@ -92,6 +92,38 @@
parse();
}
+ // The map point this tab last opened on. A tab is never unmounted once
+ // visited, so without it the prefill below could only ever fire once.
+ let openedOn = null;
+
+ /**
+ * Open on the point the map is on, rather than on an empty field: the tab is
+ * reached from the map more often than it is typed into.
+ *
+ * It follows the map rather than filling once: the map moving is the analyst
+ * looking somewhere else, and a tab still reading the point before it is a
+ * tab answering about the wrong ground. Between two moves the field is
+ * theirs — what they typed, or the row they picked, stands.
+ *
+ * The conversion is local, and that is the whole of what happens here. Naming
+ * the place is a Nominatim call, which the local-first rule keeps behind an
+ * action — so the row offers it instead of making it.
+ */
+ $effect(() => {
+ if (uiState.tool !== 'coordinates') return;
+ const last = uiState.mapPoint;
+ if (!last || parsing) return;
+ const asked = `${last.lat.toFixed(6)}, ${last.lon.toFixed(6)}`;
+ if (asked === openedOn) return;
+ // Arriving on a tab that already holds an answer leaves it standing: the
+ // map has not moved since, so there is nothing newer to show.
+ const held = openedOn === null && (point || text.trim());
+ openedOn = asked;
+ if (held) return;
+ text = asked;
+ void parse({ name: false });
+ });
+
// Hand the point to the Satellite map and switch tabs; it consumes
// uiState.gotoCoords on the next tick and flies there (lib/navigate.js).
function openInSatellite() {
@@ -139,8 +171,10 @@
in every notation.
{:else if placeLoading}
Resolving place…
- {:else}
+ {:else if place}
{place}
+ {:else}
+ <button class="name-place" onclick={lookupPlace}>Name this place</button>
{/if}
</span>
<button
@@ -233,6 +267,16 @@
.head-row .place.muted {
color: var(--text-3);
}
+ /* The place name is a network call, so it is offered as one rather than made
+ on arrival. Reads as the line it will become, not as a button. */
+ .name-place {
+ color: var(--accent);
+ font-size: var(--fs-md);
+ cursor: pointer;
+ }
+ .name-place:hover {
+ text-decoration: underline;
+ }
.head-row .btn {
flex-shrink: 0;
white-space: nowrap;
diff --git a/frontend/src/tools/Coordinates.test.js b/frontend/src/tools/Coordinates.test.js
new file mode 100644
index 0000000..4868a6d
--- /dev/null
+++ b/frontend/src/tools/Coordinates.test.js
@@ -0,0 +1,36 @@
+import { describe, expect, it } from 'vitest';
+import { readFileSync } from 'node:fs';
+
+const tool = readFileSync(new URL('./Coordinates.svelte', import.meta.url), 'utf8');
+const map = readFileSync(new URL('./Satellite.svelte', import.meta.url), 'utf8');
+const state = readFileSync(new URL('../lib/state.svelte.js', import.meta.url), 'utf8');
+
+describe('the tab opens on the point the map is on', () => {
+ it('is handed that point by the map, once the map has been moved off its home view', () => {
+ expect(state).toContain('mapPoint: null,');
+ expect(map).toContain(
+ 'uiState.mapPoint = { lat: displayCoords.lat, lon: displayCoords.lon, zoom: center.zoom };'
+ );
+ // a window still sitting on the saved home view has no point to offer, while a
+ // view the address named is one: it came from a link or from case work
+ expect(map).toContain('const asked = openingView?.lat != null;');
+ expect(map).toContain(
+ 'if (!asked && center.lat === home.lat && center.lon === home.lon && center.zoom === home.zoom) return;'
+ );
+ });
+
+ it('follows that point, and only while the tab is the one on screen', () => {
+ expect(tool).toContain("if (uiState.tool !== 'coordinates') return;");
+ // the tab is never unmounted once visited, so the point it last opened on is
+ // what says whether the map has moved since (Coordinates.render.test.js)
+ expect(tool).toContain('if (asked === openedOn) return;');
+ expect(tool).toContain("const held = openedOn === null && (point || text.trim());");
+ });
+
+ it('converts locally and leaves the place name to a press', () => {
+ // Nominatim on mount would be a network call nobody asked for
+ expect(tool).toContain('void parse({ name: false });');
+ expect(tool).toContain('if (name) lookupPlace();');
+ expect(tool).toContain('<button class="name-place" onclick={lookupPlace}>Name this place</button>');
+ });
+});
diff --git a/frontend/src/tools/Graph.svelte b/frontend/src/tools/Graph.svelte
index 610c1b1..7d84eea 100644
--- a/frontend/src/tools/Graph.svelte
+++ b/frontend/src/tools/Graph.svelte
@@ -151,6 +151,8 @@
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 { claimActionTitle } from '../lib/quickClaim.js';
import ConfirmDialog from '../components/ConfirmDialog.svelte';
import EntityCreate from '../components/EntityCreate.svelte';
import EntityDetails from '../components/EntityDetails.svelte';
@@ -463,6 +465,8 @@
let hovered = $state(null);
let hoveredLink = $state(null);
let openId = $state(null);
+ /** The node a claim is being filed from, while its form is open. */
+ let claimFor = $state(null);
let snapshotOpen = $state(null);
let dirty = $state(false);
/** The edge under the panel. An edge is a statement, and often the finding. */
@@ -4934,7 +4938,7 @@
onclick={showResting}
title={singling
? 'Click again to bring the rest of the case back.'
- : 'These cite several sources, but one account published every one of them. Click to light just those statements.'}
+ : 'These cite several sources, but one account published every one of them. Click to light just those claims.'}
>
{payload.single_account} on one account
</button>
@@ -5731,6 +5735,7 @@
{#if at}
{@const away = offScreen(at.id)}
{@const takes = root ? 0 : foldableCount(at.id, nodes, links, new Set(pinnedIds))}
+ {@const seat = claimSeat(at)}
<!-- Where a node says what can be done with it, and the one place all three
acts on the drawing are named at once: a canvas teaches no gesture on its
own, and the switch on the node only ever offers one of them at a time. -->
@@ -5783,6 +5788,13 @@
<li><button onclick={() => chose(askWayFrom)}>Path to…</button></li>
<li><button onclick={() => chose(traceFrom)}>Walk by hand</button></li>
<li><button onclick={() => chose((id) => (openId = id))}>Details</button></li>
+ {#if seat}
+ <li>
+ <button onclick={() => chose((id) => (claimFor = byId.get(id) ?? null))} title={claimActionTitle(seat.slot)}>
+ Add claim…
+ </button>
+ </li>
+ {/if}
{#if pinnedIds.includes(at.id)}
<li><button onclick={() => chose(unpinNode)}>Let it go</button></li>
{/if}
@@ -5914,6 +5926,17 @@
/>
{/if}
+{#if claimFor && !snapshotReading}
+ <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}
<Modal title="Details" onclose={() => (openId = null)} width="640px">
<EntityDetails
diff --git a/frontend/src/tools/Graph.test.js b/frontend/src/tools/Graph.test.js
index dd2c6a2..c6b03e8 100644
--- a/frontend/src/tools/Graph.test.js
+++ b/frontend/src/tools/Graph.test.js
@@ -2132,3 +2132,17 @@ describe('exporting the drawing', () => {
expect(source).toContain('<PlateExport surface="graph" plate={capturePlate}');
});
});
+
+describe('filing a claim from a node', () => {
+ it('names it in the node menu wherever the verb registry gives the node a seat', () => {
+ 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…');
+ });
+
+ 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('{#if claimFor && !snapshotReading}');
+ });
+});
diff --git a/frontend/src/tools/Inspector.svelte b/frontend/src/tools/Inspector.svelte
index 5a23828..bccc204 100644
--- a/frontend/src/tools/Inspector.svelte
+++ b/frontend/src/tools/Inspector.svelte
@@ -15,6 +15,7 @@
} from '../lib/naming.js';
import { createHistory } from '../lib/history.js';
import { deletedToast } from '../lib/trash.js';
+ import { openInReverseSearch } from '../lib/navigate.js';
import { IDENTITY, matrixCss, rotateAbout, isIdentity, matrixAngleDeg, pointerAngleDeg } from '../lib/frameRotate.js';
import Icon from '../components/Icon.svelte';
import SearchInput from '../components/SearchInput.svelte';
@@ -614,8 +615,8 @@
};
}
- // Render a recipe (video frame / image + ops) to a blob URL, no filing.
- async function renderUrl(path, time, ops = []) {
+ // Render a recipe (video frame / image + ops) to a PNG, no filing.
+ async function renderBlob(path, time, ops = []) {
const res = await fetch(`/api/cases/${caseState.current.id}/inspect/render-preview`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
@@ -630,7 +631,26 @@
}
throw new Error(detail);
}
- return URL.createObjectURL(await res.blob());
+ return res.blob();
+ }
+
+ async function renderUrl(path, time, ops = []) {
+ return URL.createObjectURL(await renderBlob(path, time, ops));
+ }
+
+ /**
+ * Hand a tray frame to Reverse Search as it reads here — turned, adjusted and
+ * cropped — without filing it. The crop is usually the subject, and an engine
+ * matches a subject better than the whole picture it sits in.
+ */
+ async function reverseFrame(frame) {
+ try {
+ const blob = await renderBlob(frame.path, frame.time, buildFrameOps(filters, frame));
+ const name = session.source?.title || session.source?.filename || frame.path.split('/').pop();
+ openInReverseSearch({ blob, label: frame.time != null ? `${name} · t=${frame.time.toFixed(2)}s` : name });
+ } catch (e) {
+ toast(e.message, 'danger');
+ }
}
function imageSize(url) {
@@ -1447,6 +1467,7 @@
bind:cropAspect={frameAspect} bind:cropEditing {beginCrop} {commitCrop}
setRotation={setFrameRotation} rotationBusy={frameOrientationBusy}
setActive={(id) => (session.activeFrameId = id)}
+ reverse={reverseFrame}
/>
{:else if activeTab === 'collage'}
<CollageMenu
@@ -1504,7 +1525,7 @@
<div class="modal source-modal" onclick={(e) => e.stopPropagation()} role="dialog" aria-modal="true" aria-labelledby="new-session-title" tabindex="-1">
<div class="modal-head">
<h3 id="new-session-title">New session</h3>
- <button class="btn btn-ghost btn-xs" onclick={() => (sourceModalOpen = false)} aria-label="Close">
+ <button class="btn btn-ghost btn-xs" onclick={() => (sourceModalOpen = false)} aria-label="Close" title="Close">
<Icon name="x" size={15} />
</button>
</div>
@@ -1592,7 +1613,7 @@
<div class="modal" onclick={(e) => e.stopPropagation()} role="dialog" aria-modal="true" tabindex="-1">
<div class="modal-head">
<h3>Open session</h3>
- <button class="btn btn-ghost btn-xs" onclick={() => (sessionModal.open = false)} aria-label="Close">
+ <button class="btn btn-ghost btn-xs" onclick={() => (sessionModal.open = false)} aria-label="Close" title="Close">
<Icon name="x" size={15} />
</button>
</div>
@@ -1640,7 +1661,7 @@
<span class="session-title">{s.title}</span>
<span class="session-meta">{s.frames} frame{s.frames === 1 ? '' : 's'} · {s.collage} collage piece{s.collage === 1 ? '' : 's'}</span>
</button>
- <button class="btn btn-ghost btn-xs" disabled={sessionLoading} onclick={() => deleteSession(s.name)} aria-label="Delete session">
+ <button class="btn btn-ghost btn-xs" disabled={sessionLoading} onclick={() => deleteSession(s.name)} aria-label="Delete session" title="Delete session">
<Icon name="trash" size={14} />
</button>
</div>
diff --git a/frontend/src/tools/Inspector.test.js b/frontend/src/tools/Inspector.test.js
index d69f7ce..d5658fc 100644
--- a/frontend/src/tools/Inspector.test.js
+++ b/frontend/src/tools/Inspector.test.js
@@ -206,3 +206,20 @@ describe('Inspect — work that outlived what it was started against', () => {
expect(source).toContain('cropBefore = activeFrame.crop ? { ...activeFrame.crop } : null;');
});
});
+
+describe('Inspect → Reverse Search', () => {
+ it('hands the frame over as it reads here, rendered without filing it', () => {
+ // The same recipe Save and the collage use, so what is searched is what is
+ // on screen: turned, adjusted and cropped.
+ expect(source).toContain(
+ 'const blob = await renderBlob(frame.path, frame.time, buildFrameOps(filters, frame));'
+ );
+ expect(source).toContain('openInReverseSearch({ blob, label:');
+ expect(source).toContain('reverse={reverseFrame}');
+ });
+
+ it('keeps one render route for the tray, the collage and the handoff', () => {
+ expect(source).toContain('return URL.createObjectURL(await renderBlob(path, time, ops));');
+ expect(source.match(/inspect\/render-preview/g)).toHaveLength(1);
+ });
+});
diff --git a/frontend/src/tools/MediaLibrary.render.test.js b/frontend/src/tools/MediaLibrary.render.test.js
index edd9c99..96723df 100644
--- a/frontend/src/tools/MediaLibrary.render.test.js
+++ b/frontend/src/tools/MediaLibrary.render.test.js
@@ -99,6 +99,10 @@ async function key(name) {
beforeEach(() => {
page = { items: ITEMS, total: ITEMS.length, next_cursor: null, facets: {} };
+ uiState.tool = 'media';
+ uiState.reverseTarget = null;
+ uiState.inspectPath = null;
+ uiState.composeQueue = [];
vi.clearAllMocks();
});
@@ -174,3 +178,101 @@ describe('the upkeep menu', () => {
expect(rows().map((r) => r.disabled)).toEqual([true, true]);
});
});
+
+describe('open in… from a row', () => {
+ const doors = () => [...target.querySelectorAll('[title="Open in…"]')];
+ const doorOf = (path) => doors().find((b) => b.closest('[data-path]')?.dataset.path === path);
+ const choices = () =>
+ [...document.querySelectorAll('.open-in-menu [role="menuitem"]')].map((b) => b.textContent.trim());
+ const choice = (label) =>
+ [...document.querySelectorAll('.open-in-menu [role="menuitem"]')].find((b) => b.textContent.trim() === label);
+
+ it('keeps the tools behind one door per row instead of a button each', async () => {
+ await open();
+ expect(doors()).toHaveLength(2);
+ expect(target.querySelector('[title="Open in Inspect"]')).toBeNull();
+ expect(target.querySelector('[title="Send to Geo Proof"]')).toBeNull();
+ });
+
+ it('offers Geo Proof for a picture and not for a video', async () => {
+ await open();
+ await press(doorOf('media/quai.jpg'));
+ expect(choices()).toEqual(['Inspect', 'Reverse Search', 'Geo Proof']);
+
+ await press(doorOf('media/clip.mp4'));
+ expect(choices()).toEqual(['Inspect', 'Reverse Search']);
+ });
+
+ it('hands Reverse Search the row it was opened on, and closes', async () => {
+ // By the row rather than by position: the list is sorted, and the failure
+ // worth catching is a menu that sends the other row's file.
+ await open();
+ await press(doorOf('media/clip.mp4'));
+ await press(choice('Reverse Search'));
+
+ expect(uiState.tool).toBe('reverse');
+ expect(uiState.reverseTarget).toEqual({
+ path: 'media/clip.mp4',
+ blob: null,
+ kind: 'video',
+ label: 'clip.mp4',
+ time: null,
+ });
+ expect(document.querySelector('.open-in-menu')).toBeNull();
+ });
+
+ it('still reaches Inspect and Geo Proof', async () => {
+ await open();
+ await press(doorOf('media/quai.jpg'));
+ await press(choice('Inspect'));
+ expect(uiState.tool).toBe('inspect');
+ expect(uiState.inspectPath).toBe('media/quai.jpg');
+
+ await press(doorOf('media/quai.jpg'));
+ await press(choice('Geo Proof'));
+ expect(uiState.tool).toBe('proof');
+ expect(uiState.composeQueue).toContain('media/quai.jpg');
+ });
+
+ it('closes on the backdrop and on Escape without going anywhere', async () => {
+ await open();
+ await press(doorOf('media/quai.jpg'));
+ await press(document.querySelector('.open-in-backdrop'));
+ expect(document.querySelector('.open-in-menu')).toBeNull();
+
+ await press(doorOf('media/quai.jpg'));
+ await key('Escape');
+ expect(document.querySelector('.open-in-menu')).toBeNull();
+ expect(uiState.tool).toBe('media');
+ });
+
+ it('opens toward the side with room, so a card by the rail does not hang over it', async () => {
+ const rect = (left, right) => () => ({ left, right, top: 300, bottom: 330, width: right - left, height: 30 });
+ await open();
+
+ const door = doorOf('media/quai.jpg');
+ door.getBoundingClientRect = rect(160, 190);
+ await press(door);
+ let menu = document.querySelector('.open-in-menu');
+ expect(menu.style.left).toBe('160px');
+ expect(menu.style.right).toBe('');
+
+ await press(door); // closes
+ door.getBoundingClientRect = rect(window.innerWidth - 60, window.innerWidth - 30);
+ await press(door);
+ menu = document.querySelector('.open-in-menu');
+ expect(menu.style.right).toBe('30px');
+ expect(menu.style.left).toBe('');
+ });
+
+ it('gives a document no door', async () => {
+ page = {
+ items: [{ ...ITEMS[0], path: 'media/plan.pdf', filename: 'plan.pdf', kind: 'file', thumbnail: null }],
+ total: 1,
+ next_cursor: null,
+ facets: {},
+ };
+ await open();
+ expect(doors()).toHaveLength(0);
+ });
+});
diff --git a/frontend/src/tools/MediaLibrary.svelte b/frontend/src/tools/MediaLibrary.svelte
index 97e0aa1..b1db0e5 100644
--- a/frontend/src/tools/MediaLibrary.svelte
+++ b/frontend/src/tools/MediaLibrary.svelte
@@ -18,7 +18,8 @@
SORTS,
} from '../lib/mediaFilter.js';
import { listenForPaste, pasteImage, resolvePaste } from '../lib/clipboardPaste.js';
- import { gotoPoint } from '../lib/navigate.js';
+ import { gotoPoint, openInReverseSearch } from '../lib/navigate.js';
+ import { TOOL_LABELS } from '../lib/workspaces.js';
import { revealMediaFolder } from '../lib/reveal.js';
import { thisBrowser } from '../lib/thisBrowser.js';
import { deletedToast, RESTORABLE } from '../lib/trash.js';
@@ -307,13 +308,14 @@
lightboxItem = lightboxImages[next];
}
- // One handler for the tool's two overlays: the lightbox owns the arrows, the
- // upkeep menu only needs the Escape, and it reads first because it is the one
+ // One handler for the tool's overlays: the lightbox owns the arrows, the two
+ // menus only need the Escape, and they read first because they are the ones
// that can be open while the lightbox is not.
function onMediaKey(e) {
if (uiState.tool !== 'media') return;
- if (e.key === 'Escape' && upkeepOpen) {
+ if (e.key === 'Escape' && (upkeepOpen || openIn)) {
upkeepOpen = false;
+ openIn = null;
return;
}
if (!lightboxItem) return;
@@ -713,6 +715,53 @@
uiState.tool = 'inspect';
}
+ function reverseSearch(item) {
+ openInReverseSearch({ path: item.path, kind: item.kind, label: item.title ?? item.filename });
+ }
+
+ // --- open in… ---
+ // The tools a picture can be taken on to, behind one door per row. Three of them
+ // side by side made the widest row seven buttons, and a small card more buttons
+ // than card; the ones that stay out are about the file itself.
+ const OPEN_IN_HEIGHT = 130; // room the menu needs under its button before it opens upward
+ let openIn = $state(null); // { item, left, right, top, bottom } while a row's menu is up
+
+ const openInOptions = (item) => [
+ { id: 'inspect', icon: 'inspect', run: inspect },
+ { id: 'reverse', icon: 'search', run: reverseSearch },
+ ...(item.kind === 'image' ? [{ id: 'proof', icon: 'proof', run: sendToComposer }] : []),
+ ];
+
+ /**
+ * Open a row's menu beside its button. Placed against the window rather than
+ * inside the row: a card clips what overflows it and the list scrolls, and a menu
+ * cut off at the bottom row is one whose last choice cannot be pressed.
+ */
+ function toggleOpenIn(event, item) {
+ if (openIn?.item.path === item.path) {
+ openIn = null;
+ return;
+ }
+ const at = event.currentTarget.getBoundingClientRect();
+ const below = window.innerHeight - at.bottom > OPEN_IN_HEIGHT;
+ // Toward whichever side has more room: a list row's button sits at the far right
+ // and hangs its menu leftward, a card by the rail opens away from the rail.
+ const leftward = at.left > window.innerWidth - at.right;
+ openIn = {
+ item,
+ left: leftward ? null : at.left,
+ right: leftward ? window.innerWidth - at.right : null,
+ top: below ? at.bottom + 4 : null,
+ bottom: below ? null : window.innerHeight - at.top + 4,
+ };
+ }
+
+ function runOpenIn(option) {
+ const { item } = openIn;
+ openIn = null;
+ option.run(item);
+ }
+
function fmtSize(bytes) {
if (bytes == null) return '—';
if (bytes >= 1 << 30) return (bytes / (1 << 30)).toFixed(1) + ' GB';
@@ -825,6 +874,23 @@
}
</script>
+<!-- A picture or a video goes on to other tools from here; any other file has no
+ tool to go to, so it gets no door. -->
+{#snippet openInToggle(item)}
+ {#if item.kind === 'image' || item.kind === 'video'}
+ <button
+ class="btn btn-ghost btn-sm"
+ class:active={openIn?.item.path === item.path}
+ title="Open in…"
+ aria-haspopup="menu"
+ aria-expanded={openIn?.item.path === item.path}
+ onclick={(event) => toggleOpenIn(event, item)}
+ >
+ <Icon name="arrowRight" size={14} />
+ </button>
+ {/if}
+{/snippet}
+
<div
class="tool"
role="region"
@@ -867,7 +933,7 @@
<button
class="btn upkeep-toggle"
onclick={() => (upkeepOpen = !upkeepOpen)}
- aria-label="Media upkeep"
+ aria-label="Media upkeep" title="Media upkeep"
aria-haspopup="menu"
aria-expanded={upkeepOpen}
>
@@ -1152,16 +1218,7 @@
<Icon name="external" size={14} />
</a>
{/if}
- {#if item.kind === 'image' || item.kind === 'video'}
- <button class="btn btn-ghost btn-sm" title="Open in Inspect" onclick={() => inspect(item)}>
- <Icon name="inspect" size={14} />
- </button>
- {/if}
- {#if item.kind === 'image'}
- <button class="btn btn-ghost btn-sm" title="Send to Geo Proof" onclick={() => sendToComposer(item)}>
- <Icon name="proof" size={14} />
- </button>
- {/if}
+ {@render openInToggle(item)}
<button class="btn btn-ghost btn-sm del" title="Delete" onclick={() => (deleteTarget = item)}>
<Icon name="trash" size={14} />
</button>
@@ -1277,24 +1334,7 @@
<Icon name="external" size={14} />
</a>
{/if}
- {#if item.kind === 'image' || item.kind === 'video'}
- <button
- class="btn btn-ghost btn-sm"
- title="Open in Inspect"
- onclick={() => inspect(item)}
- >
- <Icon name="inspect" size={14} />
- </button>
- {/if}
- {#if item.kind === 'image'}
- <button
- class="btn btn-ghost btn-sm"
- title="Send to Geo Proof"
- onclick={() => sendToComposer(item)}
- >
- <Icon name="proof" size={14} />
- </button>
- {/if}
+ {@render openInToggle(item)}
<button class="btn btn-ghost btn-sm del" title="Delete" onclick={() => (deleteTarget = item)}>
<Icon name="trash" size={14} />
</button>
@@ -1323,6 +1363,26 @@
{/if}
</div>
+{#if openIn}
+ <button class="open-in-backdrop" onclick={() => (openIn = null)} aria-label="Close the Open in menu"></button>
+ <div
+ class="open-in-menu card"
+ role="menu"
+ aria-label={`Open ${openIn.item.title ?? openIn.item.filename} in`}
+ style:left={openIn.left == null ? null : `${openIn.left}px`}
+ style:right={openIn.right == null ? null : `${openIn.right}px`}
+ style:top={openIn.top == null ? null : `${openIn.top}px`}
+ style:bottom={openIn.bottom == null ? null : `${openIn.bottom}px`}
+ >
+ {#each openInOptions(openIn.item) as option (option.id)}
+ <button class="upkeep-option" role="menuitem" onclick={() => runOpenIn(option)}>
+ <Icon name={option.icon} size={14} />
+ <span>{TOOL_LABELS[option.id]}</span>
+ </button>
+ {/each}
+ </div>
+{/if}
+
<!-- multi-item picker: shown when a URL has several attachments (e.g. a tweet
with several photos) — pick which ones to download, before anything is fetched -->
{#if picker}
@@ -1495,7 +1555,7 @@
aria-label="Image preview"
tabindex="-1"
>
- <button class="lb-close btn btn-ghost" onclick={() => (lightboxItem = null)} aria-label="Close">
+ <button class="lb-close btn btn-ghost" onclick={() => (lightboxItem = null)} aria-label="Close" title="Close">
<Icon name="x" size={20} />
</button>
{#if lightboxImages.length > 1}
@@ -1590,6 +1650,21 @@
width: min(480px, 40vw);
}
+ /* open in… — fixed to the window, so neither a card nor the scrolling list clips it */
+ .open-in-backdrop {
+ position: fixed;
+ inset: 0;
+ z-index: 90;
+ cursor: default;
+ }
+ .open-in-menu {
+ position: fixed;
+ z-index: 100;
+ min-width: 180px;
+ padding: 5px;
+ box-shadow: var(--shadow-2);
+ }
+
/* upkeep menu */
.upkeep {
position: relative;
@@ -1940,18 +2015,18 @@
So the actions cell is a fixed width, and it is computed rather than typed:
one ghost icon button is a 14px glyph plus 8px of padding and a 1px border
- on each side, and the widest row holds six of them — GPS pin, info,
- open, inspect, proof, delete. A literal here goes stale the next time a tool earns
+ on each side, and the widest row holds five of them — GPS pin, info,
+ open, open in, delete. A literal here goes stale the next time a tool earns
a row action, and the symptom is the delete button quietly clipped off the
end of the row. */
--media-action: 32px;
--media-action-gap: 2px;
- /* the seven buttons plus slack. Sized to the exact sum, the cell fits only
+ /* the buttons plus slack. Sized to the exact sum, the cell fits only
until a sub-pixel of rounding says otherwise, and then Delete — which
`margin-left: auto` holds at the right edge — is the one that goes. The
slack is also where that auto margin lives, so the row still reads as
"actions, then delete". */
- --media-actions: calc(6 * var(--media-action) + 5 * var(--media-action-gap) + 10px);
+ --media-actions: calc(5 * var(--media-action) + 4 * var(--media-action-gap) + 10px);
--media-columns: 54px minmax(180px, 1fr) 90px 82px minmax(100px, 0.45fr) 132px
var(--media-actions);
padding: 6px 20px 18px;
diff --git a/frontend/src/tools/MediaLibrary.test.js b/frontend/src/tools/MediaLibrary.test.js
index f834224..25f64d8 100644
--- a/frontend/src/tools/MediaLibrary.test.js
+++ b/frontend/src/tools/MediaLibrary.test.js
@@ -384,12 +384,12 @@ describe('row and card actions fit', () => {
const source = readFileSync(new URL('./MediaLibrary.svelte', import.meta.url), 'utf8');
it('sizes the list actions cell from the widest row, not from a literal', () => {
- // six at its widest: GPS pin, info, open, inspect, proof, delete. A typed
- // width goes stale the next time a tool earns a row action, and the symptom
- // is Delete clipped off the end of the row.
+ // five at its widest: GPS pin, info, open, open in, delete. A typed width
+ // goes stale the next time a tool earns a row action, and the symptom is
+ // Delete clipped off the end of the row.
expect(source).toContain('--media-action: 32px');
expect(source).toContain(
- '--media-actions: calc(6 * var(--media-action) + 5 * var(--media-action-gap) + 10px)'
+ '--media-actions: calc(5 * var(--media-action) + 4 * var(--media-action-gap) + 10px)'
);
// sized to the exact sum, the cell fits only until a sub-pixel of rounding
// says otherwise, and then Delete wraps to a line of its own
diff --git a/frontend/src/tools/Notebook.svelte b/frontend/src/tools/Notebook.svelte
index 651d5f2..8ed831d 100644
--- a/frontend/src/tools/Notebook.svelte
+++ b/frontend/src/tools/Notebook.svelte
@@ -678,7 +678,7 @@
<button class="tab-main" onclick={() => selectTab(tab)} title={tabTitle}>
<Icon name="note" size={13} /><span>{tabTitle}</span>
</button>
- {#if tab.id !== 'case'}<button class="tab-close" aria-label={`Close ${tabTitle}`} onclick={(event) => closeTab(event, tab)}><Icon name="x" size={12} /></button>{/if}
+ {#if tab.id !== 'case'}<button class="tab-close" aria-label={`Close ${tabTitle}`} title={`Close ${tabTitle}`} onclick={(event) => closeTab(event, tab)}><Icon name="x" size={12} /></button>{/if}
</div>
{/each}
</div>
@@ -712,7 +712,7 @@
aria-expanded={!markdownHelpCollapsed}
onclick={toggleMarkdownHelpCollapsed}
><Icon name={markdownHelpCollapsed ? 'chevronDown' : 'chevronUp'} size={14} /></button>
- <button class="btn btn-ghost btn-sm" aria-label="Close Markdown help" onclick={() => (markdownHelpOpen = false)}><Icon name="x" size={14} /></button>
+ <button class="btn btn-ghost btn-sm" aria-label="Close Markdown help" title="Close Markdown help" onclick={() => (markdownHelpOpen = false)}><Icon name="x" size={14} /></button>
</div>
{#if !markdownHelpCollapsed}
<div class="help-body">
diff --git a/frontend/src/tools/Overview.render.test.js b/frontend/src/tools/Overview.render.test.js
index 19d5549..98afeaf 100644
--- a/frontend/src/tools/Overview.render.test.js
+++ b/frontend/src/tools/Overview.render.test.js
@@ -241,6 +241,19 @@ describe('with a case open', () => {
expect(uiState.tool).toBe('media');
});
+ it('reads the recent work first and the counts after it', async () => {
+ await open();
+ const recent = target.querySelector('.area-recent');
+ const waiting = target.querySelector('.area-waiting');
+ expect(recent).not.toBeNull();
+ // DOCUMENT_POSITION_FOLLOWING: the counts come after the work, for a reader too
+ expect(recent.compareDocumentPosition(waiting) & 4).toBe(4);
+ // a count keeps the sentence saying what it means, on the pointer
+ const tile = target.querySelector('.tiles .tile');
+ expect(tile.getAttribute('title')).toBeTruthy();
+ expect(tile.querySelector('.say-hint')).toBeNull();
+ });
+
it('draws the case by family in the hues the Graph gives those families', async () => {
await open();
const bars = [...target.querySelectorAll('.bars li')];
diff --git a/frontend/src/tools/Overview.svelte b/frontend/src/tools/Overview.svelte
index 114881a..2a19a31 100644
--- a/frontend/src/tools/Overview.svelte
+++ b/frontend/src/tools/Overview.svelte
@@ -258,6 +258,44 @@
</ul>
</section>
{:else}
+ <!-- What was just filed comes first: it is what somebody coming back
+ reaches for. The counts below it are upkeep, read second. -->
+ {#if recent.length}
+ <section class="area-recent">
+ <h2 class="label">
+ <span>Recent work</span>
+ {#if week}
+ <button class="aside" onclick={() => askBoard('week')}>
+ {week} added this week
+ </button>
+ {/if}
+ </h2>
+ <ul class="rows">
+ {#each recent as item (item.id)}
+ {@const src = thumbSrc(item)}
+ <li>
+ <button class="row thin" onclick={() => openEntity(item)}>
+ <span class="glyph" class:shot={Boolean(src)}>
+ {#if src}
+ <img src={src} alt="" loading="lazy" />
+ {:else}
+ <Icon name={entityIcon(item)} size={15} />
+ {/if}
+ </span>
+ <span class="say">
+ <span class="say-label">{item.label}</span>
+ <span class="say-hint">{entityKindLabel(item, entityLabel(item.type))}</span>
+ </span>
+ <span class="when" title={exactStamp(item.provenance?.at)}>
+ {timeAgo(item.provenance?.at)}
+ </span>
+ </button>
+ </li>
+ {/each}
+ </ul>
+ </section>
+ {/if}
+
<section class="area-waiting">
<h2 class="label">What is waiting</h2>
{#if !summary}
@@ -272,13 +310,12 @@
class="tile"
class:none={row.count === 0}
disabled={row.count === 0}
- title={row.count === 0 ? 'Nothing here' : row.hint}
+ title={row.hint}
onclick={() => ask(row)}
>
<span class="tile-mark"><Icon name={row.icon} size={15} /></span>
<span class="n">{row.count}</span>
<span class="say-label">{row.label}</span>
- <span class="say-hint">{row.hint}</span>
</button>
</li>
{/each}
@@ -298,41 +335,6 @@
</section>
{/if}
- {#if recent.length}
- <section class="area-recent">
- <h2 class="label">
- <span>Recent work</span>
- {#if week}
- <button class="aside" onclick={() => askBoard('week')}>
- {week} added this week
- </button>
- {/if}
- </h2>
- <ul class="rows">
- {#each recent as item (item.id)}
- {@const src = thumbSrc(item)}
- <li>
- <button class="row thin" onclick={() => openEntity(item)}>
- <span class="glyph" class:shot={Boolean(src)}>
- {#if src}
- <img src={src} alt="" loading="lazy" />
- {:else}
- <Icon name={entityIcon(item)} size={15} />
- {/if}
- </span>
- <span class="say">
- <span class="say-label">{item.label}</span>
- <span class="say-hint">{entityKindLabel(item, entityLabel(item.type))}</span>
- </span>
- <span class="when" title={exactStamp(item.provenance?.at)}>
- {timeAgo(item.provenance?.at)}
- </span>
- </button>
- </li>
- {/each}
- </ul>
- </section>
- {/if}
{#if bars.length}
<section class="area-figures">
@@ -571,9 +573,9 @@
display: grid;
grid-template-columns: minmax(0, 1.05fr) minmax(0, 0.95fr);
grid-template-areas:
- 'waiting places'
- 'todos figures'
- 'recent recent';
+ 'recent places'
+ 'todos waiting'
+ 'todos figures';
gap: 30px 40px;
align-items: start;
padding-top: 4px;
@@ -582,9 +584,8 @@
than leaving a hole where the map would have been. */
.grid.flat {
grid-template-areas:
- 'waiting figures'
- 'todos .'
- 'recent recent';
+ 'recent waiting'
+ 'todos figures';
}
.grid.empty-case {
grid-template-areas: 'todos start';
@@ -614,7 +615,7 @@
.grid.flat,
.grid.empty-case {
grid-template-columns: minmax(0, 1fr);
- grid-template-areas: 'waiting' 'todos' 'places' 'recent' 'figures';
+ grid-template-areas: 'recent' 'todos' 'places' 'waiting' 'figures';
gap: 30px;
}
.grid.empty-case {
@@ -630,24 +631,25 @@
margin-bottom: 10px;
}
- /* Four counts as tiles rather than four lines: this is the band somebody opens the
- app to read, and a number is read at a glance or it is not read. */
+ /* Four counts, read after the work itself: one line each, number first, and the
+ sentence saying what the count means kept for the pointer. They are upkeep
+ somebody glances at, not the band the page is opened for. */
.tiles {
display: grid;
grid-template-columns: 1fr 1fr;
- gap: 10px;
+ gap: 6px;
list-style: none;
margin: 0;
padding: 0;
}
.tile {
display: grid;
- grid-template-columns: minmax(0, 1fr) auto;
- align-items: start;
+ grid-template-columns: auto minmax(0, 1fr) auto;
+ align-items: center;
gap: 0 8px;
width: 100%;
height: 100%;
- padding: 13px 14px 14px;
+ padding: 7px 10px;
border: 1px solid var(--border);
border-radius: var(--r-md);
background: var(--bg-1);
@@ -661,7 +663,7 @@
outline: none;
}
.tile-mark {
- grid-column: 2;
+ grid-column: 3;
grid-row: 1;
display: flex;
color: var(--text-3);
@@ -669,30 +671,19 @@
.tile .n {
grid-column: 1;
grid-row: 1;
- font-size: 1.75rem;
+ font-size: 1.1rem;
font-weight: 600;
font-variant-numeric: tabular-nums;
- letter-spacing: -0.03em;
- line-height: 1.1;
+ line-height: 1.2;
color: var(--text-1);
}
.tile .say-label {
- grid-column: 1 / -1;
- margin-top: 6px;
- }
- /* A tile is not a row: the hint has the width to be read, so it wraps to a second
- line rather than being cut off mid-clause. */
- .tile .say-hint {
- grid-column: 1 / -1;
- display: -webkit-box;
- -webkit-box-orient: vertical;
- -webkit-line-clamp: 2;
- line-clamp: 2;
- white-space: normal;
- line-height: 1.45;
- }
- /* A count of nothing is the answer, so the tile states it and stops being a control
- rather than offering a press that lands on an empty table. */
+ grid-column: 2;
+ grid-row: 1;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
.tile.none {
cursor: default;
background: transparent;
@@ -702,9 +693,6 @@
color: var(--text-3);
font-weight: 500;
}
- .tile.none .say-hint {
- opacity: 0.65;
- }
.rows {
list-style: none;
diff --git a/frontend/src/tools/PostComposer.svelte b/frontend/src/tools/PostComposer.svelte
index 8571e87..c168b79 100644
--- a/frontend/src/tools/PostComposer.svelte
+++ b/frontend/src/tools/PostComposer.svelte
@@ -23,6 +23,7 @@
} from '../lib/post.js';
import { extensionOutdated, extensionVersion, handOffPost } from '../lib/extBridge.js';
import { bidiSafe } from '../lib/bidi.js';
+ import { mapLinks } from '../lib/maplinks.js';
import { matchesQuery } from '../lib/mediaFilter.js';
import Icon from '../components/Icon.svelte';
import SearchInput from '../components/SearchInput.svelte';
@@ -31,7 +32,9 @@
import FolderSelect from '../components/FolderSelect.svelte';
let coordsText = $state('');
- let geo = $state(null); // {lat, lon, dms, plus_code, links}
+ let geo = $state(null); // {lat, lon, dms, plus_code}
+ // The same verified table Coords & Sky and the point menu open, labelled for a reader.
+ const geoLinks = $derived(geo ? mapLinks(geo.lat, geo.lon) : []);
let place = $state('');
let placeLoading = $state(false);
let description = $state('');
@@ -933,7 +936,7 @@
coordinates,
points,
dms: geo?.dms,
- mapLinks: geo?.links,
+ mapLinks: Object.fromEntries(geoLinks.map((link) => [link.label, link.url])),
description,
source,
attachments: reportAttachmentPaths(),
@@ -1085,10 +1088,10 @@
<Icon name="reset" size={14} /> Discard
</button>
{/if}
- <button class="btn btn-ghost btn-sm" onclick={saveDraft} disabled={saving || !postName.trim()}>
+ <button class="btn btn-ghost 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}>
+ <button class="btn btn-ghost 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}`}>
@@ -1208,8 +1211,8 @@
<Icon name="hash" size={12} /> {geo.plus_code}
</button>
<div class="links">
- {#each Object.entries(geo.links) as [name, url] (name)}
- <a href={url} target="_blank" rel="noreferrer" class="badge info">{name}</a>
+ {#each geoLinks as link (link.id)}
+ <a href={link.url} target="_blank" rel="noreferrer" class="badge info">{link.label}</a>
{/each}
</div>
</div>
diff --git a/frontend/src/tools/PostComposer.test.js b/frontend/src/tools/PostComposer.test.js
index 059dee1..091b84d 100644
--- a/frontend/src/tools/PostComposer.test.js
+++ b/frontend/src/tools/PostComposer.test.js
@@ -45,6 +45,22 @@ describe('Geo Report actions', () => {
expect(source).toContain("...(draftName ? [specPath('draft', draftName)] : []),");
});
+ it('says what each save produces', () => {
+ caseState.current = { id: 'case-1', folders: [], entities: [] };
+ const { body } = render(PostComposer);
+ expect(body).toContain('title="Keep this thread to reopen and edit here"');
+ expect(body).toContain('title="Write the finding up as a Notebook note"');
+ });
+
+ it('labels the map links from the verified table rather than printing site ids', () => {
+ expect(source).toContain("import { mapLinks } from '../lib/maplinks.js';");
+ expect(source).toContain('const geoLinks = $derived(geo ? mapLinks(geo.lat, geo.lon) : []);');
+ expect(source).toContain('>{link.label}</a>');
+ // the saved report writes the same labels
+ expect(source).toContain('mapLinks: Object.fromEntries(geoLinks.map((link) => [link.label, link.url])),');
+ expect(source).not.toContain('geo.links');
+ });
+
it('checks the current hidden draft path before claiming a saved draft was deleted', () => {
expect(source).toContain("lookupEntity(id, specAttr('draft'), specPath('draft', draft))");
});
diff --git a/frontend/src/tools/ProofComposer.svelte b/frontend/src/tools/ProofComposer.svelte
index 60280ea..f8351dc 100644
--- a/frontend/src/tools/ProofComposer.svelte
+++ b/frontend/src/tools/ProofComposer.svelte
@@ -14,7 +14,7 @@
import { templatesState } from '../lib/state.svelte.js';
import Icon from '../components/Icon.svelte';
import Modal from '../components/Modal.svelte';
- import TemporalInput from '../components/TemporalInput.svelte';
+ import DateField from '../components/DateField.svelte';
import SearchInput from '../components/SearchInput.svelte';
import FolderBrowser from '../components/FolderBrowser.svelte';
import ConfirmDialog from '../components/ConfirmDialog.svelte';
@@ -37,7 +37,7 @@
BG, TEXT_MAIN, normSpace, textColors,
layoutPanels, panelsBottom, panelScale, freeNormalizeDelta, legendLineHeight, footerBand,
attributionLine, docSize, offsetShape, autoLayoutRows,
- autoCoords, formatCoords, autoSourceUrls, proofSource, statedSources,
+ autoCoords, formatCoords, autoSourceUrls, proofSource, statedSources, openableSource,
specPoints, statePanelPoint, footerLines, coordsPostLines, proofCoordsLines, MAX_POINTS,
normalizeMaterial, resolveSourceUrls,
toSpec, newId, loadImage, orderedFeatureColors, notesFromShapes,
@@ -68,6 +68,8 @@
viewCentrePoint,
} from '../lib/proofEdits.js';
import {
+ blurPatch,
+ blurRadiusFor,
mapSurfaceShapes,
normalizeSourceCrop,
normalizeSurfaceAngle,
@@ -103,6 +105,8 @@
{ id: 'curve', icon: 'curve', label: 'Curve (click points, double-click to finish)', shortcut: 'c' },
{ id: 'freehand', icon: 'freehand', label: 'Freehand', shortcut: 'd' },
{ id: 'text', icon: 'text', label: 'Text', shortcut: 't' },
+ { id: 'number', icon: 'numbered', label: 'Numbered marker', shortcut: 'n' },
+ { id: 'blur', icon: 'blurBox', label: 'Blur box', shortcut: 'b' },
];
// Document state. Notes are keyed by color, shapes bind to surfaces and pasted
@@ -1732,6 +1736,20 @@
dirty = true;
return;
}
+ // A numbered marker is stamped like a symbol, and keeps the tool: numbering
+ // four things in a picture is one act. The number is the first one free in
+ // its own colour, so deleting #2 and stamping again fills the hole rather
+ // than leaving a proof that counts 1, 3, 4.
+ if (tool === 'number') {
+ const s = {
+ id: newId('s'), panel: panel.id, kind: 'number', color,
+ x: hit.nx, y: hit.ny, size: iconSizeFor(hit.box.baseScale), n: nextMarkerNumber(color),
+ };
+ proof.shapes.push(s);
+ selectedIds = [s.id];
+ dirty = true;
+ return;
+ }
// curve: each click drops a vertex; double-click / Enter finishes
if (tool === 'curve') {
// A vertex dropped on another surface ends the curve where it was and
@@ -1772,6 +1790,16 @@
node = new Konva.Rect({
x: hit.nx, y: hit.ny, width: 1, height: 1, cornerRadius: 2, fill: paint, ...common,
});
+ } else if (tool === 'blur') {
+ // The draft is a dashed box over a darkened patch: the blur itself is
+ // built from the picture once the box is a box, and a filter re-applied
+ // on every pointer move would blur the whole drag.
+ node = new Konva.Rect({
+ x: hit.nx, y: hit.ny, width: 1, height: 1,
+ fill: 'rgba(20, 22, 26, 0.45)',
+ dash: [7 / hit.box.baseScale, 5 / hit.box.baseScale],
+ ...common,
+ });
} else if (tool === 'ellipse') {
node = new Konva.Ellipse({ x: hit.nx, y: hit.ny, radiusX: 1, radiusY: 1, fill: paint, ...common });
} else {
@@ -1830,7 +1858,7 @@
const lx = points[points.length - 2];
const ly = points[points.length - 1];
if (nx !== lx || ny !== ly) node.points([...points, nx, ny]);
- } else if (kind === 'rect') {
+ } else if (kind === 'rect' || kind === 'blur') {
node.setAttrs({
x: Math.min(start.x, nx), y: Math.min(start.y, ny),
width: Math.abs(nx - start.x), height: Math.abs(ny - start.y),
@@ -1883,7 +1911,7 @@
drawing = null;
const minSize = 5 / box.scale;
let shape = null;
- if (kind === 'rect' && node.width() > minSize && node.height() > minSize) {
+ if ((kind === 'rect' || kind === 'blur') && node.width() > minSize && node.height() > minSize) {
shape = { kind, x: node.x(), y: node.y(), w: node.width(), h: node.height() };
} else if (kind === 'ellipse' && node.radiusX() * 2 > minSize && node.radiusY() * 2 > minSize) {
shape = { kind, x: node.x(), y: node.y(), w: node.radiusX() * 2, h: node.radiusY() * 2 };
@@ -1901,8 +1929,11 @@
node.destroy();
if (shape) {
const s = {
- id: newId('s'), panel: panel.id, color,
- strokeWidth: strokeW,
+ id: newId('s'), panel: panel.id,
+ // A blur box carries neither: it hides what is under it rather than
+ // pointing at it, so it is drawn from the picture's own pixels and
+ // nothing ever reads a colour or a line width off it.
+ ...(kind === 'blur' ? {} : { color, strokeWidth: strokeW }),
// only the kinds that can hold one carry the field, and only once asked
...(canFill(kind) && fillOpacity > 0 ? { fillOpacity } : {}),
...shape,
@@ -2146,7 +2177,7 @@
if (panel.img) group.add(surfaceImageNode(panel, image));
if (panel.frame) group.add(frameNode(panel.frame, image));
for (const s of proof.shapes.filter((x) => x.panel === panel.id)) {
- group.add(makeShapeNode(s, box));
+ group.add(makeShapeNode(s, box, panel));
}
docLayer.add(group);
if (panel.caption?.trim()) {
@@ -2238,7 +2269,7 @@
if (paste.img) group.add(surfaceImageNode(paste, image));
if (paste.frame) group.add(frameNode(paste.frame, image));
for (const s of proof.shapes.filter((x) => x.panel === paste.id)) {
- group.add(makeShapeNode(s, box));
+ group.add(makeShapeNode(s, box, paste));
}
docLayer.add(group);
}
@@ -2397,11 +2428,15 @@
: panelNode ? [panelNode] : pasteNode ? [pasteNode] : sigNode ? [sigNode] : []
);
const selKind = selectedShape?.kind;
- transformer.keepRatio(!!sigNode || !!panelNode || !!pasteNode || selKind === 'icon');
+ // A marker is a disc and a symbol is a glyph: both keep their ratio, because
+ // an oval number and a squashed symbol are not the same mark drawn bigger.
+ transformer.keepRatio(
+ !!sigNode || !!panelNode || !!pasteNode || selKind === 'icon' || selKind === 'number'
+ );
transformer.rotateEnabled(
!!panelNode || !!pasteNode
|| selKind === 'text' || selKind === 'rect' || selKind === 'ellipse' || selKind === 'icon'
- || selKind === 'freehand'
+ || selKind === 'freehand' || selKind === 'number' || selKind === 'blur'
);
// A symbol gets corners only: the side handles are what would let it be
// stretched, and a squashed symbol is a different symbol. A freehand stroke
@@ -2410,9 +2445,10 @@
// stroke showed a dashed frame and nothing to pull, which reads as a broken
// selection rather than a stroke that can only be moved.
transformer.enabledAnchors(
- selKind === 'rect' || selKind === 'ellipse' || selKind === 'freehand'
+ selKind === 'rect' || selKind === 'ellipse' || selKind === 'freehand' || selKind === 'blur'
? ['top-left', 'top-right', 'bottom-left', 'bottom-right', 'middle-left', 'middle-right', 'top-center', 'bottom-center']
- : selKind === 'text' || selKind === 'icon' || panelNode || pasteNode || sigNode
+ : selKind === 'text' || selKind === 'icon' || selKind === 'number'
+ || panelNode || pasteNode || sigNode
? ['top-left', 'top-right', 'bottom-left', 'bottom-right']
: []
);
@@ -2736,9 +2772,15 @@
if (!from) return { fromBox: null, toBox: null };
const fromBox = from.box;
let anchor;
- if (s.kind === 'rect') {
+ // Boxed kinds answer for their middle, a polyline for the mean of its
+ // vertices, and everything else for the origin it is drawn from. Sorted by
+ // what the shape holds rather than by a list of kinds: a numbered marker and
+ // a blur box both used to fall through to the polyline branch, where reading
+ // the points they have none of threw inside `dragend` — so the drop was
+ // never written down and the mark sprang back to where it had been picked up.
+ if (s.kind === 'rect' || s.kind === 'blur') {
anchor = { x: node.x() + (s.w ?? 0) / 2, y: node.y() + (s.h ?? 0) / 2 };
- } else if (s.kind === 'ellipse' || s.kind === 'text' || s.kind === 'icon') {
+ } else if (!Array.isArray(s.points)) {
anchor = { x: node.x(), y: node.y() };
} else {
const pts = s.points.map((v, i) => v + (i % 2 === 0 ? node.x() : node.y()));
@@ -2759,7 +2801,7 @@
// (that mapping at scale 1). Stroke width and arrow heads are normalised by
// baseScale so they read the same across image resolutions yet still grow
// proportionally when the panel is scaled up.
- function makeShapeNode(s, box) {
+ function makeShapeNode(s, box, surface) {
const panelScale = box.baseScale;
if (s.kind === 'text') {
// The glyph itself: always built first so its measured size drives the
@@ -2827,6 +2869,8 @@
return node;
}
if (s.kind === 'icon') return makeIconNode(s, panelScale);
+ if (s.kind === 'number') return makeNumberNode(s, panelScale);
+ if (s.kind === 'blur') return makeBlurNode(s, surface);
const sw = (s.strokeWidth ?? 4) / panelScale;
const common = {
id: s.id, stroke: s.color, strokeWidth: sw, rotation: s.rotation ?? 0,
@@ -2915,6 +2959,179 @@
* anchor point the shape stores — the pin's tip, everything else's centre —
* which is what keeps a pin on its pixel while it is resized or turned.
*/
+ /**
+ * The first number no marker of this colour holds.
+ *
+ * Counted per colour, because colour is what this composer says "same feature"
+ * with everywhere else — the legend is a list of colours. So a second colour
+ * is a second series and starts at 1, rather than carrying on from wherever
+ * the first one stopped and numbering two different things 1 through 9.
+ *
+ * A gap is refilled rather than left: deleting #2 and stamping again gives 2
+ * back, instead of a proof that counts 1, 3, 4.
+ */
+ function nextMarkerNumber(ink) {
+ const taken = new Set(
+ proof.shapes
+ .filter((x) => x.kind === 'number' && x.color === ink)
+ .map((x) => Number(x.n))
+ .filter(Number.isFinite)
+ );
+ let n = 1;
+ while (taken.has(n)) n += 1;
+ return n;
+ }
+
+ /**
+ * A numbered marker: a filled disc carrying its number.
+ *
+ * Filled rather than outlined, and the ink read off the colour, because this
+ * one has to survive being printed over anything — a numeral in a thin line
+ * over a bright roof is a numeral nobody can read.
+ */
+ function makeNumberNode(s, panelScale) {
+ const size = s.size ?? iconSizeFor(panelScale);
+ const ink = glyphInk(s.color, 1);
+ const group = new Konva.Group({
+ id: s.id, x: s.x, y: s.y, rotation: s.rotation ?? 0, draggable: true,
+ });
+ group.add(new Konva.Circle({
+ x: 0, y: 0, radius: size / 2, fill: s.color,
+ stroke: ink, strokeWidth: Math.max(size * 0.04, 0.5),
+ }));
+ const label = new Konva.Text({
+ text: String(s.n ?? 1), fontSize: size * 0.58, fontStyle: 'bold',
+ fontFamily: 'system-ui, sans-serif', fill: ink, listening: false,
+ });
+ label.position({ x: -label.width() / 2, y: -label.height() / 2 });
+ group.add(label);
+ bindShapePick(group, s);
+ group.on('dragstart', () => {
+ dragMoved = true;
+ group.getParent()?.moveToTop();
+ });
+ group.on('dragend', () => {
+ const { fromBox, toBox } = rebindOnDrop(s, group);
+ const p = toBox ? remapPanelXY(group.x(), group.y(), fromBox, toBox) : { x: group.x(), y: group.y() };
+ s.x = p.x;
+ s.y = p.y;
+ dirty = true;
+ });
+ group.on('transformend', () => {
+ s.size = Math.max(ICON_SIZE_MIN / panelScale, Math.abs(size * group.scaleX()));
+ s.x = group.x();
+ s.y = group.y();
+ s.rotation = group.rotation();
+ group.scale({ x: 1, y: 1 });
+ dirty = true;
+ });
+ return group;
+ }
+
+ /**
+ * A box that hides what is under it, by redrawing the picture through a blur.
+ *
+ * Not paint: the same source image is drawn again, cropped to the box and
+ * filtered, so what comes out is the picture's own pixels made unreadable
+ * rather than a rectangle laid over evidence. It follows the panel's turn and
+ * crop because it lives in the panel's own space, and it is rebuilt as it is
+ * dragged so the patch always shows the ground it is standing on.
+ *
+ * A blur is only ever as strong as the box is big (`blurRadiusFor`). Where the
+ * surface has no picture — an image still loading — the box is drawn solid
+ * instead, because a blur box that shows nothing is a blur box that hides
+ * nothing.
+ */
+ function makeBlurNode(s, surface) {
+ const radius = blurRadiusFor(s);
+ const turn = s.rotation ?? 0;
+ const group = new Konva.Group({
+ id: s.id, x: s.x, y: s.y, rotation: turn, draggable: true,
+ // The filter reads a margin of ground around the box; the clip is what
+ // keeps the box the size it was drawn.
+ clip: { x: 0, y: 0, width: s.w, height: s.h },
+ });
+ // The transformer and the marquee both measure a node by what it draws, and
+ // Konva measures a group by its children without looking at the clip — so
+ // this one measured a blur's margin past its own edges, and the frame stood
+ // that far off the box it was framing. It is the box.
+ group.getClientRect = ({ skipTransform, relativeTo } = {}) => {
+ const rect = { x: 0, y: 0, width: s.w, height: s.h };
+ if (skipTransform) return rect;
+ const at = group.getAbsoluteTransform(relativeTo);
+ const corners = [[0, 0], [s.w, 0], [s.w, s.h], [0, s.h]]
+ .map(([x, y]) => at.point({ x, y }));
+ const xs = corners.map((p) => p.x);
+ const ys = corners.map((p) => p.y);
+ const left = Math.min(...xs);
+ const top = Math.min(...ys);
+ return { x: left, y: top, width: Math.max(...xs) - left, height: Math.max(...ys) - top };
+ };
+ // The whole box catches the pointer, including the part hanging off the
+ // picture: what is selected has to be what is drawn.
+ group.add(new Konva.Rect({
+ name: 'blur-hit', x: 0, y: 0, width: s.w, height: s.h, fill: 'transparent', listening: true,
+ }));
+
+ const paint = () => {
+ for (const node of group.find('.blur-fill')) node.destroy();
+ // A turned box still hides the ground it stands on: the patch is read
+ // upright and turned back the other way inside the box (`blurPatch`).
+ const patch = surface?.img
+ ? blurPatch(
+ { x: group.x(), y: group.y(), w: s.w, h: s.h, rotation: group.rotation() },
+ surface.sourceNatural,
+ surface.crop,
+ radius
+ )
+ : null;
+ const node = patch
+ ? new Konva.Image({
+ name: 'blur-fill', image: surface.img,
+ x: patch.dx, y: patch.dy, rotation: patch.turn,
+ width: patch.w, height: patch.h, crop: patch.crop,
+ filters: [Konva.Filters.Blur], blurRadius: radius, listening: false,
+ })
+ : new Konva.Rect({
+ name: 'blur-fill', x: 0, y: 0, width: s.w, height: s.h,
+ fill: 'rgba(20, 22, 26, 0.92)', listening: false,
+ });
+ group.add(node);
+ if (patch) node.cache();
+ node.moveToTop();
+ };
+ paint();
+
+ bindShapePick(group, s);
+ group.on('dragstart', () => {
+ dragMoved = true;
+ group.getParent()?.moveToTop();
+ });
+ // The patch is rebuilt as the box is moved and as it is turned, so what it
+ // shows is always the ground it is standing on rather than a picture of
+ // where it started. A resize waits for the release: the box's own size only
+ // changes there, and until then the scale is doing the work.
+ group.on('dragmove', paint);
+ group.on('transform', paint);
+ group.on('dragend', () => {
+ const { fromBox, toBox } = rebindOnDrop(s, group);
+ const p = toBox ? remapPanelXY(group.x(), group.y(), fromBox, toBox) : { x: group.x(), y: group.y() };
+ s.x = p.x;
+ s.y = p.y;
+ dirty = true;
+ });
+ group.on('transformend', () => {
+ s.w = Math.max(4, Math.abs(s.w * group.scaleX()));
+ s.h = Math.max(4, Math.abs(s.h * group.scaleY()));
+ s.x = group.x();
+ s.y = group.y();
+ s.rotation = group.rotation();
+ group.scale({ x: 1, y: 1 });
+ dirty = true;
+ });
+ return group;
+ }
+
function makeIconNode(s, panelScale) {
const entry = iconByName(s.name);
const size = s.size ?? iconSizeFor(panelScale);
@@ -3088,21 +3305,37 @@
dirty = true;
}
- // Reorder a shape among same-panel siblings only — order doubles as z-order
- // (rebuild() adds shapes to their panel group in array order), so moving
- // past a shape bound to a different panel would silently no-op visually.
- function moveShape(index, delta) {
- const target = groupNeighborIndex(proof.shapes, index, delta, (s) => s.panel);
- if (target < 0) return;
- const [s] = proof.shapes.splice(index, 1);
- proof.shapes.splice(target, 0, s);
+ /**
+ * Move an element to a place in the order: `to` is the index it ends at.
+ *
+ * Forward is *later* in the array, since a panel's shapes are added in array
+ * order and the last one drawn sits on top. The side list shows them
+ * front-first, the way the Panels list above it does, so it speaks of forward
+ * and backward rather than of the array's up and down.
+ *
+ * One order for the whole proof, crossing pictures: the list is one list, and
+ * an arrow greyed out at a picture's edge read as a broken button rather than
+ * as the rule it was enforcing. What an element is actually drawn over is
+ * still decided inside its own picture — two marks on two panels are stacked
+ * by the panels, not by this — and the row says which picture it is on so the
+ * press that changes nothing is a press whose reason is on screen.
+ */
+ function moveShapeTo(from, to) {
+ const last = proof.shapes.length - 1;
+ if (from === to || from < 0 || to < 0 || from > last) return;
+ const next = [...proof.shapes];
+ const [s] = next.splice(from, 1);
+ next.splice(Math.min(to, next.length), 0, s);
+ proof.shapes = next;
dirty = true;
}
- const canMoveShapeUp = (i) => hasGroupNeighbor(proof.shapes, i, -1, (s) => s.panel);
- const canMoveShapeDown = (i) => hasGroupNeighbor(proof.shapes, i, 1, (s) => s.panel);
+ const bringForward = (i) => moveShapeTo(i, i + 1);
+ const sendBackward = (i) => moveShapeTo(i, i - 1);
+ const canBringForward = (i) => i < proof.shapes.length - 1;
+ const canSendBackward = (i) => i > 0;
- const KIND_ICON = { rect: 'square', ellipse: 'circle', arrow: 'arrow', line: 'line', curve: 'curve', freehand: 'freehand', text: 'text', icon: 'pin' };
- const KIND_LABEL = { rect: 'Box', ellipse: 'Ellipse', arrow: 'Arrow', line: 'Line', curve: 'Curve', freehand: 'Freehand', text: 'Text', icon: 'Symbol' };
+ const KIND_ICON = { rect: 'square', ellipse: 'circle', arrow: 'arrow', line: 'line', curve: 'curve', freehand: 'freehand', text: 'text', icon: 'pin', number: 'numbered', blur: 'blurBox' };
+ const KIND_LABEL = { rect: 'Box', ellipse: 'Ellipse', arrow: 'Arrow', line: 'Line', curve: 'Curve', freehand: 'Freehand', text: 'Text', icon: 'Symbol', number: 'Marker', blur: 'Blur box' };
// Colour / stroke / fill live-edit everything in hand and always remember the
// pick as the default for the next drawn one — the last value you touched
@@ -3110,9 +3343,19 @@
// controls set defaults only, so picking a new colour between two strokes no
// longer repaints the stroke that came before it (`editableShapes`).
function setColor(c) {
- if (editableShapes.length) {
- const before = [...new Set(editableShapes.map((s) => s.color))];
- for (const s of editableShapes) s.color = c;
+ // A blur box hides what is under it rather than pointing at it, so it has no
+ // colour to set — and it stays out of the legend for the same reason.
+ const inked = editableShapes.filter((s) => s.kind !== 'blur');
+ if (inked.length) {
+ const before = [...new Set(inked.map((s) => s.color))];
+ for (const s of inked) {
+ // A marker belongs to its colour's series (see nextMarkerNumber), so one
+ // moved to another colour takes the first number free in the series it
+ // joins. Assigned before the colour, so a family recoloured at once
+ // numbers itself in order rather than all landing on the same number.
+ if (s.kind === 'number' && s.color !== c) s.n = nextMarkerNumber(c);
+ s.color = c;
+ }
// A legend note is written against a colour. Carry it over for each colour
// the recolouring has just emptied, once no shape wears it any more.
for (const old of before) {
@@ -3258,6 +3501,8 @@
else if (e.key === 'd') tool = 'freehand';
else if (e.key === 't') tool = 'text';
else if (e.key === 's') tool = 'icon';
+ else if (e.key === 'n') tool = 'number';
+ else if (e.key === 'b') tool = 'blur';
else if (e.key === 'f') fit();
}
@@ -3766,6 +4011,21 @@
? editableShapes.every((s) => s.kind === 'icon' && isSolidIcon(s.name))
: tool === 'icon' && isSolidIcon(iconName),
);
+ // Neither a numbered marker nor a blur box is drawn with a line: one is sized
+ // by its corner handles, the other by the box itself. Same rule as a solid
+ // symbol — a control that would write nothing stays away.
+ const strokeless = $derived(
+ editableShapes.length
+ ? editableShapes.every((s) => s.kind === 'number' || s.kind === 'blur')
+ : tool === 'number' || tool === 'blur',
+ );
+ // A blur box is drawn from the picture's own pixels, so there is no ink in it
+ // to choose. The swatch used to sit there taking a colour nothing read back.
+ const colorless = $derived(
+ editableShapes.length
+ ? editableShapes.every((s) => s.kind === 'blur')
+ : tool === 'blur',
+ );
const activeColor = $derived(editableShape?.color ?? color);
const activeFill = $derived(
canFill(editableShape?.kind) ? (editableShape.fillOpacity ?? 0) : fillOpacity
@@ -4077,7 +4337,7 @@
<button
class="btn btn-sm export-toggle"
onclick={toggleExportMenu}
- aria-label="More export options"
+ aria-label="More export options" title="More export options"
aria-haspopup="menu"
aria-expanded={exportMenuOpen}
>
@@ -4129,7 +4389,8 @@
selectedShape={editableShape}
selectedCount={editableShapes.length}
{fillableSelection}
- showStroke={!solidIconOnly}
+ showStroke={!solidIconOnly && !strokeless}
+ showColor={!colorless}
{iconName}
setIconName={(name) => { iconName = name; tool = 'icon'; }}
{strokeW}
@@ -4247,39 +4508,45 @@
conclusion. A single-point proof shows the field it always did. -->
{#each proof.points as point, i (i)}
<div class="point-row">
- <input
- class="input meta-input"
- class:warn={i === 0 && !displayedCoords}
- placeholder="lat, lon"
- value={i === 0 ? displayedCoords : point.coords}
- oninput={(e) => { proof.points[i].coords = e.target.value; dirty = true; }}
- />
<!-- Six decimals is a tenth of a metre, and nobody moves a corner
- of a building by editing digits. -->
- <button
- class="point-map"
- title="Move this point on the map"
- onclick={() => (pointMap = { row: i, view: pointMapView(i) })}
- >
- <Icon name="pin" size={13} />
- </button>
- <input
- class="input point-label"
- placeholder="label"
- value={point.label}
- oninput={(e) => namePoint(i, e.target.value)}
- />
- <!-- What the point means. Nothing in the composition can answer it:
- a rooftop shot is recorded somewhere it never shows, and a
- distant skyline is shown from kilometres away. -->
- <button
- class="point-pov"
- class:on={point.pov}
- title="Point of view"
- onclick={() => togglePov(i)}
- >
- <Icon name="eye" size={13} />
- </button>
+ of a building by editing digits — so the map is one press from
+ the field, inside the same box, the way the date beside it
+ opens its calendar. -->
+ <div class="field-with-act coords-field" class:warn={i === 0 && !displayedCoords}>
+ <input
+ class="input meta-input"
+ placeholder="lat, lon"
+ value={i === 0 ? displayedCoords : point.coords}
+ oninput={(e) => { proof.points[i].coords = e.target.value; dirty = true; }}
+ />
+ <button
+ class="field-act"
+ title="Move this point on the map"
+ onclick={() => (pointMap = { row: i, view: pointMapView(i) })}
+ >
+ <Icon name="pin" size={13} />
+ </button>
+ </div>
+ <!-- The name and what the point means, in one box: nothing in the
+ composition can answer the second — a rooftop shot is recorded
+ somewhere it never shows, and a distant skyline is shown from
+ kilometres away. -->
+ <div class="field-with-act label-field">
+ <input
+ class="input point-label"
+ placeholder="label"
+ value={point.label}
+ oninput={(e) => namePoint(i, e.target.value)}
+ />
+ <button
+ class="field-act"
+ class:on={point.pov}
+ title="Point of view"
+ onclick={() => togglePov(i)}
+ >
+ <Icon name="eye" size={13} />
+ </button>
+ </div>
{#if i > 0}
<button class="point-move" title="Make this the proof's conclusion" onclick={() => raisePoint(i)}>
<Icon name="chevronUp" size={13} />
@@ -4322,13 +4589,30 @@
them is a link of its own. -->
{#each sourceRows as row, at (at)}
<div class="meta-row">
- <input
- class="input meta-input"
- class:warn={!displayedSource}
- placeholder="https://…"
- value={row}
- oninput={(e) => editSource(at, e.target.value)}
- />
+ <!-- The address itself, one press away in a tab of its own: a
+ source is read far more often than it is typed, and copying a
+ link into the browser to see what it points at is the long way
+ round. -->
+ <div class="field-with-act source-field" class:warn={!displayedSource}>
+ <input
+ class="input meta-input"
+ placeholder="https://…"
+ value={row}
+ oninput={(e) => editSource(at, e.target.value)}
+ />
+ <a
+ class="field-act"
+ class:disabled={!openableSource(row)}
+ href={openableSource(row) || undefined}
+ target="_blank"
+ rel="noreferrer"
+ title={openableSource(row) ? 'Open this source in a new tab' : 'Not a web address'}
+ aria-disabled={!openableSource(row)}
+ onclick={(e) => { if (!openableSource(row)) e.preventDefault(); }}
+ >
+ <Icon name="external" size={13} />
+ </a>
+ </div>
{#if missingSource(row)}
<!-- The case holds nothing from this address. Offering to fetch it here
is the difference between a proof that names its material and one
@@ -4396,9 +4680,15 @@
</button>
{/if}
</div>
- <TemporalInput
+ <!-- The calendar builds the common answer, a whole day, for the
+ analyst who would rather point at one than spell it; a month, a
+ range or a mark of doubt is still typed, which is what the
+ placeholder shows. -->
+ <DateField
id="proof-when"
- compact
+ label="Date the material was taken"
+ placeholder="dd/mm/yyyy · Oct 2025 · ~2025"
+ calendar
value={proof.when}
onchange={(value) => { proof.when = value; dirty = true; }}
/>
@@ -4435,9 +4725,11 @@
{featureList}
{moveLegendColor}
{setColor}
- {canMoveShapeUp}
- {canMoveShapeDown}
- {moveShape}
+ {canBringForward}
+ {canSendBackward}
+ {bringForward}
+ {sendBackward}
+ {moveShapeTo}
kindIcon={KIND_ICON}
kindLabel={KIND_LABEL}
{duplicateShape}
@@ -5066,6 +5358,7 @@
.meta-row { display: flex; align-items: center; gap: 4px; }
.meta-row + .meta-row { margin-top: 4px; }
.meta-row .meta-input { flex: 1; min-width: 0; }
+ .meta-row .source-field { flex: 1; min-width: 0; }
.meta-drop {
display: inline-flex;
color: var(--text-3);
@@ -5116,21 +5409,22 @@
}
.tpl-inline-link:hover { color: var(--text-2); }
.meta-input { width: 100%; font-size: var(--fs-xs); padding: 5px 8px; }
- .meta-input.warn { border-color: color-mix(in srgb, var(--warn, #e8a33d) 55%, transparent); }
/* One point per row. A proof with a single point shows a coordinate field, a
label and the marker — no cross, no arrow, nothing to move. */
.point-row { display: flex; align-items: center; gap: 4px; }
.point-row + .point-row { margin-top: 4px; }
.point-row .meta-input { flex: 1; min-width: 0; }
- .point-label { width: 84px; flex: none; font-size: var(--fs-xs); padding: 5px 8px; }
- .point-map, .point-pov, .point-move, .point-drop {
+ .point-row .coords-field { flex: 1; min-width: 0; }
+ /* The name is as wide as a name needs to be; the coordinate takes the rest. */
+ .point-row .label-field { width: 110px; flex: none; }
+ .point-label { width: 100%; min-width: 0; font-size: var(--fs-xs); padding: 5px 8px; }
+ .point-move, .point-drop {
display: inline-flex;
color: var(--text-3);
padding: 2px;
border-radius: var(--r-sm);
}
- .point-map:hover, .point-pov:hover, .point-move:hover { color: var(--text-1); background: var(--bg-2); }
- .point-pov.on { color: var(--accent, #6ea8fe); background: var(--bg-2); }
+ .point-move:hover { color: var(--text-1); background: var(--bg-2); }
.point-drop:hover { color: var(--danger, #e05c5c); background: var(--bg-2); }
.point-hint { margin-top: 5px; font-size: var(--fs-xs); color: var(--text-3); }
.desc-input { resize: vertical; min-height: 44px; line-height: 1.35; }
diff --git a/frontend/src/tools/ProofComposer.test.js b/frontend/src/tools/ProofComposer.test.js
index 040ba5e..4588126 100644
--- a/frontend/src/tools/ProofComposer.test.js
+++ b/frontend/src/tools/ProofComposer.test.js
@@ -857,8 +857,9 @@ describe('stamping a symbol', () => {
expect(node).toContain('const origin = iconOrigin(s.name, size)');
expect(node).toContain('id: s.id, x: s.x, y: s.y');
- // and it rebinds by that same point when dropped onto another surface
- expect(source).toContain("s.kind === 'ellipse' || s.kind === 'text' || s.kind === 'icon'");
+ // and it rebinds by that same point when dropped onto another surface:
+ // everything that is not a box and not a polyline answers for its origin
+ expect(bodyOfFn('rebindOnDrop')).toContain('} else if (!Array.isArray(s.points)) {');
});
it('turns the fill into a badge disc behind the glyph', () => {
@@ -1199,9 +1200,10 @@ describe('Proof Composer — what the proof says about itself', () => {
expect(side.match(/class="meta-optional">optional</g)).toHaveLength(2);
});
- it('edits the date with the one temporal editor the app has, compact', () => {
- expect(side).toContain('<TemporalInput');
- expect(side).toContain('compact');
+ it('edits the date in one field that writes the case\'s temporal profile', () => {
+ expect(side).toContain('<DateField');
+ expect(side).not.toContain('<TemporalInput');
+ expect(side).toContain('placeholder="dd/mm/yyyy · Oct 2025 · ~2025"');
expect(side).toContain('onchange={(value) => { proof.when = value; dirty = true; }}');
});
@@ -1248,3 +1250,102 @@ describe('Proof Composer — dating the material', () => {
expect(body).toContain('`Dated ${dated.length} files this proof rests on`');
});
});
+
+describe('Proof Composer — numbered markers and blur boxes', () => {
+ it('offers both on the rail, with a key each', () => {
+ expect(source).toContain("{ id: 'number', icon: 'numbered', label: 'Numbered marker', shortcut: 'n' },");
+ expect(source).toContain("{ id: 'blur', icon: 'blurBox', label: 'Blur box', shortcut: 'b' },");
+ expect(source).toContain("else if (e.key === 'n') tool = 'number';");
+ expect(source).toContain("else if (e.key === 'b') tool = 'blur';");
+ });
+
+ it('stamps a marker and keeps the tool, the way the symbol stamp does', () => {
+ const body = bodyOfFn('onPointerDown');
+ expect(body).toContain("if (tool === 'number') {");
+ expect(body).toContain('n: nextMarkerNumber(color)');
+ // no `tool = 'select'` in that branch: numbering four things is one act
+ const branch = body.slice(body.indexOf("if (tool === 'number') {"));
+ expect(branch.slice(0, branch.indexOf('return;'))).not.toContain("tool = 'select'");
+ });
+
+ it('counts each colour as its own series, starting back at 1', () => {
+ const body = bodyOfFn('nextMarkerNumber');
+ // colour is what this composer says "same feature" with, so a second colour
+ // is a second series rather than a continuation of the first
+ expect(body).toContain("x.kind === 'number' && x.color === ink");
+ expect(body).toContain('while (taken.has(n)) n += 1;');
+ });
+
+ it('renumbers a marker recoloured into another series', () => {
+ const body = bodyOfFn('setColor');
+ expect(body).toContain("if (s.kind === 'number' && s.color !== c) s.n = nextMarkerNumber(c);");
+ });
+
+ it('gives both a marker and a blur box handles to resize and turn', () => {
+ const ui = source.slice(source.indexOf('transformer.keepRatio('), source.indexOf('if (handles) {'));
+ // a disc stays a disc
+ expect(ui).toMatch(/keepRatio\([\s\S]*?selKind === 'number'/);
+ expect(ui).toMatch(/rotateEnabled\([\s\S]*?selKind === 'number' \|\| selKind === 'blur'/);
+ // a box takes the full set, a marker the corners
+ expect(ui).toMatch(/enabledAnchors\([\s\S]*?selKind === 'blur'[\s\S]*?'middle-left'/);
+ expect(ui).toMatch(/selKind === 'text' \|\| selKind === 'icon' \|\| selKind === 'number'/);
+ });
+
+ it('writes down where either one was dropped, panel and all', () => {
+ // both used to fall through to the polyline branch, where reading the points
+ // they have none of threw inside dragend: the drop was never written and the
+ // mark sprang back to where it had been picked up
+ const body = bodyOfFn('rebindOnDrop');
+ expect(body).toContain("if (s.kind === 'rect' || s.kind === 'blur') {");
+ expect(body).toContain('} else if (!Array.isArray(s.points)) {');
+ });
+
+ it('keeps a colour away from the one mark drawn in no ink', () => {
+ expect(source).toContain("? editableShapes.every((s) => s.kind === 'blur')");
+ expect(source).toContain('showColor={!colorless}');
+ // and never writes one on it either, at the draw or from the palette
+ expect(source).toContain("...(kind === 'blur' ? {} : { color, strokeWidth: strokeW }),");
+ expect(bodyOfFn('setColor')).toContain(
+ "const inked = editableShapes.filter((s) => s.kind !== 'blur');"
+ );
+ });
+
+ it('draws a blur box by dragging, and files it as a rectangle', () => {
+ expect(source).toContain("} else if (tool === 'blur') {");
+ expect(source).toContain("if ((kind === 'rect' || kind === 'blur') && node.width() > minSize");
+ // the draft is resized as a box, not as a polyline: a Rect has no points()
+ expect(source).toContain("} else if (kind === 'rect' || kind === 'blur') {");
+ });
+
+ it('blurs the picture itself, through the surface the box sits on', () => {
+ const body = bodyOfFn('makeBlurNode');
+ expect(body).toContain('filters: [Konva.Filters.Blur]');
+ expect(body).toContain('const radius = blurRadiusFor(s);');
+ expect(body).toContain('blurRadius: radius');
+ expect(body).toContain('surface.sourceNatural');
+ expect(body).toContain('surface.crop');
+ // a filter only draws once the node is cached
+ expect(body).toContain('if (patch) node.cache();');
+ // the margin is read, not drawn: the clip keeps the box the size it was drawn
+ expect(body).toContain('clip: { x: 0, y: 0, width: s.w, height: s.h }');
+ // and it follows the box as it is dragged and as it is turned
+ expect(body).toContain("group.on('dragmove', paint);");
+ expect(body).toContain("group.on('transform', paint);");
+ // a turned box hides the ground under it, so the patch is turned back level
+ expect(body).toContain('w: s.w, h: s.h, rotation: group.rotation()');
+ expect(body).toContain('rotation: patch.turn');
+ // Konva measures a group by its children and ignores the clip, so the frame
+ // stood a blur radius off the box until this answered with the box itself
+ expect(body).toContain('group.getClientRect = ({ skipTransform, relativeTo } = {}) => {');
+ });
+
+ it('hands each shape the surface it stands on, panel or pasted image', () => {
+ expect(source).toContain('group.add(makeShapeNode(s, box, panel));');
+ expect(source).toContain('group.add(makeShapeNode(s, box, paste));');
+ });
+
+ it('keeps a line width away from the two marks that have no line', () => {
+ expect(source).toContain("editableShapes.every((s) => s.kind === 'number' || s.kind === 'blur')");
+ expect(source).toContain('showStroke={!solidIconOnly && !strokeless}');
+ });
+});
diff --git a/frontend/src/tools/ReverseSearch.render.test.js b/frontend/src/tools/ReverseSearch.render.test.js
new file mode 100644
index 0000000..82b3ba4
--- /dev/null
+++ b/frontend/src/tools/ReverseSearch.render.test.js
@@ -0,0 +1,94 @@
+// @vitest-environment happy-dom
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { flushSync, mount, unmount } from 'svelte';
+
+/**
+ * Arriving in Reverse Search with a picture another tool handed over. The tab has
+ * to open on that picture rather than on the empty picker, spend the handoff once,
+ * and say when what it shows is not a file of the case.
+ */
+
+vi.mock('../lib/api.js', () => ({ api: { get: vi.fn(async () => []) } }));
+const uiState = { tool: 'reverse', reverseTarget: null };
+vi.mock('../lib/state.svelte.js', () => ({
+ caseState: { current: { id: 'case-a' } },
+ prefs: { reversePrefill: false },
+ uiState,
+ toast: vi.fn(),
+}));
+
+const { default: ReverseSearch } = await import('./ReverseSearch.svelte');
+
+let live = null;
+let target = null;
+
+function open() {
+ target = document.createElement('div');
+ document.body.append(target);
+ live = mount(ReverseSearch, { target });
+ flushSync();
+}
+
+beforeEach(() => {
+ uiState.tool = 'reverse';
+ vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:frame');
+ vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => {});
+});
+
+afterEach(() => {
+ if (live) unmount(live);
+ live = null;
+ target?.remove();
+ vi.restoreAllMocks();
+});
+
+describe('a picture handed over by another tool', () => {
+ it('opens on a case image and spends the handoff', () => {
+ uiState.reverseTarget = { path: 'media/quai.jpg', blob: null, kind: 'image', label: 'Quai', time: null };
+ open();
+
+ expect(target.querySelector('.preview img').getAttribute('src')).toBe('/files/case-a/media/quai.jpg');
+ expect(target.querySelector('.preview-bar .name').textContent).toBe('Quai');
+ expect(uiState.reverseTarget).toBeNull();
+ expect(target.textContent).not.toContain('not saved in the case');
+ });
+
+ it('shows a frame held only in memory, and says it is not in the case', () => {
+ const blob = new Blob(['png'], { type: 'image/png' });
+ uiState.reverseTarget = { path: null, blob, kind: 'image', label: 'clip.mp4 · t=12.40s', time: null };
+ open();
+
+ expect(URL.createObjectURL).toHaveBeenCalledWith(blob);
+ expect(target.querySelector('.preview img').getAttribute('src')).toBe('blob:frame');
+ expect(target.textContent).toContain('This image is not saved in the case.');
+ // Inspect is where it came from and has no path to reopen it by.
+ expect(target.textContent).not.toContain('Finer control in Inspect');
+ });
+
+ it('lets the address go when the picture is discarded', () => {
+ uiState.reverseTarget = {
+ path: null,
+ blob: new Blob(['png'], { type: 'image/png' }),
+ kind: 'image',
+ label: 'Frame',
+ time: null,
+ };
+ open();
+
+ [...target.querySelectorAll('button')].find((b) => b.textContent.includes('Discard')).click();
+ flushSync();
+
+ expect(URL.revokeObjectURL).toHaveBeenCalledWith('blob:frame');
+ expect(target.querySelector('.preview')).toBeNull();
+ });
+
+ it('waits for its own tab before spending a handoff', () => {
+ uiState.tool = 'media';
+ uiState.reverseTarget = { path: 'media/quai.jpg', blob: null, kind: 'image', label: 'Quai', time: null };
+ open();
+
+ expect(uiState.reverseTarget).not.toBeNull();
+ expect(target.querySelector('.preview')).toBeNull();
+ uiState.reverseTarget = null;
+ });
+});
diff --git a/frontend/src/tools/ReverseSearch.svelte b/frontend/src/tools/ReverseSearch.svelte
index da8eec3..f06b8f6 100644
--- a/frontend/src/tools/ReverseSearch.svelte
+++ b/frontend/src/tools/ReverseSearch.svelte
@@ -9,10 +9,12 @@
// engine searches. That is a press of the same button, and the clipboard road
// is still what every refusal falls back to.
//
- // Pick a case photo, or scrub a case video to a frame. Adjustments
+ // Pick a case photo, or scrub a case video to a frame — or arrive from the Media
+ // Library or Inspect already holding one (`uiState.reverseTarget`). Adjustments
// (brightness, contrast, …) preview live and are baked into the exported
// image via a same-origin canvas — nothing leaves the machine until an
// engine tab is opened by the analyst.
+ import { untrack } from 'svelte';
import { api } from '../lib/api.js';
import { fileUrl } from '../lib/fileUrl.js';
import { matchesTerms } from '../lib/folderBrowse.js';
@@ -78,7 +80,9 @@
);
const resetAdjust = () => (adjust = { ...NEUTRAL });
- const srcOf = (item) => fileUrl(caseState.current.id, item.path);
+ // A picture that exists nowhere on disk is shown from an address made for it here,
+ // and revoked once it is replaced or discarded.
+ const srcOf = (item) => item.src ?? fileUrl(caseState.current.id, item.path);
const nameOf = (item) => (item.label || item.path).replace(/^media\//, '');
const frameLabel = $derived(selected?.kind === 'video' ? 'frame' : 'image');
const downloadName = () =>
@@ -110,12 +114,37 @@
}
}
- function pickMedia(item) {
- selected = item;
+ /** Put a picture in front of the engines, dropping the address of the one before. */
+ function show(item) {
+ if (selected?.src) URL.revokeObjectURL(selected.src);
+ selected = item.blob ? { ...item, src: URL.createObjectURL(item.blob) } : item;
resetAdjust();
+ }
+
+ function pickMedia(item) {
+ show(item);
pickerOpen = false;
}
+ // Arriving from another tool with the picture it was pressed on. Consumed once,
+ // and only on this tab: the tool stays mounted after its first visit, so a
+ // handoff written while it is hidden waits for the visit it was meant for.
+ $effect(() => {
+ const target = uiState.reverseTarget;
+ if (uiState.tool !== 'reverse' || !target || !caseState.current) return;
+ uiState.reverseTarget = null;
+ untrack(() => {
+ pickerOpen = false;
+ show(target);
+ });
+ });
+
+ /** A video handed over at a moment opens there, ready to be copied or nudged. */
+ function seekToTarget() {
+ if (!videoEl || selected?.time == null) return;
+ videoEl.currentTime = Math.min(selected.time, videoEl.duration || selected.time);
+ }
+
function matchesMediaName(item, query) {
return matchesTerms(item.title || item.filename || '', query);
}
@@ -165,6 +194,7 @@
}
function discard() {
+ if (selected?.src) URL.revokeObjectURL(selected.src);
selected = null;
resetAdjust();
adjustOpen = false;
@@ -381,6 +411,7 @@
controls
preload="metadata"
style="filter: {filterCss}"
+ onloadedmetadata={seekToTarget}
></video>
{:else}
<img src={srcOf(selected)} alt={nameOf(selected)} style="filter: {filterCss}" />
@@ -389,6 +420,8 @@
</div>
{#if selected.kind === 'video'}
<p class="hint">Scrub to the moment, then copy or save the frame.</p>
+ {:else if selected.blob}
+ <p class="hint">This {frameLabel} is not saved in the case.</p>
{/if}
</div>
diff --git a/frontend/src/tools/Satellite.svelte b/frontend/src/tools/Satellite.svelte
index 511c8cd..788b9a8 100644
--- a/frontend/src/tools/Satellite.svelte
+++ b/frontend/src/tools/Satellite.svelte
@@ -28,7 +28,7 @@
import { isMode, KINDS } from '../lib/geoTree.js';
import { stackOf } from '../lib/mediaViewer.js';
import {
- caseState, uiState, ensureCase, reloadCase, toast, prefs, fmtCoords, prefsReady,
+ caseState, uiState, ensureCase, reloadCase, toast, dismissToast, prefs, fmtCoords, prefsReady,
} from '../lib/state.svelte.js';
import { markerGeometry, markerSvg } from '../lib/mapMarkers.js';
import { startRectDrag, startRotateDrag } from '../lib/map/gestures.js';
@@ -41,6 +41,7 @@
import { extensionVersion, mapLinkRelay, onActivated } from '../lib/extBridge.js';
import { SENTINEL_ID } from '../lib/sentinel.js';
import { WAYBACK_ID } from '../lib/wayback.js';
+ import { COMPARE_SOURCES, comparePair } from '../lib/map/comparePair.js';
import { buildHash, readSolo, splitHash } from '../lib/hash.js';
import { readView, readWindowLabel, viewParams } from '../lib/map/view.js';
import { createViewLink } from '../lib/map/link.js';
@@ -84,6 +85,7 @@
import AddedLayers from './satellite/AddedLayers.svelte';
import AddedLayersOverlay from './satellite/AddedLayersOverlay.svelte';
import AddLayerDialog from './satellite/AddLayerDialog.svelte';
+ import GeoConfirmedDialog from './satellite/GeoConfirmedDialog.svelte';
import MapLayers from './satellite/MapLayers.svelte';
import MapContextMenu from './satellite/MapContextMenu.svelte';
import MapStatusBar from './satellite/MapStatusBar.svelte';
@@ -150,7 +152,8 @@
const savedWork = createSavedState({ api, notify: toast, assignFolder, reloadCase });
// The layers the analyst added themselves: a file they opened, a map they
// follow. Its own store, because it owns the one network rule this feature
- // has — a feed is read on case open, on Refresh, and never otherwise.
+ // has — a feed is read when first switched on in a session, on Refresh, and
+ // never otherwise — and the switch itself, which every reload turns off.
const addedLayers = createAddedLayersState({
api,
notify: toast,
@@ -242,6 +245,18 @@
const firmsAskable = $derived(askable(fires));
const firmsSummary = $derived(summary(fires, fires.sensors));
+ /** The archives a right-click can build a pair from. A keyed provider that is
+ * not configured is left out rather than offered and refused. */
+ const compareSources = $derived(
+ COMPARE_SOURCES.filter((source) => !source.provider || imagery.find(source.provider))
+ );
+
+ /** Where a FIRMS key is entered, reached from the layer that needs it. */
+ function openImagerySettings() {
+ uiState.settingsTab = 'imagery';
+ uiState.tool = 'settings';
+ }
+
/**
* Which instruments are on offer, and whether the key for them is saved.
*
@@ -883,6 +898,33 @@
engine.setView(point, Math.max(center.zoom, 15));
await tick();
if (!wb.menuOpen) wb.toggleMenu();
+ } else if (id === 'compare') {
+ await comparePoint(point, value);
+ }
+ }
+
+ /**
+ * Open Compare on the last two pictures of this point.
+ *
+ * The lookup happens here, before the tab changes: a Compare that opened and
+ * *then* said the archive holds nothing would have thrown away the map view
+ * for an error message. The dates travel with the pair, so the tool applies
+ * them the way it applies a saved comparison.
+ */
+ async function comparePoint(point, source) {
+ const name = COMPARE_SOURCES.find((entry) => entry.id === source)?.label ?? 'the archive';
+ // Held up until the answer lands rather than for a guessed few seconds: the
+ // walk through Esri's releases takes as long as it takes, and a message that
+ // went out halfway through left the map looking like nothing was happening.
+ const waiting = toast(`Asking ${name} for the last two pictures…`, 'info', 0);
+ try {
+ const pair = await comparePair(api, source, { ...point, zoom: center.zoom });
+ uiState.compareAt = { ...point, zoom: center.zoom, ...pair };
+ uiState.tool = 'compare';
+ } catch (error) {
+ toast(error.message, 'warn', 6000);
+ } finally {
+ dismissToast(waiting);
}
}
@@ -1058,6 +1100,7 @@
label: 'OSM labels',
on: osmOverlay,
disabled: !baseIsImagery,
+ detail: baseIsImagery ? '' : 'imagery only',
title: baseIsImagery
? 'Roads and place names over the imagery'
: 'Only useful over satellite imagery',
@@ -1082,6 +1125,7 @@
label: 'Roads',
on: refLayers.roads,
disabled: !baseIsImagery,
+ detail: baseIsImagery ? '' : 'imagery only',
title: baseIsImagery ? 'Road network over the imagery, from Esri' : 'Only useful over satellite imagery',
toggle: () => (refLayers.roads = !refLayers.roads),
},
@@ -1112,11 +1156,14 @@
label: 'Active fires',
on: fires.on,
disabled: !fires.keyed,
- detail: fires.keyed ? firmsSummary : '',
+ detail: fires.keyed ? firmsSummary : 'needs a free key',
title: fires.keyed
? 'Thermal detections from NASA FIRMS, live or from the archive'
: 'Add a NASA FIRMS key in Settings → Imagery',
toggle: () => (fires.on = !fires.on),
+ // A switch that cannot be pressed says why and where the key goes, on the
+ // row itself rather than only on a greyed-out eye nobody hovers.
+ actions: fires.keyed ? null : [{ label: 'Add a FIRMS key', quiet: true, run: openImagerySettings }],
// its two questions — which instrument, and over what — are asked in the
// row rather than in a card of its own floating somewhere
controls: fires.on && fires.keyed ? firmsControls : null,
@@ -1568,6 +1615,17 @@
moveMode && markerLatLng ? markerLatLng : { lat: center.lat, lon: center.lon }
);
+ /** Hand that same point to the tools that open on a coordinate. Held back
+ * only while the map still sits on the saved home view nobody has moved: that
+ * is a setting, not a point somebody is looking at. A view the address named
+ * is a point — it came from a link, or from case work opening the map. */
+ $effect(() => {
+ const home = openingHome;
+ const asked = openingView?.lat != null;
+ if (!asked && center.lat === home.lat && center.lon === home.lon && center.zoom === home.zoom) return;
+ uiState.mapPoint = { lat: displayCoords.lat, lon: displayCoords.lon, zoom: center.zoom };
+ });
+
// --- capture: what shape the crop is, and filing what is inside it ---
// The output size, the marquee's ratio lock, the resolution, which mode the
// button re-runs and both roads to a filed crop are its own store
@@ -2347,6 +2405,7 @@
format={prefs.coordFormat}
{fullscreen}
lookup={pointMenu.lookup}
+ {compareSources}
onpick={onPointMenu}
onclose={closePointMenu}
/>
@@ -2446,8 +2505,10 @@
addedLayers.toggleCategory(caseState.current?.id, row, name)}
onrefresh={(row) => addedLayers.refresh(caseState.current?.id, row)}
onremove={(row) => (removingLayer = row)}
- onreveal={(row) => addedLayers.reveal(caseState.current?.id, row)}
onpick={(row, hit) => addedLayers.pick(caseState.current?.id, row, hit)}
+ dates={addedLayers.dates}
+ onperiod={(row, period, commit) =>
+ addedLayers.setPeriod(caseState.current?.id, row, period, commit)}
onadd={() => (addedLayers.adding = true)}
/>
{:else if mediaView}
@@ -2500,6 +2561,20 @@
onclose={() => (addedLayers.adding = false)}
onfile={(file, icons) => addedLayers.addFile(file, icons)}
onurl={(url, icons) => addedLayers.subscribe(url, icons)}
+ ongeoconfirmed={() => {
+ addedLayers.adding = false;
+ addedLayers.geoconfirmed = true;
+ }}
+ />
+{/if}
+
+{#if addedLayers.geoconfirmed}
+ <GeoConfirmedDialog
+ busy={addedLayers.saving}
+ load={addedLayers.conflicts}
+ view={() => engine?.viewBounds?.() ?? null}
+ onclose={() => (addedLayers.geoconfirmed = false)}
+ onadd={(body) => addedLayers.addGeoConfirmed(body)}
/>
{/if}
diff --git a/frontend/src/tools/Satellite.test.js b/frontend/src/tools/Satellite.test.js
index 03300ad..beda3da 100644
--- a/frontend/src/tools/Satellite.test.js
+++ b/frontend/src/tools/Satellite.test.js
@@ -389,6 +389,15 @@ describe('what is laid over the imagery', () => {
const rows = source.slice(source.indexOf('const layerRows = $derived(['));
expect(rows).toContain('disabled: !fires.keyed');
expect(rows).toContain('Add a NASA FIRMS key in Settings → Imagery');
+ // said on the row, where it can be read without hovering a greyed switch
+ expect(rows).toContain("detail: fires.keyed ? firmsSummary : 'needs a free key'");
+ expect(rows).toContain("actions: fires.keyed ? null : [{ label: 'Add a FIRMS key', quiet: true, run: openImagerySettings }]");
+ expect(source).toContain("uiState.settingsTab = 'imagery';");
+ });
+
+ it('says a layer is for imagery only when the basemap is not imagery', () => {
+ const rows = source.slice(source.indexOf('const layerRows = $derived(['));
+ expect(rows.match(/detail: baseIsImagery \? '' : 'imagery only'/g)).toHaveLength(2);
});
it('asks for no tile until the choice is one the service can answer', () => {
diff --git a/frontend/src/tools/Settings.svelte b/frontend/src/tools/Settings.svelte
index 4688c61..675ce09 100644
--- a/frontend/src/tools/Settings.svelte
+++ b/frontend/src/tools/Settings.svelte
@@ -972,7 +972,7 @@
<div class="tpl-modal-head">
<input class="tpl-title" type="text" placeholder="Template name"
maxlength="120" bind:value={editing.name} />
- <button class="btn btn-ghost btn-sm" onclick={cancelEdit} aria-label="Close">
+ <button class="btn btn-ghost btn-sm" onclick={cancelEdit} aria-label="Close" title="Close">
<Icon name="x" size={16} />
</button>
</div>
diff --git a/frontend/src/tools/Sheet.svelte b/frontend/src/tools/Sheet.svelte
index c8f3cc6..aead40f 100644
--- a/frontend/src/tools/Sheet.svelte
+++ b/frontend/src/tools/Sheet.svelte
@@ -4066,7 +4066,7 @@
{/if}
{/if}
<div class="spacer"></div>
- <button class="btn btn-ghost btn-sm" aria-label="Close"
+ <button class="btn btn-ghost btn-sm" aria-label="Close" title="Close"
onclick={() => (reading = null)}>
<Icon name="x" size={13} />
</button>
diff --git a/frontend/src/tools/Timeline.svelte b/frontend/src/tools/Timeline.svelte
index 436da6c..84d70e2 100644
--- a/frontend/src/tools/Timeline.svelte
+++ b/frontend/src/tools/Timeline.svelte
@@ -1300,7 +1300,7 @@
);
pendingEdit = null;
await reloadCase();
- toast('Time assessment updated', 'ok', 1600);
+ toast('Claim updated', 'ok', 1600);
} catch (error) {
toast(error.message, 'danger');
} finally {
@@ -1410,7 +1410,7 @@
/>
<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 assessment</button>
+ <button class="btn btn-primary add-event" disabled={snapshotReading} onclick={() => openEditor()}><Icon name="plus" size={13} />Add claim</button>
</div>
</header>
@@ -1441,7 +1441,7 @@
<strong>Date quality</strong>
<span><i class="sample approximate"></i>Approximate date</span>
<span><i class="sample uncertain"></i>Uncertain date</span>
- <strong>Assessment</strong>
+ <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>
@@ -1501,8 +1501,8 @@
<div class="blank-state">
<Icon name="clock" size={24} />
<h2>No dated entries yet</h2>
- <p>Add a time assessment here or from an entity's Time tab.</p>
- <button class="btn btn-primary" disabled={snapshotReading} onclick={() => openEditor()}>Add first assessment</button>
+ <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>
</div>
{:else}
<section class="overview-card" aria-label="Timeline overview">
@@ -1658,7 +1658,7 @@
}}
><Icon name="grip" size={11} /></button>
{/if}
- <button class="fold-track" aria-label={`${track.collapsed ? 'Expand' : 'Fold'} ${track.label}`} disabled={snapshotReading} onclick={() => setTrackCollapsed(baseId, !track.collapsed)}>
+ <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>
@@ -1770,7 +1770,7 @@
onclick={() => expandTrack(baseId)}
>+{cluster.count}</button>
{/each}
- {#if canCreate}<span class="track-hint">Click or drag to add an assessment</span>{/if}
+ {#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}
{:else}<span class="folded-note">Track folded</span>{/if}
</div>
@@ -1933,7 +1933,7 @@
</div>
<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 assessment</button>{/if}
+ {#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}
@@ -1974,7 +1974,7 @@
{#if item.category === 'statement'}
<li>
<button disabled={snapshotReading} onclick={() => fromItemMenu((entry) => openEditor(entry))}>
- <Icon name="edit" size={12} />Edit assessment
+ <Icon name="edit" size={12} />Edit claim
</button>
</li>
{/if}
@@ -1990,7 +1990,7 @@
{/if}
{#if editor}
- <Modal title={editor.item ? 'Edit time assessment' : 'Add assessment'} onclose={() => (editor = null)} width="660px">
+ <Modal title={editor.item ? 'Edit claim' : 'Add claim'} onclose={() => (editor = null)} width="660px">
<TemporalClaimEditor
caseId={caseState.current.id}
item={editor.item}
diff --git a/frontend/src/tools/Timeline.test.js b/frontend/src/tools/Timeline.test.js
index 2e45685..47cfabc 100644
--- a/frontend/src/tools/Timeline.test.js
+++ b/frontend/src/tools/Timeline.test.js
@@ -45,8 +45,8 @@ describe('Timeline workspace', () => {
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 an assessment');
- expect(source).toContain('Add assessment');
+ expect(source).toContain('Click or drag to add a claim');
+ expect(source).toContain('Add claim');
});
it('shows uncertainty through patterns and a visible legend', () => {
diff --git a/frontend/src/tools/compare/AnalyzerPanel.svelte b/frontend/src/tools/compare/AnalyzerPanel.svelte
index f4dd0d5..f145a03 100644
--- a/frontend/src/tools/compare/AnalyzerPanel.svelte
+++ b/frontend/src/tools/compare/AnalyzerPanel.svelte
@@ -48,6 +48,9 @@
onusecurrentview = () => {},
onsources = () => {},
onclose = () => {},
+ /** What a run still lacks, said above everything else; empty when nothing. */
+ needs = '',
+ onsettings = () => {},
} = $props();
const EMPTY_SOURCE = { provider: 'sentinel2', date: '', layer: 'TRUE_COLOR', maxcc: 30 };
@@ -533,6 +536,12 @@
</div>
<div class="cmp-dock-body">
+ {#if needs}
+ <p class="warn needs">
+ {needs}
+ <button class="btn btn-sm" onclick={onsettings}>Open Settings</button>
+ </p>
+ {/if}
{#if error}<p class="warn" role="alert">{error}</p>{/if}
{#if !catalogue}<p class="hint">Reading the local analyzer library…</p>{/if}
@@ -559,12 +568,12 @@
{#if zones.length}
{#each zones as zone (zone.id)}
<div class="row area-row">
- <button class="cmp-icon" aria-label={`Show ${zone.name}`}
+ <button class="cmp-icon" aria-label={`Show ${zone.name}`} title={`Show ${zone.name}`}
onclick={() => { selectedZone = zone.id; drawing = 'select'; focus(zone.points[0]); }}>
<Icon name="pin" size={13} />
</button>
<input class="grow" aria-label="Area name" bind:value={zone.name} maxlength="120" />
- <button class="cmp-icon" aria-label={`Remove ${zone.name}`} onclick={() => removeZone(zone.id)}>
+ <button class="cmp-icon" aria-label={`Remove ${zone.name}`} title={`Remove ${zone.name}`} onclick={() => removeZone(zone.id)}>
<Icon name="x" size={12} />
</button>
</div>
@@ -818,9 +827,9 @@
{#if candidate}
<section class="candidate">
<div class="row nav">
- <button class="cmp-icon" aria-label="Previous candidate" onclick={() => step(-1)}><Icon name="chevronLeft" size={14} /></button>
+ <button class="cmp-icon" aria-label="Previous candidate" title="Previous candidate" onclick={() => step(-1)}><Icon name="chevronLeft" size={14} /></button>
<span class="grow centre position">{candidates.findIndex((r) => r.id === candidateId) + 1} of {candidates.length}</span>
- <button class="cmp-icon" aria-label="Next candidate" onclick={() => step(1)}><Icon name="chevronRight" size={14} /></button>
+ <button class="cmp-icon" aria-label="Next candidate" title="Next candidate" onclick={() => step(1)}><Icon name="chevronRight" size={14} /></button>
</div>
<strong>{candidate.phenomenon}</strong>
<img class="preview" src={`${base()}/runs/${current.id}/results/${candidate.id}/preview`}
@@ -858,7 +867,7 @@
<strong>Result layers</strong>
{#each layers as layer (layer.id)}
<div class="row">
- <button class="cmp-icon" aria-label={`Toggle ${layer.title}`} aria-pressed={layer.visible}
+ <button class="cmp-icon" aria-label={`Toggle ${layer.title}`} title={`Toggle ${layer.title}`} aria-pressed={layer.visible}
onclick={() => { layer.visible = !layer.visible; }}>
<Icon name={layer.visible ? 'eye' : 'eyeOff'} size={15} />
</button>
@@ -882,7 +891,7 @@
{row.title}<small>{row.created_at}</small>
</button>
<button class="btn btn-sm" disabled={busy || pending} onclick={() => act(() => runWatch(row.id))}>Run again</button>
- <button class="cmp-icon" disabled={busy} aria-label={`Delete ${row.title}`} onclick={() => act(() => removeItem('followups', row.id))}>
+ <button class="cmp-icon" disabled={busy} aria-label={`Delete ${row.title}`} title={`Delete ${row.title}`} onclick={() => act(() => removeItem('followups', row.id))}>
<Icon name="trash" size={13} />
</button>
</div>
@@ -898,7 +907,7 @@
{row.title}<small>{row.created_at}{row.status ? ` · ${statusLabel(row.status)}` : ''}</small>
</button>
<button class="cmp-icon" disabled={busy || ['queued', 'running'].includes(row.status)}
- aria-label={`Delete ${row.title}`} onclick={() => act(() => removeItem(kind, row.id))}>
+ aria-label={`Delete ${row.title}`} title={`Delete ${row.title}`} onclick={() => act(() => removeItem(kind, row.id))}>
<Icon name="trash" size={13} />
</button>
</div>
@@ -927,6 +936,11 @@
</aside>
<style>
+ .needs {
+ display: grid;
+ gap: 6px;
+ justify-items: start;
+ }
.views { margin: 10px 12px 0; }
/* The two ways to start one of your own, said in full rather than implied by
a "duplicate" button next to a save. */
diff --git a/frontend/src/tools/compare/AnnotationCanvas.svelte b/frontend/src/tools/compare/AnnotationCanvas.svelte
index 881b137..46f349f 100644
--- a/frontend/src/tools/compare/AnnotationCanvas.svelte
+++ b/frontend/src/tools/compare/AnnotationCanvas.svelte
@@ -1,11 +1,15 @@
<script>
import { onMount } from 'svelte';
- import { markLabel, movedMark, onSide, projectMark } from '../../lib/map/compareAnnotations.js';
+ import {
+ STAMPED, glyphBox, markGlyph, markLabel, markSize, movedMark, nextMarkNumber, onSide,
+ projectMark, stampInk,
+ } from '../../lib/map/compareAnnotations.js';
+ import { isSolidIcon } from '../../lib/proofIcons.js';
let { annotations = [], engine, letter = 'a', units = 'metric', active = true,
tool = $bindable('select'), selectedId = $bindable(null), colour = '#f6a81a',
- strokeWidth = 4, fillOpacity = 0, annotationSide = 'both', editVertices = false,
- edgeOnly = false, onchange = () => {} } = $props();
+ strokeWidth = 4, fillOpacity = 0, annotationSide = 'both', glyph = 'point',
+ stampSize = 16, editVertices = false, edgeOnly = false, onchange = () => {} } = $props();
let svg = $state();
let revision = $state(0);
let draft = $state(null);
@@ -43,6 +47,32 @@
vertices: editVertices && GRIPPED.has(mark.kind) ? mark.points.map(project) : [] }))
);
const pathOf = (shape) => shape.path.map(([x, y], i) => `${i ? 'L' : 'M'}${x},${y}`).join(' ') + (shape.closed ? ' Z' : '');
+ /**
+ * The wheel belongs to the map, wherever the pointer happens to be.
+ *
+ * This overlay is a sibling of the map rather than a child, so a wheel over a
+ * mark stopped here and the view would not zoom until the pointer was moved
+ * off whatever had been drawn. A press is the mark's; the wheel is handed down
+ * to the picture under it.
+ */
+ function relayWheel(event) {
+ const container = engine?.container;
+ if (!container) return;
+ const below = document
+ .elementsFromPoint(event.clientX, event.clientY)
+ .find((element) => !svg?.contains(element) && container.contains(element));
+ if (!below) return;
+ event.preventDefault();
+ below.dispatchEvent(new WheelEvent('wheel', {
+ deltaX: event.deltaX, deltaY: event.deltaY, deltaZ: event.deltaZ,
+ deltaMode: event.deltaMode,
+ clientX: event.clientX, clientY: event.clientY,
+ ctrlKey: event.ctrlKey, shiftKey: event.shiftKey,
+ altKey: event.altKey, metaKey: event.metaKey,
+ bubbles: true, cancelable: true,
+ }));
+ }
+
function point(event) {
const box = svg?.getBoundingClientRect();
if (!box?.width || !engine) return null;
@@ -51,7 +81,24 @@
}
function makeMark(points) {
return { id: crypto.randomUUID(), kind: tool, side: annotationSide, colour, points,
- stroke_width: strokeWidth, fill_opacity: fillOpacity, font_size: 16, text: '' };
+ stroke_width: strokeWidth, fill_opacity: fillOpacity, font_size: stampSize, text: '',
+ // Only the mark that carries one: a marker takes the first number free in
+ // its own colour's series, so deleting #2 and stamping again fills that
+ // hole, and a symbol carries the glyph in hand.
+ ...(tool === 'number' ? { number: nextMarkNumber(annotations, colour) } : {}),
+ ...(tool === 'icon' ? { glyph } : {}) };
+ }
+
+ /**
+ * Put a stamp down: one press, no drag, and the tool stays in hand.
+ *
+ * Numbering four things or marking six vehicles is one act, not four or six,
+ * which is the rule the Proof Maker's rail already follows.
+ */
+ function stamp(at) {
+ const mark = makeMark([at]);
+ onchange([...annotations, mark], true);
+ selectedId = mark.id;
}
/**
* Anchor the tool in hand at a ground point and let the pointer draw the rest.
@@ -62,6 +109,8 @@
*/
export function startFrom(at) {
if (!at || tool === 'select' || tool === 'text' || tool === 'polygon') return;
+ // A stamp needs no second point: it lands on the one the menu was opened on.
+ if (STAMPED.has(tool)) { stamp(at); return; }
draft = makeMark([at, at]);
gesture = { kind: 'trail', start: at };
}
@@ -93,6 +142,10 @@
editor = { mark: makeMark([at]), value: '' };
return;
}
+ if (STAMPED.has(tool)) {
+ stamp(at);
+ return;
+ }
if (tool === 'polygon') {
if (!draft) draft = makeMark([at, at, at]);
else draft = { ...draft, points: [...draft.points.slice(0, -1), at, at].slice(0, 200) };
@@ -241,12 +294,33 @@
<svg class="annotation-canvas" class:drawing={active && tool !== 'select'}
bind:this={svg} aria-label={`Annotations on imagery ${letter.toUpperCase()}`}
onpointerdown={begin} onpointermove={move} onpointerup={finish}
- onpointercancel={finish} ondblclick={finishPolygon}>
+ onpointercancel={finish} ondblclick={finishPolygon} onwheel={relayWheel}>
{#each marks as { mark, shape, label, vertices } (mark.id)}
<!-- svelte-ignore a11y_no_static_element_interactions -->
<g class="mark" class:area={edgeOnly} class:selected={selectedId === mark.id} style:color={mark.colour}
onpointerdown={(event) => select(event, mark)} ondblclick={(event) => edit(event, mark)}>
- {#if mark.kind !== 'text'}
+ {#if STAMPED.has(mark.kind)}
+ <!-- A stamp is one point on the ground: a numbered disc, or a symbol in
+ its own box. Both are drawn from `compareAnnotations.js`, which the
+ export draws from too, so a picture holds what the screen showed. -->
+ {#if mark.kind === 'number'}
+ <circle cx={shape.anchor[0]} cy={shape.anchor[1]} r={markSize(mark) / 2}
+ fill={mark.colour} stroke={stampInk(mark)}
+ stroke-width={Math.max(1, markSize(mark) * 0.05)} />
+ <text class="numeral" x={shape.anchor[0]} y={shape.anchor[1]}
+ font-size={markSize(mark) * 0.58} fill={stampInk(mark)}>{mark.number}</text>
+ {:else}
+ {@const box = glyphBox(mark, shape.anchor)}
+ {@const entry = markGlyph(mark)}
+ <path d={entry.path} transform={`translate(${box.x} ${box.y}) scale(${box.scale})`}
+ fill={isSolidIcon(entry.name) ? mark.colour : 'none'} fill-rule="evenodd"
+ stroke={isSolidIcon(entry.name) ? 'none' : mark.colour}
+ stroke-width={Math.max(1.5, mark.stroke_width) / box.scale} />
+ <!-- A stroked glyph is mostly holes, so the press lands on its box
+ rather than on a 2px line. -->
+ <rect class="hit" x={box.x} y={box.y} width={box.size} height={box.size} fill="transparent" />
+ {/if}
+ {:else if mark.kind !== 'text'}
<path d={pathOf(shape)} stroke={mark.colour} stroke-width={mark.stroke_width}
fill={shape.closed ? mark.colour : 'none'} fill-opacity={mark.fill_opacity}
stroke-dasharray={mark.kind === 'measure' ? '8 6' : undefined} />
@@ -291,6 +365,7 @@
.annotation-canvas.drawing { pointer-events: auto; cursor: crosshair; touch-action: none; }
.mark { pointer-events: visiblePainted; cursor: move; }
.mark .edge { pointer-events: stroke; cursor: move; }
+ .mark .hit { pointer-events: all; cursor: move; }
.mark.area { pointer-events: none; }
.drawing .mark, .drawing .mark .edge { pointer-events: none; }
.vertex { pointer-events: auto; cursor: crosshair; }
@@ -298,6 +373,15 @@
.mark path { stroke-linecap: round; stroke-linejoin: round; }
.mark.selected { filter: drop-shadow(0 0 3px white); }
text { fill: white; stroke: #111; stroke-width: 3px; paint-order: stroke; font-family: system-ui, sans-serif; font-weight: 600; }
+ /* The numeral is read off its own disc, so it takes the disc's ink and none of
+ the dark casing a label needs over imagery. */
+ .numeral {
+ stroke: none;
+ font-weight: 700;
+ text-anchor: middle;
+ dominant-baseline: central;
+ pointer-events: none;
+ }
.text-editor { position: absolute; z-index: 620; display: flex; gap: 5px; padding: 8px; max-width: 90%; transform: translateY(-100%); }
.text-editor input { min-width: 100px; width: 220px; }
</style>
diff --git a/frontend/src/tools/compare/AnnotationToolbar.svelte b/frontend/src/tools/compare/AnnotationToolbar.svelte
index 9be0f31..45cea77 100644
--- a/frontend/src/tools/compare/AnnotationToolbar.svelte
+++ b/frontend/src/tools/compare/AnnotationToolbar.svelte
@@ -1,9 +1,14 @@
<script>
import Icon from '../../components/Icon.svelte';
- import { canFill, ANNOTATION_TOOLS } from '../../lib/map/compareAnnotations.js';
+ import ProofGlyph from '../../components/ProofGlyph.svelte';
+ import { PROOF_ICONS, isSolidIcon } from '../../lib/proofIcons.js';
+ import { STAMPED, canFill, ANNOTATION_TOOLS } from '../../lib/map/compareAnnotations.js';
let {
tool = $bindable(),
+ glyph = PROOF_ICONS[0].name,
+ setGlyph = () => {},
+ stampSize = 16,
selected = null,
canUndo = false,
canRedo = false,
@@ -15,6 +20,7 @@
fillOpacity,
setColour = () => {},
setStroke = () => {},
+ setOutline = () => {},
setFill = () => {},
removeSelected = () => {},
clear = () => {},
@@ -25,9 +31,22 @@
const contextual = $derived(tool !== 'select' || Boolean(selected));
const fillable = $derived(canFill(selected?.kind ?? tool));
- const sizeValue = $derived(selected?.kind === 'text'
- ? (selected.font_size ?? 20)
+ // A note and a stamp are sized by their own number: neither has a line to
+ // widen, so the one slider sets that instead of a stroke width.
+ const sizedByFont = $derived(
+ selected ? (selected.kind === 'text' || STAMPED.has(selected.kind))
+ : (tool === 'text' || STAMPED.has(tool))
+ );
+ const sizeValue = $derived(sizedByFont
+ ? (selected?.font_size ?? stampSize)
: (selected?.stroke_width ?? strokeWidth));
+ // A symbol has both: how big it is drawn, and how heavy the line it is drawn
+ // with. A silhouette is a shape with no line, so it takes the size alone.
+ const outlined = $derived(
+ (selected ? selected.kind === 'icon' : tool === 'icon')
+ && !isSolidIcon(selected?.glyph ?? glyph)
+ );
+ const outlineValue = $derived(selected?.stroke_width ?? strokeWidth);
let open = $state('');
let flyout = $state({});
// The panel floats free of the rail, so closing it on an outside press needs
@@ -51,7 +70,7 @@
// nothing selected, or deletes what was selected. Drop the panel with them
// rather than leaving it floating over the maps with nothing behind it.
$effect(() => {
- if (!contextual || (open === 'fill' && !fillable)) open = '';
+ if (!contextual || (open === 'fill' && !fillable) || (open === 'outline' && !outlined)) open = '';
});
$effect(() => {
@@ -76,14 +95,37 @@
<button class="tool-button" title="Undo (Ctrl+Z)" disabled={!canUndo} onclick={undo}><Icon name="undo" size={18} /></button>
<button class="tool-button" title="Redo (Ctrl+Shift+Z)" disabled={!canRedo} onclick={redo}><Icon name="redo" size={18} /></button>
<div class="separator"></div>
+ <!-- Pressing the tool in hand puts it down: the way out of a drawing tool was
+ aiming at the cursor button, and the button you are already on is the
+ easier target of the two. -->
{#each ANNOTATION_TOOLS as entry (entry.id)}
- <button
- class="tool-button"
- class:active={tool === entry.id}
- aria-pressed={tool === entry.id}
- title={`${entry.label} (${entry.shortcut})`}
- onclick={() => (tool = entry.id)}
- ><Icon name={entry.icon} size={18} /></button>
+ {#if entry.id === 'icon'}
+ <!-- The symbol button takes the tool like every other button on the rail,
+ and opens the grid with it: coming back to the stamp never costs
+ re-picking a glyph already chosen. -->
+ <button
+ class="tool-button"
+ class:active={tool === 'icon'}
+ aria-pressed={tool === 'icon'}
+ title={`${entry.label} (${entry.shortcut})`}
+ onclick={(event) => {
+ // With the stamp in hand and the grid shut, the press opens the grid
+ // again: changing a glyph never costs the tool. The press with the grid
+ // open is the one that puts the stamp down.
+ if (tool === 'icon' && open === 'glyph') { tool = 'select'; open = ''; return; }
+ tool = 'icon';
+ toggle('glyph', event);
+ }}
+ ><ProofGlyph name={glyph} size={18} /></button>
+ {:else}
+ <button
+ class="tool-button"
+ class:active={tool === entry.id}
+ aria-pressed={tool === entry.id}
+ title={`${entry.label} (${entry.shortcut})`}
+ onclick={() => (tool = tool === entry.id ? 'select' : entry.id)}
+ ><Icon name={entry.icon} size={18} /></button>
+ {/if}
{/each}
{#if contextual}
@@ -94,9 +136,14 @@
<button class="tool-button" title="Annotation colour" onclick={(event) => toggle('colour', event)}>
<span class="swatch" style:background={selected?.colour ?? colour}></span>
</button>
- <button class="tool-button sized" title={selected?.kind === 'text' ? 'Font size' : 'Stroke width'} onclick={(event) => toggle('size', event)}>
+ <button class="tool-button sized" title={sizedByFont ? 'Size' : 'Stroke width'} onclick={(event) => toggle('size', event)}>
<Icon name="sliders" size={17} /><small>{sizeValue}</small>
</button>
+ {#if outlined}
+ <button class="tool-button sized" title="Outline width" onclick={(event) => toggle('outline', event)}>
+ <Icon name="line" size={17} /><small>{outlineValue}</small>
+ </button>
+ {/if}
{#if fillable}
<button class="tool-button sized" title="Fill opacity" onclick={(event) => toggle('fill', event)}>
<span class="fill-sample" style:opacity={selected?.fill_opacity ?? fillOpacity}></span>
@@ -114,7 +161,19 @@
{/if}
</aside>
-{#if open === 'colour'}
+{#if open === 'glyph'}
+ <div class="flyout glyphs" bind:this={flyoutEl} style:left={flyout.left} style:top={flyout.top} style:bottom={flyout.bottom}>
+ {#each PROOF_ICONS as entry (entry.name)}
+ <button
+ class="glyph-button"
+ class:active={glyph === entry.name}
+ title={entry.label}
+ aria-label={entry.label}
+ onclick={() => { setGlyph(entry.name); open = ''; }}
+ ><ProofGlyph name={entry.name} size={20} /></button>
+ {/each}
+ </div>
+{:else if open === 'colour'}
<div class="flyout colours" bind:this={flyoutEl} style:left={flyout.left} style:top={flyout.top} style:bottom={flyout.bottom}>
{#each palette as entry (entry)}
<button
@@ -135,12 +194,23 @@
<input
type="range"
min="1"
- max={selected?.kind === 'text' ? 72 : 24}
+ max={sizedByFont ? 72 : 24}
value={sizeValue}
- aria-label={selected?.kind === 'text' ? 'Font size' : 'Stroke width'}
+ aria-label={sizedByFont ? 'Size' : 'Stroke width'}
oninput={(event) => setStroke(Number(event.currentTarget.value))}
/>
</div>
+{:else if open === 'outline'}
+ <div class="flyout slider" bind:this={flyoutEl} style:left={flyout.left} style:top={flyout.top} style:bottom={flyout.bottom}>
+ <input
+ type="range"
+ min="1"
+ max="24"
+ value={outlineValue}
+ aria-label="Outline width"
+ oninput={(event) => setOutline(Number(event.currentTarget.value))}
+ />
+ </div>
{:else if open === 'fill'}
<div class="flyout slider" bind:this={flyoutEl} style:left={flyout.left} style:top={flyout.top} style:bottom={flyout.bottom}>
<input
@@ -220,6 +290,19 @@
box-shadow: var(--shadow-2);
}
.colours { display: grid; grid-template-columns: repeat(3, 28px); gap: 7px; }
+ .glyphs { display: grid; grid-template-columns: repeat(5, 30px); gap: 4px; }
+ .glyph-button {
+ width: 30px;
+ height: 30px;
+ display: grid;
+ place-items: center;
+ border: 1px solid transparent;
+ border-radius: var(--r-sm);
+ color: var(--text-2);
+ cursor: pointer;
+ }
+ .glyph-button:hover { border-color: var(--border); color: var(--text-1); }
+ .glyph-button.active { border-color: var(--accent); color: var(--text-1); background: var(--bg-3); }
.colour-button { width: 28px; height: 28px; border: 2px solid transparent; border-radius: 50%; }
.colour-button.active { border-color: #fff; box-shadow: 0 0 0 1px var(--accent); }
.colour-button.custom { position: relative; display: grid; place-items: center; color: white; cursor: pointer; }
diff --git a/frontend/src/tools/compare/AnnotationToolbar.test.js b/frontend/src/tools/compare/AnnotationToolbar.test.js
index 3131595..41e1cb3 100644
--- a/frontend/src/tools/compare/AnnotationToolbar.test.js
+++ b/frontend/src/tools/compare/AnnotationToolbar.test.js
@@ -115,3 +115,43 @@ describe('the flyout a rail button opens', () => {
expect(panel()).toBeNull();
});
});
+
+describe('the two stamps the rail gained', () => {
+ const trigger = (title) => target.querySelector(`button[title="${title}"]`);
+
+ it('offers them beside the shapes, each with its own letter', () => {
+ const rail = stage().innerHTML;
+ expect(rail).toContain('Numbered marker (N)');
+ expect(rail).toContain('Symbol (S)');
+ });
+
+ it('opens the symbol grid with the tool, and picks a glyph from it', () => {
+ const setGlyph = vi.fn();
+ stage({ setGlyph });
+ trigger('Symbol (S)').click();
+ flushSync();
+
+ const grid = document.querySelector('.flyout.glyphs');
+ expect(grid).not.toBeNull();
+ grid.querySelectorAll('.glyph-button')[1].click();
+ flushSync();
+ expect(setGlyph).toHaveBeenCalledTimes(1);
+ expect(document.querySelector('.flyout.glyphs')).toBeNull();
+ });
+
+ it('puts the tool down when the button it is on is pressed again', () => {
+ const rail = stage({ tool: 'number' });
+ expect(rail.querySelector('button[title="Numbered marker (N)"]').getAttribute('aria-pressed'))
+ .toBe('true');
+ // the rail binds `tool`, so the press is read back off the button's own state
+ expect(source).toContain("onclick={() => (tool = tool === entry.id ? 'select' : entry.id)}");
+ expect(source).toContain("if (tool === 'icon' && open === 'glyph') { tool = 'select'; open = ''; return; }");
+ });
+
+ it('sizes a stamp rather than widening a line it has not got', () => {
+ expect(stage({ tool: 'number' }).innerHTML).toContain('Size');
+ unmount(live);
+ live = null;
+ expect(stage({ tool: 'rect' }).innerHTML).toContain('Stroke width');
+ });
+});
diff --git a/frontend/src/tools/compare/ModeDock.render.test.js b/frontend/src/tools/compare/ModeDock.render.test.js
new file mode 100644
index 0000000..659e2ba
--- /dev/null
+++ b/frontend/src/tools/compare/ModeDock.render.test.js
@@ -0,0 +1,66 @@
+import { describe, expect, it } from 'vitest';
+import { render } from 'svelte/server';
+import { readFileSync } from 'node:fs';
+import ModeDock from './ModeDock.svelte';
+import AnalyzerPanel from './AnalyzerPanel.svelte';
+
+const compare = readFileSync(new URL('../Compare.svelte', import.meta.url), 'utf8');
+
+/** Each named group, with the labels of the modes inside it. */
+function groups(body) {
+ return body
+ .split('role="group" aria-label="')
+ .slice(1)
+ .map((chunk) => [
+ chunk.slice(0, chunk.indexOf('"')),
+ [...chunk.matchAll(/<span class="svelte-[^"]*">([^<]+)<\/span>/g)].map((label) => label[1]),
+ ]);
+}
+
+describe('the mode dock', () => {
+ const ready = { ok: true, reason: '' };
+
+ it('names its two kinds of choice apart', () => {
+ const { body } = render(ModeDock, { props: { mode: 'side', change: ready } });
+ expect(groups(body)).toEqual([
+ ['View', ['Side by side', 'Swipe', 'Fade', 'Blink']],
+ ['Analysis', ['Difference', 'Detect']],
+ ]);
+ });
+
+ it('says what an analysis still needs on the button itself', () => {
+ const { body } = render(ModeDock, {
+ props: {
+ mode: 'side',
+ change: { ok: false, reason: 'Add imagery A and B first.' },
+ detect: { ok: false, reason: 'Detect reads Copernicus Sentinel-2: add your credentials in Settings → Imagery.' },
+ },
+ });
+ expect(body).toMatch(/class="mode-btn[^"]*blocked[^"]*"[^>]*title="Add imagery A and B first\."/);
+ expect(body).toMatch(/class="mode-btn[^"]*blocked[^"]*"[^>]*title="Detect reads Copernicus Sentinel-2/);
+ // a ready mode keeps its name and key as the tooltip
+ expect(body).toContain('title="Swipe (2)"');
+ });
+
+ it('marks nothing when every analysis can run', () => {
+ const { body } = render(ModeDock, { props: { mode: 'change', change: ready, detect: ready } });
+ expect(body).not.toContain('blocked');
+ });
+});
+
+describe('Detect without Copernicus', () => {
+ it('asks only once the provider list has been read, and never locks the panel', () => {
+ expect(compare).toContain("imagery.providers.length && !imagery.find('sentinel2')");
+ // saved areas and runs stay reachable: setMode refuses Difference, not Detect
+ expect(compare).toContain("if (next === 'change' && !changeStatus.ok) {");
+ expect(compare).not.toContain("next === 'analysis' && !detectStatus.ok");
+ });
+
+ it('says so at the top of the panel, with the way to Settings', () => {
+ const { body } = render(AnalyzerPanel, {
+ props: { caseId: 'c1', needs: 'Detect reads Copernicus Sentinel-2: add your credentials in Settings → Imagery.' },
+ });
+ expect(body).toContain('Detect reads Copernicus Sentinel-2');
+ expect(body).toContain('Open Settings');
+ });
+});
diff --git a/frontend/src/tools/compare/ModeDock.svelte b/frontend/src/tools/compare/ModeDock.svelte
index 6474a5b..d7eedc9 100644
--- a/frontend/src/tools/compare/ModeDock.svelte
+++ b/frontend/src/tools/compare/ModeDock.svelte
@@ -3,32 +3,41 @@
import Icon from '../../components/Icon.svelte';
import { COMPARE_MODES } from '../../lib/map/compare.js';
- let { mode, change, onmode = () => {}, onswap = () => {} } = $props();
+ let { mode, change, detect = { ok: true }, onmode = () => {}, onswap = () => {} } = $props();
+
+ // Two kinds of choice, named: how the pair is shown, and what gets computed
+ // over it. A computing mode says what it needs before it is pressed.
+ const GROUPS = [
+ { id: 'read', label: 'View' },
+ { id: 'find', label: 'Analysis' },
+ ];
+ const needs = $derived({ change, analysis: detect });
</script>
<div class="mode-dock cmp-glass" role="toolbar" aria-label="Comparison view">
- <div class="cmp-seg">
- {#each COMPARE_MODES as entry, index (entry.id)}
- {@const blocked = entry.id === 'change' && !change.ok}
- {#if index > 0 && entry.group !== COMPARE_MODES[index - 1].group}
- <!-- Left of the rule: how the pair is shown. Right of it: what gets
- computed over the pair, which is a different kind of choice. -->
- <span class="group-rule" aria-hidden="true"></span>
- {/if}
- <button
- class="mode-btn"
- class:on={mode === entry.id}
- class:blocked
- class:find={entry.group === 'find'}
- aria-pressed={mode === entry.id}
- title={blocked ? change.reason : `${entry.label} (${entry.key})`}
- onclick={() => onmode(entry.id)}
- >
- <Icon name={entry.icon} size={14} />
- <span>{entry.label}</span>
- </button>
- {/each}
- </div>
+ {#each GROUPS as group (group.id)}
+ <div class="group" role="group" aria-label={group.label}>
+ <span class="group-name">{group.label}</span>
+ <div class="cmp-seg">
+ {#each COMPARE_MODES.filter((entry) => entry.group === group.id) as entry (entry.id)}
+ {@const missing = needs[entry.id] && !needs[entry.id].ok ? needs[entry.id].reason : ''}
+ <button
+ class="mode-btn"
+ class:on={mode === entry.id}
+ class:blocked={Boolean(missing)}
+ class:find={entry.group === 'find'}
+ aria-pressed={mode === entry.id}
+ title={missing || `${entry.label} (${entry.key})`}
+ onclick={() => onmode(entry.id)}
+ >
+ <Icon name={entry.icon} size={14} />
+ <span>{entry.label}</span>
+ {#if missing}<Icon name="alert" size={11} />{/if}
+ </button>
+ {/each}
+ </div>
+ </div>
+ {/each}
<button class="cmp-icon" onclick={onswap} title="Swap A and B" aria-label="Swap A and B">
<Icon name="swap" size={15} />
</button>
@@ -38,18 +47,25 @@
.mode-dock {
display: flex;
align-items: center;
- gap: 4px;
- padding: 4px;
+ gap: 10px;
+ padding: 4px 6px;
+ }
+ .group {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ }
+ .group-name {
+ font-size: var(--fs-xs);
+ letter-spacing: 0.04em;
+ text-transform: uppercase;
+ color: var(--glass-dim);
}
.mode-btn.blocked:not(.on) {
color: var(--glass-dim);
}
- .group-rule {
- align-self: center;
- width: 1px;
- height: 18px;
- margin: 0 4px;
- background: var(--glass-line);
+ .mode-btn.blocked :global(svg:last-child) {
+ color: var(--warn);
}
/* A computing mode stays legible as one when it is on: the pair is unchanged
underneath and something is being laid over it. */
@@ -57,7 +73,8 @@
color: var(--accent);
}
@media (max-width: 1100px) {
- .mode-btn:not(.find) span {
+ .mode-btn:not(.find) span,
+ .group-name {
display: none;
}
}
diff --git a/frontend/src/tools/coordinates.fixture.svelte.js b/frontend/src/tools/coordinates.fixture.svelte.js
new file mode 100644
index 0000000..5557600
--- /dev/null
+++ b/frontend/src/tools/coordinates.fixture.svelte.js
@@ -0,0 +1,19 @@
+/**
+ * Reactive stand-in for `Coordinates.render.test.js`.
+ *
+ * The tab reads the map's point out of an effect, so a plain object would never
+ * make it run again when the test moves the map. Runes only work in
+ * `.svelte.js` and a `vi.mock` factory runs inside the `.test.js`, so the state
+ * lives here and the test hands this module back.
+ */
+export const uiState = $state({ tool: 'coordinates', mapPoint: null, gotoCoords: null });
+
+export const caseState = $state({ current: null });
+
+/** Put the fixture back the way every test starts. */
+export function resetCoordinatesFixture() {
+ uiState.tool = 'coordinates';
+ uiState.mapPoint = null;
+ uiState.gotoCoords = null;
+ caseState.current = null;
+}
diff --git a/frontend/src/tools/coordinates/SkyPanel.svelte b/frontend/src/tools/coordinates/SkyPanel.svelte
index 9dc811c..18f8f8f 100644
--- a/frontend/src/tools/coordinates/SkyPanel.svelte
+++ b/frontend/src/tools/coordinates/SkyPanel.svelte
@@ -8,6 +8,7 @@
import { api } from '../../lib/api.js';
import { toast, uiState } from '../../lib/state.svelte.js';
import Icon from '../../components/Icon.svelte';
+ import DateField from '../../components/DateField.svelte';
import MoonGlyph from '../../components/MoonGlyph.svelte';
import DayChart from './DayChart.svelte';
import SkyRose from './SkyRose.svelte';
@@ -112,14 +113,16 @@
<div class="sky" class:loading>
<div class="sky-head">
<h3>Sun &amp; moon</h3>
- <input
- class="input input-sm"
- type="date"
- value={shownDay}
- disabled={!point}
- onchange={(e) => (day = e.currentTarget.value)}
- title="Local date at this point"
- />
+ <div class="day-field">
+ <DateField
+ day
+ reading={false}
+ label="Local date at this point"
+ value={shownDay}
+ disabled={!point}
+ onchange={(value) => (day = value)}
+ />
+ </div>
<input
class="input input-sm"
type="time"
@@ -301,6 +304,9 @@
gap: 10px;
flex-wrap: wrap;
}
+ .day-field {
+ width: 9.5rem;
+ }
h3 {
margin: 0;
font-size: var(--fs-md);
diff --git a/frontend/src/tools/coordinates/SkyPanel.test.js b/frontend/src/tools/coordinates/SkyPanel.test.js
index 30827b4..2083752 100644
--- a/frontend/src/tools/coordinates/SkyPanel.test.js
+++ b/frontend/src/tools/coordinates/SkyPanel.test.js
@@ -35,7 +35,10 @@ describe('Sun & moon panel', () => {
});
it('treats the date and time as local wall-clock readings', () => {
- expect(panel).toContain('type="date"');
+ // a day typed dd/mm/yyyy in any browser language, not the browser's own picker
+ expect(panel).toContain('<DateField');
+ expect(panel).toContain('day\n');
+ expect(panel).not.toContain('type="date"');
expect(panel).toContain('type="time"');
expect(panel).toContain('Local date at this point');
// empty means "let the backend pick", so the point's own today is used
diff --git a/frontend/src/tools/inspect/CollageMenu.svelte b/frontend/src/tools/inspect/CollageMenu.svelte
index 4bb6132..81fd081 100644
--- a/frontend/src/tools/inspect/CollageMenu.svelte
+++ b/frontend/src/tools/inspect/CollageMenu.svelte
@@ -281,7 +281,7 @@
</button>
{/if}
{#if session.collages.length > 1}
- <button class="ctab-x" onclick={() => removeCollage(cl.id)} aria-label="Delete collage"><Icon name="x" size={11} /></button>
+ <button class="ctab-x" onclick={() => removeCollage(cl.id)} aria-label="Delete collage" title="Delete collage"><Icon name="x" size={11} /></button>
{/if}
</div>
{/each}
diff --git a/frontend/src/tools/inspect/FrameMenu.render.test.js b/frontend/src/tools/inspect/FrameMenu.render.test.js
new file mode 100644
index 0000000..d132588
--- /dev/null
+++ b/frontend/src/tools/inspect/FrameMenu.render.test.js
@@ -0,0 +1,82 @@
+// @vitest-environment happy-dom
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { flushSync, mount, unmount } from 'svelte';
+
+/**
+ * The Frame tab's reverse-search press, driven the way an analyst drives it: the
+ * frame pressed on is the one handed over, and a second press while the first is
+ * still rendering does not send it twice.
+ */
+
+vi.mock('../../lib/api.js', () => ({ api: { post: vi.fn(), get: vi.fn() } }));
+vi.mock('../../lib/state.svelte.js', () => ({ caseState: { current: { id: 'case-a' } }, toast: vi.fn() }));
+
+const { default: FrameMenu } = await import('./FrameMenu.svelte');
+
+const FRAME = {
+ id: 'fr1', path: 'media/clip.mp4', time: 12.4, url: 'blob:frame', adjust: {}, crop: null,
+ sourceOps: [], rotation: 0, w: 640, h: 360,
+};
+
+let live = null;
+let target = null;
+
+function open(reverse) {
+ target = document.createElement('div');
+ document.body.append(target);
+ live = mount(FrameMenu, {
+ target,
+ props: {
+ session: { frames: [FRAME], activeFrameId: FRAME.id, saved: {} },
+ filters: [],
+ analyses: [],
+ activeFrame: FRAME,
+ shared: {},
+ removeFrame: vi.fn(),
+ setActive: vi.fn(),
+ setRotation: vi.fn(),
+ reverse,
+ },
+ });
+ flushSync();
+}
+
+const button = () => [...target.querySelectorAll('button')].find((b) => b.textContent.includes('Reverse image search') || b.textContent.includes('Preparing'));
+
+afterEach(() => {
+ if (live) unmount(live);
+ live = null;
+ target?.remove();
+});
+
+describe('reverse search from the Frame tab', () => {
+ it('hands over the active frame', async () => {
+ const reverse = vi.fn(async () => {});
+ open(reverse);
+
+ button().click();
+ await Promise.resolve();
+
+ expect(reverse).toHaveBeenCalledTimes(1);
+ expect(reverse).toHaveBeenCalledWith(FRAME);
+ });
+
+ it('holds the button while the frame renders, so one press sends it once', async () => {
+ let finish;
+ const reverse = vi.fn(() => new Promise((resolve) => (finish = resolve)));
+ open(reverse);
+
+ button().click();
+ flushSync();
+ expect(button().disabled).toBe(true);
+ expect(button().textContent).toContain('Preparing');
+ button().click();
+ expect(reverse).toHaveBeenCalledTimes(1);
+
+ finish();
+ await Promise.resolve();
+ await Promise.resolve();
+ flushSync();
+ expect(button().disabled).toBe(false);
+ });
+});
diff --git a/frontend/src/tools/inspect/FrameMenu.svelte b/frontend/src/tools/inspect/FrameMenu.svelte
index bce45c6..cd3e75d 100644
--- a/frontend/src/tools/inspect/FrameMenu.svelte
+++ b/frontend/src/tools/inspect/FrameMenu.svelte
@@ -13,13 +13,24 @@
let {
session, filters, analyses, activeFrame, shared, removeFrame, setActive,
cropAspect = $bindable(null), cropEditing = $bindable(false), beginCrop, commitCrop,
- setRotation, rotationBusy = false,
+ setRotation, rotationBusy = false, reverse,
} = $props();
let showAnalyze = $state(false);
let analyzing = $state(null);
let analysis = $state(null);
let canvasEl = $state();
+ let reversing = $state(false);
+
+ async function reverseActive() {
+ if (!activeFrame || reversing) return;
+ reversing = true;
+ try {
+ await reverse(activeFrame);
+ } finally {
+ reversing = false;
+ }
+ }
async function reset() {
if (!activeFrame) return;
@@ -96,7 +107,7 @@
<span class="num">{i + 1}</span>
{#if session.saved[`frame:${fr.id}`]}<span class="saved" title="Saved"><Icon name="check" size={11} /></span>{/if}
</button>
- <button class="del" onclick={() => removeFrame(fr.id)} aria-label="Remove frame"><Icon name="x" size={12} /></button>
+ <button class="del" onclick={() => removeFrame(fr.id)} aria-label="Remove frame" title="Remove frame"><Icon name="x" size={12} /></button>
</div>
{/each}
{#if session.frames.length === 0}
@@ -137,6 +148,14 @@
{/if}
</div>
<button class="btn btn-ghost btn-sm reset" onclick={reset}><Icon name="reset" size={14} /> Reset frame</button>
+ <button
+ class="btn btn-sm reverse"
+ disabled={reversing}
+ onclick={reverseActive}
+ title="Search the web for this image as it is adjusted and cropped here"
+ >
+ <Icon name="search" size={14} /> {reversing ? 'Preparing…' : 'Reverse image search'}
+ </button>
</div>
<div class="section">
@@ -274,7 +293,8 @@
color: var(--accent);
border-color: var(--accent);
}
- .reset {
+ .reset,
+ .reverse {
align-self: flex-start;
}
.section-head {
diff --git a/frontend/src/tools/inspect/VideoPlayer.svelte b/frontend/src/tools/inspect/VideoPlayer.svelte
index 8379af7..9e9196c 100644
--- a/frontend/src/tools/inspect/VideoPlayer.svelte
+++ b/frontend/src/tools/inspect/VideoPlayer.svelte
@@ -87,7 +87,7 @@
></video>
</div>
<div class="player-bar">
- <button class="player-btn" onclick={togglePlayback} aria-label={paused ? 'Play' : 'Pause'}>
+ <button class="player-btn" onclick={togglePlayback} aria-label={paused ? 'Play' : 'Pause'} title={paused ? 'Play' : 'Pause'}>
<Icon name={paused ? 'play' : 'pause'} size={16} />
</button>
<input
@@ -101,10 +101,10 @@
aria-label="Video position"
/>
<span class="player-time mono">{fmt(currentTime)} / {fmt(totalDuration)}</span>
- <button class="player-btn" onclick={toggleMute} aria-label={muted ? 'Unmute' : 'Mute'}>
+ <button class="player-btn" onclick={toggleMute} aria-label={muted ? 'Unmute' : 'Mute'} title={muted ? 'Unmute' : 'Mute'}>
<Icon name={muted ? 'volumeOff' : 'volume'} size={16} />
</button>
- <button class="player-btn" onclick={toggleFullscreen} aria-label="Full screen">
+ <button class="player-btn" onclick={toggleFullscreen} aria-label="Full screen" title="Full screen">
<Icon name="maximize" size={16} />
</button>
</div>
diff --git a/frontend/src/tools/overview/CaseTodos.svelte b/frontend/src/tools/overview/CaseTodos.svelte
index fbbed31..e637168 100644
--- a/frontend/src/tools/overview/CaseTodos.svelte
+++ b/frontend/src/tools/overview/CaseTodos.svelte
@@ -146,13 +146,13 @@
<li>
<input type="checkbox" aria-label={`Complete ${task.text}`} checked={task.done} onchange={(e) => updateTask(task.id, { done: e.currentTarget.checked }, e.currentTarget)} />
<input class="task" class:done={task.done} aria-label="Task text" value={task.text} maxlength="2000" onchange={(e) => updateTask(task.id, { text: e.currentTarget.value.trim() }, e.currentTarget)} onkeydown={(e) => { if (e.key === 'Enter') e.currentTarget.blur(); }} />
- <button class="btn btn-ghost btn-sm" aria-label={`Delete ${task.text}`} onclick={() => deleteTask(task.id)}><Icon name="trash" size={14} /></button>
+ <button class="btn btn-ghost btn-sm" aria-label={`Delete ${task.text}`} title={`Delete ${task.text}`} onclick={() => deleteTask(task.id)}><Icon name="trash" size={14} /></button>
</li>
{/each}
</ul>
<form class="entry" onsubmit={addTask}>
<input class="input" aria-label="New task" placeholder="Add a task…" maxlength="2000" bind:value={taskText} bind:this={taskInput} disabled={selected.tasks.length >= 200} />
- <button class="btn btn-sm" aria-label="Add task" disabled={!taskText.trim() || selected.tasks.length >= 200}><Icon name="plus" size={15} /></button>
+ <button class="btn btn-sm" aria-label="Add task" title="Add task" disabled={!taskText.trim() || selected.tasks.length >= 200}><Icon name="plus" size={15} /></button>
</form>
{:else}
<p class="quiet">Add a list to start.</p>
diff --git a/frontend/src/tools/proof/ImportProofDialog.svelte b/frontend/src/tools/proof/ImportProofDialog.svelte
index 3c9b704..dbcfe9e 100644
--- a/frontend/src/tools/proof/ImportProofDialog.svelte
+++ b/frontend/src/tools/proof/ImportProofDialog.svelte
@@ -521,7 +521,7 @@
{/if}
<div class="import-view-bar">
{#if held.length > 1}
- <button class="btn btn-sm" onclick={() => step(-1)} aria-label="Previous file">
+ <button class="btn btn-sm" onclick={() => step(-1)} aria-label="Previous file" title="Previous file">
<Icon name="chevronLeft" size={14} />
</button>
{/if}
@@ -533,7 +533,7 @@
</span>{/if}
</p>
{#if held.length > 1}
- <button class="btn btn-sm" onclick={() => step(1)} aria-label="Next file">
+ <button class="btn btn-sm" onclick={() => step(1)} aria-label="Next file" title="Next file">
<Icon name="chevronRight" size={14} />
</button>
{/if}
diff --git a/frontend/src/tools/proof/NewProofDialog.svelte b/frontend/src/tools/proof/NewProofDialog.svelte
index 13fb04a..4f93c0b 100644
--- a/frontend/src/tools/proof/NewProofDialog.svelte
+++ b/frontend/src/tools/proof/NewProofDialog.svelte
@@ -69,7 +69,7 @@
<Icon name="search" size={13} />
<input placeholder="Search panels…" bind:value={query} />
{#if query}
- <button type="button" onclick={() => (query = '')} aria-label="Clear search">
+ <button type="button" onclick={() => (query = '')} aria-label="Clear search" title="Clear search">
<Icon name="x" size={12} />
</button>
{/if}
diff --git a/frontend/src/tools/proof/ProofLayersPanel.svelte b/frontend/src/tools/proof/ProofLayersPanel.svelte
index c2bbca6..61d4e5f 100644
--- a/frontend/src/tools/proof/ProofLayersPanel.svelte
+++ b/frontend/src/tools/proof/ProofLayersPanel.svelte
@@ -38,9 +38,11 @@
featureList,
moveLegendColor,
setColor,
- canMoveShapeUp,
- canMoveShapeDown,
- moveShape,
+ canBringForward,
+ canSendBackward,
+ bringForward,
+ sendBackward,
+ moveShapeTo,
kindIcon,
kindLabel,
duplicateShape,
@@ -49,9 +51,89 @@
} = $props();
// A row says which symbol it is, not merely that it is one: eleven rows all
- // reading "Symbol" would be a list nobody can navigate.
- const rowLabel = (shape) =>
- (shape.kind === 'icon' ? iconByName(shape.name)?.label : null) ?? kindLabel[shape.kind];
+ // reading "Symbol" would be a list nobody can navigate. A marker says its
+ // number for the same reason — that number is the whole of what it states.
+ const rowLabel = (shape) => {
+ if (shape.kind === 'icon') return iconByName(shape.name)?.label ?? kindLabel.icon;
+ if (shape.kind === 'number') return `${kindLabel.number} ${shape.n ?? ''}`.trim();
+ return kindLabel[shape.kind];
+ };
+
+ /**
+ * The elements front-first, which is how the Panels list above already reads
+ * and how every layer list anywhere reads: the row on top is the mark on top
+ * of the picture.
+ *
+ * The array runs the other way — a panel's shapes are drawn in array order, so
+ * the last one is the one in front — and that is the spec's order, not a
+ * reading order. So it is turned round here and nowhere else, and each row
+ * carries the index it came from.
+ */
+ const rows = $derived(proof.shapes.map((shape, index) => ({ shape, index })).reverse());
+
+ /**
+ * Which picture each row is drawn on, named the way the lists above number
+ * them — but shown only once more than one picture holds elements.
+ *
+ * The order is one order for the whole proof, while what an element is drawn
+ * *over* is decided inside its own picture: two marks on two panels are
+ * stacked by the panels. So a row moved past a row of another picture changes
+ * nothing on screen, and this is the reason, on the row, rather than an arrow
+ * greyed out with none.
+ */
+ const surfaceNames = $derived.by(() => {
+ const names = new Map();
+ proof.panels.forEach((panel, at) => names.set(panel.id, `P${at + 1}`));
+ proof.pastes.forEach((paste, at) => names.set(paste.id, `I${at + 1}`));
+ return names;
+ });
+ const manySurfaces = $derived(new Set(proof.shapes.map((shape) => shape.panel)).size > 1);
+
+ // Dragging a row to reorder it. A press is armed first and becomes a drag a
+ // few pixels later, so a plain click still picks the element it lands on, and
+ // a press that starts on a field or a button belongs to that control.
+ let armed = null;
+ let dragging = $state(-1); // the seat being dragged, in list order
+ let over = $state(-1); // the seat it would land on
+
+ function rowPointerDown(event, seat) {
+ if (event.button !== 0 || event.target.closest('input, button, label')) return;
+ armed = { seat, x: event.clientX, y: event.clientY };
+ }
+
+ function rowPointerMove(event) {
+ if (!armed) return;
+ if (Math.hypot(event.clientX - armed.x, event.clientY - armed.y) < 4) return;
+ dragging = armed.seat;
+ over = armed.seat;
+ armed = null;
+ }
+
+ function rowPointerEnter(seat) {
+ if (dragging >= 0) over = seat;
+ }
+
+ function endDrag() {
+ if (dragging >= 0 && over >= 0 && over !== dragging) {
+ moveShapeTo(rows[dragging].index, rows[over].index);
+ }
+ armed = null;
+ dragging = -1;
+ over = -1;
+ }
+
+ // The release can land anywhere — outside the list, outside the window — so it
+ // is heard at the window for as long as the panel is up. A press that never
+ // became a drag is disarmed by the same handler, or it would turn into one the
+ // next time the pointer crossed that row with no button held.
+ $effect(() => {
+ window.addEventListener('pointerup', endDrag, true);
+ window.addEventListener('pointercancel', endDrag, true);
+ return () => {
+ window.removeEventListener('pointerup', endDrag, true);
+ window.removeEventListener('pointercancel', endDrag, true);
+ };
+ });
</script>
<!-- Coloured border for a panel or a pasted image. Picking a colour adds one,
@@ -300,30 +382,48 @@
</span>
</button>
{#if !collapsed.elements}
- {#each proof.shapes as shape, index (shape.id)}
+ <!-- Front-first: the row on top is the mark on top of the picture, and it is
+ dragged up to bring it further forward. -->
+ {#each rows as { shape, index }, seat (shape.id)}
<div
class="shape-row"
class:selected={selectionLive && selectedIds.includes(shape.id)}
+ class:dragging={dragging === seat}
+ class:landing={dragging >= 0 && over === seat && dragging !== seat}
+ class:from-below={dragging > seat}
onclick={(event) => selectShape(shape.id, event.shiftKey)}
+ onpointerdown={(event) => rowPointerDown(event, seat)}
+ onpointermove={rowPointerMove}
+ onpointerenter={() => rowPointerEnter(seat)}
role="button"
tabindex="0"
+ title="Drag to reorder"
onkeydown={(event) => event.key === 'Enter' && selectShape(shape.id, event.shiftKey)}
>
<div class="reorder">
<button
class="btn btn-ghost reorder-btn"
- disabled={!canMoveShapeUp(index)}
- title="Move up (z-order within its panel)"
- onclick={(event) => { event.stopPropagation(); moveShape(index, -1); }}
+ disabled={!canBringForward(index)}
+ title="Bring forward (over the others on its picture)"
+ onclick={(event) => { event.stopPropagation(); bringForward(index); }}
><Icon name="chevronUp" size={11} /></button>
<button
class="btn btn-ghost reorder-btn"
- disabled={!canMoveShapeDown(index)}
- title="Move down (z-order within its panel)"
- onclick={(event) => { event.stopPropagation(); moveShape(index, 1); }}
+ disabled={!canSendBackward(index)}
+ title="Send backward"
+ onclick={(event) => { event.stopPropagation(); sendBackward(index); }}
><Icon name="chevronDown" size={11} /></button>
</div>
- <span class="chip" style:background={shape.color}></span>
+ <!-- A blur box has no colour to show: it is the one mark drawn from the
+ picture's own pixels rather than in ink. -->
+ {#if shape.kind !== 'blur'}
+ <span class="chip" style:background={shape.color}></span>
+ {/if}
+ {#if manySurfaces}
+ <span class="on-what" title="Drawn on {surfaceNames.get(shape.panel) ?? 'a picture'}">
+ {surfaceNames.get(shape.panel) ?? '–'}
+ </span>
+ {/if}
{#if shape.kind === 'icon'}
<ProofGlyph name={shape.name} size={13} />
{:else}
@@ -370,7 +470,9 @@
><Icon name="x" size={11} /></button>
{/if}
{:else}
- <span class="el-label">{rowLabel(shape)} <span class="el-id">#{index + 1}</span></span>
+ <!-- Numbered by where the row sits, so the count follows the eye down
+ the list rather than the array underneath it. -->
+ <span class="el-label">{rowLabel(shape)} <span class="el-id">#{seat + 1}</span></span>
{/if}
<button
class="btn btn-ghost btn-sm"
@@ -384,6 +486,9 @@
><Icon name="trash" size={13} /></button>
</div>
{/each}
+ {#if manySurfaces}
+ <div class="list-hint">Elements stack inside the picture they are drawn on.</div>
+ {/if}
{/if}
<style>
@@ -579,9 +684,36 @@
color: var(--text-3);
cursor: pointer;
}
+ /* A row is dragged by its middle, and a drag over words selects them unless it
+ is said not to. The label a text element carries is still a field, so it
+ keeps its own selection. */
+ .shape-row {
+ -webkit-user-select: none;
+ user-select: none;
+ }
+ .shape-row input {
+ -webkit-user-select: text;
+ user-select: text;
+ }
.shape-row:hover { background: var(--bg-2); }
.shape-row.selected { border-color: var(--accent); background: var(--accent-soft); }
+ /* Dragging: the row being carried fades, and a rule marks the gap it would
+ drop into — on the side it is coming from, so the line is between the two
+ rows it would end up between. */
+ .shape-row.dragging { opacity: 0.45; }
+ .shape-row.landing { box-shadow: inset 0 -2px 0 var(--accent); }
+ .shape-row.landing.from-below { box-shadow: inset 0 2px 0 var(--accent); }
.chip { width: 12px; height: 12px; border-radius: 50%; flex-shrink: 0; }
+ .on-what {
+ flex-shrink: 0;
+ padding: 0 4px;
+ border-radius: var(--r-sm);
+ background: var(--bg-3);
+ color: var(--text-3);
+ font-size: 9px;
+ font-weight: 700;
+ }
+ .list-hint { margin: 4px 0 2px; font-size: var(--fs-xs); color: var(--text-3); }
.comment-input {
flex: 1;
font-size: var(--fs-xs);
diff --git a/frontend/src/tools/proof/ProofToolbar.svelte b/frontend/src/tools/proof/ProofToolbar.svelte
index 755cc11..c4a1dae 100644
--- a/frontend/src/tools/proof/ProofToolbar.svelte
+++ b/frontend/src/tools/proof/ProofToolbar.svelte
@@ -20,6 +20,9 @@
// A silhouette has no outline, so the width control is hidden for it. Any
// caller that says nothing gets the control.
showStroke = true,
+ // A blur box is drawn from the picture rather than in ink, so the swatch is
+ // hidden for it — same rule, and same default.
+ showColor = true,
iconName = PROOF_ICONS[0].name,
setIconName = () => {},
strokeW,
@@ -153,12 +156,16 @@
<Icon name="redo" size={18} />
</button>
<div class="tb-sep"></div>
+ <!-- Pressing the tool in hand puts it down: the way out of a drawing tool was
+ aiming at the cursor button, and the button you are already on is the
+ easier target of the two. -->
{#each drawTools as entry (entry.id)}
<button
class="tb-btn"
class:active={tool === entry.id}
+ aria-pressed={tool === entry.id}
title="{entry.label} ({entry.shortcut})"
- onclick={() => (tool = entry.id)}
+ onclick={() => (tool = tool === entry.id ? 'select' : entry.id)}
>
<Icon name={entry.icon} size={18} />
</button>
@@ -171,8 +178,17 @@
<button
class="tb-btn"
class:active={tool === 'icon'}
+ aria-pressed={tool === 'icon'}
title="Symbol (s)"
- onclick={() => { tool = 'icon'; toggle('icon'); }}
+ onclick={() => {
+ // The grid is a picker: with the stamp in hand and the grid shut, the
+ // press opens it again, so changing a glyph never costs the tool. It is
+ // the press *with the grid open* that puts the stamp down, which is what
+ // pressing the tool you are already on means everywhere else on the rail.
+ if (tool === 'icon' && iconOpen) { tool = 'select'; toggle(''); return; }
+ tool = 'icon';
+ toggle('icon');
+ }}
bind:this={iconBtn}
>
<ProofGlyph name={iconName} size={18} />
@@ -258,10 +274,13 @@
</div>
</div>
- {#if showContextTools}
+ <!-- A blur box answers to none of these, so the group is empty for it and the
+ rule that marks it would be a line under nothing. -->
+ {#if showContextTools && (showColor || showStroke || showFill)}
<div class="tb-sep"></div>
<!-- Colour: a swatch that opens the palette + custom picker. -->
+ {#if showColor}
<div class="tb-group" bind:this={colorEl}>
<button
class="tb-btn"
@@ -305,6 +324,7 @@
</label>
</div>
</div>
+ {/if}
<!-- Size: a horizontal slider for stroke width / font size. -->
{#if showStroke}
diff --git a/frontend/src/tools/proof/ProofToolbar.test.js b/frontend/src/tools/proof/ProofToolbar.test.js
index fabdb49..c3b99ed 100644
--- a/frontend/src/tools/proof/ProofToolbar.test.js
+++ b/frontend/src/tools/proof/ProofToolbar.test.js
@@ -205,8 +205,10 @@ describe('the symbol button', () => {
it('takes the tool as well as opening the grid, like the `s` it promises', () => {
// It was the one button on the rail that only opened a flyout, so coming
// back to the stamp meant re-picking a glyph already chosen.
- expect(src).toContain("onclick={() => { tool = 'icon'; toggle('icon'); }}");
- expect(src).toContain('onclick={() => (tool = entry.id)}'); // as the rest of the rail does
+ expect(src).toContain("tool = 'icon';\n toggle('icon');");
+ // …and pressing it again puts the stamp down, as the rest of the rail does
+ expect(src).toContain("if (tool === 'icon' && iconOpen) { tool = 'select'; toggle(''); return; }");
+ expect(src).toContain("onclick={() => (tool = tool === entry.id ? 'select' : entry.id)}");
});
it('is lit by the tool in hand, not by the grid being open', () => {
diff --git a/frontend/src/tools/satellite/AddLayerDialog.render.test.js b/frontend/src/tools/satellite/AddLayerDialog.render.test.js
index 4931a08..253b997 100644
--- a/frontend/src/tools/satellite/AddLayerDialog.render.test.js
+++ b/frontend/src/tools/satellite/AddLayerDialog.render.test.js
@@ -75,6 +75,16 @@ describe('the add-a-layer dialog', () => {
expect(onurl).toHaveBeenCalledWith('https://www.google.com/maps/d/viewer?mid=XyZ', true);
});
+ it('offers GeoConfirmed without a tick: its icons arrive inside the export', () => {
+ const ongeoconfirmed = vi.fn();
+ show({ ongeoconfirmed });
+
+ button('Choose a conflict').click();
+
+ expect(ongeoconfirmed).toHaveBeenCalledOnce();
+ expect(ticks()).toHaveLength(2);
+ });
+
it('hands it over untouched when the box was cleared', () => {
const onurl = vi.fn();
show({ onurl });
diff --git a/frontend/src/tools/satellite/AddLayerDialog.svelte b/frontend/src/tools/satellite/AddLayerDialog.svelte
index ce75213..aefce21 100644
--- a/frontend/src/tools/satellite/AddLayerDialog.svelte
+++ b/frontend/src/tools/satellite/AddLayerDialog.svelte
@@ -15,7 +15,7 @@
import Modal from '../../components/Modal.svelte';
import { ACCEPTS, looksLikeUrl } from '../../lib/map/addedLayers.js';
- let { busy = false, onclose, onfile, onurl } = $props();
+ let { busy = false, onclose, onfile, onurl, ongeoconfirmed } = $props();
let url = $state('');
let picker = $state(null);
@@ -93,10 +93,18 @@
for, when, and what it will not do on its own. -->
<p class="note">
A My Maps share link, or any KML or GeoJSON address. It is read now, when
- you press Refresh, and when this case opens — never on a timer, and never
- while the layer is off.
+ you press Refresh, and the first time you switch it on after opening
+ Azimut — never on a timer, and never while the layer is off.
</p>
</section>
+
+ <section>
+ <h4>GeoConfirmed</h4>
+ <button class="btn" disabled={busy} onclick={() => ongeoconfirmed?.()}>
+ Choose a conflict
+ </button>
+ <p class="note">Geolocated conflict events, by dates and area, in GeoConfirmed's icons.</p>
+ </section>
</Modal>
<style>
diff --git a/frontend/src/tools/satellite/AddedLayers.render.test.js b/frontend/src/tools/satellite/AddedLayers.render.test.js
index 349b952..00cb6a9 100644
--- a/frontend/src/tools/satellite/AddedLayers.render.test.js
+++ b/frontend/src/tools/satellite/AddedLayers.render.test.js
@@ -126,11 +126,13 @@ describe('a row', () => {
expect(byText('button', 'Refresh')).toBeTruthy();
});
- it('owns its layer the way a curated row does not: Remove and Reveal', () => {
+ it('owns its layer the way a curated row does not: it can be removed', () => {
show({ rows: [LAYER] });
expect(byText('button', 'Remove')).toBeTruthy();
- expect(byText('button', 'Reveal file')).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();
});
it('counts only what is being drawn in the section head', () => {
@@ -290,11 +292,10 @@ describe('finding a pin', () => {
});
describe('the acts', () => {
- it('reports the switch, the refresh, the reveal and the remove', () => {
+ it('reports the switch, the refresh and the remove', () => {
const handlers = {
ontoggle: vi.fn(),
onrefresh: vi.fn(),
- onreveal: vi.fn(),
onremove: vi.fn(),
onadd: vi.fn(),
};
@@ -302,7 +303,6 @@ describe('the acts', () => {
document.querySelector('.eye').click();
byText('button', 'Refresh').click();
- byText('button', 'Reveal file').click();
byText('button', 'Remove').click();
byText('button', 'Add a layer').click();
diff --git a/frontend/src/tools/satellite/AddedLayers.svelte b/frontend/src/tools/satellite/AddedLayers.svelte
index 3fd63bb..8a655ab 100644
--- a/frontend/src/tools/satellite/AddedLayers.svelte
+++ b/frontend/src/tools/satellite/AddedLayers.svelte
@@ -16,8 +16,8 @@
* worst thing this could do;
* - **its legend, which is the filter**, one row per category with its colour
* and its count, clicking one hides exactly those features;
- * - **Remove, Refresh and Reveal**, because the analyst owns this layer in a
- * way they do not own the borders overlay.
+ * - **Refresh and Remove**, because the analyst owns this layer in a way
+ * they do not own the borders overlay.
*
* Everything a row states is computed in `lib/map/addedLayers.js`, so the
* rules are read off a test rather than off a screen.
@@ -31,8 +31,10 @@
*/
import Icon from '../../components/Icon.svelte';
import SearchInput from '../../components/SearchInput.svelte';
+ import LayerTimeStrip from './LayerTimeStrip.svelte';
import {
countLabel,
+ followed,
freshness,
grouped,
legend,
@@ -52,9 +54,12 @@
oncategory,
onrefresh,
onremove,
- onreveal,
onpick,
onadd,
+ /** `(layer) => index | null`, the days its features carry (`layerDates.js`). */
+ dates,
+ /** `(layer, period, commit)`: the time strip moved, or was let go. */
+ onperiod,
} = $props();
const live = $derived(rows.filter((row) => row.enabled).length);
@@ -108,7 +113,7 @@
from is a way of getting there: this is the one thing on the row
that leaves the app, and it leaves on a click rather than on a
render. A file has no such address and stays plain text. -->
- {#if row.source?.kind === 'url' && row.source.url}
+ {#if followed(row) && row.source.url}
<a
class="from"
href={row.source.url}
@@ -127,6 +132,23 @@
one passing for the other. -->
<p class="meta counts">{countLabel(row)}</p>
+ <!-- Only on a layer being drawn, and only once its features are in hand
+ and turn out to be dated: a filter over marks nobody can see would
+ be a control with nothing to show for it. -->
+ {#if row.enabled}
+ {@const index = dates?.(row)}
+ {#if index}
+ <LayerTimeStrip
+ {index}
+ hidden={row.hidden}
+ period={row.period}
+ label={row.title}
+ oninput={(period) => onperiod?.(row, period, false)}
+ onchange={(period) => onperiod?.(row, period, true)}
+ />
+ {/if}
+ {/if}
+
{#if row.categories.length}
<button
type="button"
@@ -172,7 +194,11 @@
type="button"
class="cat"
class:off={hit.hidden}
- title={hit.hidden ? 'Show this group and go there' : 'Go to this pin'}
+ title={hit.outside
+ ? 'Show every date and go there'
+ : hit.hidden
+ ? 'Show this group and go there'
+ : 'Go to this pin'}
onclick={() => onpick?.(row, hit)}
>
<span class="swatch" style="--swatch: {hit.colour}"></span>
@@ -210,14 +236,13 @@
{/if}
<nav class="acts" aria-label={row.title}>
- {#if row.source?.kind === 'url'}
+ {#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={() => onreveal?.(row)}>Reveal file</button>
<button class="btn btn-sm quiet" onclick={() => onremove?.(row)}>Remove</button>
</nav>
</li>
diff --git a/frontend/src/tools/satellite/AddedLayersOverlay.svelte b/frontend/src/tools/satellite/AddedLayersOverlay.svelte
index 15710e1..04afc70 100644
--- a/frontend/src/tools/satellite/AddedLayersOverlay.svelte
+++ b/frontend/src/tools/satellite/AddedLayersOverlay.svelte
@@ -56,8 +56,8 @@
for (const row of layers) {
const existing = live.get(row.name);
if (existing && existing.sha === row.sha256) {
- // already drawn from these bytes: only the legend can have moved
- existing.layer.filter(row.hidden);
+ // already drawn from these bytes: only the legend or the period can have moved
+ existing.layer.filter(row.hidden, row.period);
continue;
}
if (existing) drop(row.name);
@@ -73,6 +73,7 @@
layer.set(collection, {
categories: row.categories,
hidden: row.hidden,
+ period: row.period,
attribution: attribution(row),
});
})
diff --git a/frontend/src/tools/satellite/GeoConfirmedDialog.render.test.js b/frontend/src/tools/satellite/GeoConfirmedDialog.render.test.js
new file mode 100644
index 0000000..cd40bc3
--- /dev/null
+++ b/frontend/src/tools/satellite/GeoConfirmedDialog.render.test.js
@@ -0,0 +1,134 @@
+// @vitest-environment happy-dom
+/**
+ * The GeoConfirmed dialog: one conflict, a window, and optionally the view.
+ *
+ * Opening it is the act that asks GeoConfirmed for anything, so what is asserted
+ * first is that the list is asked for once, here, and that a failure to reach it
+ * says so and can be tried again rather than leaving an empty menu.
+ */
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { flushSync, mount, tick, unmount } from 'svelte';
+import GeoConfirmedDialog from './GeoConfirmedDialog.svelte';
+
+const CONFLICTS = [
+ { conflict: 'World', name: 'World', start: '2023-01-01', end: '' },
+ { conflict: 'Ukraine', name: 'Ukraine', start: '2013-01-01', end: '' },
+ { conflict: 'Israel', name: 'Israel/Gaza/Lebanon', start: '2023-10-07', end: '' },
+];
+
+let held = null;
+
+async function show(props = {}) {
+ held = mount(GeoConfirmedDialog, {
+ target: document.body,
+ props: {
+ busy: false,
+ load: vi.fn(async () => CONFLICTS),
+ view: () => ({ west: 30, south: 44, east: 40, north: 52 }),
+ ...props,
+ },
+ });
+ await tick();
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ flushSync();
+ return document.body;
+}
+
+afterEach(() => {
+ if (held) unmount(held);
+ held = null;
+ document.body.innerHTML = '';
+});
+
+const button = (label) =>
+ [...document.body.querySelectorAll('button')].find(
+ (node) => node.textContent.trim() === label
+ );
+const select = () => document.body.querySelector('select');
+
+describe('the GeoConfirmed dialog', () => {
+ it('asks for the conflict list once, on opening, and opens on Ukraine', async () => {
+ const load = vi.fn(async () => CONFLICTS);
+ await show({ load });
+
+ expect(load).toHaveBeenCalledOnce();
+ expect([...select().options].map((option) => option.textContent)).toEqual([
+ 'World',
+ 'Ukraine',
+ 'Israel/Gaza/Lebanon',
+ ]);
+ expect(select().value).toBe('Ukraine');
+ });
+
+ it('adds the last thirty days of the whole conflict by default', async () => {
+ const onadd = vi.fn();
+ await show({ onadd });
+
+ button('Add').click();
+
+ expect(onadd).toHaveBeenCalledWith({ conflict: 'Ukraine', days: 30 });
+ });
+
+ it('sends the chosen window and the view when asked to keep to it', async () => {
+ const onadd = vi.fn();
+ await show({ onadd });
+
+ button('7 days').click();
+ const box = document.body.querySelector('input[type="checkbox"]');
+ box.checked = true;
+ box.dispatchEvent(new Event('change', { bubbles: true }));
+ flushSync();
+ button('Add').click();
+
+ expect(onadd).toHaveBeenCalledWith({ conflict: 'Ukraine', days: 7, area: [30, 44, 40, 52] });
+ });
+
+ it('asks for the whole history, and says it is read again only on Refresh', async () => {
+ const onadd = vi.fn();
+ await show({ onadd });
+
+ button('All history').click();
+ flushSync();
+
+ expect(document.body.textContent).not.toContain('switch it on');
+ button('Add').click();
+ expect(onadd).toHaveBeenCalledWith({ conflict: 'Ukraine', everything: true });
+ });
+
+ it('holds Add back on a range with no first day yet', async () => {
+ await show();
+
+ button('Dates…').click();
+ flushSync();
+
+ expect(button('Add').disabled).toBe(true);
+ });
+
+ it('says why a view across the antimeridian cannot be sent', async () => {
+ await show({ view: () => ({ west: 170, south: 0, east: -170, north: 10 }) });
+
+ const box = document.body.querySelector('input[type="checkbox"]');
+ box.checked = true;
+ box.dispatchEvent(new Event('change', { bubbles: true }));
+ flushSync();
+
+ expect(document.body.textContent).toContain('crosses the antimeridian');
+ expect(button('Add').disabled).toBe(true);
+ });
+
+ it('says GeoConfirmed could not be reached, and tries again on request', async () => {
+ const load = vi
+ .fn()
+ .mockRejectedValueOnce(new Error('could not reach that source: offline'))
+ .mockResolvedValueOnce(CONFLICTS);
+ await show({ load });
+
+ expect(document.body.textContent).toContain('could not reach that source');
+ button('Try again').click();
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ flushSync();
+
+ expect(load).toHaveBeenCalledTimes(2);
+ expect(select().value).toBe('Ukraine');
+ });
+});
diff --git a/frontend/src/tools/satellite/GeoConfirmedDialog.svelte b/frontend/src/tools/satellite/GeoConfirmedDialog.svelte
new file mode 100644
index 0000000..c874f19
--- /dev/null
+++ b/frontend/src/tools/satellite/GeoConfirmedDialog.svelte
@@ -0,0 +1,251 @@
+<script>
+ /**
+ * One GeoConfirmed conflict, over a window of days and optionally the view,
+ * added as a layer.
+ *
+ * Opening this is the act that asks GeoConfirmed anything: the conflict list is
+ * read now, through the backend, and not when the add dialog before it opened.
+ * The layer itself is fetched by the backend on Add (`engine/geoconfirmed.py`),
+ * in GeoConfirmed's own icons, which arrive inside the export.
+ */
+ import { onMount } from 'svelte';
+ import Modal from '../../components/Modal.svelte';
+ import DayPicker from '../../components/DayPicker.svelte';
+ import {
+ ALL,
+ DEFAULT_CONFLICT,
+ DEFAULT_SPAN,
+ RANGE,
+ WINDOWS,
+ areaOf,
+ layerRequest,
+ } from '../../lib/map/geoconfirmed.js';
+
+ let {
+ busy = false,
+ /** `() => Promise<conflict[]>`, the list GeoConfirmed publishes. */
+ load,
+ /** `() => bounds | null`, the map's view at the moment of asking. */
+ view,
+ onclose,
+ onadd,
+ } = $props();
+
+ let conflicts = $state([]);
+ let reading = $state(true);
+ let failed = $state('');
+
+ let conflict = $state('');
+ let span = $state(DEFAULT_SPAN);
+ let start = $state('');
+ let end = $state('');
+ let limited = $state(false);
+
+ const today = new Date().toISOString().slice(0, 10);
+ const chosen = $derived(conflicts.find((entry) => entry.conflict === conflict));
+
+ async function fetchList() {
+ reading = true;
+ failed = '';
+ try {
+ const list = await load();
+ conflicts = Array.isArray(list) ? list : [];
+ const preferred = conflicts.find((entry) => entry.conflict === DEFAULT_CONFLICT);
+ if (!conflicts.some((entry) => entry.conflict === conflict)) {
+ conflict = (preferred ?? conflicts[0])?.conflict ?? '';
+ }
+ } catch (error) {
+ failed = error?.message || 'GeoConfirmed could not be reached.';
+ } finally {
+ reading = false;
+ }
+ }
+
+ onMount(fetchList);
+
+ const viewable = $derived(limited ? areaOf(view?.()) !== null : true);
+
+ function submit() {
+ const body = layerRequest({
+ conflict,
+ span,
+ start,
+ end,
+ limited,
+ bounds: limited ? view?.() : null,
+ });
+ if (body) onadd?.(body);
+ }
+
+ const ready = $derived(
+ Boolean(conflict) && (span !== RANGE || Boolean(start)) && viewable && !busy
+ );
+</script>
+
+<Modal title="GeoConfirmed" {onclose} width="460px">
+ <p class="lead">
+ Events GeoConfirmed's volunteers geolocated, each with its sources. They are
+ drawn and filtered here; nothing joins the case.
+ </p>
+
+ {#if reading}
+ <p class="note">Reading GeoConfirmed's conflicts…</p>
+ {:else if failed}
+ <p class="note error">{failed}</p>
+ <button class="btn" onclick={fetchList}>Try again</button>
+ {:else}
+ <section>
+ <h4>Conflict</h4>
+ <select class="input" bind:value={conflict} aria-label="Conflict">
+ {#each conflicts as entry (entry.conflict)}
+ <option value={entry.conflict}>{entry.name}</option>
+ {/each}
+ </select>
+ </section>
+
+ <section>
+ <h4>Dates</h4>
+ <div class="chips">
+ {#each WINDOWS as entry (entry.span)}
+ <button
+ type="button"
+ class="chip"
+ class:on={span === entry.span}
+ aria-pressed={span === entry.span}
+ onclick={() => (span = entry.span)}
+ >{entry.label}</button>
+ {/each}
+ <button
+ type="button"
+ class="chip"
+ class:on={span === RANGE}
+ aria-pressed={span === RANGE}
+ onclick={() => (span = RANGE)}
+ >Dates…</button>
+ </div>
+ {#if span === RANGE}
+ <div class="range">
+ <div class="date">
+ <span>From</span>
+ <DayPicker
+ value={start}
+ min={chosen?.start || ''}
+ max={end || today}
+ label="First day"
+ placeholder="Pick a day"
+ onpick={(day) => (start = day)}
+ />
+ </div>
+ <div class="date">
+ <span>To</span>
+ <DayPicker
+ value={end}
+ min={start}
+ max={today}
+ label="Last day; blank reads up to the day of each refresh"
+ placeholder="Today"
+ clearable
+ onpick={(day) => (end = day)}
+ />
+ </div>
+ </div>
+ {/if}
+ </section>
+
+ <section>
+ <label class="tick">
+ <input type="checkbox" bind:checked={limited} />
+ <span>Only the area in view</span>
+ </label>
+ {#if limited && !viewable}
+ <p class="note error">This view crosses the antimeridian; zoom in first.</p>
+ {/if}
+ </section>
+
+ <button class="btn btn-primary" disabled={!ready} onclick={submit}>
+ {busy ? 'Reading…' : 'Add'}
+ </button>
+ <p class="note">
+ {span === ALL
+ ? 'Read from geoconfirmed.org now and when you press Refresh.'
+ : 'Read from geoconfirmed.org now, when you press Refresh, and the first time you switch it on after opening Azimut.'}
+ Undated sites start hidden.
+ </p>
+ {/if}
+</Modal>
+
+<style>
+ .lead {
+ margin: 0 0 14px;
+ color: var(--text-2);
+ font-size: var(--fs-sm);
+ }
+ section {
+ margin-bottom: 12px;
+ }
+ h4 {
+ margin: 0 0 8px;
+ color: var(--text-1);
+ font-size: var(--fs-sm);
+ }
+ .input {
+ width: 100%;
+ }
+ .chips {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 4px;
+ }
+ .chip {
+ padding: 4px 9px;
+ 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;
+ }
+ .chip:hover {
+ border-color: var(--border-strong);
+ color: var(--text-1);
+ }
+ .chip.on {
+ border-color: var(--accent);
+ background: var(--accent-soft);
+ color: var(--accent);
+ }
+ .range {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ margin-top: 8px;
+ }
+ .date {
+ display: flex;
+ align-items: flex-start;
+ gap: 8px;
+ color: var(--text-3);
+ font-size: var(--fs-xs);
+ }
+ .date > span {
+ flex: none;
+ width: 36px;
+ padding-top: 6px;
+ }
+ .tick {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ color: var(--text-2);
+ font-size: var(--fs-xs);
+ cursor: pointer;
+ }
+ .note {
+ margin: 8px 0 0;
+ color: var(--text-3);
+ font-size: var(--fs-xs);
+ }
+ .note.error {
+ color: var(--warn, #ffcc66);
+ }
+</style>
diff --git a/frontend/src/tools/satellite/LayerTimeStrip.render.test.js b/frontend/src/tools/satellite/LayerTimeStrip.render.test.js
new file mode 100644
index 0000000..b3a9e2c
--- /dev/null
+++ b/frontend/src/tools/satellite/LayerTimeStrip.render.test.js
@@ -0,0 +1,116 @@
+// @vitest-environment happy-dom
+/**
+ * The time strip on an added layer's row. The drags themselves need a laid-out
+ * page to measure against, which happy-dom does not lay out; what is asserted
+ * here is everything that does not: what the strip says, and what each of its
+ * other ways in hands back.
+ */
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { flushSync, mount, unmount } from 'svelte';
+import LayerTimeStrip from './LayerTimeStrip.svelte';
+import { indexDates } from '../../lib/map/layerDates.js';
+
+const at = (date, category = 'Russia') => ({ properties: { category, date } });
+const INDEX = indexDates({
+ features: [at('2026-09-01'), at('2026-09-01'), at('2026-09-10', 'Ukraine'), at('2026-09-18')],
+});
+
+let held = null;
+
+function show(props = {}) {
+ held = mount(LayerTimeStrip, {
+ target: document.body,
+ props: { index: INDEX, label: 'GeoConfirmed', ...props },
+ });
+ flushSync();
+}
+
+afterEach(() => {
+ if (held) unmount(held);
+ held = null;
+ document.body.innerHTML = '';
+});
+
+const bars = () => [...document.body.querySelectorAll('rect')];
+const button = (text) =>
+ [...document.body.querySelectorAll('button')].find((node) => node.textContent.trim() === text);
+const handles = () => [...document.body.querySelectorAll('[role="slider"]')];
+
+describe('the time strip', () => {
+ it('draws a bar a day across a short layer, and says what it spans', () => {
+ show();
+
+ expect(bars()).toHaveLength(18);
+ expect(button('1 Sep 2026')).toBeTruthy();
+ expect(button('18 Sep 2026')).toBeTruthy();
+ });
+
+ it('offers no way to clear a period nobody set', () => {
+ show();
+
+ expect(document.body.querySelector('[aria-label="Show every date"]')).toBeNull();
+ });
+
+ it('says the period that is kept, and clears it in one press', () => {
+ const onchange = vi.fn();
+ show({ period: { start: '2026-09-05', end: '2026-09-12' }, onchange });
+
+ expect(button('5 Sep 2026')).toBeTruthy();
+ expect(button('12 Sep 2026')).toBeTruthy();
+ document.body.querySelector('[aria-label="Show every date"]').click();
+
+ expect(onchange).toHaveBeenCalledWith(null);
+ });
+
+ it('moves a bound a day with the arrow keys', () => {
+ const onchange = vi.fn();
+ show({ period: { start: '2026-09-05', end: '2026-09-12' }, onchange });
+
+ handles()[1].dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowRight', bubbles: true }));
+
+ expect(onchange).toHaveBeenCalledWith({ start: '2026-09-05', end: '2026-09-13' });
+ });
+
+ it('leaves a bound pushed to the layer’s own edge open', () => {
+ const onchange = vi.fn();
+ show({ period: { start: '2026-09-05', end: '2026-09-12' }, onchange });
+
+ handles()[1].dispatchEvent(new KeyboardEvent('keydown', { key: 'End', bubbles: true }));
+
+ expect(onchange).toHaveBeenCalledWith({ start: '2026-09-05', end: '' });
+ });
+
+ it('opens a calendar on a date, bounded by the layer’s own days', () => {
+ const onchange = vi.fn();
+ show({ onchange });
+
+ button('1 Sep 2026').click();
+ flushSync();
+
+ expect(document.body.querySelector('[aria-label="First day calendar"]')).toBeTruthy();
+ const day = [...document.body.querySelectorAll('button')].find(
+ (node) => node.textContent.trim() === '10' && !node.disabled
+ );
+ day.click();
+ flushSync();
+
+ expect(onchange).toHaveBeenCalledWith({ start: '2026-09-10', end: '' });
+ expect(document.body.querySelector('[aria-label="First day calendar"]')).toBeNull();
+ });
+
+ it('lets every date back in on a double click', () => {
+ const onchange = vi.fn();
+ show({ period: { start: '2026-09-05', end: '' }, onchange });
+
+ document.body.querySelector('.track').dispatchEvent(new MouseEvent('dblclick', { bubbles: true }));
+
+ expect(onchange).toHaveBeenCalledWith(null);
+ });
+
+ it('leaves the bars of a hidden group out', () => {
+ show({ hidden: ['Russia'] });
+
+ const tall = bars().filter((rect) => Number(rect.getAttribute('height')) > 0);
+ expect(tall).toHaveLength(1); // only Ukraine's day
+ });
+});
diff --git a/frontend/src/tools/satellite/LayerTimeStrip.svelte b/frontend/src/tools/satellite/LayerTimeStrip.svelte
new file mode 100644
index 0000000..b71d982
--- /dev/null
+++ b/frontend/src/tools/satellite/LayerTimeStrip.svelte
@@ -0,0 +1,365 @@
+<script>
+ /**
+ * An added layer's time filter: its events over time as a strip of bars, and
+ * the period kept, in two lines of the row.
+ *
+ * Everything is done on the strip itself, so it needs no room of its own:
+ *
+ * - **a handle** at each end of the period, dragged, or moved a day at a time
+ * with the arrow keys (a week with Page Up and Page Down);
+ * - **the band** between them, dragged to slide the period along whole;
+ * - **the bars**: dragged across to draw a new period, clicked to keep one
+ * bar's day, week or month; a double click lets everything back in;
+ * - **the two dates** under it, each opening a calendar for the exact day.
+ *
+ * The period is shown on the map while it is dragged (`oninput`) and kept on
+ * the layer when the pointer lets go (`onchange`). A bound left on the layer's
+ * own first or last day stays open (`periodFrom`), so a followed layer's new
+ * events are not filtered out by a period nobody narrowed.
+ */
+ import Icon from '../../components/Icon.svelte';
+ import MonthGrid from '../../components/MonthGrid.svelte';
+ import {
+ active,
+ bars,
+ dayLabel,
+ dayNumber,
+ histogram,
+ isoDay,
+ periodFrom,
+ span,
+ } from '../../lib/map/layerDates.js';
+
+ let {
+ /** `indexDates` of the layer's features. */
+ index,
+ /** Groups the legend switched off, which the bars leave out. */
+ hidden = [],
+ /** `{ start, end }`, or null for every date. */
+ period = null,
+ /** Names the strip for a reader that cannot see the row. */
+ label = 'Dates',
+ oninput,
+ onchange,
+ } = $props();
+
+ const first = $derived(index.first);
+ const last = $derived(index.last);
+ const days = $derived(last - first + 1);
+ const edges = $derived(bars(first, last));
+ const counts = $derived(histogram(index, hidden, edges));
+ const peak = $derived(Math.max(1, ...counts));
+
+ /** The period while a pointer is moving it, ahead of what the row holds. */
+ let draft = $state(null);
+ const kept = $derived.by(() => {
+ const { from, to } = span(period, index);
+ return { from: Math.max(first, from), to: Math.min(last, to) };
+ });
+ const shown = $derived(draft ?? kept);
+ const on = $derived(draft ? true : active(period));
+
+ let track = $state(null);
+ /** Which date's calendar is open: 'start', 'end' or ''. */
+ let picking = $state('');
+
+ const place = (day) => ((day - first) / days) * 100;
+
+ function dayAt(clientX) {
+ const box = track.getBoundingClientRect();
+ const share = (clientX - box.left) / Math.max(1, box.width);
+ return first + Math.min(days - 1, Math.max(0, Math.floor(share * days)));
+ }
+
+ /** One frame's worth of map updates, however fast the pointer moves. */
+ let frame = 0;
+ function preview(from, to) {
+ draft = { from: Math.min(from, to), to: Math.max(from, to) };
+ if (frame) return;
+ frame = requestAnimationFrame(() => {
+ frame = 0;
+ if (draft) oninput?.(periodFrom(draft.from, draft.to, index));
+ });
+ }
+
+ function commit(from, to) {
+ draft = null;
+ onchange?.(periodFrom(from, to, index));
+ }
+
+ /**
+ * A drag, whichever part of the strip it started on. `move` turns the day
+ * under the pointer into the period so far; a press that never moved is a
+ * click, answered by `click` when one is given.
+ */
+ function drag(event, move, click) {
+ event.preventDefault();
+ event.stopPropagation();
+ const target = event.currentTarget;
+ target.setPointerCapture?.(event.pointerId);
+ const startX = event.clientX;
+ let moved = false;
+ const onmove = (next) => {
+ if (!moved && Math.abs(next.clientX - startX) < 3) return;
+ moved = true;
+ const [from, to] = move(dayAt(next.clientX));
+ preview(from, to);
+ };
+ const onup = (next) => {
+ target.removeEventListener('pointermove', onmove);
+ target.removeEventListener('pointerup', onup);
+ target.removeEventListener('pointercancel', onup);
+ if (moved && draft) commit(draft.from, draft.to);
+ else {
+ draft = null;
+ click?.(dayAt(next.clientX));
+ }
+ };
+ target.addEventListener('pointermove', onmove);
+ target.addEventListener('pointerup', onup);
+ target.addEventListener('pointercancel', onup);
+ }
+
+ function grabHandle(event, which) {
+ const { from, to } = shown;
+ drag(event, (day) => (which === 'start' ? [day, to] : [from, day]));
+ }
+
+ function grabBand(event) {
+ const { from, to } = shown;
+ const width = to - from;
+ const anchor = dayAt(event.clientX);
+ drag(event, (day) => {
+ const start = Math.min(last - width, Math.max(first, from + day - anchor));
+ return [start, start + width];
+ });
+ }
+
+ function grabTrack(event) {
+ const anchor = dayAt(event.clientX);
+ drag(
+ event,
+ (day) => [anchor, day],
+ (day) => {
+ const bar = edges.find((edge) => day >= edge.from && day <= edge.to);
+ if (bar) commit(bar.from, bar.to);
+ }
+ );
+ }
+
+ function nudge(event, which) {
+ const step = { ArrowLeft: -1, ArrowRight: 1, PageDown: -7, PageUp: 7 }[event.key];
+ const edge = { Home: first, End: last }[event.key];
+ if (step === undefined && edge === undefined) return;
+ event.preventDefault();
+ const { from, to } = kept;
+ const clamp = (day) => Math.min(last, Math.max(first, day));
+ if (which === 'start') commit(clamp(edge ?? from + step), to);
+ else commit(from, clamp(edge ?? to + step));
+ }
+
+ function pick(which, iso) {
+ picking = '';
+ const day = dayNumber(iso);
+ if (day === null) return;
+ if (which === 'start') commit(day, Math.max(day, kept.to));
+ else commit(Math.min(day, kept.from), day);
+ }
+</script>
+
+<div class="strip" class:on>
+ <!-- svelte-ignore a11y_no_static_element_interactions -->
+ <div
+ class="track"
+ bind:this={track}
+ onpointerdown={grabTrack}
+ ondblclick={() => onchange?.(null)}
+ title="Drag across the bars to pick dates"
+ >
+ <svg viewBox="0 0 {days} 1" preserveAspectRatio="none" aria-hidden="true">
+ {#each edges as edge, i (edge.from)}
+ {@const height = counts[i] ? Math.max(0.1, counts[i] / peak) : 0}
+ <rect
+ class:inside={edge.to >= shown.from && edge.from <= shown.to}
+ x={edge.from - first + (edge.to - edge.from + 1) * 0.1}
+ y={1 - height}
+ width={(edge.to - edge.from + 1) * 0.8}
+ {height}
+ />
+ {/each}
+ </svg>
+ <!-- svelte-ignore a11y_no_static_element_interactions -->
+ <div
+ class="band"
+ style:left="{place(shown.from)}%"
+ style:width="{place(shown.to + 1) - place(shown.from)}%"
+ onpointerdown={grabBand}
+ ></div>
+ {#each ['start', 'end'] as which (which)}
+ {@const day = which === 'start' ? shown.from : shown.to + 1}
+ <div
+ class="handle"
+ style:left="{place(day)}%"
+ role="slider"
+ tabindex="0"
+ aria-label={which === 'start' ? `${label}: first day` : `${label}: last day`}
+ aria-valuemin={first}
+ aria-valuemax={last}
+ aria-valuenow={which === 'start' ? shown.from : shown.to}
+ aria-valuetext={dayLabel(isoDay(which === 'start' ? shown.from : shown.to))}
+ onpointerdown={(event) => grabHandle(event, which)}
+ onkeydown={(event) => nudge(event, which)}
+ ></div>
+ {/each}
+ </div>
+
+ <div class="dates">
+ <button
+ type="button"
+ class="day"
+ class:open={picking === 'start'}
+ title="Pick the first day"
+ onclick={() => (picking = picking === 'start' ? '' : 'start')}
+ >{dayLabel(isoDay(shown.from))}</button>
+ <span class="dash">–</span>
+ <button
+ type="button"
+ class="day"
+ class:open={picking === 'end'}
+ title="Pick the last day"
+ onclick={() => (picking = picking === 'end' ? '' : 'end')}
+ >{dayLabel(isoDay(shown.to))}</button>
+ {#if on}
+ <button
+ type="button"
+ class="clear"
+ title="Show every date"
+ aria-label="Show every date"
+ onclick={() => {
+ picking = '';
+ onchange?.(null);
+ }}
+ ><Icon name="x" size={10} /></button>
+ {/if}
+ </div>
+
+ {#if picking}
+ <MonthGrid
+ value={isoDay(picking === 'start' ? kept.from : kept.to)}
+ min={isoDay(first)}
+ max={isoDay(last)}
+ label={picking === 'start' ? 'First day' : 'Last day'}
+ onpick={(iso) => pick(picking, iso)}
+ />
+ {/if}
+</div>
+
+<style>
+ .strip {
+ padding: 4px 4px 0 30px;
+ }
+ .track {
+ position: relative;
+ height: 22px;
+ cursor: crosshair;
+ touch-action: none;
+ user-select: none;
+ }
+ svg {
+ display: block;
+ width: 100%;
+ height: 100%;
+ }
+ rect {
+ fill: var(--text-3);
+ opacity: 0.35;
+ }
+ .on rect.inside,
+ rect.inside {
+ fill: var(--accent);
+ opacity: 0.85;
+ }
+ .strip:not(.on) rect.inside {
+ fill: var(--text-2);
+ opacity: 0.6;
+ }
+ /* Only a period can be slid: with none set the band spans everything, and it
+ must not swallow the drag that draws the first one. */
+ .band {
+ position: absolute;
+ top: 0;
+ bottom: 0;
+ border-radius: 2px;
+ pointer-events: none;
+ }
+ .on .band {
+ background: var(--accent-soft);
+ pointer-events: auto;
+ cursor: grab;
+ }
+ .handle {
+ position: absolute;
+ top: -2px;
+ bottom: -2px;
+ width: 9px;
+ margin-left: -4px;
+ cursor: ew-resize;
+ }
+ /* The grip is drawn inside a wider hit area, so it is easy to catch and thin
+ to look at. */
+ .handle::after {
+ content: '';
+ position: absolute;
+ top: 0;
+ bottom: 0;
+ left: 3px;
+ width: 3px;
+ border-radius: 2px;
+ background: var(--text-3);
+ }
+ .on .handle::after,
+ .handle:hover::after,
+ .handle:focus-visible::after {
+ background: var(--accent);
+ }
+ .handle:focus-visible {
+ outline: none;
+ }
+ .dates {
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ margin-top: 2px;
+ font-size: 10px;
+ font-variant-numeric: tabular-nums;
+ color: var(--text-3);
+ }
+ .day {
+ padding: 0 2px;
+ border-radius: var(--r-sm);
+ color: inherit;
+ cursor: pointer;
+ }
+ .day:hover,
+ .day.open {
+ color: var(--text-1);
+ background: var(--bg-3);
+ }
+ .on .day {
+ color: var(--accent);
+ }
+ .clear {
+ display: grid;
+ place-items: center;
+ width: 16px;
+ height: 16px;
+ margin-left: auto;
+ border-radius: var(--r-sm);
+ color: var(--text-3);
+ cursor: pointer;
+ }
+ .clear:hover {
+ color: var(--text-1);
+ background: var(--bg-3);
+ }
+</style>
diff --git a/frontend/src/tools/satellite/MapContextMenu.svelte b/frontend/src/tools/satellite/MapContextMenu.svelte
index 360fc97..3e431aa 100644
--- a/frontend/src/tools/satellite/MapContextMenu.svelte
+++ b/frontend/src/tools/satellite/MapContextMenu.svelte
@@ -32,19 +32,23 @@
lookup = null,
/** The acts offered, in `ACTIONS` order; a tool passes the subset it has. */
actions = ACTIONS,
- /** `(id, value)`: `copy` with the text, or an action id from `ACTIONS`. */
+ /** Archives this point can be compared across; none hides the row. */
+ compareSources = [],
+ /** `(id, value)`: `copy` with the text, `compare` with a source id, or an
+ * action id from `ACTIONS`. */
onpick,
onclose,
} = $props();
let menuEl = $state();
let subEl = $state();
- let openRowEl = $state();
+ /** The row each submenu hangs from, by submenu id. */
+ let subRowEl = $state({});
let width = $state(0);
let height = $state(0);
let subWidth = $state(0);
let subHeight = $state(0);
- let linksOpen = $state(false);
+ let openSub = $state(null); // 'compare' | 'links' | null
const copies = $derived(copyRows(at.lat, at.lon, format));
const links = $derived(openRows(at.lat, at.lon, zoom));
@@ -75,13 +79,13 @@
* — one outside-click, one arrow walk, one keyboard handler across both.
*/
const sub = $derived(
- linksOpen
+ openSub
? placeSubmenu(
{
left: place.left,
top: place.top,
width: width || 236,
- rowTop: place.top + (openRowEl?.offsetTop ?? 0),
+ rowTop: place.top + (subRowEl[openSub]?.offsetTop ?? 0),
},
{ width: subWidth || 168, height: subHeight || 300 },
frame
@@ -94,35 +98,37 @@
return [...rows(menuEl), ...rows(subEl)];
}
- /** Open the external maps and step into them, as a submenu does. */
- async function openLinks() {
- linksOpen = true;
+ /** Open one submenu and step into it. */
+ async function openFlyout(id) {
+ openSub = id;
await tick();
subEl?.querySelector('[role="menuitem"]')?.focus();
}
- function closeLinks() {
- linksOpen = false;
- openRowEl?.focus();
+ function closeFlyout() {
+ const row = subRowEl[openSub];
+ openSub = null;
+ row?.focus();
}
function onkeydown(event) {
const inSub = Boolean(subEl?.contains(document.activeElement));
- if (event.key === 'ArrowRight' && document.activeElement === openRowEl) {
+ const onRow = Object.entries(subRowEl).find(([, element]) => element === document.activeElement);
+ if (event.key === 'ArrowRight' && onRow) {
event.preventDefault();
- openLinks();
+ openFlyout(onRow[0]);
return;
}
if (event.key === 'ArrowLeft' && inSub) {
event.preventDefault();
- closeLinks();
+ closeFlyout();
return;
}
- if (event.key === 'Escape' && linksOpen) {
+ if (event.key === 'Escape' && openSub) {
// the submenu is what Escape leaves first, as it is everywhere else
event.preventDefault();
event.stopPropagation();
- closeLinks();
+ closeFlyout();
return;
}
const rows = items();
@@ -201,14 +207,30 @@
<!-- A submenu, not a fold: the list opens beside the menu so the menu itself
never changes size, and nothing the cursor is resting on moves. -->
+ {#if compareSources.length}
+ <button
+ bind:this={subRowEl.compare}
+ class="item"
+ class:open={openSub === 'compare'}
+ role="menuitem"
+ aria-haspopup="menu"
+ aria-expanded={openSub === 'compare'}
+ onclick={() => (openSub === 'compare' ? closeFlyout() : openFlyout('compare'))}
+ >
+ <Icon name="compare" size={13} />
+ <span>Compare here…</span>
+ <Icon name="chevronRight" size={12} />
+ </button>
+ {/if}
+
<button
- bind:this={openRowEl}
+ bind:this={subRowEl.links}
class="item"
- class:open={linksOpen}
+ class:open={openSub === 'links'}
role="menuitem"
aria-haspopup="menu"
- aria-expanded={linksOpen}
- onclick={() => (linksOpen ? closeLinks() : openLinks())}
+ aria-expanded={openSub === 'links'}
+ onclick={() => (openSub === 'links' ? closeFlyout() : openFlyout('links'))}
>
<Icon name="external" size={13} />
<span>Open in…</span>
@@ -224,28 +246,49 @@
class="ctx card sub"
role="menu"
tabindex="-1"
- aria-label="Open this point in"
+ aria-label={openSub === 'compare' ? 'Compare this point across' : 'Open this point in'}
style:left={`${sub.left}px`}
style:top={`${sub.top}px`}
{onkeydown}
oncontextmenu={(event) => event.preventDefault()}
>
- {#each links as link (link.id)}
- <a
- class="item link"
- role="menuitem"
- href={fullscreen ? undefined : link.url}
- target="_blank"
- rel="noreferrer"
- aria-disabled={fullscreen}
- title={fullscreen ? 'Exit fullscreen first. This leaves the map' : link.url}
- onclick={() => !fullscreen && onclose()}
- >{link.label}</a>
- {/each}
+ {#if openSub === 'compare'}
+ <!-- Each row is a request: the archive is asked which two pictures of
+ this point are the last two, and only then does Compare open. -->
+ {#each compareSources as source (source.id)}
+ <button class="item pair" role="menuitem" onclick={() => onpick('compare', source.id)}>
+ <span>{source.label}</span>
+ <small>{source.detail}</small>
+ </button>
+ {/each}
+ {:else}
+ {#each links as link (link.id)}
+ <a
+ class="item link"
+ role="menuitem"
+ href={fullscreen ? undefined : link.url}
+ target="_blank"
+ rel="noreferrer"
+ aria-disabled={fullscreen}
+ title={fullscreen ? 'Exit fullscreen first. This leaves the map' : link.url}
+ onclick={() => !fullscreen && onclose()}
+ >{link.label}</a>
+ {/each}
+ {/if}
</div>
{/if}
<style>
+ /* Two lines: what the archive is, and what it will be asked for. */
+ .item.pair {
+ display: grid;
+ gap: 1px;
+ text-align: left;
+ }
+ .item.pair small {
+ color: var(--text-3);
+ font-size: var(--fs-xs);
+ }
.ctx {
position: absolute;
z-index: 800;
diff --git a/frontend/src/tools/satellite/MapContextMenu.test.js b/frontend/src/tools/satellite/MapContextMenu.test.js
index 97c0f52..4f4a318 100644
--- a/frontend/src/tools/satellite/MapContextMenu.test.js
+++ b/frontend/src/tools/satellite/MapContextMenu.test.js
@@ -58,6 +58,19 @@ describe('the right-click menu', () => {
expect(body).not.toContain('chevronDown');
});
+ it('offers a pair only where an archive can build one', () => {
+ const sources = [
+ { id: 'wayback', label: 'Esri Wayback', detail: 'the last two pictures of this point' },
+ { id: 'sentinel', label: 'Copernicus', detail: 'the last two passes over this point', provider: 'sentinel2' },
+ ];
+ expect(render(MapContextMenu, { props: props() }).body).not.toContain('Compare here…');
+ const { body } = render(MapContextMenu, { props: props({ compareSources: sources }) });
+ expect(body).toContain('Compare here…');
+ // folded like the links, for the same reason: the menu cannot change size
+ expect(body).not.toContain('Esri Wayback');
+ expect(body.match(/aria-haspopup="menu"/g)).toHaveLength(2);
+ });
+
it('states the lookup where it was asked, while it runs and once it answered', () => {
expect(
render(MapContextMenu, { props: props({ lookup: { busy: true } }) }).body
diff --git a/frontend/src/tools/satellite/MapLayers.render.test.js b/frontend/src/tools/satellite/MapLayers.render.test.js
new file mode 100644
index 0000000..1e2f70a
--- /dev/null
+++ b/frontend/src/tools/satellite/MapLayers.render.test.js
@@ -0,0 +1,26 @@
+import { describe, expect, it } from 'vitest';
+import { render } from 'svelte/server';
+import MapLayers from './MapLayers.svelte';
+
+describe('a layer that cannot be switched on', () => {
+ const rows = [
+ {
+ id: 'firms',
+ label: 'Active fires',
+ on: false,
+ disabled: true,
+ detail: 'needs a free key',
+ title: 'Add a NASA FIRMS key in Settings → Imagery',
+ toggle: () => {},
+ actions: [{ label: 'Add a FIRMS key', quiet: true, run: () => {} }],
+ },
+ ];
+
+ it('says why on the row, and carries the reason on its name', () => {
+ const { body } = render(MapLayers, { props: { rows } });
+ expect(body).toContain('needs a free key');
+ expect(body).toContain('Add a FIRMS key');
+ // the reason is on the name too, not only on the greyed switch
+ expect(body).toMatch(/class="name[^"]*"[^>]*title="Add a NASA FIRMS key in Settings → Imagery"/);
+ });
+});
diff --git a/frontend/src/tools/satellite/MapLayers.svelte b/frontend/src/tools/satellite/MapLayers.svelte
index d3a59a6..f5784ed 100644
--- a/frontend/src/tools/satellite/MapLayers.svelte
+++ b/frontend/src/tools/satellite/MapLayers.svelte
@@ -54,7 +54,8 @@
>
<Icon name="eye" size={13} />
</button>
- <span class="name" class:off={!row.on || row.disabled}>{row.label}</span>
+ <!-- the name repeats the tooltip, so the reason a switch is greyed is on a word, not only on its icon -->
+ <span class="name" class:off={!row.on || row.disabled} title={row.title ?? row.label}>{row.label}</span>
{#if row.detail}<span class="detail">{row.detail}</span>{/if}
</div>
<!-- A layer that is a question answers it here, under its own switch:
diff --git a/frontend/src/tools/satellite/SentinelPicker.svelte b/frontend/src/tools/satellite/SentinelPicker.svelte
index 2385fff..1ed820f 100644
--- a/frontend/src/tools/satellite/SentinelPicker.svelte
+++ b/frontend/src/tools/satellite/SentinelPicker.svelte
@@ -108,11 +108,11 @@
<div class="cal">
<div class="cal-head">
- <button class="cal-nav" onclick={() => s2.stepMonth(-1)} aria-label="Previous month">
+ <button class="cal-nav" onclick={() => s2.stepMonth(-1)} aria-label="Previous month" title="Previous month">
<Icon name="chevronLeft" size={13} />
</button>
<span class="cal-month">{monthLabel(s2.month)}</span>
- <button class="cal-nav" onclick={() => s2.stepMonth(1)} aria-label="Next month">
+ <button class="cal-nav" onclick={() => s2.stepMonth(1)} aria-label="Next month" title="Next month">
<Icon name="chevronRight" size={13} />
</button>
</div>
diff --git a/frontend/src/tools/satellite/TemporalMapOverlay.svelte b/frontend/src/tools/satellite/TemporalMapOverlay.svelte
index 15e1405..804d26f 100644
--- a/frontend/src/tools/satellite/TemporalMapOverlay.svelte
+++ b/frontend/src/tools/satellite/TemporalMapOverlay.svelte
@@ -90,7 +90,7 @@
title:
mark.items.length === 1
? mark.items[0].label
- : `${mark.items.length} statements at ${mark.label}`,
+ : `${mark.items.length} claims at ${mark.label}`,
popup: {
content: () => card(mark),
className: 'temporal-popup',
diff --git a/frontend/src/tools/satellite/WaybackPicker.svelte b/frontend/src/tools/satellite/WaybackPicker.svelte
index ffc4d10..566bfd8 100644
--- a/frontend/src/tools/satellite/WaybackPicker.svelte
+++ b/frontend/src/tools/satellite/WaybackPicker.svelte
@@ -27,16 +27,22 @@
</script>
<div class="wb-wrap" bind:this={menuEl}>
+ <!-- The wait is on the chip, not only inside the menu: reading a point's
+ history is a walk through Esri's tiles that takes seconds, it runs with
+ the picker shut once it is following the map, and a basemap that answers
+ nothing for that long without saying so reads as a broken one. -->
<button
class="chip"
class:on={wb.menuOpen}
onclick={() => wb.toggleMenu()}
- title="Wayback release"
+ title={wb.busy ? 'Reading Esri’s releases for this point…' : 'Wayback release'}
aria-label="Wayback release"
aria-expanded={wb.menuOpen}
+ aria-busy={wb.busy}
>
<Icon name="clock" size={13} />
- <span class="mono">{wb.date || 'Newest'}</span>
+ <span class="mono">{wb.date || (wb.busy ? 'Reading…' : 'Newest')}</span>
+ {#if wb.busy}<span class="spinner" aria-hidden="true"></span>{/if}
</button>
{#if wb.menuOpen}
@@ -44,7 +50,9 @@
{#if wb.listNote}
<div class="menu-hint warn">{wb.listNote}</div>
{:else if !wb.releases.length}
- <div class="menu-hint dim">Reading the release list…</div>
+ <div class="menu-hint dim waiting">
+ <span class="spinner" aria-hidden="true"></span> Reading the release list…
+ </div>
{:else}
{#if !wb.reading}
<div class="step-row">
@@ -98,7 +106,10 @@
{#if wb.changesOnly}
{#if wb.changesBusy}
- <div class="menu-hint dim">Reading this point's history…</div>
+ <div class="menu-hint dim waiting">
+ <span class="spinner" aria-hidden="true"></span>
+ Reading this point's history…
+ </div>
{:else if wb.changesNote}
<div class="menu-hint warn">{wb.changesNote}</div>
{:else if wb.stale}
@@ -163,6 +174,17 @@
.chip.on {
color: var(--accent);
}
+ .spinner {
+ width: 11px;
+ height: 11px;
+ border: 2px solid currentColor;
+ border-top-color: transparent;
+ border-radius: 50%;
+ animation: spin 0.7s linear infinite;
+ }
+ @keyframes spin {
+ to { transform: rotate(360deg); }
+ }
/* down and left of the chip, like the Sentinel-2 picker beside it: the
surface's own corner clips anything opening upwards */
.wb-menu {
@@ -272,6 +294,11 @@
.menu-hint.dim {
opacity: 0.8;
}
+ .menu-hint.waiting {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ }
.menu-hint .warn,
.menu-hint.warn {
color: var(--warn, #e2a03f);
diff --git a/frontend/src/tools/satellite/WaybackPicker.test.js b/frontend/src/tools/satellite/WaybackPicker.test.js
index 8a5aa0a..346388b 100644
--- a/frontend/src/tools/satellite/WaybackPicker.test.js
+++ b/frontend/src/tools/satellite/WaybackPicker.test.js
@@ -20,6 +20,7 @@ function props(wb = {}) {
changesOnly: true,
changes: [64776, 10],
changesBusy: false,
+ busy: false,
changesNote: '',
stale: false,
reading: false,
@@ -45,6 +46,24 @@ describe('the Wayback chip', () => {
});
expect(early.body).toContain('Newest');
});
+
+ it('says it is waiting while Esri is being read, picker open or shut', () => {
+ // the walk takes seconds and runs with the menu closed once the history
+ // follows the map, so the chip is where the wait has to show
+ const { body } = render(WaybackPicker, {
+ props: props({ menuOpen: false, releases: [], date: '', busy: true }),
+ });
+ expect(body).toContain('Reading…');
+ expect(body).toMatch(/class="spinner\b/);
+ expect(body).toContain('aria-busy="true"');
+ expect(body).not.toContain('Newest');
+ });
+
+ it('keeps the release it already names while the next answer is read', () => {
+ const { body } = render(WaybackPicker, { props: props({ menuOpen: false, busy: true }) });
+ expect(body).toContain('2023-08-31');
+ expect(body).toMatch(/class="spinner\b/);
+ });
});
describe('the picker', () => {
diff --git a/frontend/src/tools/satellite/state/addedLayers.svelte.js b/frontend/src/tools/satellite/state/addedLayers.svelte.js
index 9637e84..8729b07 100644
--- a/frontend/src/tools/satellite/state/addedLayers.svelte.js
+++ b/frontend/src/tools/satellite/state/addedLayers.svelte.js
@@ -3,10 +3,15 @@
*
* Holds the list, the acts that change it, and the one thing that decides
* whether this feature is honest about the network: **nothing here fetches on
- * mount.** Opening a case reads the layers already on disk, and only then, only
- * for subscriptions that are enabled and asked to, does `refreshOnOpen` reach
- * out. A disabled layer never costs a request, and a case opened offline draws
- * every snapshot it holds.
+ * mount.** Opening a case reads the layers already on disk and draws none of
+ * them.
+ *
+ * **Whether a layer is on lives here and nowhere else**, so every layer starts
+ * off when the app or the page is opened again: one heavy enough to take the tab
+ * down would otherwise take it down again on every reload. Switching a followed
+ * layer on for the first time in the session is what re-reads it, when it asked
+ * to be; an off layer never costs a request, and one switched on offline draws
+ * the snapshot it holds.
*
* The parsed GeoJSON is kept here rather than in the overlay component so that
* switching a layer off and on again does not re-read a file the browser already
@@ -20,10 +25,11 @@
*/
import {
drawable,
- refreshable,
+ renewsOnShow,
searchFeatures,
toggleCategory,
} from '../../../lib/map/addedLayers.js';
+import { active, indexDates, within } from '../../../lib/map/layerDates.js';
export function createAddedLayersState({ api, notify, ensureCase, reloadCase }) {
let rows = $state([]);
@@ -31,6 +37,10 @@ export function createAddedLayersState({ api, notify, ensureCase, reloadCase })
let busy = $state(''); // the layer name an act is running on
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
+ /** GeoConfirmed's conflicts, read the first time its dialog opens and kept for
+ * the session: they change a few times a year. */
+ let conflictList = null;
/** name → the parsed collection, once something has asked to draw it. */
const drawings = new Map();
@@ -44,17 +54,62 @@ export function createAddedLayersState({ api, notify, ensureCase, reloadCase })
let picked = $state(null);
let picks = 0;
let loadedFor = null; // the case every row was read for
+ /** The layers switched on in this page. Never stored: see the header. */
+ let on = $state(new Set());
+ /** name → the period a strip is being dragged to, ahead of the stored one, so
+ * the map and the counter follow the pointer and the backend hears the end. */
+ let drafts = $state({});
+ /** name → `{ collection, index }`: the days of a layer's features, indexed
+ * once per snapshot rather than on every frame of a drag. */
+ const indexes = new Map();
+ /** …and the ones already re-read this session, so switching one off and on
+ * again draws what is in hand rather than asking its source again. */
+ const renewed = new Set();
function reset() {
rows = [];
drawings.clear();
held = new Set();
picked = null;
+ on = new Set();
+ renewed.clear();
+ }
+
+ function show(name, visible) {
+ const next = new Set(on);
+ if (visible) next.add(name);
+ else next.delete(name);
+ on = next;
+ }
+
+ /** The rows as the panel and the map read them, each saying whether it is on. */
+ function listed() {
+ return rows.map((row) => {
+ const period = row.name in drafts ? drafts[row.name] : (row.period ?? null);
+ const listing = { ...row, enabled: on.has(row.name), period };
+ const index = active(period) ? datesOf(row.name) : null;
+ if (!index) return listing;
+ // what a period leaves on the map, which the counter and the legend state
+ const counted = within(index, row.hidden, period);
+ return { ...listing, shown: counted.total, shownBy: counted.byGroup };
+ });
+ }
+
+ /** The indexed days of a layer whose features are in hand, or null. */
+ function datesOf(name) {
+ if (!held.has(name)) return null;
+ const collection = drawings.get(name);
+ const memo = indexes.get(name);
+ if (memo?.collection === collection) return memo.index;
+ const index = indexDates(collection);
+ indexes.set(name, { collection, index });
+ return index;
}
/** Drop a layer's features, which is what a new snapshot and a removal both do. */
function forget(name) {
drawings.delete(name);
+ indexes.delete(name);
if (!held.has(name)) return;
const next = new Set(held);
next.delete(name);
@@ -68,7 +123,7 @@ export function createAddedLayersState({ api, notify, ensureCase, reloadCase })
}
/**
- * Read this case's layers. Disk only — the network boundary is `refreshOnOpen`.
+ * Read this case's layers. Disk only, and every one of them starts off.
*
* Returns the teardown that makes a response arriving after the case changed
* land nowhere, as the other panel indexes do.
@@ -85,7 +140,6 @@ export function createAddedLayersState({ api, notify, ensureCase, reloadCase })
.then((list) => {
if (!live) return;
rows = Array.isArray(list) ? list : [];
- refreshOnOpen(caseId);
})
.catch(() => {
if (live) rows = [];
@@ -96,14 +150,14 @@ export function createAddedLayersState({ api, notify, ensureCase, reloadCase })
}
/**
- * Re-read the feeds a case open is allowed to re-read, and only those.
+ * Re-read a followed layer the first time it is switched on in the session.
*
- * One request per layer, all of them failing silently: a subscription that
- * cannot be reached is not an error worth a toast on every case open — the row
- * already says how old what it is drawing is.
+ * Silent when it fails: the snapshot is already being drawn, and the row says
+ * how old it is — a source that cannot be reached is not worth a toast.
*/
- async function refreshOnOpen(caseId) {
- for (const layer of refreshable(rows)) {
+ function renew(caseId, layer) {
+ renewed.add(layer.name);
+ return act(layer.name, async () => {
try {
const row = await api.post(`/api/cases/${caseId}/map-layers/${layer.name}/refresh`);
if (loadedFor !== caseId) return;
@@ -112,13 +166,21 @@ export function createAddedLayersState({ api, notify, ensureCase, reloadCase })
} catch {
/* the snapshot stays on the map, and the row says when it was last read */
}
- }
+ });
}
- /** The parsed collection for one layer, read once and kept. */
+ /**
+ * The parsed collection for one layer, read once and kept.
+ *
+ * Always checked with the server: the address stays the same through every
+ * refresh, and a browser cache filled before the backend said `no-cache`
+ * would otherwise go on handing back the features it read then.
+ */
async function drawing(caseId, name) {
if (drawings.has(name)) return drawings.get(name);
- const data = await api.get(`/api/cases/${caseId}/map-layers/${name}/data`);
+ const data = await api.get(`/api/cases/${caseId}/map-layers/${name}/data`, {
+ cache: 'no-cache',
+ });
drawings.set(name, data);
held = new Set(held).add(name);
return data;
@@ -134,7 +196,7 @@ export function createAddedLayersState({ api, notify, ensureCase, reloadCase })
}
/**
- * Both halves of the `+`, which differ only in what they post.
+ * Every way in through the `+`, which differ only in what they post.
*
* A refusal is a toast and an open dialog, not a closed one: the reason the
* backend gave — a KMZ with no KML in it, a My Maps that was never shared — is
@@ -147,7 +209,11 @@ export function createAddedLayersState({ api, notify, ensureCase, reloadCase })
try {
const row = await post(kase.id);
replace(row);
+ // on, since it was added to be looked at, and just read
+ show(row.name, true);
+ renewed.add(row.name);
adding = false;
+ geoconfirmed = false;
await reloadCase();
notify(`${row.title} added`, 'ok');
return row;
@@ -182,6 +248,19 @@ export function createAddedLayersState({ api, notify, ensureCase, reloadCase })
);
}
+ /** One GeoConfirmed conflict over a window, as `lib/map/geoconfirmed.js` builds it. */
+ function addGeoConfirmed(body) {
+ return add(
+ (caseId) => api.post(`/api/cases/${caseId}/map-layers/geoconfirmed`, body),
+ 'GeoConfirmed could not be read'
+ );
+ }
+
+ async function conflicts() {
+ conflictList ??= await api.get('/api/geoconfirmed/conflicts');
+ return conflictList;
+ }
+
async function patch(caseId, name, body) {
const row = await api.patch(`/api/cases/${caseId}/map-layers/${name}`, body);
replace(row);
@@ -190,10 +269,10 @@ export function createAddedLayersState({ api, notify, ensureCase, reloadCase })
return {
get rows() {
- return rows;
+ return listed();
},
get drawn() {
- return drawable(rows);
+ return drawable(listed());
},
get open() {
return open;
@@ -210,6 +289,12 @@ export function createAddedLayersState({ api, notify, ensureCase, reloadCase })
set adding(value) {
adding = value;
},
+ get geoconfirmed() {
+ return geoconfirmed;
+ },
+ set geoconfirmed(value) {
+ geoconfirmed = value;
+ },
get saving() {
return saving;
},
@@ -221,6 +306,8 @@ export function createAddedLayersState({ api, notify, ensureCase, reloadCase })
drawing,
addFile,
subscribe,
+ addGeoConfirmed,
+ conflicts,
/**
* The features of one layer that match what was typed.
@@ -237,6 +324,7 @@ export function createAddedLayersState({ api, notify, ensureCase, reloadCase })
...searchFeatures(drawings.get(name), query, {
categories: layer.categories,
hidden: layer.hidden,
+ period: layer.period,
}),
ready: true,
};
@@ -250,18 +338,57 @@ export function createAddedLayersState({ api, notify, ensureCase, reloadCase })
* drawn would be the map travelling somewhere to show nothing.
*/
async pick(caseId, layer, result) {
- if (result?.hidden) {
+ if (result?.hidden && layer.hidden?.includes(result.category)) {
await patch(caseId, layer.name, {
hidden: toggleCategory(layer, result.category),
}).catch(() => {});
}
+ // a match outside the period lets every date back in: the map cannot be
+ // sent to a feature it is filtering out
+ if (result?.outside) await this.setPeriod(caseId, layer, null, true);
picks += 1;
picked = { name: layer.name, index: result.index, at: picks };
},
- /** The eye on the row. Off costs nothing and asks for nothing. */
+ /**
+ * The days a layer's features carry, indexed, for its time strip — or null
+ * while they are on their way, or when the source dated none of them.
+ */
+ dates(layer) {
+ return datesOf(layer?.name ?? '');
+ },
+
+ /**
+ * The row's time filter. While the strip is dragged (`commit` false) only
+ * the page follows it; on release it is kept on the layer, as the legend is.
+ * A failed save puts back what the layer held.
+ */
+ async setPeriod(caseId, layer, period, commit) {
+ const name = layer.name;
+ drafts = { ...drafts, [name]: period };
+ if (!commit) return;
+ try {
+ await patch(caseId, name, { period: period ?? { start: '', end: '' } });
+ } catch {
+ /* the stored period stands, and the strip goes back to it */
+ }
+ const rest = { ...drafts };
+ delete rest[name];
+ drafts = rest;
+ },
+
+ /**
+ * The eye on the row, which stores nothing. Off costs nothing and asks for
+ * nothing; the first time on in the session re-reads a followed layer that
+ * asked for it, while the snapshot already on disk is drawn.
+ */
toggle(caseId, layer) {
- return patch(caseId, layer.name, { enabled: !layer.enabled }).catch(() => {});
+ const visible = !on.has(layer.name);
+ show(layer.name, visible);
+ if (visible && !renewed.has(layer.name) && renewsOnShow(layer)) {
+ return renew(caseId, layer);
+ }
+ return Promise.resolve();
},
/** One legend row, which hides exactly its own features. */
@@ -293,6 +420,8 @@ export function createAddedLayersState({ api, notify, ensureCase, reloadCase })
try {
await api.del(`/api/cases/${caseId}/map-layers/${layer.name}`);
forget(layer.name);
+ show(layer.name, false);
+ renewed.delete(layer.name);
rows = rows.filter((entry) => entry.name !== layer.name);
await reloadCase();
} catch (error) {
@@ -300,14 +429,5 @@ export function createAddedLayersState({ api, notify, ensureCase, reloadCase })
}
});
},
-
- /** What a hidden folder owes the analyst: where the bytes actually are. */
- async reveal(caseId, layer) {
- try {
- await api.post(`/api/cases/${caseId}/map-layers/${layer.name}/reveal`);
- } catch (error) {
- notify(error?.message || 'That folder could not be opened', 'error');
- }
- },
};
}
diff --git a/frontend/src/tools/satellite/state/addedLayers.svelte.test.js b/frontend/src/tools/satellite/state/addedLayers.svelte.test.js
index 13dd974..81420b2 100644
--- a/frontend/src/tools/satellite/state/addedLayers.svelte.test.js
+++ b/frontend/src/tools/satellite/state/addedLayers.svelte.test.js
@@ -14,7 +14,6 @@ const FILE_LAYER = {
name: 'Sightings',
title: 'Sightings',
source: { kind: 'file', name: 'sightings.kml' },
- enabled: true,
hidden: [],
features: 3,
categories: [{ name: 'Checkpoints', count: 3, colour: '#f00' }],
@@ -75,47 +74,88 @@ beforeEach(() => {
});
describe('opening a case', () => {
- it('reads what is on disk and nothing else when every layer is a file', async () => {
+ it('reads what is on disk and nothing else', async () => {
+ rows = [FILE_LAYER, followed()];
const layers = store();
layers.load('c1');
await settle();
expect(calls).toEqual([['GET', '/api/cases/c1/map-layers']]);
- expect(layers.rows).toEqual([FILE_LAYER]);
+ expect(layers.rows.map((row) => row.name)).toEqual(['Sightings', 'Roadblocks']);
});
- it('re-reads a followed map that is enabled and asked to be', async () => {
+ it('draws nothing: every layer starts off, whatever it was before the reload', async () => {
+ // a layer heavy enough to take the tab down would take it down again on
+ // every reload if the switch were remembered
+ rows = [FILE_LAYER, followed()];
+ const layers = store();
+ layers.load('c1');
+ await settle();
+
+ expect(layers.rows.every((row) => row.enabled === false)).toBe(true);
+ expect(layers.drawn).toEqual([]);
+ });
+
+ it('forgets what was on in the previous store, as a reload does', async () => {
+ const before = store();
+ before.load('c1');
+ await settle();
+ await before.toggle('c1', before.rows[0]);
+ expect(before.drawn).toHaveLength(1);
+
+ const after = store();
+ after.load('c1');
+ await settle();
+
+ expect(after.drawn).toEqual([]);
+ });
+});
+
+describe('switching a layer on', () => {
+ it('re-reads a followed map the first time, and never again in the session', async () => {
rows = [followed()];
const layers = store();
layers.load('c1');
await settle();
+ calls.length = 0;
- expect(calls).toEqual([
- ['GET', '/api/cases/c1/map-layers'],
- ['POST', '/api/cases/c1/map-layers/Roadblocks/refresh'],
- ]);
+ await layers.toggle('c1', layers.rows[0]); // on
+ await layers.toggle('c1', layers.rows[0]); // off
+ await layers.toggle('c1', layers.rows[0]); // on again
+
+ expect(calls).toEqual([['POST', '/api/cases/c1/map-layers/Roadblocks/refresh']]);
+ expect(layers.drawn.map((row) => row.name)).toEqual(['Roadblocks']);
});
- it('leaves a disabled subscription alone — an off layer costs nothing', async () => {
- rows = [followed({ enabled: false })];
+ it('asks nothing of a file, or of a subscription that asked not to be', async () => {
+ rows = [FILE_LAYER, followed({ refresh: { on_open: false } })];
const layers = store();
layers.load('c1');
await settle();
+ calls.length = 0;
- expect(calls).toEqual([['GET', '/api/cases/c1/map-layers']]);
+ await layers.toggle('c1', layers.rows[0]);
+ await layers.toggle('c1', layers.rows[1]);
+
+ expect(calls).toEqual([]);
+ expect(layers.drawn).toHaveLength(2);
});
- it('leaves one alone that asked not to be read on open', async () => {
- rows = [followed({ refresh: { on_open: false } })];
+ it('stores nothing: the switch is never sent to the backend', async () => {
const layers = store();
layers.load('c1');
await settle();
+ calls.length = 0;
- expect(calls).toEqual([['GET', '/api/cases/c1/map-layers']]);
+ await layers.toggle('c1', layers.rows[0]);
+ await layers.toggle('c1', layers.rows[0]);
+
+ expect(calls).toEqual([]);
+ expect(layers.drawn).toEqual([]);
});
it('draws the last snapshot when the feed cannot be reached', async () => {
- // a case opened offline is a case that still works
+ // switched on offline, a layer still draws what it holds
rows = [followed()];
api.post = vi.fn(async () => {
throw new Error('network down');
@@ -124,6 +164,8 @@ describe('opening a case', () => {
layers.load('c1');
await settle();
+ await layers.toggle('c1', layers.rows[0]);
+
expect(layers.drawn.map((row) => row.name)).toEqual(['Roadblocks']);
expect(notify).not.toHaveBeenCalled();
});
@@ -141,6 +183,20 @@ describe('drawing', () => {
expect(calls.filter(([, path]) => path.endsWith('/data'))).toHaveLength(1);
});
+ it('asks the server for the features, past whatever the browser kept', async () => {
+ // the address is the same through every refresh, and Chrome had kept one
+ // it filled before the backend said no-cache
+ const layers = store();
+ layers.load('c1');
+ await settle();
+
+ await layers.drawing('c1', 'Sightings');
+
+ expect(api.get).toHaveBeenCalledWith('/api/cases/c1/map-layers/Sightings/data', {
+ cache: 'no-cache',
+ });
+ });
+
it('re-reads it only when a refresh actually moved the bytes', async () => {
rows = [followed({ refresh: { on_open: false } })];
const layers = store();
@@ -162,30 +218,19 @@ describe('drawing', () => {
expect(reads()).toBe(2);
});
- it('draws only what is enabled', async () => {
- rows = [FILE_LAYER, followed({ enabled: false, refresh: { on_open: false } })];
+ it('draws only what is switched on', async () => {
+ rows = [FILE_LAYER, followed({ refresh: { on_open: false } })];
const layers = store();
layers.load('c1');
await settle();
+ await layers.toggle('c1', layers.rows[0]);
+
expect(layers.drawn.map((row) => row.name)).toEqual(['Sightings']);
});
});
describe('the acts on a row', () => {
- it('switches a layer off without asking anyone for anything', async () => {
- const layers = store();
- layers.load('c1');
- await settle();
- calls.length = 0;
-
- await layers.toggle('c1', layers.rows[0]);
-
- expect(calls).toEqual([
- ['PATCH', '/api/cases/c1/map-layers/Sightings', { enabled: false }],
- ]);
- });
-
it('hides one category by sending the whole list back', async () => {
const layers = store();
layers.load('c1');
@@ -255,6 +300,18 @@ describe('adding', () => {
expect(layers.rows).toHaveLength(1);
});
+ it('draws what was just added, without reading its source a second time', async () => {
+ const layers = store();
+
+ await layers.subscribe('https://example.test/roadblocks.kml');
+ calls.length = 0;
+ await layers.toggle('c1', layers.rows[0]); // off
+ await layers.toggle('c1', layers.rows[0]); // on again
+
+ expect(layers.drawn.map((row) => row.name)).toEqual(['Roadblocks']);
+ expect(calls).toEqual([]);
+ });
+
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
@@ -302,6 +359,146 @@ describe('adding', () => {
});
});
+describe('the time filter', () => {
+ const DATED = {
+ type: 'FeatureCollection',
+ features: [
+ { properties: { name: 'a', category: 'Checkpoints', date: '2026-09-01', index: 0 } },
+ { properties: { name: 'b', category: 'Checkpoints', date: '2026-09-10', index: 1 } },
+ { properties: { name: 'c', category: 'Checkpoints', date: '2026-09-18', index: 2 } },
+ ],
+ };
+
+ async function drawn() {
+ collection = DATED;
+ const layers = store();
+ layers.load('c1');
+ await settle();
+ await layers.toggle('c1', layers.rows[0]);
+ await layers.drawing('c1', 'Sightings');
+ return layers;
+ }
+
+ it('has nothing to index until the features are in hand, nor for an undated layer', async () => {
+ const layers = store();
+ layers.load('c1');
+ await settle();
+ expect(layers.dates(layers.rows[0])).toBeNull();
+
+ collection = { type: 'FeatureCollection', features: [{ properties: { name: 'x' } }] };
+ await layers.drawing('c1', 'Sightings');
+ expect(layers.dates(layers.rows[0])).toBeNull();
+ });
+
+ it('follows a dragged strip in the page and tells the backend nothing yet', async () => {
+ const layers = await drawn();
+ calls.length = 0;
+
+ await layers.setPeriod('c1', layers.rows[0], { start: '2026-09-05', end: '' }, false);
+
+ expect(calls).toEqual([]);
+ expect(layers.rows[0].period).toEqual({ start: '2026-09-05', end: '' });
+ expect(layers.rows[0].shown).toBe(2);
+ expect(layers.drawn[0].period).toEqual({ start: '2026-09-05', end: '' });
+ });
+
+ it('keeps the period on the layer when the strip is let go', async () => {
+ const layers = await drawn();
+ calls.length = 0;
+ const period = { start: '2026-09-05', end: '2026-09-12' };
+
+ await layers.setPeriod('c1', layers.rows[0], period, true);
+
+ expect(calls).toEqual([['PATCH', '/api/cases/c1/map-layers/Sightings', { period }]]);
+ expect(layers.rows[0].period).toEqual(period);
+ expect(layers.rows[0].shown).toBe(1);
+ });
+
+ it('clears it with two blanks, which is what the backend reads as none', async () => {
+ const layers = await drawn();
+ calls.length = 0;
+
+ await layers.setPeriod('c1', layers.rows[0], null, true);
+
+ expect(calls).toEqual([
+ ['PATCH', '/api/cases/c1/map-layers/Sightings', { period: { start: '', end: '' } }],
+ ]);
+ });
+
+ it('puts back the stored period when it could not be kept', async () => {
+ const layers = await drawn();
+ api.patch = vi.fn(async () => {
+ throw new Error('offline');
+ });
+
+ await layers.setPeriod('c1', layers.rows[0], { start: '2026-09-05', end: '' }, true);
+
+ expect(layers.rows[0].period).toBeNull();
+ expect(layers.rows[0].shown).toBeUndefined();
+ });
+
+ it('lets every date back in before going to a match outside the period', async () => {
+ const layers = await drawn();
+ calls.length = 0;
+
+ await layers.pick('c1', layers.rows[0], { index: 0, category: 'Checkpoints', hidden: true, outside: true });
+
+ expect(calls).toContainEqual([
+ 'PATCH',
+ '/api/cases/c1/map-layers/Sightings',
+ { period: { start: '', end: '' } },
+ ]);
+ // the group was never off, so it is not switched
+ expect(calls.some(([, , body]) => body?.hidden)).toBe(false);
+ expect(layers.picked.index).toBe(0);
+ });
+});
+
+describe('adding from GeoConfirmed', () => {
+ it('posts the query and closes both dialogs on success', async () => {
+ const layers = store();
+ layers.geoconfirmed = true;
+ const body = { conflict: 'Ukraine', days: 30 };
+
+ await layers.addGeoConfirmed(body);
+
+ expect(api.post).toHaveBeenCalledWith('/api/cases/c1/map-layers/geoconfirmed', body);
+ expect(layers.geoconfirmed).toBe(false);
+ expect(layers.adding).toBe(false);
+ });
+
+ it('keeps the dialog open with the reason when GeoConfirmed refused', async () => {
+ api.post = vi.fn(async () => {
+ throw new Error('GeoConfirmed maps no conflict called Atlantis');
+ });
+ const layers = store();
+ layers.geoconfirmed = true;
+
+ await layers.addGeoConfirmed({ conflict: 'Atlantis', days: 7 });
+
+ expect(notify).toHaveBeenCalledWith('GeoConfirmed maps no conflict called Atlantis', 'error');
+ expect(layers.geoconfirmed).toBe(true);
+ });
+
+ it('reads the conflict list once per session, however often the dialog opens', async () => {
+ rows = [{ conflict: 'Ukraine', name: 'Ukraine' }];
+ const layers = store();
+
+ await layers.conflicts();
+ await layers.conflicts();
+
+ expect(calls.filter(([, path]) => path === '/api/geoconfirmed/conflicts')).toHaveLength(1);
+ });
+
+ it('asks nothing of GeoConfirmed until its dialog does', async () => {
+ const layers = store();
+ layers.load('c1');
+ await settle();
+
+ expect(calls.some(([, path]) => path.includes('geoconfirmed'))).toBe(false);
+ });
+});
+
describe('switching case', () => {
it('drops the previous case, rather than drawing its layers over the new one', async () => {
const layers = store();
@@ -377,6 +574,7 @@ describe('finding a pin', () => {
await layers.drawing('c1', 'Roadblocks');
// a feed that had not moved: the features in hand are still the right ones
+ api.post = vi.fn(async () => followed());
await layers.refresh('c1', layers.rows[0]);
expect(layers.search(layers.rows[0], 'gate').ready).toBe(true);
diff --git a/frontend/src/tools/satellite/state/wayback.svelte.js b/frontend/src/tools/satellite/state/wayback.svelte.js
index 57fbdc4..8f7ffab 100644
--- a/frontend/src/tools/satellite/state/wayback.svelte.js
+++ b/frontend/src/tools/satellite/state/wayback.svelte.js
@@ -34,6 +34,7 @@ export function createWaybackState({ api, place }) {
let releases = $state([]); // [{ release, date }], newest first
let listNote = $state('');
let listing = null; // the one in-flight read of the list
+ let listBusy = $state(false); // …as the chip shows it
let release = $state(null); // null = the newest
let menuOpen = $state(false);
let watching = $state(false); // the picker has been opened: the history follows the map
@@ -55,6 +56,7 @@ export function createWaybackState({ api, place }) {
async function loadReleases() {
if (releases.length) return releases;
listing ??= (async () => {
+ listBusy = true;
try {
const answer = await api.get('/api/satellite/wayback/releases');
releases = answer.releases ?? [];
@@ -63,6 +65,7 @@ export function createWaybackState({ api, place }) {
listNote = `Could not read the release list: ${error.message}`;
} finally {
listing = null;
+ listBusy = false;
}
return releases;
})();
@@ -133,6 +136,18 @@ export function createWaybackState({ api, place }) {
get changesBusy() {
return changesBusy;
},
+ /**
+ * Esri is being asked something, list or history.
+ *
+ * Both walks take their time — the history reads a tile per release and
+ * compares the pixels — and both can be running with the picker shut, since
+ * the history follows the map once it has been opened. So the chip carries
+ * the wait: a basemap that answers nothing for ten seconds and says nothing
+ * about it reads as one that is broken.
+ */
+ get busy() {
+ return listBusy || changesBusy;
+ },
get changesNote() {
return changesNote;
},
diff --git a/frontend/src/tools/satellite/state/wayback.svelte.test.js b/frontend/src/tools/satellite/state/wayback.svelte.test.js
index 9c54a5f..b296dac 100644
--- a/frontend/src/tools/satellite/state/wayback.svelte.test.js
+++ b/frontend/src/tools/satellite/state/wayback.svelte.test.js
@@ -51,6 +51,21 @@ describe('asking Esri', () => {
expect(wb.date).toBe('2026-08-05');
});
+ it('says it is busy for either read, so a chip can carry the wait', async () => {
+ const wb = store();
+ expect(wb.busy).toBe(false);
+
+ const list = wb.loadReleases();
+ expect(wb.busy).toBe(true);
+ await list;
+ expect(wb.busy).toBe(false);
+
+ const history = wb.loadChanges();
+ expect(wb.busy).toBe(true);
+ await history;
+ expect(wb.busy).toBe(false);
+ });
+
it('opening the picker reads the list and this point’s history', async () => {
const wb = store();
wb.toggleMenu();
diff --git a/src/azimut/api/compare.py b/src/azimut/api/compare.py
index f3efdae..a23f99f 100644
--- a/src/azimut/api/compare.py
+++ b/src/azimut/api/compare.py
@@ -129,7 +129,10 @@ class CompareChangeAssist(BaseModel):
AnnotationKind = Literal[
- "text", "arrow", "line", "rect", "ellipse", "freehand", "measure", "polygon"
+ "text", "arrow", "line", "rect", "ellipse", "freehand", "measure", "polygon",
+ # Stamped whole on one point: a numbered disc, and a symbol from the drawing
+ # set the Proof Maker stamps onto a panel.
+ "number", "icon",
]
#: How many ground points each kind holds: an exact count, or (minimum, maximum).
_POINT_COUNTS: dict[str, tuple[int, int]] = {
@@ -141,6 +144,8 @@ _POINT_COUNTS: dict[str, tuple[int, int]] = {
"ellipse": (2, 2),
"freehand": (2, 400),
"polygon": (3, 200),
+ "number": (1, 1),
+ "icon": (1, 1),
}
@@ -155,8 +160,16 @@ class CompareAnnotation(BaseModel):
points: list[tuple[float, float]] = Field(min_length=1, max_length=400)
stroke_width: int = Field(default=3, ge=1, le=24)
fill_opacity: float = Field(default=0, ge=0, le=1)
+ #: Also the side of a stamp, which has no letters to size and no line to widen.
font_size: int = Field(default=16, ge=8, le=72)
text: str = Field(default="", max_length=240)
+ #: What a numbered marker counts to. Its series is its colour's, and the
+ #: browser assigns it; the ceiling is what one picture can carry legibly.
+ number: int = Field(default=1, ge=1, le=999)
+ #: Which symbol a stamp draws, by name. Not checked against the drawing set:
+ #: that set lives in the browser and grows there, and a name this build does
+ #: not know is drawn as the first symbol rather than refused on the way in.
+ glyph: str = Field(default="", max_length=40)
@model_validator(mode="after")
def _shape(self) -> "CompareAnnotation":
@@ -301,7 +314,10 @@ def change_refusal(a: dict[str, Any], b: dict[str, Any], method: str = "colour")
and a["wayback_release"] == b["wayback_release"]
)
if same_picture:
- return "Choose two different Esri releases"
+ return (
+ "Both sides show the same picture. Pick another Esri release, "
+ "or two dated Sentinel-2 passes"
+ )
if not _same_layers(a, b):
return "Match the reference layers on A and B"
return None
diff --git a/src/azimut/api/maplayers.py b/src/azimut/api/maplayers.py
index 47bd71d..38cce96 100644
--- a/src/azimut/api/maplayers.py
+++ b/src/azimut/api/maplayers.py
@@ -1,16 +1,20 @@
"""REST API for the layers an analyst adds to a case's map.
-Two ways in — a file opened from the computer, and a URL subscribed to — and one
-kind of thing out. Everything a layer is parsed from is read in Python
+Three ways in — a file opened from the computer, a URL subscribed to, and a
+GeoConfirmed query — and one kind of thing out. Everything a layer is parsed from is read in Python
(`engine/maplayers.py`): the browser gets JSON, never XML, never a zip, and never
the remote host's address.
**The network boundary is the part to keep honest.** Nothing here polls. A fetch
-happens when a subscription is created, when Refresh is pressed, and when a case
-is opened holding an enabled layer that asked to refresh on open — and that last
-one is a route the frontend calls deliberately, not something a mount does.
-Listing layers, drawing them and toggling a category all read the snapshot
-already on disk, offline included.
+happens when a subscription is created, when Refresh is pressed, and when the
+analyst switches a layer on for the first time in a session and it asked to be
+re-read then — and that last one is the Refresh route, called by the frontend on
+that switch, never by a mount. Listing layers, drawing them and toggling a
+category all read the snapshot already on disk, offline included.
+
+**Whether a layer is on is not stored here.** Every layer starts off when the app
+or the page is opened again: one heavy enough to take the tab down would
+otherwise take it down again on every reload.
The source's own icons ride on those same three acts and nowhere else. They are
composed once, at the moment the analyst ticks the box, and served from the case
@@ -24,16 +28,18 @@ from typing import Any
from fastapi import APIRouter, Form, HTTPException, UploadFile
from fastapi.responses import FileResponse, Response
-from pydantic import BaseModel, Field
+from pydantic import BaseModel, Field, field_validator
from .. import layout
from ..engine import artifacts as artifact_engine
+from ..engine import geoconfirmed
from ..engine import maplayers as layer_engine
-from ..engine import reveal as reveal_engine
from ..workspace import CaseError
from .cases import delete_by_path, get_case
router = APIRouter(prefix="/api/cases", tags=["map-layers"])
+#: What GeoConfirmed offers, which belongs to no case.
+geoconfirmed_router = APIRouter(prefix="/api/geoconfirmed", tags=["map-layers"])
#: A source file is read into memory to be parsed, so the upload is bounded by
#: the same number the parser refuses at. One more than the limit is enough to
@@ -44,8 +50,8 @@ MAX_UPLOAD = layer_engine.MAX_SOURCE_BYTES
class SubscribeIn(BaseModel):
url: str = Field(min_length=1, max_length=4000)
title: str | None = Field(default=None, max_length=200)
- #: Whether opening the case re-reads the feed. Off leaves a layer that only
- #: moves when Refresh is pressed.
+ #: Whether the first switch-on of a session re-reads the feed. Off leaves a
+ #: layer that only moves when Refresh is pressed.
on_open: bool = True
#: Whether to compose the map's own pictograms. On by default here and off on
#: the upload: following a pasted address already reaches the network, and
@@ -53,11 +59,43 @@ class SubscribeIn(BaseModel):
icons: bool = True
+class GeoConfirmedIn(BaseModel):
+ #: The conflict's short name, as the conflict list gives it.
+ conflict: str = Field(min_length=1, max_length=64)
+ #: The last this many days, counted from each read…
+ days: int | None = Field(default=None, ge=1, le=geoconfirmed.MAX_DAYS)
+ #: …or a first day and an optional last one, `YYYY-MM-DD`…
+ start: str | None = Field(default=None, max_length=10)
+ end: str | None = Field(default=None, max_length=10)
+ #: …or the conflict's whole history.
+ everything: bool = False
+ #: `[west, south, east, north]`, or nothing for the whole conflict.
+ area: list[float] | None = Field(default=None, min_length=4, max_length=4)
+ #: Unset re-reads a window on its first switch-on of a session and the whole
+ #: history only on Refresh (`engine/geoconfirmed.subscribe`).
+ on_open: bool | None = None
+
+
+class PeriodIn(BaseModel):
+ """The row's time filter: a first and a last day, either "" for no bound."""
+
+ start: str = Field(default="", max_length=10)
+ end: str = Field(default="", max_length=10)
+
+ @field_validator("start", "end")
+ @classmethod
+ def _a_day(cls, value: str) -> str:
+ if value and not layer_engine.iso_day(value):
+ raise ValueError("a day is YYYY-MM-DD")
+ return value
+
+
class UpdateIn(BaseModel):
- enabled: bool | None = None
#: Category names the legend has switched off, which is the whole of the
#: filter: a hidden category is not drawn and not counted as visible.
hidden: list[str] | None = Field(default=None, max_length=2000)
+ #: The time filter; both days "" clears it.
+ period: PeriodIn | None = None
on_open: bool | None = None
title: str | None = Field(default=None, max_length=200)
@@ -121,6 +159,40 @@ def subscribe_layer(case_id: str, body: SubscribeIn) -> dict[str, Any]:
raise HTTPException(status_code=400, detail=str(exc)) from exc
[email protected]("/{case_id}/map-layers/geoconfirmed")
+def geoconfirmed_layer(case_id: str, body: GeoConfirmedIn) -> dict[str, Any]:
+ """One GeoConfirmed conflict over a window of days and, if asked, one area.
+
+ Two requests to GeoConfirmed, the conflict's factions and its export, and
+ nothing for the icons: they arrive inside the export.
+ """
+ case = get_case(case_id)
+ try:
+ return geoconfirmed.subscribe(
+ case,
+ body.conflict,
+ days=body.days,
+ start=body.start,
+ end=body.end,
+ everything=body.everything,
+ box=body.area,
+ on_open=body.on_open,
+ )
+ except layer_engine.LayerError as exc:
+ raise _refused(exc) from exc
+ except CaseError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+
+
+@geoconfirmed_router.get("/conflicts")
+def geoconfirmed_conflicts() -> list[dict[str, Any]]:
+ """The conflicts GeoConfirmed maps, read when its dialog opens and not before."""
+ try:
+ return geoconfirmed.conflicts()
+ except layer_engine.LayerError as exc:
+ raise _refused(exc) from exc
+
+
@router.post("/{case_id}/map-layers/{name}/refresh")
def refresh_layer(case_id: str, name: str) -> dict[str, Any]:
"""Read the feed again. The snapshot is replaced only if the bytes moved."""
@@ -141,13 +213,20 @@ def read_layer(case_id: str, name: str) -> dict[str, Any]:
@router.get("/{case_id}/map-layers/{name}/data")
def layer_data(case_id: str, name: str) -> FileResponse:
- """The parsed GeoJSON the map draws, rebuilt from the snapshot if need be."""
+ """The parsed GeoJSON the map draws, rebuilt from the snapshot if need be.
+
+ Never reused unasked: a refresh changes what this one address holds, and a
+ browser left to guess a lifetime from Last-Modified goes on drawing the
+ features it read before.
+ """
case = get_case(case_id)
try:
path = layer_engine.drawing(case, _stem(name))
except layer_engine.LayerError as exc:
raise HTTPException(status_code=404, detail=str(exc)) from exc
- return FileResponse(path, media_type="application/geo+json")
+ return FileResponse(
+ path, media_type="application/geo+json", headers={"Cache-Control": "no-cache"}
+ )
@router.get("/{case_id}/map-layers/{name}/icons/{key}")
@@ -174,14 +253,15 @@ def layer_icon(case_id: str, name: str, key: str) -> Response:
@router.patch("/{case_id}/map-layers/{name}")
def update_layer(case_id: str, name: str, body: UpdateIn) -> dict[str, Any]:
- """The switch, the legend and the refresh policy. Touches no network."""
+ """The legend, the time filter, the refresh policy and the title. Touches no
+ network."""
case = get_case(case_id)
try:
return layer_engine.update(
case,
_stem(name),
- enabled=body.enabled,
hidden=body.hidden,
+ period=(body.period.start, body.period.end) if body.period else None,
on_open=body.on_open,
title=body.title,
)
@@ -189,29 +269,6 @@ def update_layer(case_id: str, name: str, body: UpdateIn) -> dict[str, Any]:
raise HTTPException(status_code=404, detail=str(exc)) from exc
[email protected]("/{case_id}/map-layers/{name}/reveal")
-def reveal_layer(case_id: str, name: str) -> dict[str, str]:
- """Show the saved copy in the file manager.
-
- What a hidden folder owes the analyst: the bytes are theirs, and the row is
- the only place that says where they are.
- """
- case = get_case(case_id)
- stem = _stem(name)
- try:
- layer_engine.read(case, stem)
- target = case.resolve_inside(layout.layer_snapshot_rel(stem))
- except layer_engine.LayerError as exc:
- raise HTTPException(status_code=404, detail=str(exc)) from exc
- except CaseError as exc:
- raise HTTPException(status_code=403, detail=str(exc)) from exc
- try:
- reveal_engine.reveal(target)
- except reveal_engine.RevealError as exc:
- raise HTTPException(status_code=422, detail=str(exc)) from exc
- return {"path": str(target)}
-
-
@router.delete("/{case_id}/map-layers/{name}")
def delete_layer(case_id: str, name: str) -> dict[str, Any]:
"""Through the chokepoint, so the layer goes to the Trash like everything else."""
diff --git a/src/azimut/api/satellite.py b/src/azimut/api/satellite.py
index 97c17bf..693cd33 100644
--- a/src/azimut/api/satellite.py
+++ b/src/azimut/api/satellite.py
@@ -718,7 +718,6 @@ def parse_coordinates(body: ParseIn) -> dict[str, Any]:
"plus_code": geo.plus_code(lat, lon),
# the Coordinates tool renders this ordered list wholesale
"formats": geo.all_formats(lat, lon),
- "links": geo.map_links(lat, lon),
}
diff --git a/src/azimut/engine/artifacts.py b/src/azimut/engine/artifacts.py
index 5d0407a..01f4b6b 100644
--- a/src/azimut/engine/artifacts.py
+++ b/src/azimut/engine/artifacts.py
@@ -172,7 +172,7 @@ NO_FILES: dict[str, str] = {
"structure": "an identity in the graph",
"equipment-type": "a model in the graph, which owns no object of its own",
"bookmark": "a URL in the graph",
- "claim": "a statement in the graph, and the edges that carry it",
+ "claim": "a claim in the graph, and the edges that carry it",
}
diff --git a/src/azimut/engine/entities.py b/src/azimut/engine/entities.py
index 3ce71e3..36b23f8 100644
--- a/src/azimut/engine/entities.py
+++ b/src/azimut/engine/entities.py
@@ -446,7 +446,7 @@ ENTITY_TYPES: tuple[EntityType, ...] = (
# things to keep in step for no answer the field does not already give.
EntityType(
"equipment-type", "Equipment type", CLASS, "stack", SUBJECT, manual=True,
- hint="a model or class, counted in statements rather than owned",
+ hint="a model or class, counted in claims rather than owned",
image_gallery=True,
identity_label="Model or class",
identity_placeholder="T-72B3, ZU-23-2, Mi-8",
@@ -634,33 +634,33 @@ ENTITY_TYPES: tuple[EntityType, ...] = (
EntityType(
"claim", "Claim", CLAIM, "quote", SUBJECT, manual=True,
hint="something you are saying about the case, with its reasoning and its sources",
- identity_label="Statement",
+ identity_label="Claim",
identity_placeholder="What are you asserting?",
attrs=(
Attr(
"count", "How many", kind="number",
- hint="how many of the one thing this statement counts",
+ hint="how many of the one thing this claim counts",
minimum=1, maximum=MAX_COUNT, whole=True,
group="What it states",
),
Attr(
"condition", "Condition",
- hint="the state at the moment this statement describes",
+ hint="the state at the moment this claim describes",
kind="choice", options=ASSET_CONDITIONS,
),
Attr(
"when", "When", kind="temporal",
- hint="when this statement applies",
+ hint="when this claim applies",
group="When",
),
Attr(
"time_role", "Time role", kind="choice",
- hint="what this value means for the statement",
+ hint="what this value means for the claim",
options=CLAIM_TIME_ROLES,
),
Attr(
"confidence", "Confidence",
- hint="how strongly the statement is supported",
+ hint="how strongly the claim is supported",
kind="choice", options=CLAIM_CONFIDENCE,
group="Reasoning",
),
diff --git a/src/azimut/engine/geo.py b/src/azimut/engine/geo.py
index 2ee3704..0cca24e 100644
--- a/src/azimut/engine/geo.py
+++ b/src/azimut/engine/geo.py
@@ -445,24 +445,6 @@ def all_formats(lat: float, lon: float) -> list[dict[str, str]]:
return [{"id": i, "label": lb, "value": v} for i, lb, v in rows if v]
-# -- map links (quick-open, spec Coordinates tool preview) --------------------------
-
-
-def map_links(lat: float, lon: float, zoom: int = 17) -> dict[str, str]:
- return {
- "google": f"https://www.google.com/maps/@{lat},{lon},{zoom}z",
- "google_sat": f"https://www.google.com/maps/@{lat},{lon},2000m/data=!3m1!1e3",
- "google_earth": f"https://earth.google.com/web/@{lat},{lon},0a,1000d,35y,0h,0t,0r",
- "apple": f"https://maps.apple.com/?ll={lat},{lon}&z={zoom}&t=k",
- "osm": f"https://www.openstreetmap.org/?mlat={lat}&mlon={lon}#map={zoom}/{lat}/{lon}",
- "bing": f"https://www.bing.com/maps?cp={lat}~{lon}&lvl={zoom}&style=h",
- "yandex": f"https://yandex.com/maps/?ll={lon},{lat}&z={zoom}&l=sat",
- "sentinel": f"https://browser.dataspace.copernicus.eu/?zoom={zoom}&lat={lat}&lng={lon}",
- "zoom_earth": f"https://zoom.earth/#view={lat},{lon},{zoom}z",
- "satellites_pro": f"https://satellites.pro/#{lat},{lon},{zoom}",
- }
-
-
# -- reverse geocoding (Nominatim, polite) ------------------------------------------
diff --git a/src/azimut/engine/geoconfirmed.py b/src/azimut/engine/geoconfirmed.py
new file mode 100644
index 0000000..fc6adcc
--- /dev/null
+++ b/src/azimut/engine/geoconfirmed.py
@@ -0,0 +1,428 @@
+"""GeoConfirmed's map as an added layer, asked for by conflict, dates and area.
+
+GeoConfirmed publishes the events its volunteers geolocated, each with the
+posts it was sourced from and the geolocation that placed it, behind a
+documented read-only API that needs no key (https://geoconfirmed.org/scalar/v1).
+Three of its calls are used, all behind an act of the analyst's: the conflict
+list when the GeoConfirmed dialog opens, and a conflict's factions plus its
+filtered export when a layer is added or refreshed.
+
+**The export is the KMZ, not the JSON the site's own map loads.** It is the
+documented bulk export, filtered on GeoConfirmed's side by date and by polygon;
+it carries every pictogram inside itself, so one request dresses the whole layer
+in GeoConfirmed's own icons; and each placemark's description already holds the
+event, its sources and its geolocation, which is what the card shows. It is also
+a KMZ, so it goes through `engine/maplayers.py` like any other, and a bundle
+carries it as the bytes GeoConfirmed sent.
+
+What the KMZ does not state outright, and where `reading` finds it:
+
+- **The faction** is in the icon's path, `api/icons/<colour>/<invert>/…`, and
+ the conflict's factions name each colour. Factions sharing one are one legend
+ row named after all of them, since their marks cannot be told apart either.
+- **The date** is the placemark's name, `13 SEP 2026`. A placemark without one
+ is a reference site (a base, a plant) the export includes whatever the dates
+ asked for, so those are grouped as `UNDATED` and start switched off.
+- **The folders** file events by age relative to the day of the export ("Last 7
+ days"), which is wrong the next morning. They are replaced by the factions.
+- **The hotspot** is declared as 16,16 pixels on 56-pixel discs, which is the
+ middle of a 32-pixel icon. Honoured, it would put every event a third of an
+ icon away from its point, so the disc is centred on it instead.
+"""
+
+from __future__ import annotations
+
+import json
+import re
+from datetime import date, datetime, timedelta, timezone
+from math import isfinite
+from typing import TYPE_CHECKING, Any
+from urllib.parse import quote
+
+from .. import __version__
+from . import maplayers
+
+if TYPE_CHECKING: # pragma: no cover - typing only
+ from ..workspace import Case
+
+SITE = "https://geoconfirmed.org"
+API = f"{SITE}/api"
+
+#: GeoConfirmed asks integrations to say who they are and how to reach them, so
+#: this is not the tile proxy's generic one.
+USER_AGENT = f"Azimut/{__version__} (+https://github.com/OsintMeThat/azimut)"
+
+#: What the conflict list and a conflict's factions may weigh. Both are a few
+#: kilobytes; the bound is for a server that sends something else.
+MAX_JSON_BYTES = 2 * 1024 * 1024
+
+#: The longest window a layer may ask for by days. Ten years reaches back past
+#: the start of every conflict GeoConfirmed maps, bar the two World Wars.
+MAX_DAYS = 3650
+
+#: The group a placemark with no date lands in.
+UNDATED = "Undated sites"
+#: …and the one a mark whose colour no faction claims lands in.
+UNLISTED = "Faction not listed"
+
+#: How much of an event's first line heads its card, after the date.
+HEADING = 140
+
+#: A conflict's short name, which is what the export is addressed by.
+_CONFLICT = re.compile(r"^[A-Za-z0-9_-]{1,64}$")
+_COLOUR = re.compile(r"^#?([0-9a-fA-F]{6})$")
+_ICON_COLOUR = re.compile(r"api/icons/([0-9a-fA-F]{6})/", re.IGNORECASE)
+_DAY = re.compile(r"^(\d{1,2}) ([A-Za-z]{3}) (\d{4})$")
+#: English whatever the machine's locale, which `strptime`'s `%b` is not.
+_MONTH_NAMES = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
+_MONTHS = {month.upper(): index for index, month in enumerate(_MONTH_NAMES, start=1)}
+
+
+# ---------------------------------------------------------------------------
+# What GeoConfirmed offers
+# ---------------------------------------------------------------------------
+
+
+def conflicts() -> list[dict[str, Any]]:
+ """The public conflicts, in GeoConfirmed's own order."""
+ listed = _json(f"{API}/Conflict")
+ if not isinstance(listed, list):
+ raise maplayers.LayerFetchError("GeoConfirmed sent a conflict list this app cannot read")
+ out = []
+ for entry in sorted(
+ (entry for entry in listed if isinstance(entry, dict)), key=_order
+ ):
+ short = str(entry.get("shortName") or "")
+ if entry.get("isPrivate") or not _CONFLICT.match(short):
+ continue
+ out.append(
+ {
+ "conflict": short,
+ "name": _words(entry.get("name")) or short,
+ "start": str(entry.get("startDate") or "")[:10],
+ "end": str(entry.get("endDate") or "")[:10],
+ }
+ )
+ return out
+
+
+def _order(entry: dict[str, Any]) -> int:
+ order = entry.get("order")
+ return order if isinstance(order, int) else 0
+
+
+def conflict(short: str) -> dict[str, Any]:
+ """One conflict's name, map page and factions, the colours its marks wear."""
+ short = _checked(short)
+ detail = _json(f"{API}/Conflict/{quote(short)}")
+ if detail is None: # what GeoConfirmed answers for a name it does not know
+ raise maplayers.LayerError(f"GeoConfirmed maps no conflict called {short}")
+ if not isinstance(detail, dict):
+ raise maplayers.LayerFetchError("GeoConfirmed sent a conflict this app cannot read")
+ slug = str(detail.get("url") or "")
+ factions = []
+ for faction in detail.get("factions") or []:
+ if not isinstance(faction, dict):
+ continue
+ colour = _colour(faction.get("backgroundColor"))
+ name = _words(faction.get("name"))
+ if colour and name:
+ factions.append({"name": name, "colour": colour})
+ return {
+ "conflict": short,
+ "name": _words(detail.get("name")) or short,
+ "url": f"{SITE}/map/{quote(slug)}" if re.fullmatch(r"[A-Za-z0-9_-]+", slug) else SITE,
+ "factions": factions,
+ }
+
+
+def _json(address: str) -> Any:
+ """A JSON answer, or None for an empty one."""
+ data, _ = maplayers.download(address, limit=MAX_JSON_BYTES, user_agent=USER_AGENT)
+ if not data.strip():
+ return None
+ try:
+ return json.loads(data.decode("utf-8-sig"))
+ except (UnicodeDecodeError, json.JSONDecodeError) as exc:
+ raise maplayers.LayerFetchError("GeoConfirmed sent something that is not JSON") from exc
+
+
+def _checked(short: str) -> str:
+ short = str(short or "").strip()
+ if not _CONFLICT.match(short):
+ raise maplayers.LayerError("that is not one of GeoConfirmed's conflicts")
+ return short
+
+
+def _words(value: Any) -> str:
+ return re.sub(r"\s+", " ", str(value or "")).strip()[: maplayers.MAX_NAME]
+
+
+def _colour(value: Any) -> str:
+ match = _COLOUR.match(str(value or "").strip())
+ return f"#{match.group(1).lower()}" if match else ""
+
+
+# ---------------------------------------------------------------------------
+# The window and the area
+# ---------------------------------------------------------------------------
+
+
+def window(
+ *,
+ days: int | None = None,
+ start: str | None = None,
+ end: str | None = None,
+ everything: bool = False,
+) -> dict[str, Any]:
+ """The dates a layer asks for: the last `days`, from `start` to `end`, or all.
+
+ A number of days is counted back from the day of each read, so a layer asked
+ for "the last 30 days" is still that a month later. A range stays put.
+ """
+ if everything:
+ if days is not None or start or end:
+ raise maplayers.LayerError("ask for the whole history or for dates, not both")
+ return {"everything": True}
+ if days is not None:
+ if start or end:
+ raise maplayers.LayerError("ask for a number of days or for dates, not both")
+ if not 1 <= int(days) <= MAX_DAYS:
+ raise maplayers.LayerError(f"a window runs from 1 to {MAX_DAYS:,} days")
+ return {"days": int(days)}
+ first = _iso_day(start, "the first day")
+ if first is None:
+ raise maplayers.LayerError("pick a number of days, a first day or the whole history")
+ last = _iso_day(end, "the last day")
+ if last is not None and last < first:
+ raise maplayers.LayerError("the last day comes before the first")
+ return {"start": first.isoformat(), "end": last.isoformat() if last else ""}
+
+
+def _iso_day(value: str | None, what: str) -> date | None:
+ text = str(value or "").strip()
+ if not text:
+ return None
+ try:
+ return date.fromisoformat(text)
+ except ValueError as exc:
+ raise maplayers.LayerError(f"{what} is not a date") from exc
+
+
+def bounds(
+ spec: dict[str, Any], today: date | None = None
+) -> tuple[str | None, str | None]:
+ """The window as the export's `start` and `end`, whole days either side."""
+ today = today or datetime.now(timezone.utc).date()
+ if spec.get("everything"):
+ return None, None
+ if spec.get("days"):
+ return f"{(today - timedelta(days=int(spec['days']))).isoformat()}T00:00:00", None
+ end = spec.get("end") or ""
+ return f"{spec['start']}T00:00:00", f"{end}T23:59:59" if end else None
+
+
+def window_label(spec: dict[str, Any]) -> str:
+ """`last 30 days`, `since 1 Aug 2026`, `1 Aug – 18 Sep 2026`, `all history`."""
+ if spec.get("everything"):
+ return "all history"
+ if spec.get("days"):
+ count = int(spec["days"])
+ return "last day" if count == 1 else f"last {count} days"
+ first = date.fromisoformat(spec["start"])
+ if not spec.get("end"):
+ return f"since {_day_label(first)}"
+ last = date.fromisoformat(spec["end"])
+ if first == last:
+ return _day_label(first)
+ if first.year == last.year:
+ return f"{first.day} {_MONTH_NAMES[first.month - 1]} – {_day_label(last)}"
+ return f"{_day_label(first)} – {_day_label(last)}"
+
+
+def _day_label(day: date) -> str:
+ return f"{day.day} {_MONTH_NAMES[day.month - 1]} {day.year}"
+
+
+def area(box: list[float] | tuple[float, ...] | None) -> list[float] | None:
+ """`[west, south, east, north]`, checked, or None for the whole conflict."""
+ if box is None:
+ return None
+ if len(box) != 4 or not all(isinstance(v, (int, float)) and isfinite(v) for v in box):
+ raise maplayers.LayerError("an area is four numbers: west, south, east, north")
+ west, south, east, north = (float(v) for v in box)
+ if not (-180 <= west < east <= 180 and -90 <= south < north <= 90):
+ raise maplayers.LayerError(
+ "that area is not a box on the map — it may cross the antimeridian"
+ )
+ return [round(west, 6), round(south, 6), round(east, 6), round(north, 6)]
+
+
+def request(
+ spec: dict[str, Any], box: list[float] | None, today: date | None = None
+) -> dict[str, Any]:
+ """The export's JSON body: the window, and the area as one GeoJSON polygon."""
+ start, end = bounds(spec, today)
+ polygons = None
+ if box:
+ west, south, east, north = box
+ ring = [[west, south], [east, south], [east, north], [west, north], [west, south]]
+ polygons = [[ring]]
+ return {"start": start, "end": end, "polygons": polygons}
+
+
+# ---------------------------------------------------------------------------
+# Adding and re-reading
+# ---------------------------------------------------------------------------
+
+
+def subscribe(
+ case: "Case",
+ short: str,
+ *,
+ days: int | None = None,
+ start: str | None = None,
+ end: str | None = None,
+ everything: bool = False,
+ box: list[float] | None = None,
+ on_open: bool | None = None,
+) -> dict[str, Any]:
+ """One conflict, over a window and optionally an area, as a layer of this case.
+
+ `on_open` left unset re-reads a window the first time it is switched on in a
+ session, but not the whole history: for Ukraine that is 6 MB and some six
+ seconds each time, for a map that changes by a few dozen events a day.
+ Refresh still reads it on demand.
+ """
+ spec = window(days=days, start=start, end=end, everything=everything)
+ source: dict[str, Any] = {
+ "kind": maplayers.GEOCONFIRMED,
+ "conflict": _checked(short),
+ "window": spec,
+ "area": area(box),
+ }
+ if on_open is None:
+ on_open = not spec.get("everything")
+ data, source = read_again(source)
+ title = f"GeoConfirmed · {source['label']} · {window_label(source['window'])}"
+ parsed = maplayers.parse(
+ data, filename=source["name"], title=title, reading=reading(source)
+ )
+ return maplayers.add_source(
+ case,
+ data,
+ parsed,
+ source=source,
+ title=title,
+ # GeoConfirmed's own pictograms, which cost nothing: they are inside the
+ # export, so no request is made for any of them.
+ icons=True,
+ on_open=on_open,
+ # The analyst asked for dates, and these have none.
+ hidden=(UNDATED,),
+ )
+
+
+def read_again(source: dict[str, Any]) -> tuple[bytes, dict[str, Any]]:
+ """The export for a layer's query, and its source updated to match.
+
+ The factions are read each time as well: a conflict gains one now and then,
+ and a colour nobody claims would otherwise land in `UNLISTED` for good.
+ """
+ detail = conflict(str(source.get("conflict") or ""))
+ body = request(source.get("window") or {}, source.get("area"))
+ data, filename = maplayers.download(
+ f"{API}/Map/export/{quote(detail['conflict'])}", body=body, user_agent=USER_AGENT
+ )
+ return data, {
+ **source,
+ "label": detail["name"],
+ "url": detail["url"],
+ "factions": detail["factions"],
+ "name": filename or f"{detail['conflict']}.kmz",
+ "format": "kmz",
+ }
+
+
+# ---------------------------------------------------------------------------
+# Reading the export
+# ---------------------------------------------------------------------------
+
+
+def reading(source: dict[str, Any]) -> "maplayers.Reading":
+ """GeoConfirmed's reading of its own KMZ, for `maplayers.parse`."""
+ names = _faction_names(source.get("factions") or [])
+
+ def read(
+ features: list[dict[str, Any]], icons: dict[str, dict[str, Any]]
+ ) -> dict[str, dict[str, Any]]:
+ centred = {}
+ for key, descriptor in icons.items():
+ moved = {**descriptor, "hotspot": None}
+ centred[key] = (maplayers.icon_key(moved), moved)
+ for feature in features:
+ properties = feature["properties"]
+ href = str((icons.get(properties["icon"]) or {}).get("href") or "")
+ match = _ICON_COLOUR.search(href)
+ colour = f"#{match.group(1).lower()}" if match else ""
+ day = _day(properties["name"])
+ dated = day is not None
+ properties["category"] = (
+ names.get(colour, UNLISTED) if dated else UNDATED
+ )
+ if day is not None:
+ properties["date"] = day.isoformat()
+ properties["colour"] = colour
+ properties["name"], properties["description"] = _heading(
+ properties["name"] if dated else "", properties["description"]
+ )
+ if properties["icon"] in centred:
+ properties["icon"] = centred[properties["icon"]][0]
+ return dict(centred.values())
+
+ return read
+
+
+def _faction_names(factions: list[dict[str, Any]]) -> dict[str, str]:
+ """colour → the factions wearing it, in GeoConfirmed's order."""
+ wearing: dict[str, list[str]] = {}
+ for faction in factions:
+ colour = _colour(faction.get("colour"))
+ name = _words(faction.get("name"))
+ if colour and name and name not in wearing.get(colour, []):
+ wearing.setdefault(colour, []).append(name)
+ return {colour: " / ".join(names) for colour, names in wearing.items()}
+
+
+def _day(name: str) -> date | None:
+ match = _DAY.match(str(name or "").strip())
+ if not match:
+ return None
+ month = _MONTHS.get(match.group(2).upper())
+ if month is None:
+ return None
+ try:
+ return date(int(match.group(3)), month, int(match.group(1)))
+ except ValueError:
+ return None
+
+
+def _heading(day: str, description: str) -> tuple[str, str]:
+ """What the card and the search call an event, and what is left to read.
+
+ The date alone says nothing to someone searching for a town, so the event's
+ first line joins it; when it fits whole it is taken out of the body rather
+ than said twice.
+ """
+ lines = str(description or "").split("\n")
+ first = lines[0].strip()
+ if first.endswith(":"): # a section heading such as "Source(s):", not the event
+ first = ""
+ if not first:
+ return day, description
+ if len(first) <= HEADING:
+ heading = f"{day} · {first}" if day else first
+ return heading[: maplayers.MAX_NAME], "\n".join(lines[1:]).strip()
+ cut = first[:HEADING].rsplit(" ", 1)[0].rstrip(" ,;:.")
+ heading = f"{day} · {cut}…" if day else f"{cut}…"
+ return heading, description
diff --git a/src/azimut/engine/graph.py b/src/azimut/engine/graph.py
index e90458f..5b490d0 100644
--- a/src/azimut/engine/graph.py
+++ b/src/azimut/engine/graph.py
@@ -262,7 +262,7 @@ def lenses() -> tuple[Lens, ...]:
CASE_ROLES,
),
Lens(
- "claims", "Statements",
+ "claims", "Claims",
"what is asserted, and what it rests on",
_relation_verbs(lambda e: e.action == "claim"),
CASE_ROLES,
diff --git a/src/azimut/engine/links.py b/src/azimut/engine/links.py
index 156ca1f..e8cf475 100644
--- a/src/azimut/engine/links.py
+++ b/src/azimut/engine/links.py
@@ -393,7 +393,7 @@ RELATION_TYPES: tuple[RelationType, ...] = (
RelationType(
ABOUT, "is about",
inverse_label="has claim",
- hint="what the statement concerns",
+ hint="what the claim concerns",
from_families=frozenset({entities.CLAIM}),
# `class` is here because a counted statement has nowhere else to point: "two
# of these were destroyed" is about the model, not about two objects nobody
@@ -408,7 +408,7 @@ RELATION_TYPES: tuple[RelationType, ...] = (
RelationType(
AT, "places it at",
inverse_label="is a claim location",
- hint="where the statement places its subject or event",
+ hint="where the claim places its subject or event",
from_families=frozenset({entities.CLAIM}),
to_families=frozenset({entities.PLACE}),
action="claim",
@@ -417,7 +417,7 @@ RELATION_TYPES: tuple[RelationType, ...] = (
RelationType(
CITES, "cites",
inverse_label="supports claim",
- hint="the evidence the statement relies on",
+ hint="the evidence the claim relies on",
from_families=frozenset({entities.CLAIM}),
# A statement rests on material, and it may rest on **another statement**: an
# intermediate conclusion is what the next one is built out of. Without it a
@@ -452,7 +452,7 @@ RELATION_TYPES: tuple[RelationType, ...] = (
RelationType(
CONTRADICTS, "contradicts",
inverse_label="is contradicted by",
- hint="the two statements cannot both hold",
+ hint="the two claims cannot both hold",
from_families=frozenset({entities.CLAIM}),
to_families=frozenset({entities.CLAIM}),
action="claim",
diff --git a/src/azimut/engine/maplayers.py b/src/azimut/engine/maplayers.py
index e5b0bd7..b3f1672 100644
--- a/src/azimut/engine/maplayers.py
+++ b/src/azimut/engine/maplayers.py
@@ -51,10 +51,10 @@ import json
import re
import zipfile
from collections import Counter
-from datetime import datetime, timedelta, timezone
+from datetime import date, datetime, timedelta, timezone
from io import BytesIO
from pathlib import Path
-from typing import TYPE_CHECKING, Any, Iterator
+from typing import TYPE_CHECKING, Any, Callable, Iterator
from urllib.parse import unquote
import httpx
@@ -109,9 +109,16 @@ MAX_HREF = 2_000
#: How many distinct pictograms one layer stores. A source declares one style per
#: (icon, colour) pair its creator used, which is a couple of dozen for a busy My
-#: Maps. Past this the rest fall back to the app's own shapes rather than the
-#: layer being refused: the marks are the map, the icons are how it was dressed.
-MAX_ICONS = 64
+#: Maps and a few hundred for GeoConfirmed's Ukraine map, one per faction and
+#: event type. Past this the rest fall back to the app's own shapes rather than
+#: the layer being refused: the marks are the map, the icons are how it was
+#: dressed.
+MAX_ICONS = 512
+
+#: …and how many of them may be read off the web, one request each. An icon inside
+#: a KMZ costs a zip lookup; one at an address is a request to somebody else's
+#: server, and that is what this bounds.
+MAX_FETCHED_ICONS = 64
#: What one icon may weigh on the wire, and what a layer's icons may weigh
#: together. Both are checked as the bytes arrive, because a server is free to
@@ -219,7 +226,15 @@ def _suffix(filename: str) -> str:
# ---------------------------------------------------------------------------
-def parse(data: bytes, *, filename: str = "", title: str = "") -> dict[str, Any]:
+#: A publisher's own reading of its file, run over the features before the legend
+#: is counted: it may rename, regroup and recolour them in place, and returns the
+#: icon descriptions to keep. GeoConfirmed's is `engine/geoconfirmed.reading`.
+Reading = Callable[[list[dict[str, Any]], dict[str, dict[str, Any]]], dict[str, dict[str, Any]]]
+
+
+def parse(
+ data: bytes, *, filename: str = "", title: str = "", reading: Reading | None = None
+) -> dict[str, Any]:
"""Bytes as received → `{geojson, summary, icons}`, or `LayerError` with a reason.
Pure: it reads no file, reaches no network and writes nothing. A caller
@@ -261,6 +276,8 @@ def parse(data: bytes, *, filename: str = "", title: str = "") -> dict[str, Any]
if not features:
raise LayerError("the file holds no points, lines or areas")
+ if reading is not None:
+ icons = reading(features, icons)
return _collection(
features, title=title or name or _stem(filename), fmt=source_format, icons=icons
)
@@ -401,19 +418,45 @@ def _properties(
category: str = "",
colour: str = "",
icon: str = "",
+ date: str = "",
) -> dict[str, Any]:
- """The five fields every feature carries, whatever it was read from.
+ """The five fields every feature carries, whatever it was read from, and a
+ sixth when the source dated it.
`icon` names a stored pictogram rather than holding an address: the browser
- is told which image to draw, never where the source kept it.
+ is told which image to draw, never where the source kept it. `date` is a day,
+ `YYYY-MM-DD`, which is what the row's time filter compares; absent rather
+ than empty, since most layers state none and a map may hold 100,000 features.
"""
- return {
+ properties = {
"name": _text(name, MAX_NAME),
"description": _rich_text(description, MAX_DESCRIPTION),
"category": _text(category, MAX_NAME) or UNGROUPED,
"colour": colour or "",
"icon": icon or "",
}
+ day = iso_day(date)
+ if day:
+ properties["date"] = day
+ return properties
+
+
+_ISO_DAY = re.compile(r"^\s*(\d{4}-\d{2}-\d{2})")
+
+
+def iso_day(value: Any) -> str:
+ """The day a timestamp falls on, `YYYY-MM-DD`, or "" for anything else.
+
+ Read off the front of the string, so `2024-05-10T14:03:00Z` is that day as
+ written: a source's own clock is not second-guessed into another timezone.
+ """
+ match = _ISO_DAY.match(str(value or ""))
+ if not match:
+ return ""
+ try:
+ return date.fromisoformat(match.group(1)).isoformat()
+ except ValueError:
+ return ""
_HEX = re.compile(r"^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$")
@@ -792,6 +835,7 @@ def _placemark(
description = _kml_extended_data(element)
style = _kml_style(element, styles)
colour = str(style.get("colour") or "")
+ day = _kml_day(element)
icon = _icon_of(style)
key = ""
if icon is not None:
@@ -812,11 +856,23 @@ def _placemark(
# only a point draws a pictogram; a line and an area are
# drawn by their own stroke and fill
icon=key if _kind(geometry) == "point" else "",
+ date=day,
),
}
)
+def _kml_day(element: Element) -> str:
+ """When a placemark says it happened: a TimeStamp, else where a TimeSpan starts."""
+ stamp = _child(element, "TimeStamp")
+ if stamp is not None:
+ return iso_day(_child_text(stamp, "when"))
+ span = _child(element, "TimeSpan")
+ if span is not None:
+ return iso_day(_child_text(span, "begin"))
+ return ""
+
+
def _kml_extended_data(element: Element) -> str:
"""A My Maps puts its columns here rather than in the description."""
data = _child(element, "ExtendedData")
@@ -949,8 +1005,13 @@ def _icon_of(style: dict[str, Any]) -> tuple[str, dict[str, Any]] | None:
"scale": float(style.get("scale") or 1.0),
"hotspot": list(style["hotspot"]) if style.get("hotspot") else None,
}
+ return icon_key(descriptor), descriptor
+
+
+def icon_key(descriptor: dict[str, Any]) -> str:
+ """The name a pictogram is stored under: the hash of what decides its pixels."""
seed = json.dumps(descriptor, sort_keys=True).encode("utf-8")
- return hashlib.sha256(seed).hexdigest()[:ICON_KEY_LENGTH], descriptor
+ return hashlib.sha256(seed).hexdigest()[:ICON_KEY_LENGTH]
def _kml_abgr(value: str) -> str:
@@ -1090,7 +1151,10 @@ def _from_gpx(data: bytes) -> tuple[list[dict[str, Any]], str]:
"type": "Feature",
"geometry": {"type": "Point", "coordinates": point},
"properties": _properties(
- name=name, description=description, category=category
+ name=name,
+ description=description,
+ category=category,
+ date=_child_text(child, "time"),
),
}
)
@@ -1168,9 +1232,14 @@ def icon_images(
archive = _icon_archive(source)
out: dict[str, bytes] = {}
total = 0
+ fetched = 0
try:
for key in list(descriptors)[:MAX_ICONS]:
descriptor = descriptors[key]
+ if _on_the_web(descriptor):
+ if fetched >= MAX_FETCHED_ICONS:
+ continue
+ fetched += 1
raw = _icon_bytes(descriptor, archive)
if not raw:
continue
@@ -1197,12 +1266,16 @@ def _icon_archive(source: bytes) -> zipfile.ZipFile | None:
return None
+def _on_the_web(descriptor: dict[str, Any]) -> bool:
+ return str(descriptor.get("href") or "").lower().startswith(("http://", "https://"))
+
+
def _icon_bytes(
descriptor: dict[str, Any], archive: zipfile.ZipFile | None
) -> bytes:
"""The image a descriptor points at: out of the archive, or off the web."""
href = str(descriptor.get("href") or "")
- if href.lower().startswith(("http://", "https://")):
+ if _on_the_web(descriptor):
return _fetch_icon(href)
return _zipped_icon(archive, href) if archive is not None else b""
@@ -1445,7 +1518,7 @@ SPEC_VERSION = 1
#: the day it was dropped in, for as long as the case lives. Bumped whenever a
#: change here would give the same bytes a different reading; the next request
#: for that layer reparses the snapshot already on disk.
-PARSE_VERSION = 2
+PARSE_VERSION = 3
#: Where that stamp is written. A GeoJSON object may carry members it does not
#: define, and this one is written first so the check reads the head of the file
@@ -1495,6 +1568,24 @@ class LayerFetchError(LayerError):
that will never be readable: the last snapshot stays on the map."""
+#: A layer asked of GeoConfirmed by conflict, dates and area rather than by
+#: address (`engine/geoconfirmed.py`).
+GEOCONFIRMED = "geoconfirmed"
+
+#: The sources a layer follows rather than holds: re-read on Refresh and on case
+#: open, and stale when that was too long ago. A file is never either.
+FOLLOWED = ("url", GEOCONFIRMED)
+
+
+def _reading(source: dict[str, Any]) -> Reading | None:
+ """The publisher's own reading of this source's bytes, where it has one."""
+ if source.get("kind") != GEOCONFIRMED:
+ return None
+ from . import geoconfirmed # it imports this module, so not at the top
+
+ return geoconfirmed.reading(source)
+
+
def my_maps_mid(url: str) -> str:
"""The map id out of any My Maps link, or "" when it is not one."""
match = _MY_MAPS.match(str(url or "").strip())
@@ -1646,7 +1737,12 @@ def drawing(case: "Case", name: str) -> Path:
data = snapshot.read_bytes()
except OSError as exc:
raise LayerError("this layer's saved copy is missing") from exc
- parsed = parse(data, filename=_source_name(spec), title=spec.get("title", ""))
+ parsed = parse(
+ data,
+ filename=_source_name(spec),
+ title=spec.get("title", ""),
+ reading=_reading(spec.get("source") or {}),
+ )
return _write_cache(case, name, parsed["geojson"])
@@ -1671,25 +1767,8 @@ def add_file(
need the network, and following a link does.
"""
parsed = parse(data, filename=filename, title=title or "")
- summary = parsed["summary"]
- name = _free_name(case, title or summary["title"])
- spec = {
- "azimut_layer": SPEC_VERSION,
- "title": summary["title"],
- "source": {"kind": "file", "name": filename, "format": summary["format"]},
- "enabled": True,
- "hidden": [],
- # What the analyst asked for at import, kept so a refresh composes the
- # same layer again rather than a differently dressed one.
- "source_icons": bool(icons),
- "created_at": _now(),
- "updated_at": _now(),
- "summary": summary,
- "snapshot": _store(case, name, data, parsed, icons=bool(icons)),
- }
- _write_spec(case, name, spec)
- _file_entity(case, name, spec)
- return row(name, spec)
+ source = {"kind": "file", "name": filename, "format": parsed["summary"]["format"]}
+ return add_source(case, data, parsed, source=source, title=title, icons=icons)
def subscribe(
@@ -1706,30 +1785,56 @@ def subscribe(
raise LayerError("a subscribed layer needs an http or https address")
data, filename = fetch(address)
parsed = parse(data, filename=filename, title=title or "")
+ source = {
+ "kind": "url",
+ "url": address,
+ "feed": feed_url(address),
+ "name": filename,
+ "format": parsed["summary"]["format"],
+ "my_maps": bool(my_maps_mid(address)),
+ }
+ return add_source(
+ case, data, parsed, source=source, title=title, icons=icons, on_open=on_open
+ )
+
+
+def add_source(
+ case: "Case",
+ data: bytes,
+ parsed: dict[str, Any],
+ *,
+ source: dict[str, Any],
+ title: str | None,
+ icons: bool,
+ on_open: bool | None = None,
+ hidden: tuple[str, ...] = (),
+) -> dict[str, Any]:
+ """File a parsed source as a layer of this case: its spec, its files, its node.
+
+ `on_open` is for a followed source only, and `hidden` names the groups that
+ start switched off — only those the source actually holds.
+ """
summary = parsed["summary"]
name = _free_name(case, title or summary["title"])
- spec = {
+ live = {entry["name"] for entry in summary["categories"]}
+ spec: dict[str, Any] = {
"azimut_layer": SPEC_VERSION,
"title": summary["title"],
- "source": {
- "kind": "url",
- "url": address,
- "feed": feed_url(address),
- "name": filename,
- "format": summary["format"],
- "my_maps": bool(my_maps_mid(address)),
- },
- # Refreshing on case open is what "subscribed" means; turning it off
- # leaves a layer that only moves when the analyst presses Refresh.
- "refresh": {"on_open": bool(on_open)},
- "enabled": True,
- "hidden": [],
+ "source": source,
+ "hidden": sorted(set(hidden) & live),
+ # What the analyst asked for at import, kept so a refresh composes the
+ # same layer again rather than a differently dressed one.
"source_icons": bool(icons),
"created_at": _now(),
"updated_at": _now(),
"summary": summary,
"snapshot": _store(case, name, data, parsed, icons=bool(icons)),
}
+ if on_open is not None:
+ # Re-read the first time it is switched on in a session, which is what
+ # "subscribed" means; off leaves a layer that only moves on Refresh.
+ # Named for when it began as "on case open", kept so no case migrates.
+ spec["refresh"] = {"on_open": bool(on_open)}
_write_spec(case, name, spec)
_file_entity(case, name, spec)
return row(name, spec)
@@ -1741,19 +1846,35 @@ def refresh(case: "Case", name: str) -> dict[str, Any]:
An unchanged feed rewrites nothing: same bytes, same sha256, and the row
only learns that it was checked. A fetch that fails leaves the last snapshot
exactly where it was — the layer stays on the map, saying how old it is.
+
+ For GeoConfirmed the bytes are half of it: the factions that name the
+ legend are read beside the export, and a faction added since is a reason
+ to read the same bytes again.
"""
spec = _read_spec(case, name)
- source = spec.get("source") or {}
- if source.get("kind") != "url":
+ before = spec.get("source") or {}
+ if before.get("kind") not in FOLLOWED:
raise LayerError("this layer came from a file, so there is nothing to refresh")
- data, _ = fetch(str(source.get("url") or ""))
+ source = before
+ if before.get("kind") == GEOCONFIRMED:
+ from . import geoconfirmed
+
+ data, source = geoconfirmed.read_again(before)
+ spec["source"] = source
+ else:
+ data, _ = fetch(str(before.get("url") or ""))
snapshot = spec.get("snapshot") or {}
now = _now()
- if digest(data) == snapshot.get("sha256"):
+ if digest(data) == snapshot.get("sha256") and source == before:
spec["snapshot"] = {**snapshot, "checked_at": now}
else:
- parsed = parse(data, filename=_source_name(spec), title=spec.get("title", ""))
+ parsed = parse(
+ data,
+ filename=_source_name(spec),
+ title=spec.get("title", ""),
+ reading=_reading(source),
+ )
spec["summary"] = parsed["summary"]
spec["snapshot"] = {
**_store(case, name, data, parsed, icons=bool(spec.get("source_icons"))),
@@ -1771,19 +1892,35 @@ def update(
case: "Case",
name: str,
*,
- enabled: bool | None = None,
hidden: list[str] | None = None,
+ period: tuple[str, str] | None = None,
on_open: bool | None = None,
title: str | None = None,
) -> dict[str, Any]:
- """What the analyst set on the row: the switch, the legend, the policy."""
+ """What the analyst set on the row that outlives the session: the legend,
+ the time filter, the refresh policy and the title.
+
+ `period` is a first and a last day, either of them "" for no bound, and both
+ "" to clear it. It is kept whatever the layer's own dates: a refresh can move
+ those, and the filter is the analyst's question rather than a fact about the
+ data.
+
+ Not the switch. Whether a layer is drawn lives in the page and starts off on
+ every load, so a layer that crashed the tab is not drawn again by the reload.
+ """
spec = _read_spec(case, name)
- if enabled is not None:
- spec["enabled"] = bool(enabled)
if hidden is not None:
live = {entry["name"] for entry in (spec.get("summary") or {}).get("categories", [])}
spec["hidden"] = sorted({str(entry) for entry in hidden} & live)
- if on_open is not None and (spec.get("source") or {}).get("kind") == "url":
+ if period is not None:
+ start, end = iso_day(period[0]), iso_day(period[1])
+ if start and end and end < start:
+ start, end = end, start
+ if start or end:
+ spec["period"] = {"start": start, "end": end}
+ else:
+ spec.pop("period", None)
+ if on_open is not None and (spec.get("source") or {}).get("kind") in FOLLOWED:
spec["refresh"] = {**(spec.get("refresh") or {}), "on_open": bool(on_open)}
if title:
spec["title"] = _text(title, MAX_NAME) or spec["title"]
@@ -1826,8 +1963,9 @@ def row(name: str, spec: dict[str, Any]) -> dict[str, Any]:
"name": name,
"title": spec.get("title") or name,
"source": source,
- "enabled": bool(spec.get("enabled", True)),
"hidden": list(spec.get("hidden") or []),
+ # the time filter, `{start, end}`, either bound "" when open
+ "period": spec.get("period") or None,
"refresh": spec.get("refresh") or {},
"features": int(summary.get("features") or 0),
"categories": summary.get("categories") or [],
@@ -1840,7 +1978,7 @@ def row(name: str, spec: dict[str, Any]) -> dict[str, Any]:
"bytes": int(snapshot.get("bytes") or 0),
"fetched_at": snapshot.get("at") or "",
"checked_at": at,
- "stale": source.get("kind") == "url" and _stale(at),
+ "stale": source.get("kind") in FOLLOWED and _stale(at),
"created_at": spec.get("created_at") or "",
"updated_at": spec.get("updated_at") or "",
"spec": layout.layer_spec_rel(name),
@@ -1876,7 +2014,7 @@ def _file_entity(case: "Case", name: str, spec: dict[str, Any]) -> str:
return str(existing["id"])
source = spec.get("source") or {}
attrs = {"spec": rel, "format": spec.get("summary", {}).get("format", "")}
- if source.get("kind") == "url":
+ if source.get("kind") in FOLLOWED:
attrs["source_url"] = source.get("url", "")
return str(case.add_entity(ENTITY_TYPE, spec["title"], attrs=attrs, by="map-layers")["id"])
@@ -1890,35 +2028,50 @@ def fetch(url: str) -> tuple[bytes, str]:
"""Read a remote source, bounded, and say what it was called.
Nothing here runs on a timer. This is reached from adding a subscription,
- from pressing Refresh, and from opening a case that holds an enabled layer
- set to refresh on open — three acts, all of them the analyst's.
+ from pressing Refresh, and from switching a layer on for the first time in a
+ session when it asked to be re-read then — three acts, all of them the
+ analyst's.
"""
address = feed_url(url)
if not address.lower().startswith(("http://", "https://")):
raise LayerFetchError("a subscribed layer needs an http or https address")
+ return download(address)
+
+
+def download(
+ address: str,
+ *,
+ body: dict[str, Any] | None = None,
+ limit: int = MAX_FETCH_BYTES,
+ user_agent: str = USER_AGENT,
+) -> tuple[bytes, str]:
+ """One bounded request: a GET, or a POST of `body` as JSON.
+
+ The size is checked against the declared length before a byte is read and
+ again as the bytes arrive, since a server is free to lie about either.
+ """
try:
with httpx.stream(
- "GET",
+ "GET" if body is None else "POST",
address,
+ json=body,
timeout=FETCH_TIMEOUT,
follow_redirects=True,
- headers={"User-Agent": USER_AGENT},
+ headers={"User-Agent": user_agent},
) as response:
response.raise_for_status()
declared = response.headers.get("content-length")
- if declared and declared.isdigit() and int(declared) > MAX_FETCH_BYTES:
+ if declared and declared.isdigit() and int(declared) > limit:
raise LayerFetchError(
f"that source is {_megabytes(int(declared))} — the limit is "
- f"{_megabytes(MAX_FETCH_BYTES)}"
+ f"{_megabytes(limit)}"
)
chunks: list[bytes] = []
total = 0
for chunk in response.iter_bytes():
total += len(chunk)
- if total > MAX_FETCH_BYTES:
- raise LayerFetchError(
- f"that source is over {_megabytes(MAX_FETCH_BYTES)}"
- )
+ if total > limit:
+ raise LayerFetchError(f"that source is over {_megabytes(limit)}")
chunks.append(chunk)
name = _filename(response.headers.get("content-disposition"), address)
return b"".join(chunks), name
diff --git a/src/azimut/engine/sheetclaims.py b/src/azimut/engine/sheetclaims.py
index 051a59a..229715f 100644
--- a/src/azimut/engine/sheetclaims.py
+++ b/src/azimut/engine/sheetclaims.py
@@ -274,7 +274,7 @@ def plan(
if column and column not in columns:
raise SheetError(f"this sheet has no column '{column}'")
if subject_column not in columns:
- raise SheetError("a statement needs the column naming what it is about")
+ raise SheetError("a claim needs the column naming what it is about")
roles = (meta.get("roles") or {}) if isinstance(meta, dict) else {}
links = (meta.get("links") or {}) if isinstance(meta, dict) else {}
@@ -329,7 +329,7 @@ def plan(
decision["reason"] = f"'{said or identity}' is not in the case yet"
continue
if not _about_takes(str(held.get("type"))):
- decision["reason"] = f"a statement cannot be about a {held.get('type')}"
+ decision["reason"] = f"a claim cannot be about a {held.get('type')}"
continue
decision["subject_label"] = str(held.get("label") or said)
diff --git a/src/azimut/layout.py b/src/azimut/layout.py
index 34771d9..d7d1854 100644
--- a/src/azimut/layout.py
+++ b/src/azimut/layout.py
@@ -58,9 +58,9 @@ COMPARE_DIR = ".compare"
ANALYSIS_DIR = ".analysis"
#: Saved Grid Search state.
SEARCH_DIR = ".search"
-#: Map layers the analyst added themselves: a file they opened, or a URL they
-#: subscribed to. Hidden because they did not author the data — the row in the
-#: Layers panel is where it is worked with, and it offers to reveal the file.
+#: Map layers the analyst added themselves: a file they opened, a URL they
+#: subscribed to, or a GeoConfirmed query. Hidden because they did not author the
+#: data — the row in the Layers panel is where it is worked with.
LAYERS_DIR = ".layers"
#: The parsed GeoJSON a layer is drawn from. Derived from the snapshot beside
#: it, so it is dropped on delete and rebuilt on demand rather than carried.
diff --git a/src/azimut/server.py b/src/azimut/server.py
index f77710c..8c3a664 100644
--- a/src/azimut/server.py
+++ b/src/azimut/server.py
@@ -307,6 +307,7 @@ def create_app() -> FastAPI:
app.include_router(analyzers.router)
app.include_router(satellite.router)
app.include_router(maplayers.router)
+ app.include_router(maplayers.geoconfirmed_router)
app.include_router(proofs.router)
app.include_router(proofimports.router)
app.include_router(drafts.router)
@@ -348,7 +349,9 @@ def create_app() -> FastAPI:
candidate = (STATIC_DIR / path).resolve()
if path and candidate.is_file() and candidate.is_relative_to(STATIC_DIR.resolve()):
return FileResponse(candidate)
- return FileResponse(STATIC_DIR / "index.html")
+ # Asked for again on every visit: it names this build's hashed
+ # bundles, and a copy kept past an update names ones that are gone.
+ return FileResponse(STATIC_DIR / "index.html", headers={"Cache-Control": "no-cache"})
else: # dev without a built frontend: make it obvious, not broken
diff --git a/tests/test_compare_api.py b/tests/test_compare_api.py
index 4e73652..3ca5c0a 100644
--- a/tests/test_compare_api.py
+++ b/tests/test_compare_api.py
@@ -117,6 +117,10 @@ def test_compare_session_roundtrip_rename_and_sidebar_delete(client):
"points": [[2.2945, 48.8584]], "text": "Before"},
{"id": "yard", "kind": "polygon", "colour": "#22c55e",
"points": [[2.29, 48.85], [2.30, 48.85], [2.30, 48.86]], "fill_opacity": 0.2},
+ {"id": "one", "kind": "number", "colour": "#ef4444",
+ "points": [[2.2946, 48.8585]], "number": 2, "font_size": 20},
+ {"id": "truck", "kind": "icon", "colour": "#38bdf8",
+ "points": [[2.2947, 48.8586]], "glyph": "vehicle"},
]
saved = _save(client, cid, "Harbour change", spec)
assert saved.status_code == 200, saved.text
@@ -148,6 +152,9 @@ def test_compare_session_roundtrip_rename_and_sidebar_delete(client):
assert loaded["spec"]["blink"] == {"interval": 1200}
assert loaded["spec"]["annotations"][0]["side"] == "a"
assert loaded["spec"]["annotations"][1]["points"][2] == [2.30, 48.86]
+ # the two stamps: one press, one point, and what each one carries
+ assert loaded["spec"]["annotations"][2]["number"] == 2
+ assert loaded["spec"]["annotations"][3]["glyph"] == "vehicle"
entity = _entities(cid, "compare-session")[0]
renamed = _save(client, cid, "Harbour after", rename_from="Harbour change")
@@ -181,6 +188,13 @@ def test_compare_session_roundtrip_rename_and_sidebar_delete(client):
lambda spec: spec.update(frame={"points": [[2, 48], [2, 48]]}),
lambda spec: spec.update(frame={"points": [[2, 48], [200, 48]]}),
lambda spec: spec.update(change_assist={"method": "ratio"}),
+ # a stamp is one point, and its number is a count rather than a label
+ lambda spec: spec.update(annotations=[{
+ "id": "x", "kind": "number", "colour": "#ffffff", "points": [[2, 48], [3, 48]],
+ }]),
+ lambda spec: spec.update(annotations=[{
+ "id": "x", "kind": "icon", "colour": "#ffffff", "points": [[2, 48]], "number": 0,
+ }]),
],
)
def test_compare_session_refuses_what_it_cannot_reopen(client, mutate):
@@ -254,7 +268,7 @@ def test_change_assist_accepts_comparable_pairs(client, a, b, method):
("a", "b", "method", "reason"),
[
(_side("esri-world-imagery"), _side("osm"), "colour", "reads Sentinel-2"),
- (_side("esri-wayback", wayback_release=146), _side("esri-wayback", wayback_release=146), "colour", "different Esri"),
+ (_side("esri-wayback", wayback_release=146), _side("esri-wayback", wayback_release=146), "colour", "same picture"),
(
_side("esri-wayback", wayback_release=145, overlays=["roads"]),
_side("esri-wayback", wayback_release=146),
diff --git a/tests/test_entities.py b/tests/test_entities.py
index 24538f9..ae9994d 100644
--- a/tests/test_entities.py
+++ b/tests/test_entities.py
@@ -621,6 +621,27 @@ def test_mentions_are_a_separate_action_from_relations(client):
assert rows["owns"]["ratable"] is True
+def test_a_quick_claim_seats_each_type_the_way_its_form_expects(client):
+ """The quick claim form seats the entity it is filed from on the first of
+ `at`, `cites`, `about` that takes it (`frontend/src/lib/quickClaim.js`, whose
+ test copies these answers). Pinned here so a verb table change that would move
+ a place off `at` or a video off `cites` fails where the table lives."""
+ rows = {row["type"]: row for row in client.get("/api/cases/relation-types").json()}
+
+ def seats(type_):
+ return {verb for verb in ("about", "at", "cites") if type_ in rows[verb]["to_types"]}
+
+ assert seats("equipment-type") == {"about"}
+ assert seats("vehicle") == {"about"}
+ assert seats("person") == {"about"}
+ assert seats("account") == {"about"}
+ assert seats("place") == {"about", "at"}
+ assert seats("media") == {"about", "cites"}
+ assert seats("proof") == {"cites"}
+ assert seats("claim") == {"cites"}
+ assert seats("post") == set()
+
+
def test_an_order_of_battle_is_part_of_edges_between_organizations(client):
"""The tree an OSINT conflict case is built on: a battalion inside a brigade
inside a corps. `owns` would read wrong — a brigade commands its battalions
diff --git a/tests/test_geo_api.py b/tests/test_geo_api.py
index 8cfb9f3..96c4993 100644
--- a/tests/test_geo_api.py
+++ b/tests/test_geo_api.py
@@ -107,7 +107,7 @@ def test_geocode_network_failure_is_404(client, monkeypatch):
# -- /api/geo/parse: pure offline conversion, no network -------------------------------
-def test_parse_returns_every_format_and_the_map_links(client):
+def test_parse_returns_every_format(client):
result = client.post("/api/geo/parse", json={"text": "48.8583701, 2.2944813"}).json()
assert result["lat"] == pytest.approx(48.8583701)
assert result["lon"] == pytest.approx(2.2944813)
@@ -118,8 +118,8 @@ def test_parse_returns_every_format_and_the_map_links(client):
assert [f["id"] for f in result["formats"]] == [
"dd", "ddm", "dms", "utm", "mgrs", "plus_code", "geohash",
]
- # all nine external maps, keyed by site
- assert set(result["links"]) >= {"google", "yandex", "bing", "sentinel"}
+ # map links are built in the browser (lib/maplinks.js), from one verified table
+ assert "links" not in result
def test_parse_accepts_the_formats_it_emits(client):
diff --git a/tests/test_geoconfirmed.py b/tests/test_geoconfirmed.py
new file mode 100644
index 0000000..50b6edb
--- /dev/null
+++ b/tests/test_geoconfirmed.py
@@ -0,0 +1,521 @@
+"""GeoConfirmed as an added layer.
+
+Three things this has to get right, and they are what the tests are grouped by:
+
+- **the export reads as GeoConfirmed means it**: factions from the icon colours,
+ a date on every event, the undated reference sites apart, the discs centred;
+- **the query is what the analyst asked**: a window of days that slides, a range
+ that stays put, an area that becomes one polygon, and refusals in a sentence;
+- **the network boundary holds**: GeoConfirmed is asked on adding, on Refresh and
+ for the conflict list, and never on a listing or a redraw.
+
+Every GeoConfirmed answer here is built in the test. Nothing reaches the network.
+"""
+
+from __future__ import annotations
+
+import io
+import json
+import zipfile
+from datetime import date
+
+import pytest
+from PIL import Image
+
+from azimut import layout
+from azimut.engine import geoconfirmed, maplayers
+from azimut.workspace import Case
+
+# ---------------------------------------------------------------------------
+# An export, small enough to read
+# ---------------------------------------------------------------------------
+
+RED = "images/api/icons/E00000/False/template/192.png"
+BLUE = "images/api/icons/0051CA/False/template/10.png"
+GREY = "images/api/icons/777777/False/template/10.png"
+
+
+def _style(href: str) -> str:
+ """One icon's style pair, written the way GeoConfirmed's export writes it."""
+ ident = href.removeprefix("images/")
+ return (
+ f'<Style id="{ident}-normal"><IconStyle><scale>1.1</scale>'
+ f"<Icon><href>{href}</href></Icon>"
+ '<hotSpot x="16" xunits="pixels" y="16" yunits="insetPixels"/></IconStyle></Style>'
+ f'<StyleMap id="{ident}"><Pair><key>normal</key><styleUrl>#{ident}-normal</styleUrl>'
+ "</Pair></StyleMap>"
+ )
+
+
+def _placemark(name: str, description: str, href: str, lon: float, lat: float) -> str:
+ ident = href.removeprefix("images/")
+ named = f"<name><![CDATA[{name}]]></name>" if name else "<name />"
+ return (
+ f"<Placemark>{named}<description><![CDATA[{description}]]></description>"
+ f"<styleUrl>#{ident}</styleUrl>"
+ f"<Point><coordinates>{lon},{lat},0</coordinates></Point></Placemark>"
+ )
+
+
+EXPORT_KML = (
+ '<?xml version="1.0" encoding="utf-8"?>'
+ '<kml xmlns="http://www.opengis.net/kml/2.2"><Document>'
+ "<name>@GeoConfirmed - War Ukraine</name>"
+ + _style(RED)
+ + _style(BLUE)
+ + _style(GREY)
+ + "<Folder><name>A. Legend - Last Map Update 18 2227 SEP 2026</name>"
+ + _placemark("", "Airbase\n\nSource(s):\nhttps://example.test/base", RED, 37.1, 47.1)
+ + "</Folder><Folder><name>B. Last 7 days</name>"
+ + _placemark(
+ "13 SEP 2026",
+ "Strike on a depot in Shebekino\n\nSource(s):\nhttps://x.com/a/status/1"
+ "\n\nGeolocation(s):\nhttps://x.com/b/status/2",
+ BLUE,
+ 36.87,
+ 50.37,
+ )
+ + _placemark("12 SEP 2026", "Destroyed vehicle\n\nSource(s):\nhttps://t.me/c/3", RED, 37.5, 48.0)
+ + _placemark("11 SEP 2026", "Unclaimed mark", GREY, 36.0, 49.0)
+ + "</Folder></Document></kml>"
+).encode()
+
+
+def _disc(colour: tuple[int, int, int]) -> bytes:
+ buffer = io.BytesIO()
+ Image.new("RGBA", (56, 56), (*colour, 255)).save(buffer, "PNG")
+ return buffer.getvalue()
+
+
+def export_kmz(kml: bytes = EXPORT_KML) -> bytes:
+ buffer = io.BytesIO()
+ with zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED) as archive:
+ archive.writestr("doc.kml", kml)
+ archive.writestr(RED, _disc((224, 0, 0)))
+ archive.writestr(BLUE, _disc((0, 81, 202)))
+ archive.writestr(GREY, _disc((119, 119, 119)))
+ return buffer.getvalue()
+
+
+FACTIONS = [
+ {"name": "Ukraine", "backgroundColor": "#0051CA"},
+ {"name": "Russia", "backgroundColor": "#E00000"},
+ {"name": "Wagner", "backgroundColor": "#E00000"},
+]
+
+CONFLICT = {"name": "Ukraine", "shortName": "Ukraine", "url": "ukraine", "factions": FACTIONS}
+
+CONFLICTS = [
+ {"order": 2, "name": "Iran", "shortName": "Iran", "isPrivate": False,
+ "startDate": "2025-01-11T00:00:00", "endDate": None},
+ {"order": 1, "name": "Ukraine", "shortName": "Ukraine", "isPrivate": False,
+ "startDate": "2013-01-01T00:00:00", "endDate": None},
+ {"order": 3, "name": "Staff only", "shortName": "Hidden", "isPrivate": True},
+ {"order": 4, "name": "Odd", "shortName": "../../etc", "isPrivate": False},
+]
+
+
+def source(**extra) -> dict:
+ return {
+ "kind": maplayers.GEOCONFIRMED,
+ "factions": [
+ {"name": f["name"], "colour": f["backgroundColor"].lower()} for f in FACTIONS
+ ],
+ **extra,
+ }
+
+
+def read(kmz: bytes | None = None) -> dict:
+ return maplayers.parse(
+ kmz or export_kmz(), filename="export.kmz", reading=geoconfirmed.reading(source())
+ )
+
+
+def by_name(parsed: dict) -> dict[str, dict]:
+ return {f["properties"]["name"]: f["properties"] for f in parsed["geojson"]["features"]}
+
+
+# ---------------------------------------------------------------------------
+# Reading the export
+# ---------------------------------------------------------------------------
+
+
+def test_the_legend_is_the_factions_rather_than_the_age_folders():
+ """"Last 7 days" is true on the day of the export and false the next morning."""
+ names = {entry["name"] for entry in read()["summary"]["categories"]}
+
+ assert "B. Last 7 days" not in names
+ assert {"Ukraine", "Russia / Wagner", geoconfirmed.UNDATED} <= names
+
+
+def test_factions_sharing_a_colour_are_one_row_named_after_both():
+ """Their marks cannot be told apart, so a legend row that split them would be
+ filtering on something the map does not show."""
+ event = by_name(read())["12 SEP 2026 · Destroyed vehicle"]
+
+ assert event["category"] == "Russia / Wagner"
+ assert event["colour"] == "#e00000"
+
+
+def test_a_colour_no_faction_claims_says_so_rather_than_guessing():
+ assert by_name(read())["11 SEP 2026 · Unclaimed mark"]["category"] == geoconfirmed.UNLISTED
+
+
+def test_a_placemark_without_a_date_is_an_undated_site():
+ site = by_name(read())["Airbase"]
+
+ assert site["category"] == geoconfirmed.UNDATED
+ assert "date" not in site
+
+
+def test_an_event_carries_its_day_for_the_time_filter():
+ assert by_name(read())["13 SEP 2026 · Strike on a depot in Shebekino"]["date"] == "2026-09-13"
+
+
+def test_an_event_is_named_by_its_date_and_what_happened():
+ """The date alone says nothing to someone searching for a town, and the first
+ line is not repeated in the body underneath it."""
+ event = by_name(read())["13 SEP 2026 · Strike on a depot in Shebekino"]
+
+ assert event["description"].startswith("Source(s):")
+ assert "https://x.com/a/status/1" in event["description"]
+ assert "https://x.com/b/status/2" in event["description"]
+
+
+def test_a_long_first_line_is_cut_in_the_heading_and_kept_whole_in_the_body():
+ long = "A column of armour " * 20
+ kml = EXPORT_KML.replace(b"Destroyed vehicle", long.encode())
+ event = next(
+ p for p in (f["properties"] for f in read(export_kmz(kml))["geojson"]["features"])
+ if p["name"].startswith("12 SEP 2026")
+ )
+
+ assert event["name"].endswith("…")
+ assert len(event["name"]) < len(long)
+ assert event["description"].startswith(long.strip())
+
+
+def test_the_discs_are_centred_on_their_point_rather_than_on_the_declared_hotspot():
+ """16,16 pixels is the middle of a 32-pixel icon; on a 56-pixel disc it would
+ put every event a third of an icon away from where it happened."""
+ parsed = read()
+
+ assert parsed["icons"]
+ assert all(descriptor["hotspot"] is None for descriptor in parsed["icons"].values())
+ for feature in parsed["geojson"]["features"]:
+ assert feature["properties"]["icon"] in parsed["icons"]
+
+
+def test_the_icons_come_out_of_the_export_without_a_request(monkeypatch):
+ def refuse(*args, **kwargs):
+ raise AssertionError("an icon was fetched")
+
+ monkeypatch.setattr(maplayers, "_fetch_icon", refuse)
+ kmz = export_kmz()
+ parsed = read(kmz)
+
+ images = maplayers.icon_images(parsed["icons"], source=kmz)
+ assert set(images) == set(parsed["icons"])
+ for png in images.values():
+ with Image.open(io.BytesIO(png)) as image:
+ assert image.width == image.height, "a centred disc needs no padding"
+
+
+def test_a_date_is_read_in_english_whatever_the_locale():
+ assert geoconfirmed._day("13 SEP 2026") == date(2026, 9, 13)
+ assert geoconfirmed._day("13 Sep 2026") == date(2026, 9, 13)
+ assert geoconfirmed._day("31 FEB 2026") is None
+ assert geoconfirmed._day("Airbase") is None
+
+
+# ---------------------------------------------------------------------------
+# The query
+# ---------------------------------------------------------------------------
+
+
+def test_a_number_of_days_slides_with_the_day_of_each_read():
+ spec = geoconfirmed.window(days=30)
+
+ assert geoconfirmed.bounds(spec, date(2026, 9, 18)) == ("2026-08-19T00:00:00", None)
+ assert geoconfirmed.bounds(spec, date(2026, 10, 18)) == ("2026-09-18T00:00:00", None)
+
+
+def test_a_range_stays_put_and_takes_its_last_day_whole():
+ spec = geoconfirmed.window(start="2024-05-01", end="2024-05-10")
+
+ assert geoconfirmed.bounds(spec, date(2026, 9, 18)) == (
+ "2024-05-01T00:00:00",
+ "2024-05-10T23:59:59",
+ )
+
+
+def test_a_range_without_an_end_runs_to_the_day_of_each_read():
+ spec = geoconfirmed.window(start="2026-08-01")
+
+ assert geoconfirmed.bounds(spec) == ("2026-08-01T00:00:00", None)
+
+
+def test_the_whole_history_asks_for_no_dates_at_all():
+ spec = geoconfirmed.window(everything=True)
+
+ assert geoconfirmed.bounds(spec, date(2026, 9, 18)) == (None, None)
+ body = geoconfirmed.request(spec, None)
+ assert (body["start"], body["end"]) == (None, None)
+
+
+ "spec, label",
+ [
+ ({"everything": True}, "all history"),
+ ({"days": 30}, "last 30 days"),
+ ({"days": 1}, "last day"),
+ ({"start": "2026-08-01", "end": ""}, "since 1 Aug 2026"),
+ ({"start": "2026-08-01", "end": "2026-09-18"}, "1 Aug – 18 Sep 2026"),
+ ({"start": "2025-12-30", "end": "2026-01-02"}, "30 Dec 2025 – 2 Jan 2026"),
+ ({"start": "2026-08-01", "end": "2026-08-01"}, "1 Aug 2026"),
+ ],
+)
+def test_the_window_is_named_the_way_a_row_can_hold_it(spec, label):
+ assert geoconfirmed.window_label(spec) == label
+
+
+ "kwargs, reason",
+ [
+ ({"days": 30, "start": "2026-08-01"}, "not both"),
+ ({"everything": True, "days": 30}, "not both"),
+ ({"everything": True, "start": "2026-08-01"}, "not both"),
+ ({"days": 0}, "days"),
+ ({"days": geoconfirmed.MAX_DAYS + 1}, "days"),
+ ({}, "first day"),
+ ({"start": "yesterday"}, "not a date"),
+ ({"start": "2026-09-10", "end": "2026-09-01"}, "before the first"),
+ ],
+)
+def test_a_window_that_makes_no_sense_is_refused_with_a_reason(kwargs, reason):
+ with pytest.raises(maplayers.LayerError, match=reason):
+ geoconfirmed.window(**kwargs)
+
+
+def test_an_area_becomes_one_closed_polygon_in_the_export_request():
+ box = geoconfirmed.area([30, 44, 40, 52])
+ body = geoconfirmed.request({"days": 7}, box, date(2026, 9, 18))
+
+ assert body["start"] == "2026-09-11T00:00:00"
+ assert body["end"] is None
+ ring = body["polygons"][0][0]
+ assert ring[0] == ring[-1]
+ assert {tuple(point) for point in ring} == {(30, 44), (40, 44), (40, 52), (30, 52)}
+
+
+def test_no_area_asks_for_the_whole_conflict():
+ assert geoconfirmed.request({"days": 7}, None)["polygons"] is None
+
+
+ "box",
+ [[1, 2, 3], [40, 44, 30, 52], [30, 52, 40, 44], [170, 0, -170, 10], [0, 0, float("inf"), 1]],
+)
+def test_an_area_that_is_not_a_box_is_refused(box):
+ with pytest.raises(maplayers.LayerError):
+ geoconfirmed.area(box)
+
+
[email protected]("short", ["", "../Conflict", "Ukraine?x=1", "a" * 65])
+def test_a_conflict_name_is_checked_before_it_is_put_in_an_address(short):
+ with pytest.raises(maplayers.LayerError):
+ geoconfirmed.conflict(short)
+
+
+# ---------------------------------------------------------------------------
+# GeoConfirmed, stubbed
+# ---------------------------------------------------------------------------
+
+
+def served(monkeypatch):
+ """Every request GeoConfirmed would get, and the answer it gives."""
+ calls: list[dict] = []
+ state = {"export": export_kmz(), "conflict": CONFLICT}
+
+ def download(address, *, body=None, limit=maplayers.MAX_FETCH_BYTES, user_agent=""):
+ calls.append({"address": address, "body": body, "user_agent": user_agent})
+ if address.endswith("/api/Conflict"):
+ return json.dumps(CONFLICTS).encode(), "Conflict"
+ if "/api/Conflict/" in address:
+ answer = state["conflict"]
+ return (json.dumps(answer).encode() if answer else b""), "Ukraine"
+ if "/api/Map/export/" in address:
+ return state["export"], "@Geoconfirmed - Ukraine - 18 2227 SEP 2026.kmz"
+ raise AssertionError(f"unexpected request {address}")
+
+ monkeypatch.setattr(maplayers, "download", download)
+ return {"calls": calls, "state": state}
+
+
+def case_id(client) -> str:
+ return client.post("/api/cases", json={"name": "Front"}).json()["id"]
+
+
+def add(client, case_id, **body):
+ return client.post(
+ f"/api/cases/{case_id}/map-layers/geoconfirmed",
+ json={"conflict": "Ukraine", "days": 30, **body},
+ )
+
+
+def test_the_conflict_list_is_public_ordered_and_checked(client, served):
+ listed = client.get("/api/geoconfirmed/conflicts").json()
+
+ assert [entry["conflict"] for entry in listed] == ["Ukraine", "Iran"]
+ assert listed[0]["start"] == "2013-01-01"
+ assert served["calls"][0]["user_agent"].startswith("Azimut/")
+
+
+def test_adding_a_conflict_files_a_followed_layer_in_its_own_icons(client, case_id, served):
+ response = add(client, case_id, area=[30, 44, 40, 52])
+ assert response.status_code == 200, response.text
+ row = response.json()
+
+ assert row["title"] == "GeoConfirmed · Ukraine · last 30 days"
+ assert row["source"]["kind"] == "geoconfirmed"
+ assert row["source"]["url"] == "https://geoconfirmed.org/map/ukraine"
+ assert row["source"]["area"] == [30, 44, 40, 52]
+ assert row["features"] == 4
+ assert row["icons"] == 3
+ assert row["refresh"] == {"on_open": True}
+ assert row["stale"] is False
+
+ export = next(call for call in served["calls"] if "/Map/export/" in call["address"])
+ assert export["address"].endswith("/api/Map/export/Ukraine")
+ assert export["body"]["polygons"] is not None
+
+
+def test_the_whole_history_is_read_on_refresh_rather_than_on_every_case_open(
+ client, case_id, served
+):
+ """Tens of thousands of events for a long war, re-read on every case open for
+ a map that moves by a few dozen a day, is a cost nobody asked for."""
+ response = add(client, case_id, days=None, everything=True)
+ assert response.status_code == 200, response.text
+ row = response.json()
+
+ assert row["title"] == "GeoConfirmed · Ukraine · all history"
+ assert row["refresh"] == {"on_open": False}
+ export = next(call for call in served["calls"] if "/Map/export/" in call["address"])
+ assert (export["body"]["start"], export["body"]["end"]) == (None, None)
+
+
+def test_a_window_is_re_read_when_the_case_opens_unless_told_otherwise(
+ client, case_id, served
+):
+ assert add(client, case_id).json()["refresh"] == {"on_open": True}
+ assert add(client, case_id, on_open=False).json()["refresh"] == {"on_open": False}
+ assert add(client, case_id, days=None, everything=True, on_open=True).json()["refresh"] == {
+ "on_open": True
+ }
+
+
+def test_the_undated_sites_start_switched_off(client, case_id, served):
+ """The analyst asked for dates, and these have none. They stay one click away."""
+ row = add(client, case_id).json()
+
+ assert row["hidden"] == [geoconfirmed.UNDATED]
+ counts = {entry["name"]: entry["count"] for entry in row["categories"]}
+ assert counts[geoconfirmed.UNDATED] == 1
+
+
+def test_a_conflict_geoconfirmed_does_not_know_is_refused_with_its_name(
+ client, case_id, served
+):
+ served["state"]["conflict"] = None
+ response = add(client, case_id, conflict="Atlantis")
+
+ assert response.status_code == 422
+ assert "Atlantis" in response.json()["detail"]
+
+
+def test_a_bad_window_is_refused_before_geoconfirmed_is_asked(client, case_id, served):
+ response = add(client, case_id, days=None, start="2026-09-10", end="2026-09-01")
+
+ assert response.status_code == 422
+ assert served["calls"] == []
+
+
+def test_listing_and_drawing_read_the_snapshot_rather_than_geoconfirmed(
+ client, case_id, served
+):
+ row = add(client, case_id).json()
+ asked = len(served["calls"])
+
+ client.get(f"/api/cases/{case_id}/map-layers")
+ client.get(f"/api/cases/{case_id}/map-layers/{row['name']}/data")
+ client.patch(f"/api/cases/{case_id}/map-layers/{row['name']}", json={"hidden": ["Ukraine"]})
+
+ assert len(served["calls"]) == asked
+
+
+def test_the_drawn_copy_is_rebuilt_in_geoconfirmed_terms(client, case_id, served):
+ """The cache never travels, so a restored case redraws from the snapshot: it
+ has to come back with the factions, not the age folders."""
+ row = add(client, case_id).json()
+ Case.open(case_id).resolve_inside(layout.layer_cache_rel(row["name"])).unlink()
+
+ data = client.get(f"/api/cases/{case_id}/map-layers/{row['name']}/data").json()
+ categories = {feature["properties"]["category"] for feature in data["features"]}
+
+ assert "B. Last 7 days" not in categories
+ assert "Ukraine" in categories
+
+
+def test_a_refresh_asks_the_same_question_again(client, case_id, served):
+ row = add(client, case_id, area=[30, 44, 40, 52]).json()
+ first = [call for call in served["calls"] if "/Map/export/" in call["address"]]
+ served["calls"].clear()
+
+ response = client.post(f"/api/cases/{case_id}/map-layers/{row['name']}/refresh")
+ assert response.status_code == 200, response.text
+ again = [call for call in served["calls"] if "/Map/export/" in call["address"]]
+
+ assert again[0]["body"] == first[0]["body"]
+ assert response.json()["hidden"] == [geoconfirmed.UNDATED]
+
+
+def test_a_refresh_picks_up_a_faction_geoconfirmed_added_since(client, case_id, served):
+ row = add(client, case_id).json()
+ assert geoconfirmed.UNLISTED in {entry["name"] for entry in row["categories"]}
+
+ served["state"]["conflict"] = {
+ **CONFLICT,
+ "factions": [*FACTIONS, {"name": "Volunteers", "backgroundColor": "#777777"}],
+ }
+ moved = client.post(f"/api/cases/{case_id}/map-layers/{row['name']}/refresh").json()
+ names = {entry["name"] for entry in moved["categories"]}
+
+ assert "Volunteers" in names
+ assert geoconfirmed.UNLISTED not in names
+
+
+def test_a_failed_refresh_leaves_the_last_export_on_the_map(
+ client, case_id, served, monkeypatch
+):
+ row = add(client, case_id).json()
+
+ def fail(*args, **kwargs):
+ raise maplayers.LayerFetchError("could not reach that source: offline")
+
+ monkeypatch.setattr(maplayers, "download", fail)
+ response = client.post(f"/api/cases/{case_id}/map-layers/{row['name']}/refresh")
+
+ assert response.status_code == 502
+ kept = client.get(f"/api/cases/{case_id}/map-layers/{row['name']}").json()
+ assert kept["sha256"] == row["sha256"]
+
+
+def test_the_layer_is_one_map_layer_entity_citing_the_map_page(client, case_id, served):
+ row = add(client, case_id).json()
+ entity = Case.open(case_id).find_entity(attr="spec", value=row["spec"])
+
+ assert entity["type"] == maplayers.ENTITY_TYPE
+ assert entity["attrs"]["source_url"] == "https://geoconfirmed.org/map/ukraine"
diff --git a/tests/test_map_layers.py b/tests/test_map_layers.py
index a7a07ae..0d94a0f 100644
--- a/tests/test_map_layers.py
+++ b/tests/test_map_layers.py
@@ -138,6 +138,9 @@ def add(
@pytest.mark.parametrize(
"data, filename",
[(KML, "s.kml"), (kmz(), "s.kmz"), (GEOJSON, "h.geojson"), (GPX, "p.gpx")],
+ # Named, because a zip carries the second it was built in: ids made of the bytes
+ # differ between xdist workers that collect a second apart, and the run refuses.
+ ids=["kml", "kmz", "geojson", "gpx"],
)
def test_every_format_parses_to_the_same_normalised_shape(data, filename):
"""Whatever it arrived as, a feature carries the same four fields and the
@@ -413,6 +416,18 @@ def test_the_drawn_copy_is_rebuilt_when_the_cache_is_gone(client, case_id):
assert len(drawn.json()["features"]) == 3
+def test_the_drawn_copy_is_never_reused_by_the_browser_unasked(client, case_id):
+ """A refresh changes what this one address holds. Without a rule of its own,
+ Chrome guessed a lifetime from Last-Modified and went on drawing a GeoConfirmed
+ layer's old features, a day of events short, under a row saying it was read
+ just now."""
+ row = add(client, case_id, KML, "sightings.kml")
+
+ drawn = client.get(f"/api/cases/{case_id}/map-layers/{row['name']}/data")
+
+ assert drawn.headers["cache-control"] == "no-cache"
+
+
def test_a_category_toggle_is_stored_and_bounded_to_the_categories_there_are(
client, case_id
):
@@ -427,17 +442,23 @@ def test_a_category_toggle_is_stored_and_bounded_to_the_categories_there_are(
assert updated["features"] == 3, "hiding a category never changes what is loaded"
-def test_the_switch_and_the_legend_survive_a_reload(client, case_id):
+def test_the_legend_survives_a_reload_and_the_switch_is_not_stored(client, case_id):
+ """Whether a layer is drawn lives in the page and starts off on every load: a
+ layer that crashed the tab must not be drawn again by the reload."""
row = add(client, case_id, KML, "sightings.kml")
client.patch(
f"/api/cases/{case_id}/map-layers/{row['name']}",
- json={"enabled": False, "hidden": ["Damage"]},
+ json={"enabled": True, "hidden": ["Damage"]},
)
reopened = client.get(f"/api/cases/{case_id}/map-layers").json()[0]
+ spec = json.loads(
+ Case.open(case_id).resolve_inside(layout.layer_spec_rel(row["name"])).read_text()
+ )
- assert reopened["enabled"] is False
assert reopened["hidden"] == ["Damage"]
+ assert "enabled" not in reopened
+ assert "enabled" not in spec
def test_a_local_file_is_never_stale(client, case_id):
@@ -535,7 +556,7 @@ def test_adding_and_drawing_a_local_file_never_reaches_the_network(
row = add(client, case_id, KML, "sightings.kml")
client.get(f"/api/cases/{case_id}/map-layers")
client.get(f"/api/cases/{case_id}/map-layers/{row['name']}/data")
- client.patch(f"/api/cases/{case_id}/map-layers/{row['name']}", json={"enabled": True})
+ client.patch(f"/api/cases/{case_id}/map-layers/{row['name']}", json={"hidden": ["Damage"]})
def test_listing_a_subscribed_layer_reads_the_snapshot_rather_than_the_feed(
@@ -552,7 +573,7 @@ def test_listing_a_subscribed_layer_reads_the_snapshot_rather_than_the_feed(
client.get(f"/api/cases/{case_id}/map-layers")
client.get(f"/api/cases/{case_id}/map-layers/{row['name']}/data")
- client.patch(f"/api/cases/{case_id}/map-layers/{row['name']}", json={"enabled": False})
+ client.patch(f"/api/cases/{case_id}/map-layers/{row['name']}", json={"hidden": ["Damage"]})
assert len(calls) == 1, "only the subscription itself fetched"
@@ -965,6 +986,41 @@ def test_more_icons_than_the_cap_leaves_the_rest_on_the_pictogram(monkeypatch):
assert len(maplayers.icon_images(parsed["icons"], source=source)) == 1
+def _many_icons(count: int, href: str) -> bytes:
+ return (
+ '<?xml version="1.0" encoding="UTF-8"?>'
+ '<kml xmlns="http://www.opengis.net/kml/2.2"><Document><name>Many</name>'
+ + "".join(
+ f'<Style id="s{index}"><IconStyle><color>ff0000{index:02x}</color>'
+ f"<Icon><href>{href}</href></Icon></IconStyle></Style>"
+ f'<Placemark><styleUrl>#s{index}</styleUrl>'
+ f"<Point><coordinates>{index},48</coordinates></Point></Placemark>"
+ for index in range(count)
+ )
+ + "</Document></kml>"
+ ).encode()
+
+
+def test_icons_at_addresses_are_held_to_their_own_smaller_cap(monkeypatch):
+ """Each one is a request to somebody else's server, which an icon inside the
+ archive is not."""
+ monkeypatch.setattr(maplayers, "MAX_FETCHED_ICONS", 2)
+ calls = []
+ monkeypatch.setattr(maplayers, "_fetch_icon", lambda href: (calls.append(href), png())[1])
+ parsed = maplayers.parse(_many_icons(4, "https://icons.test/p.png"), filename="s.kml")
+
+ assert len(maplayers.icon_images(parsed["icons"])) == 2
+ assert len(calls) == 2
+
+
+def test_icons_inside_the_archive_are_not_held_to_the_cap_on_fetched_ones(monkeypatch):
+ monkeypatch.setattr(maplayers, "MAX_FETCHED_ICONS", 1)
+ source = kmz(_many_icons(4, "images/pin.png"), extra={"images/pin.png": png()})
+ parsed = maplayers.parse(source, filename="s.kmz")
+
+ assert len(maplayers.icon_images(parsed["icons"], source=source)) == 4
+
+
def test_an_icon_is_asked_for_by_key_rather_than_by_path(client, case_id, no_network):
"""The key is a content hash, so there is nothing in the URL to traverse
with — and anything that is not one is refused before a file is opened."""
@@ -996,3 +1052,79 @@ def _status_error(url: str, code: int) -> "maplayers.httpx.HTTPStatusError":
request = maplayers.httpx.Request("GET", maplayers.feed_url(url))
response = maplayers.httpx.Response(code, request=request)
return maplayers.httpx.HTTPStatusError("refused", request=request, response=response)
+
+
+# ---------------------------------------------------------------------------
+# Dates, which the row's time filter compares
+# ---------------------------------------------------------------------------
+
+
+def test_a_kml_timestamp_or_the_start_of_a_timespan_dates_its_placemark():
+ dated = (
+ '<?xml version="1.0" encoding="UTF-8"?>'
+ '<kml xmlns="http://www.opengis.net/kml/2.2"><Document><name>Dated</name>'
+ "<Placemark><name>Stamped</name><TimeStamp><when>2024-05-10T14:03:00Z</when>"
+ "</TimeStamp><Point><coordinates>2,48</coordinates></Point></Placemark>"
+ "<Placemark><name>Spanned</name><TimeSpan><begin>2024-05-01</begin>"
+ "<end>2024-05-09</end></TimeSpan><Point><coordinates>3,48</coordinates></Point>"
+ "</Placemark>"
+ "<Placemark><name>Undated</name><Point><coordinates>4,48</coordinates></Point>"
+ "</Placemark></Document></kml>"
+ ).encode()
+ properties = {
+ f["properties"]["name"]: f["properties"]
+ for f in maplayers.parse(dated, filename="d.kml")["geojson"]["features"]
+ }
+
+ # the day as the source wrote it, not moved into another timezone
+ assert properties["Stamped"]["date"] == "2024-05-10"
+ assert properties["Spanned"]["date"] == "2024-05-01"
+ assert "date" not in properties["Undated"]
+
+
+def test_a_gpx_waypoint_is_dated_by_its_time():
+ gpx = (
+ '<gpx version="1.1"><wpt lat="48.10" lon="2.10"><name>Start</name>'
+ "<time>2023-11-02T06:40:00Z</time></wpt></gpx>"
+ ).encode()
+
+ feature = maplayers.parse(gpx, filename="p.gpx")["geojson"]["features"][0]
+
+ assert feature["properties"]["date"] == "2023-11-02"
+
+
[email protected]("value", ["", "yesterday", "2024-02-30", "10/05/2024", None])
+def test_anything_that_is_not_a_day_dates_nothing(value):
+ assert maplayers.iso_day(value) == ""
+
+
+def test_the_time_filter_is_stored_with_the_legend_and_cleared_by_two_blanks(client, case_id):
+ row = add(client, case_id, KML, "sightings.kml")
+ url = f"/api/cases/{case_id}/map-layers/{row['name']}"
+
+ kept = client.patch(url, json={"period": {"start": "2024-05-01", "end": "2024-05-31"}})
+ assert kept.json()["period"] == {"start": "2024-05-01", "end": "2024-05-31"}
+ assert client.get(url).json()["period"] == {"start": "2024-05-01", "end": "2024-05-31"}
+
+ open_ended = client.patch(url, json={"period": {"start": "2024-05-01", "end": ""}})
+ assert open_ended.json()["period"] == {"start": "2024-05-01", "end": ""}
+
+ cleared = client.patch(url, json={"period": {"start": "", "end": ""}})
+ assert cleared.json()["period"] is None
+
+
+def test_a_period_given_backwards_is_put_the_right_way_round(client, case_id):
+ row = add(client, case_id, KML, "sightings.kml")
+ url = f"/api/cases/{case_id}/map-layers/{row['name']}"
+
+ turned = client.patch(url, json={"period": {"start": "2024-05-31", "end": "2024-05-01"}})
+
+ assert turned.json()["period"] == {"start": "2024-05-01", "end": "2024-05-31"}
+
+
+def test_a_period_that_is_not_made_of_days_is_refused(client, case_id):
+ row = add(client, case_id, KML, "sightings.kml")
+ url = f"/api/cases/{case_id}/map-layers/{row['name']}"
+
+ assert client.patch(url, json={"period": {"start": "May", "end": ""}}).status_code == 422
+ assert client.get(url).json()["period"] is None
diff --git a/tests/test_regressions.py b/tests/test_regressions.py
index 3d6890a..e6617cb 100644
--- a/tests/test_regressions.py
+++ b/tests/test_regressions.py
@@ -256,6 +256,25 @@ def test_names_one_child_is_judged_on_both_path_flavours():
assert not layout.names_one_child(hostile), hostile
+def built_frontend(monkeypatch, tmp_path):
+ (tmp_path / "assets").mkdir()
+ (tmp_path / "index.html").write_text('<div id="app"></div>', encoding="utf-8")
+ (tmp_path / "favicon.svg").write_text("<svg/>", encoding="utf-8")
+ monkeypatch.setattr("azimut.server.STATIC_DIR", tmp_path)
+
+
+def test_the_page_is_asked_for_again_on_every_visit(built_frontend, client):
+ """It names this build's hashed bundles. Kept on a guess from Last-Modified,
+ it outlives an update and names bundles that are no longer there."""
+ for route in ("/", "/satellite"):
+ page = client.get(route)
+ assert page.status_code == 200
+ assert page.headers["cache-control"] == "no-cache", route
+ # a file of its own is left to the usual rules
+ assert "cache-control" not in client.get("/favicon.svg").headers
+
+
def test_workspace_module_exposes_the_guard_it_documents():
# `Case.locate` is the only door to a case; keep the guard wired to it.
assert workspace.layout.names_one_child is layout.names_one_child
diff --git a/tests/test_tiles.py b/tests/test_tiles.py
index 66e4554..7fd6aa8 100644
--- a/tests/test_tiles.py
+++ b/tests/test_tiles.py
@@ -663,17 +663,6 @@ def test_dms_format():
assert "N" in geo.to_dms(48.8584, 2.2945)
-def test_map_links_cover_external_maps():
- links = geo.map_links(48.8584, 2.2945, 16)
- for key in (
- "google", "google_earth", "apple", "bing", "yandex",
- "sentinel", "zoom_earth", "satellites_pro",
- ):
- assert key in links and links[key].startswith("https://")
- # Yandex takes lon,lat order
- assert "ll=2.2945,48.8584" in links["yandex"]
-
-
class _FakeResp:
def __init__(self, payload):
self._payload = payload